answer stringlengths 17 10.2M |
|---|
package parser;
import interfaces.Parser;
import interfaces.Peak;
import xtandem.MgfPeak;
import xtandem.MgfPeaklist;
import xtandem.Peptide;
import xtandem.PeptideMap;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.HashMap;
/**
*
* This class is an implementation of Parser and retrieves a peak list for a mgf file.
* @author Thilo Muth
*
*/
public class MgfFileParser implements Parser{
/**
* Holds the mgf file which should be parsed.
*/
private File iMgfFile = null;
/**
* Contains the total number of the spectra.
*/
private int iSpectraNumber = -1;
/**
* Contains the hash map of the mgf peaklists.
*/
private HashMap<Integer, MgfPeaklist> iPeaklistMap = null;
/**
* Contains the title2spectrum id map.
*/
private HashMap<String, Integer> iTitle2SpectrumIdMap = null;
/**
* Contains the peptide map.
*/
private PeptideMap iPepMap = null;
/**
* The constructor gets the path to the mgf-file.
*
* @param aMgfFilePath
*/
public MgfFileParser(String aMgfFilePath, HashMap<String, Integer> aTitle2SpectrumIdMap, PeptideMap aPepMap) {
iMgfFile = new File(aMgfFilePath);
iTitle2SpectrumIdMap = aTitle2SpectrumIdMap;
iPepMap = aPepMap;
}
/**
* This method retrieves a string array with all the spectra names.
* @return spectra
*/
public String[] getAllSpectraNames(){
String spectra[] = null;
ArrayList<String> list = null;
try{
BufferedReader br = new BufferedReader(new FileReader(iMgfFile));
list = new ArrayList<String>();
String line = null;
while ((line = br.readLine()) != null) {
if (line.startsWith("TITLE")) {
// Retrieve the title.
String title = line.substring(line.indexOf("=") + 1, line.length());
if (title != null) {
title = title.trim();
}
list.add(title);
} else {
continue;
}
}
} catch (Exception e){
e.printStackTrace();
}
// Convert it to a string array.
spectra = new String[list.size()];
int i = 0;
for (String string : list) {
spectra[i++] = string;
}
return spectra;
}
/**
* This method returns a mgf peak list map with the spectrum number as key
* and the peaklist as value.
*
* @return iPeaklistMap
*/
public HashMap getPeakListMap() {
try {
BufferedReader br = new BufferedReader(new FileReader(iMgfFile));
// Get a vector for the peaks.
ArrayList<MgfPeak> peakVector = new ArrayList();
MgfPeaklist mgfPeaklist = new MgfPeaklist();
iPeaklistMap = new HashMap<Integer, MgfPeaklist>();
// Flag to show if it's inside the spectrum.
boolean flagSpectrum = false;
// Initialize the counters.
int spectraCounter = 0;
//int lineCounter = 0;
String line = null;
while ((line = br.readLine()) != null) {
//lineCounter++;
line = line.trim();
if (line.equals("")) {
continue;
}
/*if (lineCounter == 1 && line.startsWith("CHARGE")) {
continue;
}*/
if (line.equals("BEGIN IONS")) {
flagSpectrum = true;
// Empty the mgf peak list.
mgfPeaklist = new MgfPeaklist();
peakVector = new ArrayList<MgfPeak>();
spectraCounter++;
continue;
}
if(flagSpectrum){
if (line.startsWith("TITLE")) {
// Retrieve the title.
String title = line.substring(line.indexOf("=") + 1, line.length());
if (title != null) {
title = title.trim();
}
if(iTitle2SpectrumIdMap.get(title) != null){
mgfPeaklist.setIdentfied(true);
mgfPeaklist.setIdentifiedSpectrumNumber(iTitle2SpectrumIdMap.get(title));
}
// Set the title for the peaklist.
mgfPeaklist.setTitle(title);
continue;
} else if (line.startsWith("PEPMASS")) {
// Type is MS/MS.
mgfPeaklist.setMSType("MS/MS");
// Set the peptide mass.
String pepMass = line.substring((line.indexOf("=")) + 1).trim();
mgfPeaklist.setPepmass(Double.parseDouble(pepMass));
continue;
} else if (line.startsWith("CHARGE")) {
// Type is MS/MS.
mgfPeaklist.setMSType("MS/MS");
// Set the charge.
String charge = line.substring(line.indexOf("=") + 1, line.indexOf("=") + 2);
mgfPeaklist.setCharge(charge);
continue;
} else {
// Parse the masses and the intensities
try {
if (line.equals("")) {
continue;
}
if (!line.equals("END IONS")){
//if(!mgfPeaklist.isIdentfied()){
double peakMz;
double peakIntensity;
int peakCharge;
// Split on the white spaces.
String[] entries = line.split("\\s+");
try {
// The first entry is the m/z.
peakMz = Double.parseDouble(entries[0]);
// The second entry is the intensity.
peakIntensity = Double.parseDouble(entries[1]);
} catch (Exception e) {
return null;
}
// Get a mgf peak object.
MgfPeak mgfPeak = new MgfPeak();
// Set the peak mz.
mgfPeak.setPeakMz(peakMz);
// Set the peak intensity.
mgfPeak.setPeakIntensity(peakIntensity);
// Check if a charge is given.
if (entries.length == 3) {
// Delete the "+" from the original charge.
peakCharge = Integer.parseInt(entries[3].replace("+", ""));
mgfPeak.setPeakCharge(peakCharge);
}
// Add the peak to the list.
peakVector.add(mgfPeak);
} else {
// Add the peaks to the list.
flagSpectrum = false;
if(mgfPeaklist.isIdentfied()){
ArrayList<Peptide> peptides = iPepMap.getAllPeptides(mgfPeaklist.getIdentifiedSpectrumNumber());
mgfPeaklist.setIdentifiedPeptides(peptides);
}
// Add the peaks to the list.
mgfPeaklist.setPeaks(peakVector);
// Fill the peak list map.
iPeaklistMap.put(spectraCounter, mgfPeaklist);
continue;
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
// Set the total number of spectra.
iSpectraNumber = spectraCounter;
return iPeaklistMap;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* This method returns a peak list for a specific spectrum file.
* For example: orbitrapXXXXX.XXXX.XXXX.X.dta as spectrum file string.
*
* @return iMgfPeaklist
*/
public MgfPeaklist getPeaklist(String spectrumTitle) {
try {
BufferedReader br = new BufferedReader(new FileReader(iMgfFile));
ArrayList<Peak> list = new ArrayList<Peak>();
MgfPeaklist mgfPeaklist = new MgfPeaklist();
// Flag to show if inside the spectrum.
int lineCounter = 0;
String line = null;
boolean goFlag = false;
while ((line = br.readLine()) != null) {
lineCounter++;
line = line.trim();
if (line.equals("")) {
continue;
}
if (lineCounter == 1 && line.startsWith("CHARGE")) {
continue;
}
if (line.startsWith("TITLE")) {
// Retrieve the title.
String string = line.substring(line.indexOf("=") + 1, line.length());
if (string != null) {
string = string.trim();
}
if (string.equals(spectrumTitle)){
goFlag = true;
// Set the title for the peaklist.
mgfPeaklist.setTitle(string);
continue;
}
}
// Go into it with a spectrum found.
if(goFlag == true){
if (line.startsWith("PEPMASS")) {
// Type is MS/MS.
mgfPeaklist.setMSType("MS/MS");
// Set the peptide mass.
// PEPMASS line found.
String pepMass = line.substring((line.indexOf("=")) + 1).trim();
mgfPeaklist.setPepmass(Double.parseDouble(pepMass));
}
if (line.startsWith("CHARGE")) {
// Type is MS/MS.
mgfPeaklist.setMSType("MS/MS");
// Set the charge.
mgfPeaklist.setCharge(line);
}
// Format check if line start with a number.
if (line.charAt(0) >= '1' && line.charAt(0) <= '9') {
// Go until the END IONS-Section and parse.
for (; line.indexOf("END IONS") == -1 && line != null; line = br.readLine()) {
try {
if (line.equals("")) {
continue;
}
double peakMz;
double peakIntensity;
int peakCharge;
// Split on the white spaces.
String[] entries = line.split("\\s+");
try {
// The first entry is the m/z.
peakMz = Double.parseDouble(entries[0]);
// The second entry is the intensity.
peakIntensity = Double.parseDouble(entries[1]);
} catch (Exception e) {
return null;
}
// Get a mgf peak object.
MgfPeak mgfPeak = new MgfPeak();
// Set the peak mz.
mgfPeak.setPeakMz(peakMz);
// Set the peak intensity.
mgfPeak.setPeakIntensity(peakIntensity);
// Check if a charge is given.
if (entries.length == 3) {
// Delete the "+" from the original charge.
peakCharge = Integer.parseInt(entries[3].replace("+", ""));
mgfPeak.setPeakCharge(peakCharge);
}
// Add the peak to the list.
list.add(mgfPeak);
} catch (Exception e) {
e.printStackTrace();
}
} break;
}
}
}
return mgfPeaklist;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* Returns the total number of spectra in the parsed mgf file.
* @return iSpectraNumber
*/
public int getSpectraNumber() {
if(iSpectraNumber < 0){
this.getPeakListMap();
}
return iSpectraNumber;
}
} |
package edu.mit.streamjit.impl.compiler2;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.collect.ContiguousSet;
import com.google.common.collect.DiscreteDomain;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.HashBasedTable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Maps;
import com.google.common.collect.Range;
import com.google.common.collect.Sets;
import com.google.common.collect.Table;
import com.google.common.math.IntMath;
import com.google.common.math.LongMath;
import com.google.common.primitives.Ints;
import com.google.common.primitives.Primitives;
import com.google.common.reflect.TypeResolver;
import com.google.common.reflect.TypeToken;
import edu.mit.streamjit.api.DuplicateSplitter;
import edu.mit.streamjit.api.IllegalStreamGraphException;
import edu.mit.streamjit.api.Joiner;
import edu.mit.streamjit.api.RoundrobinJoiner;
import edu.mit.streamjit.api.RoundrobinSplitter;
import edu.mit.streamjit.api.Splitter;
import edu.mit.streamjit.api.StreamCompilationFailedException;
import edu.mit.streamjit.api.StreamCompiler;
import edu.mit.streamjit.api.WeightedRoundrobinJoiner;
import edu.mit.streamjit.api.WeightedRoundrobinSplitter;
import edu.mit.streamjit.api.Worker;
import edu.mit.streamjit.impl.blob.Blob;
import edu.mit.streamjit.impl.blob.Blob.Token;
import edu.mit.streamjit.impl.blob.Buffer;
import edu.mit.streamjit.impl.blob.DrainData;
import edu.mit.streamjit.impl.common.BlobHostStreamCompiler;
import edu.mit.streamjit.impl.common.Configuration;
import edu.mit.streamjit.impl.common.Configuration.IntParameter;
import edu.mit.streamjit.impl.common.Configuration.SwitchParameter;
import edu.mit.streamjit.impl.common.Workers;
import edu.mit.streamjit.impl.compiler.Schedule;
import edu.mit.streamjit.impl.compiler2.Compiler2BlobHost.DrainInstruction;
import edu.mit.streamjit.impl.compiler2.Compiler2BlobHost.ReadInstruction;
import edu.mit.streamjit.impl.compiler2.Compiler2BlobHost.WriteInstruction;
import edu.mit.streamjit.test.Benchmark;
import edu.mit.streamjit.test.Benchmarker;
import edu.mit.streamjit.test.apps.fmradio.FMRadio;
import edu.mit.streamjit.test.regression.Reg20131116_104433_226;
import edu.mit.streamjit.test.sanity.PipelineSanity;
import edu.mit.streamjit.test.sanity.SplitjoinComputeSanity;
import edu.mit.streamjit.util.CollectionUtils;
import edu.mit.streamjit.util.Combinators;
import static edu.mit.streamjit.util.Combinators.*;
import static edu.mit.streamjit.util.LookupUtils.findStatic;
import edu.mit.streamjit.util.Pair;
import edu.mit.streamjit.util.ReflectionUtils;
import edu.mit.streamjit.util.bytecode.Module;
import edu.mit.streamjit.util.bytecode.ModuleClassLoader;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.reflect.Modifier;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.NavigableSet;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.atomic.AtomicInteger;
/**
*
* @author Jeffrey Bosboom <jeffreybosboom@gmail.com>
* @since 9/22/2013
*/
public class Compiler2 {
public static final ImmutableSet<Class<?>> REMOVABLE_WORKERS = ImmutableSet.<Class<?>>of(
RoundrobinSplitter.class, WeightedRoundrobinSplitter.class, DuplicateSplitter.class,
RoundrobinJoiner.class, WeightedRoundrobinJoiner.class);
private static final MethodHandles.Lookup LOOKUP = MethodHandles.lookup();
private static final AtomicInteger PACKAGE_NUMBER = new AtomicInteger();
private final ImmutableSet<Worker<?, ?>> workers;
private final ImmutableSet<ActorArchetype> archetypes;
private final NavigableSet<Actor> actors;
private ImmutableSortedSet<ActorGroup> groups;
private ImmutableSortedSet<WorkerActor> actorsToBeRemoved;
private final Configuration config;
private final int maxNumCores;
private final DrainData initialState;
private final ImmutableMap<Token, ImmutableList<Object>> initialStateDataMap;
private final Set<Storage> storage;
private ImmutableMap<ActorGroup, Integer> externalSchedule;
private final Module module = new Module();
private ImmutableMap<ActorGroup, Integer> initSchedule;
/**
* For each token in the blob, the number of items live on that edge after
* the init schedule, without regard to removals. (We could recover this
* information from Actor.inputSlots when we're creating drain instructions,
* but storing it simplifies the code and permits asserting we didn't lose
* any items.)
*/
private ImmutableMap<Token, Integer> postInitLiveness;
/**
* ConcreteStorage instances used during initialization (bound into the
* initialization code).
*/
private ImmutableMap<Storage, ConcreteStorage> initStorage;
/**
* ConcreteStorage instances used during the steady-state (bound into the
* steady-state code).
*/
private ImmutableMap<Storage, ConcreteStorage> steadyStateStorage;
/**
* Code to run the initialization schedule. (Initialization is
* single-threaded.)
*/
private MethodHandle initCode;
/**
* Code to run the steady state schedule. The blob host takes care of
* filling/flushing buffers, adjusting storage and the global barrier.
*/
private ImmutableList<MethodHandle> steadyStateCode;
private final List<ReadInstruction> initReadInstructions = new ArrayList<>();
private final List<WriteInstruction> initWriteInstructions = new ArrayList<>();
private final List<Runnable> migrationInstructions = new ArrayList<>();
private final List<ReadInstruction> readInstructions = new ArrayList<>();
private final List<WriteInstruction> writeInstructions = new ArrayList<>();
private final List<DrainInstruction> drainInstructions = new ArrayList<>();
public Compiler2(Set<Worker<?, ?>> workers, Configuration config, int maxNumCores, DrainData initialState) {
this.workers = ImmutableSet.copyOf(workers);
Map<Class<?>, ActorArchetype> archetypesBuilder = new HashMap<>();
Map<Worker<?, ?>, WorkerActor> workerActors = new HashMap<>();
for (Worker<?, ?> w : workers) {
@SuppressWarnings("unchecked")
Class<? extends Worker<?, ?>> wClass = (Class<? extends Worker<?, ?>>)w.getClass();
if (archetypesBuilder.get(wClass) == null)
archetypesBuilder.put(wClass, new ActorArchetype(wClass, module));
WorkerActor actor = new WorkerActor(w, archetypesBuilder.get(wClass));
workerActors.put(w, actor);
}
this.archetypes = ImmutableSet.copyOf(archetypesBuilder.values());
Map<Token, TokenActor> tokenActors = new HashMap<>();
Table<Actor, Actor, Storage> storageTable = HashBasedTable.create();
int[] inputTokenId = new int[]{Integer.MIN_VALUE}, outputTokenId = new int[]{Integer.MAX_VALUE};
for (WorkerActor a : workerActors.values())
a.connect(ImmutableMap.copyOf(workerActors), tokenActors, storageTable, inputTokenId, outputTokenId);
this.actors = new TreeSet<>();
this.actors.addAll(workerActors.values());
this.actors.addAll(tokenActors.values());
this.storage = new HashSet<>(storageTable.values());
this.config = config;
this.maxNumCores = maxNumCores;
this.initialState = initialState;
ImmutableMap.Builder<Token, ImmutableList<Object>> initialStateDataMapBuilder = ImmutableMap.builder();
if (initialState != null) {
for (Table.Cell<Actor, Actor, Storage> cell : storageTable.cellSet()) {
Token tok;
if (cell.getRowKey() instanceof TokenActor)
tok = ((TokenActor)cell.getRowKey()).token();
else if (cell.getColumnKey() instanceof TokenActor)
tok = ((TokenActor)cell.getColumnKey()).token();
else
tok = new Token(((WorkerActor)cell.getRowKey()).worker(),
((WorkerActor)cell.getColumnKey()).worker());
ImmutableList<Object> data = initialState.getData(tok);
if (data != null && !data.isEmpty()) {
initialStateDataMapBuilder.put(tok, data);
cell.getValue().initialData().add(Pair.make(data, MethodHandles.identity(int.class)));
}
}
}
this.initialStateDataMap = initialStateDataMapBuilder.build();
}
public Blob compile() {
findRemovals();
fuse();
schedule();
// identityRemoval();
splitterRemoval();
joinerRemoval();
inferTypes();
unbox();
generateArchetypalCode();
createInitCode();
createSteadyStateCode();
return instantiateBlob();
}
private void findRemovals() {
ImmutableSortedSet.Builder<WorkerActor> builder = ImmutableSortedSet.naturalOrder();
for (WorkerActor a : Iterables.filter(actors, WorkerActor.class)) {
SwitchParameter<Boolean> param = config.getParameter("remove"+a.id(), SwitchParameter.class, Boolean.class);
if (param != null && param.getValue()) {
assert REMOVABLE_WORKERS.contains(a.worker().getClass()) : a;
builder.add(a);
}
}
this.actorsToBeRemoved = builder.build();
}
/**
* Fuses actors into groups as directed by the configuration.
*/
private void fuse() {
List<ActorGroup> actorGroups = new ArrayList<>();
for (Actor a : actors)
actorGroups.add(ActorGroup.of(a));
//Fuse as much as possible.
just_fused: do {
try_fuse: for (Iterator<ActorGroup> it = actorGroups.iterator(); it.hasNext();) {
ActorGroup g = it.next();
if (g.isTokenGroup())
continue try_fuse;
for (ActorGroup pg : g.predecessorGroups())
if (pg.isTokenGroup())
continue try_fuse;
if (g.isPeeking() || g.predecessorGroups().size() > 1)
continue try_fuse;
for (Storage s : g.inputs())
if (!s.initialData().isEmpty())
continue try_fuse;
String paramName = String.format("fuse%d", g.id());
SwitchParameter<Boolean> fuseParam = config.getParameter(paramName, SwitchParameter.class, Boolean.class);
if (!fuseParam.getValue())
continue try_fuse;
ActorGroup gpred = Iterables.getOnlyElement(g.predecessorGroups());
ActorGroup fusedGroup = ActorGroup.fuse(g, gpred);
it.remove();
actorGroups.remove(gpred);
actorGroups.add(fusedGroup);
continue just_fused;
}
break;
} while (true);
this.groups = ImmutableSortedSet.copyOf(actorGroups);
}
/**
* Computes each group's internal schedule and the external schedule.
*/
private void schedule() {
for (ActorGroup g : groups)
internalSchedule(g);
externalSchedule();
initSchedule();
}
private void externalSchedule() {
Schedule.Builder<ActorGroup> scheduleBuilder = Schedule.builder();
scheduleBuilder.addAll(groups);
for (ActorGroup g : groups) {
for (Storage e : g.outputs()) {
Actor upstream = Iterables.getOnlyElement(e.upstream());
Actor downstream = Iterables.getOnlyElement(e.downstream());
ActorGroup other = downstream.group();
int upstreamAdjust = g.schedule().get(upstream);
int downstreamAdjust = other.schedule().get(downstream);
scheduleBuilder.connect(g, other)
.push(e.push() * upstreamAdjust)
.pop(e.pop() * downstreamAdjust)
.peek(e.peek() * downstreamAdjust)
.bufferExactly(0);
}
}
scheduleBuilder.multiply(config.getParameter("multiplier", IntParameter.class).getValue());
try {
externalSchedule = scheduleBuilder.build().getSchedule();
} catch (Schedule.ScheduleException ex) {
throw new StreamCompilationFailedException("couldn't find external schedule", ex);
}
}
/**
* Computes the internal schedule for the given group.
*/
private void internalSchedule(ActorGroup g) {
Schedule.Builder<Actor> scheduleBuilder = Schedule.builder();
scheduleBuilder.addAll(g.actors());
for (Storage s : g.internalEdges()) {
scheduleBuilder.connect(Iterables.getOnlyElement(s.upstream()), Iterables.getOnlyElement(s.downstream()))
.push(s.push())
.pop(s.pop())
.peek(s.peek())
.bufferExactly(0);
}
try {
Schedule<Actor> schedule = scheduleBuilder.build();
g.setSchedule(schedule.getSchedule());
} catch (Schedule.ScheduleException ex) {
throw new StreamCompilationFailedException("couldn't find internal schedule for group "+g.id(), ex);
}
}
private void initSchedule() {
Schedule.Builder<ActorGroup> scheduleBuilder = Schedule.builder();
scheduleBuilder.addAll(groups);
for (Storage s : storage) {
if (s.isInternal()) continue;
Actor upstream = Iterables.getOnlyElement(s.upstream()), downstream = Iterables.getOnlyElement(s.downstream());
int upstreamAdjust = upstream.group().schedule().get(upstream);
int downstreamAdjust = downstream.group().schedule().get(downstream);
int throughput, excessPeeks;
//TODO: avoid double-buffering token groups here?
if (actorsToBeRemoved.contains(downstream) && false)
throughput = excessPeeks = 0;
else {
throughput = s.push() * upstreamAdjust * externalSchedule.get(upstream.group());
excessPeeks = Math.max(s.peek() - s.pop(), 0);
}
int initialDataSize = Iterables.getOnlyElement(s.initialData(), new Pair<>(ImmutableList.<Object>of(), (MethodHandle)null)).first.size();
scheduleBuilder.connect(upstream.group(), downstream.group())
.push(s.push() * upstreamAdjust)
.pop(s.pop() * downstreamAdjust)
.peek(s.peek() * downstreamAdjust)
.bufferAtLeast(throughput + excessPeeks - initialDataSize);
}
try {
Schedule<ActorGroup> schedule = scheduleBuilder.build();
this.initSchedule = schedule.getSchedule();
} catch (Schedule.ScheduleException ex) {
throw new StreamCompilationFailedException("couldn't find init schedule", ex);
}
ImmutableMap.Builder<Token, Integer> postInitLivenessBuilder = ImmutableMap.builder();
for (Storage s : storage) {
if (s.isInternal()) continue;
Actor upstream = Iterables.getOnlyElement(s.upstream()), downstream = Iterables.getOnlyElement(s.downstream());
int upstreamExecutions = upstream.group().schedule().get(upstream) * initSchedule.get(upstream.group());
int downstreamExecutions = downstream.group().schedule().get(downstream) * initSchedule.get(downstream.group());
int liveItems = s.push() * upstreamExecutions - s.pop() * downstreamExecutions;
assert liveItems >= 0 : s;
int index = downstream.inputs().indexOf(s);
assert index != -1;
Token token;
if (downstream instanceof WorkerActor) {
Worker<?, ?> w = ((WorkerActor)downstream).worker();
token = downstream.id() == 0 ? Token.createOverallInputToken(w) :
new Token(Workers.getPredecessors(w).get(index), w);
} else
token = ((TokenActor)downstream).token();
for (int i = 0; i < liveItems; ++i)
downstream.inputSlots(index).add(StorageSlot.live(token, i));
postInitLivenessBuilder.put(token, liveItems);
}
this.postInitLiveness = postInitLivenessBuilder.build();
}
private void splitterRemoval() {
for (WorkerActor splitter : actorsToBeRemoved) {
if (!(splitter.worker() instanceof Splitter)) continue;
List<MethodHandle> transfers = splitterTransferFunctions(splitter);
Storage survivor = Iterables.getOnlyElement(splitter.inputs());
//Remove all instances of splitter, not just the first.
survivor.downstream().removeAll(ImmutableList.of(splitter));
MethodHandle Sin = Iterables.getOnlyElement(splitter.inputIndexFunctions());
List<StorageSlot> drainInfo = splitter.inputSlots(0);
for (int i = 0; i < splitter.outputs().size(); ++i) {
Storage victim = splitter.outputs().get(i);
MethodHandle t = transfers.get(i);
for (Actor a : victim.downstream()) {
List<Storage> inputs = a.inputs();
List<MethodHandle> inputIndices = a.inputIndexFunctions();
for (int j = 0; j < inputs.size(); ++j)
if (inputs.get(j).equals(victim)) {
inputs.set(j, survivor);
survivor.downstream().add(a);
inputIndices.set(j, MethodHandles.filterReturnValue(inputIndices.get(j), t));
for (int idx = 0, q = a.translateInputIndex(j, idx); q < drainInfo.size(); ++idx, q = a.translateInputIndex(j, idx)) {
a.inputSlots(j).add(drainInfo.get(q));
drainInfo.set(q, drainInfo.get(q).duplify());
}
inputIndices.set(j, MethodHandles.filterReturnValue(inputIndices.get(j), Sin));
}
}
//TODO: victim initial data
storage.remove(victim);
}
removeActor(splitter);
assert consistency();
}
}
/**
* Returns transfer functions for the given splitter.
*
* A splitter has one transfer function for each output that maps logical
* output indices to logical input indices (representing the splitter's
* distribution pattern).
* @param a an actor
* @return transfer functions, or null
*/
private List<MethodHandle> splitterTransferFunctions(WorkerActor a) {
assert REMOVABLE_WORKERS.contains(a.worker().getClass()) : a.worker().getClass();
if (a.worker() instanceof RoundrobinSplitter || a.worker() instanceof WeightedRoundrobinSplitter) {
int[] weights = new int[a.outputs().size()];
for (int i = 0; i < weights.length; ++i)
weights[i] = a.push(i);
return roundrobinTransferFunctions(weights);
} else if (a.worker() instanceof DuplicateSplitter) {
return Collections.nCopies(a.outputs().size(), MethodHandles.identity(int.class));
} else
throw new AssertionError();
}
private void joinerRemoval() {
for (WorkerActor joiner : actorsToBeRemoved) {
if (!(joiner.worker() instanceof Joiner)) continue;
List<MethodHandle> transfers = joinerTransferFunctions(joiner);
Storage survivor = Iterables.getOnlyElement(joiner.outputs());
//Remove all instances of joiner, not just the first.
survivor.upstream().removeAll(ImmutableList.of(joiner));
MethodHandle Jout = Iterables.getOnlyElement(joiner.outputIndexFunctions());
for (int i = 0; i < joiner.inputs().size(); ++i) {
Storage victim = joiner.inputs().get(i);
MethodHandle t = transfers.get(i);
MethodHandle t2 = MethodHandles.filterReturnValue(t, Jout);
for (Actor a : victim.upstream()) {
List<Storage> outputs = a.outputs();
List<MethodHandle> outputIndices = a.outputIndexFunctions();
for (int j = 0; j < outputs.size(); ++j)
if (outputs.get(j).equals(victim)) {
outputs.set(j, survivor);
outputIndices.set(j, MethodHandles.filterReturnValue(outputIndices.get(j), t2));
survivor.upstream().add(a);
}
}
//TODO: victim initial data
storage.remove(victim);
}
//Linearize drain info from the joiner's inputs.
int maxIdx = 0;
for (int i = 0; i < joiner.inputs().size(); ++i) {
MethodHandle t = transfers.get(i);
for (int idx = 0; idx < joiner.inputSlots(i).size(); ++idx)
try {
maxIdx = Math.max(maxIdx, (int)t.invokeExact(joiner.inputSlots(i).size()-1));
} catch (Throwable ex) {
throw new AssertionError("Can't happen! transfer function threw?", ex);
}
}
List<StorageSlot> linearizedInput = new ArrayList<>(Collections.nCopies(maxIdx+1, StorageSlot.hole()));
for (int i = 0; i < joiner.inputs().size(); ++i) {
MethodHandle t = transfers.get(i);
for (int idx = 0; idx < joiner.inputSlots(i).size(); ++idx)
try {
linearizedInput.set((int)t.invokeExact(idx), joiner.inputSlots(i).get(idx));
} catch (Throwable ex) {
throw new AssertionError("Can't happen! transfer function threw?", ex);
}
joiner.inputSlots(i).clear();
joiner.inputSlots(i).trimToSize();
}
if (!linearizedInput.isEmpty()) {
for (Actor a : survivor.downstream())
for (int j = 0; j < a.inputs().size(); ++j)
if (a.inputs().get(j).equals(survivor))
for (int idx = 0, q = a.translateInputIndex(j, idx); q < linearizedInput.size(); ++idx, q = a.translateInputIndex(j, idx)) {
StorageSlot slot = linearizedInput.get(q);
a.inputSlots(j).add(slot);
linearizedInput.set(q, slot.duplify());
}
}
// System.out.println("removed "+joiner);
removeActor(joiner);
assert consistency();
}
}
private List<MethodHandle> joinerTransferFunctions(WorkerActor a) {
assert REMOVABLE_WORKERS.contains(a.worker().getClass()) : a.worker().getClass();
if (a.worker() instanceof RoundrobinJoiner || a.worker() instanceof WeightedRoundrobinJoiner) {
int[] weights = new int[a.inputs().size()];
for (int i = 0; i < weights.length; ++i)
weights[i] = a.pop(i);
return roundrobinTransferFunctions(weights);
} else
throw new AssertionError();
}
private List<MethodHandle> roundrobinTransferFunctions(int[] weights) {
int[] weightPrefixSum = new int[weights.length + 1];
for (int i = 1; i < weightPrefixSum.length; ++i)
weightPrefixSum[i] = weightPrefixSum[i-1] + weights[i-1];
int N = weightPrefixSum[weightPrefixSum.length-1];
//t_x(i) = N(i/w[x]) + sum_0_x-1{w} + (i mod w[x])
//where the first two terms select a "window" and the third is the
//index into that window.
ImmutableList.Builder<MethodHandle> transfer = ImmutableList.builder();
for (int x = 0; x < weights.length; ++x)
transfer.add(MethodHandles.insertArguments(ROUNDROBIN_TRANSFER_FUNCTION, 0, weights[x], weightPrefixSum[x], N));
return transfer.build();
}
private final MethodHandle ROUNDROBIN_TRANSFER_FUNCTION = findStatic(LOOKUP, Compiler2.class, "_roundrobinTransferFunction", int.class, int.class, int.class, int.class, int.class);
//TODO: build this directly out of MethodHandles?
private static int _roundrobinTransferFunction(int weight, int prefixSum, int N, int i) {
//assumes nonnegative indices
return N*(i/weight) + prefixSum + (i % weight);
}
/**
* Removes an Actor from this compiler's data structures. The Actor should
* already have been unlinked from the graph (no incoming edges); this takes
* care of removing it from the actors set, its actor group (possibly
* removing the group if it's now empty), and the schedule.
* @param a the actor to remove
*/
private void removeActor(Actor a) {
assert actors.contains(a) : a;
actors.remove(a);
ActorGroup g = a.group();
g.remove(a);
if (g.actors().isEmpty()) {
groups = ImmutableSortedSet.copyOf(Sets.difference(groups, ImmutableSet.of(g)));
externalSchedule = ImmutableMap.copyOf(Maps.difference(externalSchedule, ImmutableMap.of(g, 0)).entriesOnlyOnLeft());
initSchedule = ImmutableMap.copyOf(Maps.difference(initSchedule, ImmutableMap.of(g, 0)).entriesOnlyOnLeft());
}
}
private boolean consistency() {
Set<Storage> usedStorage = new HashSet<>();
for (Actor a : actors) {
usedStorage.addAll(a.inputs());
usedStorage.addAll(a.outputs());
}
if (!storage.equals(usedStorage)) {
Set<Storage> unused = Sets.difference(storage, usedStorage);
Set<Storage> untracked = Sets.difference(usedStorage, storage);
throw new AssertionError(String.format("inconsistent storage:%n\tunused: %s%n\tuntracked:%s%n", unused, untracked));
}
return true;
}
//<editor-fold defaultstate="collapsed" desc="Unimplemented optimization stuff">
// /**
// * Removes Identity instances from the graph, unless doing so would make the
// * graph empty.
// */
// private void identityRemoval() {
// //TODO: remove from group, possibly removing the group if it becomes empty
// for (Iterator<Actor> iter = actors.iterator(); iter.hasNext();) {
// if (actors.size() == 1)
// break;
// Actor actor = iter.next();
// if (!actor.archetype().workerClass().equals(Identity.class))
// continue;
// iter.remove();
// assert actor.predecessors().size() == 1 && actor.successors().size() == 1;
// Object upstream = actor.predecessors().get(0), downstream = actor.successors().get(0);
// if (upstream instanceof Actor)
// replace(((Actor)upstream).successors(), actor, downstream);
// if (downstream instanceof Actor)
// replace(((Actor)downstream).predecessors(), actor, upstream);
// //No index function changes required for Identity actors.
// private static int replace(List<Object> list, Object target, Object replacement) {
// int replacements = 0;
// for (int i = 0; i < list.size(); ++i)
// if (Objects.equals(list.get(0), target)) {
// list.set(i, replacement);
// ++replacements;
// return replacements;
//</editor-fold>
/**
* Performs type inference to replace type variables with concrete types.
* For now, we only care about wrapper types.
*/
public void inferTypes() {
while (inferUpward() || inferDownward());
}
private boolean inferUpward() {
boolean changed = false;
//For each storage, if a reader's input type is a final type, all
//writers' output types must be that final type. (Wrappers are final,
//so this works for wrappers, and maybe detects errors related to other
//types.)
for (Storage s : storage) {
Set<TypeToken<?>> finalInputTypes = new HashSet<>();
for (Actor a : s.downstream())
if (Modifier.isFinal(a.inputType().getRawType().getModifiers()))
finalInputTypes.add(a.inputType());
if (finalInputTypes.isEmpty()) continue;
if (finalInputTypes.size() > 1)
throw new IllegalStreamGraphException("Type mismatch among readers: "+s.downstream());
TypeToken<?> inputType = finalInputTypes.iterator().next();
for (Actor a : s.upstream())
if (!a.outputType().equals(inputType)) {
TypeToken<?> oldOutputType = a.outputType();
TypeResolver resolver = new TypeResolver().where(oldOutputType.getType(), inputType.getType());
TypeToken<?> newOutputType = TypeToken.of(resolver.resolveType(oldOutputType.getType()));
if (!oldOutputType.equals(newOutputType)) {
a.setOutputType(newOutputType);
System.out.println("inferUpward: inferred "+a+" output type: "+oldOutputType+" -> "+newOutputType);
changed = true;
}
TypeToken<?> oldInputType = a.inputType();
TypeToken<?> newInputType = TypeToken.of(resolver.resolveType(oldInputType.getType()));
if (!oldInputType.equals(newInputType)) {
a.setInputType(newInputType);
System.out.println("inferUpward: inferred "+a+" input type: "+oldInputType+" -> "+newInputType);
changed = true;
}
}
}
return changed;
}
private boolean inferDownward() {
boolean changed = false;
//For each storage, find the most specific common type among all the
//writers' output types, then if it's final, unify with any variable or
//wildcard reader input type. (We only unify if final to avoid removing
//a type variable too soon. We could also refine concrete types like
//Object to a more specific subclass.)
for (Storage s : storage) {
Set<? extends TypeToken<?>> commonTypes = null;
for (Actor a : s.upstream())
if (commonTypes == null)
commonTypes = a.outputType().getTypes();
else
commonTypes = Sets.intersection(commonTypes, a.outputType().getTypes());
if (commonTypes.isEmpty())
throw new IllegalStreamGraphException("No common type among writers: "+s.upstream());
TypeToken<?> mostSpecificType = commonTypes.iterator().next();
if (!Modifier.isFinal(mostSpecificType.getRawType().getModifiers()))
continue;
for (Actor a : s.downstream()) {
TypeToken<?> oldInputType = a.inputType();
//TODO: this isn't quite right?
if (!ReflectionUtils.containsVariableOrWildcard(oldInputType.getType())) continue;
TypeResolver resolver = new TypeResolver().where(oldInputType.getType(), mostSpecificType.getType());
TypeToken<?> newInputType = TypeToken.of(resolver.resolveType(oldInputType.getType()));
if (!oldInputType.equals(newInputType)) {
a.setInputType(newInputType);
System.out.println("inferDownward: inferred "+a+" input type: "+oldInputType+" -> "+newInputType);
changed = true;
}
TypeToken<?> oldOutputType = a.outputType();
TypeToken<?> newOutputType = TypeToken.of(resolver.resolveType(oldOutputType.getType()));
if (!oldOutputType.equals(newOutputType)) {
a.setOutputType(newOutputType);
System.out.println("inferDownward: inferred "+a+" output type: "+oldOutputType+" -> "+newOutputType);
changed = true;
}
}
}
return changed;
}
/**
* Unboxes storage types and Actor input and output types.
*/
private void unbox() {
for (Storage s : storage) {
//TODO: make this tunable? Would require giving storage some ID.
TypeToken<?> contents = s.contentType();
if (!Primitives.isWrapperType(contents.getRawType())) continue;
Class<?> type = contents.unwrap().getRawType();
s.setType(type);
System.out.println("unboxed "+s+" to "+type);
}
for (WorkerActor a : Iterables.filter(actors, WorkerActor.class)) {
SwitchParameter<Boolean> unboxInput = config.getParameter("unboxInput"+a.id(), SwitchParameter.class, Boolean.class);
SwitchParameter<Boolean> unboxOutput = config.getParameter("unboxOutput"+a.id(), SwitchParameter.class, Boolean.class);
if (unboxInput.getValue()) {
TypeToken<?> oldType = a.inputType();
a.setInputType(oldType.unwrap());
if (!a.inputType().equals(oldType))
System.out.println("unboxed input of "+a+": "+oldType+" -> "+a.inputType());
}
if (unboxOutput.getValue()) {
TypeToken<?> oldType = a.outputType();
a.setOutputType(oldType.unwrap());
if (!a.outputType().equals(oldType))
System.out.println("unboxed output of "+a+": "+oldType+" -> "+a.outputType());
}
}
}
private void generateArchetypalCode() {
String packageName = "compiler"+PACKAGE_NUMBER.getAndIncrement();
ModuleClassLoader mcl = new ModuleClassLoader(module);
for (final ActorArchetype archetype : archetypes)
archetype.generateCode(packageName, mcl, FluentIterable.from(actors)
.filter(WorkerActor.class)
.filter(new Predicate<WorkerActor>() {
@Override
public boolean apply(WorkerActor input) {
return input.archetype().equals(archetype);
}
}));
}
private void createInitCode() {
ImmutableMap<Actor, ImmutableList<MethodHandle>> indexFxnBackup = adjustOutputIndexFunctions(new Function<Storage, Set<Integer>>() {
@Override
public Set<Integer> apply(Storage input) {
return input.indicesLiveBeforeInit();
}
});
this.initStorage = createExternalStorage(MapConcreteStorage.initFactory());
initReadInstructions.add(new InitDataReadInstruction(initStorage, initialStateDataMap));
/**
* During init, all (nontoken) groups are assigned to the same Core in
* topological order (via the ordering on ActorGroups). At the same
* time we build the token init schedule information required by the
* blob host.
*/
Core initCore = new Core(storage, initStorage, MapConcreteStorage.initFactory());
for (ActorGroup g : groups)
if (!g.isTokenGroup())
initCore.allocate(g, Range.closedOpen(0, initSchedule.get(g)));
else {
assert g.actors().size() == 1;
TokenActor ta = (TokenActor)g.actors().iterator().next();
assert g.schedule().get(ta) == 1;
ConcreteStorage storage = initStorage.get(Iterables.getOnlyElement(ta.isInput() ? g.outputs() : g.inputs()));
int executions = initSchedule.get(g);
if (ta.isInput())
initReadInstructions.add(new TokenReadInstruction(g, storage, executions));
else
initWriteInstructions.add(new TokenWriteInstruction(g, storage, executions));
}
this.initCode = initCore.code();
restoreOutputIndexFunctions(indexFxnBackup);
}
private void createSteadyStateCode() {
for (Actor a : actors) {
for (int i = 0; i < a.outputs().size(); ++i) {
Storage s = a.outputs().get(i);
if (s.isInternal()) continue;
int itemsWritten = a.push(i) * initSchedule.get(a.group()) * a.group().schedule().get(a);
a.outputIndexFunctions().set(i, MethodHandles.filterArguments(
a.outputIndexFunctions().get(i), 0, Combinators.add(MethodHandles.identity(int.class), itemsWritten)));
}
for (int i = 0; i < a.inputs().size(); ++i) {
Storage s = a.inputs().get(i);
if (s.isInternal()) continue;
int itemsRead = a.pop(i) * initSchedule.get(a.group()) * a.group().schedule().get(a);
a.inputIndexFunctions().set(i, MethodHandles.filterArguments(
a.inputIndexFunctions().get(i), 0, Combinators.add(MethodHandles.identity(int.class), itemsRead)));
}
}
for (Storage s : storage)
s.computeSteadyStateRequirements(externalSchedule);
this.steadyStateStorage = createExternalStorage(CircularArrayConcreteStorage.factory());
List<Core> ssCores = new ArrayList<>(maxNumCores);
for (int i = 0; i < maxNumCores; ++i)
ssCores.add(new Core(storage, steadyStateStorage, InternalArrayConcreteStorage.factory()));
for (ActorGroup g : groups)
if (!g.isTokenGroup())
allocateGroup(g, ssCores);
else {
assert g.actors().size() == 1;
TokenActor ta = (TokenActor)g.actors().iterator().next();
assert g.schedule().get(ta) == 1;
ConcreteStorage storage = steadyStateStorage.get(Iterables.getOnlyElement(ta.isInput() ? g.outputs() : g.inputs()));
int executions = externalSchedule.get(g);
if (ta.isInput())
readInstructions.add(new TokenReadInstruction(g, storage, executions));
else
writeInstructions.add(new TokenWriteInstruction(g, storage, executions));
}
ImmutableList.Builder<MethodHandle> steadyStateCodeBuilder = ImmutableList.builder();
for (Core c : ssCores)
if (!c.isEmpty())
steadyStateCodeBuilder.add(c.code());
this.steadyStateCode = steadyStateCodeBuilder.build();
/**
* Create migration instructions: Runnables that move live items from
* initialization to steady-state storage.
*/
for (Storage s : initStorage.keySet())
migrationInstructions.add(new MigrationInstruction(
s, initStorage.get(s), steadyStateStorage.get(s)));
createDrainInstructions();
}
/**
* Allocates executions of the given group to the given cores (i.e.,
* performs data-parallel fission).
* @param g the group to fiss
* @param cores the cores to fiss over, subject to the configuration
*/
private void allocateGroup(ActorGroup g, List<Core> cores) {
Range<Integer> toBeAllocated = Range.closedOpen(0, externalSchedule.get(g));
for (int core = 0; core < cores.size() && !toBeAllocated.isEmpty(); ++core) {
String name = String.format("node%dcore%diter", g.id(), core);
IntParameter parameter = config.getParameter(name, IntParameter.class);
if (parameter == null || parameter.getValue() == 0) continue;
//If the node is stateful, we must put all allocations on the
//same core. Arbitrarily pick the first core with an allocation.
//(If no cores have an allocation, we'll put them on core 0 below.)
int min = toBeAllocated.lowerEndpoint();
Range<Integer> allocation = g.isStateful() ? toBeAllocated :
toBeAllocated.intersection(Range.closedOpen(min, min + parameter.getValue()));
cores.get(core).allocate(g, allocation);
toBeAllocated = Range.closedOpen(allocation.upperEndpoint(), toBeAllocated.upperEndpoint());
}
//If we have iterations left over not assigned to a core,
//arbitrarily put them on core 0.
if (!toBeAllocated.isEmpty())
cores.get(0).allocate(g, toBeAllocated);
}
/**
* Create drain instructions, which collect live items from steady-state
* storage when draining.
*/
private void createDrainInstructions() {
Map<Token, List<Pair<ConcreteStorage, Integer>>> drainReads = new HashMap<>();
for (Map.Entry<Token, Integer> e : postInitLiveness.entrySet())
drainReads.put(e.getKey(), new ArrayList<>(Collections.nCopies(e.getValue(), (Pair<ConcreteStorage, Integer>)null)));
for (Actor a : actors) {
for (int input = 0; input < a.inputs().size(); ++input) {
ConcreteStorage storage = steadyStateStorage.get(a.inputs().get(input));
for (int index = 0; index < a.inputSlots(input).size(); ++index) {
StorageSlot info = a.inputSlots(input).get(index);
if (info.isDrainable()) {
Pair<ConcreteStorage, Integer> old = drainReads.get(info.token()).
set(info.index(), new Pair<>(storage, a.translateInputIndex(input, index)));
assert old == null : "overwriting "+info;
}
}
}
}
for (Map.Entry<Token, List<Pair<ConcreteStorage, Integer>>> e : drainReads.entrySet()) {
assert !e.getValue().contains(null) : "lost an element from "+e.getKey()+": "+e.getValue();
drainInstructions.add(new XDrainInstruction(e.getKey(), e.getValue()));
}
}
//<editor-fold defaultstate="collapsed" desc="Output index function adjust/restore">
/**
* Adjust output index functions to avoid overwriting items in external
* storage. For any actor writing to external storage, we find the
* first item that doesn't hit the live index set and add that many
* (making that logical item 0 for writers).
* @param liveIndexExtractor a function that computes the relevant live
* index set for the given external storage
* @return the old output index functions, to be restored later
*/
private ImmutableMap<Actor, ImmutableList<MethodHandle>> adjustOutputIndexFunctions(Function<Storage, Set<Integer>> liveIndexExtractor) {
ImmutableMap.Builder<Actor, ImmutableList<MethodHandle>> backup = ImmutableMap.builder();
for (Actor a : actors) {
backup.put(a, ImmutableList.copyOf(a.outputIndexFunctions()));
for (int i = 0; i < a.outputs().size(); ++i) {
Storage s = a.outputs().get(i);
if (s.isInternal())
continue;
Set<Integer> liveIndices = liveIndexExtractor.apply(s);
assert liveIndices != null : s +" "+liveIndexExtractor;
int offset = 0;
while (liveIndices.contains(a.translateOutputIndex(i, offset)))
++offset;
//Check future indices are also open (e.g., that we aren't
//alternating hole/not-hole).
for (int check = 0; check < 100; ++check)
assert !liveIndices.contains(a.translateOutputIndex(i, offset + check)) : check;
a.outputIndexFunctions().set(i, Combinators.add(a.outputIndexFunctions().get(i), offset));
}
}
return backup.build();
}
/**
* Restores output index functions from a backup returned from
* {@link #adjustOutputIndexFunctions(com.google.common.base.Function)}.
* @param backup the backup to restore
*/
private void restoreOutputIndexFunctions(ImmutableMap<Actor, ImmutableList<MethodHandle>> backup) {
for (Actor a : actors) {
ImmutableList<MethodHandle> oldFxns = backup.get(a);
assert oldFxns != null : "no backup for "+a;
assert oldFxns.size() == a.outputIndexFunctions().size() : "backup for "+a+" is wrong size";
Collections.copy(a.outputIndexFunctions(), oldFxns);
}
}
//</editor-fold>
private ImmutableMap<Storage, ConcreteStorage> createExternalStorage(StorageFactory factory) {
ImmutableMap.Builder<Storage, ConcreteStorage> builder = ImmutableMap.builder();
for (Storage s : storage)
if (!s.isInternal())
builder.put(s, factory.make(s));
return builder.build();
}
private static final class MigrationInstruction implements Runnable {
private final ConcreteStorage init, steady;
private final int[] indicesToMigrate;
private MigrationInstruction(Storage storage, ConcreteStorage init, ConcreteStorage steady) {
this.init = init;
this.steady = steady;
ImmutableSortedSet.Builder<Integer> builder = ImmutableSortedSet.naturalOrder();
for (Actor a : storage.downstream())
for (int i = 0; i < a.inputs().size(); ++i)
if (a.inputs().get(i).equals(storage))
for (int idx = 0; idx < a.inputSlots(i).size(); ++idx)
if (a.inputSlots(i).get(idx).isLive())
builder.add(a.translateInputIndex(i, idx));
this.indicesToMigrate = Ints.toArray(builder.build());
}
@Override
public void run() {
init.sync();
for (int i : indicesToMigrate)
steady.write(i, init.read(i));
steady.sync();
}
}
/**
* The X doesn't stand for anything. I just needed a different name.
*/
private static final class XDrainInstruction implements DrainInstruction {
private final Token token;
private final ConcreteStorage[] storage;
private final int[] storageSelector, index;
private XDrainInstruction(Token token, List<Pair<ConcreteStorage, Integer>> reads) {
this.token = token;
Set<ConcreteStorage> set = new HashSet<>();
for (Pair<ConcreteStorage, Integer> p : reads)
set.add(p.first);
this.storage = set.toArray(new ConcreteStorage[set.size()]);
this.storageSelector = new int[reads.size()];
this.index = new int[reads.size()];
for (int i = 0; i < reads.size(); ++i) {
storageSelector[i] = Arrays.asList(storage).indexOf(reads.get(i).first);
index[i] = reads.get(i).second;
}
}
@Override
public Map<Token, Object[]> call() {
Object[] data = new Object[index.length];
int idx = 0;
for (int i = 0; i < index.length; ++i)
data[idx++] = storage[storageSelector[i]].read(index[i]);
return ImmutableMap.of(token, data);
}
}
/**
* TODO: consider using read/write handles instead of read(), write()?
* TODO: if the index function is a contiguous range and the storage is
* backed by an array, allow the storage to readAll directly into its array
*/
private static final class TokenReadInstruction implements ReadInstruction {
private final Token token;
private final MethodHandle idxFxn;
private final ConcreteStorage storage;
private final int count;
private Buffer buffer;
private TokenReadInstruction(ActorGroup tokenGroup, ConcreteStorage storage, int executions) {
assert tokenGroup.isTokenGroup();
TokenActor actor = (TokenActor)Iterables.getOnlyElement(tokenGroup.actors());
assert actor.isInput();
this.token = actor.token();
this.idxFxn = Iterables.getOnlyElement(actor.outputIndexFunctions());
this.storage = storage;
this.count = executions;
}
@Override
public void init(Map<Token, Buffer> buffers) {
this.buffer = buffers.get(token);
if (buffer == null)
throw new IllegalArgumentException("no buffer for "+token);
}
@Override
public Map<Token, Integer> getMinimumBufferCapacity() {
return ImmutableMap.of(token, count);
}
@Override
public boolean load() {
Object[] data = new Object[count];
if (!buffer.readAll(data))
return false;
for (int i = 0; i < data.length; ++i) {
int idx;
try {
idx = (int)idxFxn.invokeExact(i);
} catch (Throwable ex) {
throw new AssertionError("Can't happen! Index functions should not throw", ex);
}
storage.write(idx, data[i]);
}
storage.sync();
return true;
}
@Override
public Map<Token, Object[]> unload() {
Object[] data = new Object[count];
for (int i = 0; i < data.length; ++i) {
int idx;
try {
idx = (int)idxFxn.invokeExact(i);
} catch (Throwable ex) {
throw new AssertionError("Can't happen! Index functions should not throw", ex);
}
data[i] = storage.read(idx);
}
return ImmutableMap.of(token, data);
}
}
/**
* TODO: consider using read handles instead of read()?
* TODO: if the index function is a contiguous range and the storage is
* backed by an array, allow the storage to writeAll directly from its array
*/
private static final class TokenWriteInstruction implements WriteInstruction {
private final Token token;
private final MethodHandle idxFxn;
private final ConcreteStorage storage;
private final int count;
private Buffer buffer;
private TokenWriteInstruction(ActorGroup tokenGroup, ConcreteStorage storage, int executions) {
assert tokenGroup.isTokenGroup();
TokenActor actor = (TokenActor)Iterables.getOnlyElement(tokenGroup.actors());
assert actor.isOutput();
this.token = actor.token();
this.idxFxn = Iterables.getOnlyElement(actor.inputIndexFunctions());
this.storage = storage;
this.count = executions;
}
@Override
public void init(Map<Token, Buffer> buffers) {
this.buffer = buffers.get(token);
if (buffer == null)
throw new IllegalArgumentException("no buffer for "+token);
}
@Override
public Map<Token, Integer> getMinimumBufferCapacity() {
return ImmutableMap.of(token, count);
}
@Override
public void run() {
Object[] data = new Object[count];
for (int i = 0; i < count; ++i) {
int idx;
try {
idx = (int)idxFxn.invokeExact(i);
} catch (Throwable ex) {
throw new AssertionError("Can't happen! Index functions should not throw", ex);
}
data[i] = storage.read(idx);
}
for (int written = 0; written != data.length;) {
written += buffer.write(data, written, data.length-written);
}
}
}
/**
* Writes initial data into init storage, or "unloads" it (just returning it
* as it was in the DrainData, not actually reading the storage) if we drain
* during init. (Any remaining data after init will be migrated as normal.)
* There's only one of these per blob because it returns all the data, and
* it should be the first initReadInstruction.
*/
private static final class InitDataReadInstruction implements ReadInstruction {
private final ImmutableMap<ConcreteStorage, ImmutableList<Pair<ImmutableList<Object>, MethodHandle>>> toWrite;
private final ImmutableMap<Token, ImmutableList<Object>> initialStateDataMap;
private InitDataReadInstruction(Map<Storage, ConcreteStorage> initStorage, ImmutableMap<Token, ImmutableList<Object>> initialStateDataMap) {
ImmutableMap.Builder<ConcreteStorage, ImmutableList<Pair<ImmutableList<Object>, MethodHandle>>> toWriteBuilder = ImmutableMap.builder();
for (Map.Entry<Storage, ConcreteStorage> e : initStorage.entrySet()) {
Storage s = e.getKey();
if (s.isInternal()) continue;
if (s.initialData().isEmpty()) continue;
toWriteBuilder.put(e.getValue(), ImmutableList.copyOf(s.initialData()));
}
this.toWrite = toWriteBuilder.build();
this.initialStateDataMap = initialStateDataMap;
}
@Override
public void init(Map<Token, Buffer> buffers) {
}
@Override
public Map<Token, Integer> getMinimumBufferCapacity() {
return ImmutableMap.of();
}
@Override
public boolean load() {
for (Map.Entry<ConcreteStorage, ImmutableList<Pair<ImmutableList<Object>, MethodHandle>>> e : toWrite.entrySet())
for (Pair<ImmutableList<Object>, MethodHandle> p : e.getValue())
for (int i = 0; i < p.first.size(); ++i) {
int idx;
try {
idx = (int)p.second.invokeExact(i);
} catch (Throwable ex) {
throw new AssertionError("Can't happen! Index functions should not throw", ex);
}
e.getKey().write(idx, p.first.get(i));
}
return true;
}
@Override
public Map<Token, Object[]> unload() {
Map<Token, Object[]> r = new HashMap<>();
for (Map.Entry<Token, ImmutableList<Object>> e : initialStateDataMap.entrySet())
r.put(e.getKey(), e.getValue().toArray());
return r;
}
}
/**
* Creates the blob host. This mostly involves shuffling our state into the
* form the blob host wants.
* @return the blob
*/
public Blob instantiateBlob() {
ImmutableSortedSet.Builder<Token> inputTokens = ImmutableSortedSet.naturalOrder(),
outputTokens = ImmutableSortedSet.naturalOrder();
ImmutableMap.Builder<Token, ConcreteStorage> tokenInitStorage = ImmutableMap.builder(),
tokenSteadyStateStorage = ImmutableMap.builder();
for (TokenActor ta : Iterables.filter(actors, TokenActor.class)) {
(ta.isInput() ? inputTokens : outputTokens).add(ta.token());
Storage s = ta.isInput() ? Iterables.getOnlyElement(ta.outputs()) : Iterables.getOnlyElement(ta.inputs());
tokenInitStorage.put(ta.token(), initStorage.get(s));
tokenSteadyStateStorage.put(ta.token(), steadyStateStorage.get(s));
}
ImmutableList.Builder<MethodHandle> storageAdjusts = ImmutableList.builder();
for (ConcreteStorage s : steadyStateStorage.values())
storageAdjusts.add(s.adjustHandle());
return new Compiler2BlobHost(workers, config,
inputTokens.build(), outputTokens.build(),
initCode, steadyStateCode,
storageAdjusts.build(),
initReadInstructions, initWriteInstructions, migrationInstructions,
readInstructions, writeInstructions, drainInstructions);
}
public static void main(String[] args) {
StreamCompiler sc = new Compiler2StreamCompiler().multiplier(8).maxNumCores(8);
// Benchmark bm = new PipelineSanity.Add15();
Benchmark bm = new FMRadio.FMRadioBenchmarkProvider().iterator().next();
// Benchmark bm = new SplitjoinComputeSanity.MultiplyBenchmark();
Benchmarker.runBenchmark(bm, sc).get(0).print(System.out);
}
// public static void main(String[] args) {
// Benchmarker.runBenchmark(new Reg20131116_104433_226(), new edu.mit.streamjit.impl.compiler2.Compiler2StreamCompiler()).get(0).print(System.out);
} |
package gov.nih.nci.calab.ui.core;
import gov.nih.nci.calab.dto.characterization.CharacterizationBean;
import gov.nih.nci.calab.dto.common.LabFileBean;
import gov.nih.nci.calab.dto.common.ProtocolBean;
import gov.nih.nci.calab.dto.common.UserBean;
import gov.nih.nci.calab.dto.function.FunctionBean;
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.remote.GridNodeBean;
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.search.GridSearchService;
import gov.nih.nci.calab.service.search.SearchNanoparticleService;
import gov.nih.nci.calab.service.search.SearchReportService;
import gov.nih.nci.calab.service.security.UserService;
import gov.nih.nci.calab.service.submit.SubmitNanoparticleService;
import gov.nih.nci.calab.service.util.CaNanoLabComparators;
import gov.nih.nci.calab.service.util.CaNanoLabConstants;
import gov.nih.nci.calab.service.util.StringUtils;
import gov.nih.nci.calab.service.workflow.ExecuteWorkflowService;
import gov.nih.nci.security.exceptions.CSException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedSet;
import java.util.Set;
import java.util.Iterator;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.struts.util.LabelValueBean;
/**
* 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(CaNanoLabConstants.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("allSampleSourcesWithUnmaskedAliquots") == 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 CaNanoLabComparators.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(ServletContext appContext) throws Exception {
if (appContext.getAttribute("allSampleTypes") == null) {
List sampleTypes = lookupService.getAllSampleTypes();
appContext.setAttribute("allSampleTypes", sampleTypes);
}
}
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.getAttribute("sampleContainerInfo") == null
|| session.getAttribute("newSampleCreated") != null) {
ContainerInfoBean containerInfo = lookupService
.getSampleContainerInfo();
session.setAttribute("sampleContainerInfo", containerInfo);
}
// clear the new sample created flag
session.removeAttribute("newSampleCreated");
}
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(),
CaNanoLabConstants.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);
}
session.removeAttribute("newAliquotCreated");
}
public void clearAliquotContainerTypesSession(HttpSession session) {
session.removeAttribute("allAliquotContainerTypes");
}
public void setAllAliquotContainerInfo(HttpSession session)
throws Exception {
if (session.getAttribute("aliquotContainerInfo") == null
|| session.getAttribute("newAliquotCreated") != null) {
ContainerInfoBean containerInfo = lookupService
.getAliquotContainerInfo();
session.setAttribute("aliquotContainerInfo", containerInfo);
// exclude Other in the lists for search aliquots drop-down
List<String> rooms = new ArrayList<String>(containerInfo
.getStorageRooms());
rooms.remove(CaNanoLabConstants.OTHER);
List<String> freezers = new ArrayList<String>(containerInfo
.getStorageFreezers());
freezers.remove(CaNanoLabConstants.OTHER);
List<String> shelves = new ArrayList<String>(containerInfo
.getStorageShelves());
shelves.remove(CaNanoLabConstants.OTHER);
List<String> boxes = new ArrayList<String>(containerInfo
.getStorageBoxes());
boxes.remove(CaNanoLabConstants.OTHER);
ContainerInfoBean containerInfoExcludeOther = new ContainerInfoBean(
containerInfo.getQuantityUnits(), containerInfo
.getConcentrationUnits(), containerInfo
.getVolumeUnits(), containerInfo.getStorageLabs(),
rooms, freezers, shelves, boxes);
session.setAttribute("aliquotContainerInfoExcludeOther",
containerInfoExcludeOther);
}
session.removeAttribute("newAliquotCreated");
}
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 CaNanoLabComparators.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;
}
public boolean canUserExecuteClass(HttpSession session, Class classObj)
throws CSException {
UserBean user = (UserBean) session.getAttribute("user");
// assume the part of the package name containing the function domain
// is the same as the protection element defined in CSM
String[] nameStrs = classObj.getName().split("\\.");
String domain = nameStrs[nameStrs.length - 2];
return userService.checkExecutePermission(user, domain);
}
public void setParticleTypeParticles(HttpSession session) throws Exception {
if (session.getAttribute("particleTypeParticles") == null
|| session.getAttribute("newSampleCreated") != null
|| session.getAttribute("newParticleCreated") != null) {
Map<String, SortedSet<String>> particleTypeParticles = lookupService
.getAllParticleTypeParticles();
List<String> particleTypes = new ArrayList<String>(
particleTypeParticles.keySet());
Collections.sort(particleTypes);
session.setAttribute("allParticleTypeParticles",
particleTypeParticles);
session.setAttribute("allParticleTypes", particleTypes);
}
session.removeAttribute("newParticleCreated");
}
public void setAllVisibilityGroups(HttpSession session) throws Exception {
if (session.getAttribute("allVisibilityGroups") == null
|| session.getAttribute("newSampleCreated") != null) {
List<String> groupNames = userService.getAllVisibilityGroups();
session.setAttribute("allVisibilityGroups", groupNames);
}
}
public void setAllDendrimerCores(HttpSession session) throws Exception {
if (session.getServletContext().getAttribute("allDendrimerCores") == null) {
String[] dendrimerCores = lookupService.getAllDendrimerCores();
session.getServletContext().setAttribute("allDendrimerCores",
dendrimerCores);
}
}
public void setAllDendrimerSurfaceGroupNames(HttpSession session)
throws Exception {
if (session.getServletContext().getAttribute(
"allDendrimerSurfaceGroupNames") == null
|| session.getAttribute("newCharacterizationCreated") != null) {
String[] surfaceGroupNames = lookupService
.getAllDendrimerSurfaceGroupNames();
session.getServletContext().setAttribute(
"allDendrimerSurfaceGroupNames", surfaceGroupNames);
}
}
public void setAllDendrimerBranches(HttpSession session) throws Exception {
if (session.getServletContext().getAttribute("allDendrimerBranches") == null
|| session.getAttribute("newCharacterizationCreated") != null) {
String[] branches = lookupService.getAllDendrimerBranches();
session.getServletContext().setAttribute("allDendrimerBranches",
branches);
}
}
public void setAllDendrimerGenerations(HttpSession session)
throws Exception {
if (session.getServletContext().getAttribute("allDendrimerGenerations") == null
|| session.getAttribute("newCharacterizationCreated") != null) {
String[] generations = lookupService.getAllDendrimerGenerations();
session.getServletContext().setAttribute("allDendrimerGenerations",
generations);
}
}
public void addSessionAttributeElement(HttpSession session,
String attributeName, String newElement) throws Exception {
String[] attributeValues = (String[]) session.getServletContext()
.getAttribute(attributeName);
if (!StringUtils.contains(attributeValues, newElement, true)) {
session.getServletContext().setAttribute(attributeName,
StringUtils.add(attributeValues, newElement));
}
}
public void setAllMetalCompositions(HttpSession session) throws Exception {
if (session.getServletContext().getAttribute("allMetalCompositions") == null) {
String[] compositions = lookupService.getAllMetalCompositions();
session.getServletContext().setAttribute("allMetalCompositions",
compositions);
}
}
public void setAllPolymerInitiators(HttpSession session) throws Exception {
if ((session.getServletContext().getAttribute("allPolymerInitiators") == null)
|| (session.getAttribute("newCharacterizationCreated") != null)) {
String[] initiators = lookupService.getAllPolymerInitiators();
session.getServletContext().setAttribute("allPolymerInitiators",
initiators);
}
}
public void setAllParticleFunctionTypes(HttpSession session)
throws Exception {
if (session.getServletContext()
.getAttribute("allParticleFunctionTypes") == null) {
Map<String, String> functions = lookupService
.getAllParticleFunctions();
session.getServletContext().setAttribute(
"allParticleFunctionTypes", functions);
}
}
public void setAllParticleSources(HttpSession session) throws Exception {
if (session.getServletContext().getAttribute("allParticleSources") == null) {
List<String> sources = lookupService.getAllParticleSources();
session.getServletContext().setAttribute("allParticleSources",
sources);
}
}
public void setAllParticleCharacterizationTypes(HttpSession session)
throws Exception {
if (session.getServletContext()
.getAttribute("allCharacterizationTypes") == null) {
String[] charTypes = lookupService.getAllCharacterizationTypes();
session.getServletContext().setAttribute(
"allCharacterizationTypes", charTypes);
}
}
public void setSideParticleMenu(HttpServletRequest request,
String particleName, String particleType) throws Exception {
HttpSession session = request.getSession();
SearchNanoparticleService service = new SearchNanoparticleService();
if (session.getAttribute("charTypeChars") == null
|| session.getAttribute("newCharacterizationCreated") != null
|| session.getAttribute("newParticleCreated") != null) {
List<CharacterizationBean> charBeans = service
.getCharacterizationInfo(particleName, particleType);
Map<String, List<CharacterizationBean>> existingCharTypeChars = new HashMap<String, List<CharacterizationBean>>();
if (!charBeans.isEmpty()) {
Map<String, String[]> charTypeChars = lookupService
.getCharacterizationTypeCharacterizations();
for (String charType : charTypeChars.keySet()) {
List<CharacterizationBean> newCharBeans = new ArrayList<CharacterizationBean>();
List<String> charList = Arrays.asList(charTypeChars
.get(charType));
for (CharacterizationBean charBean : charBeans) {
if (charList.contains(charBean.getName())) {
newCharBeans.add(charBean);
}
}
if (!newCharBeans.isEmpty()) {
existingCharTypeChars.put(charType, newCharBeans);
}
}
}
session.setAttribute("charTypeChars", existingCharTypeChars);
}
if (session.getAttribute("funcTypeFuncs") == null
|| session.getAttribute("newFunctionCreated") != null
|| session.getAttribute("newParticleCreated") != null) {
Map<String, List<FunctionBean>> funcTypeFuncs = service
.getFunctionInfo(particleName, particleType);
session.setAttribute("funcTypeFuncs", funcTypeFuncs);
}
UserBean user = (UserBean) session.getAttribute("user");
SearchReportService searchReportService=new SearchReportService();
if (session.getAttribute("particleReports") == null
|| session.getAttribute("newReportCreated") != null
|| session.getAttribute("newParticleCreated") != null) {
List<LabFileBean> reportBeans = searchReportService.getReportInfo(particleName,
particleType, CaNanoLabConstants.REPORT, user);
session.setAttribute("particleReports", reportBeans);
}
if (session.getAttribute("particleAssociatedFiles") == null
|| session.getAttribute("newReportCreated") != null
|| session.getAttribute("newParticleCreated") != null) {
List<LabFileBean> associatedBeans = searchReportService.getReportInfo(
particleName, particleType,
CaNanoLabConstants.ASSOCIATED_FILE, user);
session.setAttribute("particleAssociatedFiles", associatedBeans);
}
// not part of the side menu, but need to up
if (session.getAttribute("newParticleCreated") != null) {
setParticleTypeParticles(session);
}
session.removeAttribute("newCharacterizationCreated");
session.removeAttribute("newFunctionCreated");
session.removeAttribute("newParticleCreated");
session.removeAttribute("newReportCreated");
session.removeAttribute("detailPage");
setStaticDropdowns(session);
}
public void setRemoteSideParticleMenu(HttpServletRequest request,
String particleName, GridNodeBean gridNode) throws Exception {
HttpSession session = request.getSession();
GridSearchService service = new GridSearchService();
if (session.getAttribute("remoteCharTypeChars") == null
|| session.getAttribute("newCharacterizationCreated") != null
|| session.getAttribute("newRemoteParticleCreated") != null) {
Map<String, List<CharacterizationBean>> charTypeChars = service
.getRemoteCharacterizationMap(particleName, gridNode);
session.setAttribute("remoteCharTypeChars", charTypeChars);
}
if (session.getAttribute("remoteFuncTypeFuncs") == null
|| session.getAttribute("newFunctionCreated") != null
|| session.getAttribute("newRemoteParticleCreated") != null) {
Map<String, List<FunctionBean>> funcTypeFuncs = service
.getRemoteFunctionMap(particleName, gridNode);
session.setAttribute("remoteFuncTypeFuncs", funcTypeFuncs);
}
if (session.getAttribute("remoteParticleReports") == null
|| session.getAttribute("newReportCreated") != null
|| session.getAttribute("newRemoteParticleCreated") != null) {
List<LabFileBean> reportBeans = service.getRemoteReports(
particleName, gridNode);
session.setAttribute("remoteParticleReports", reportBeans);
}
if (session.getAttribute("remoteParticleAssociatedFiles") == null
|| session.getAttribute("newReportCreated") != null
|| session.getAttribute("newRemoteParticleCreated") != null) {
List<LabFileBean> associatedBeans = service
.getRemoteAssociatedFiles(particleName, gridNode);
session.setAttribute("remoteParticleAssociatedFiles", associatedBeans);
}
// not part of the side menu, but need to up
if (session.getAttribute("newRemoteParticleCreated") != null) {
setParticleTypeParticles(session);
}
session.removeAttribute("newCharacterizationCreated");
session.removeAttribute("newFunctionCreated");
session.removeAttribute("newRemoteParticleCreated");
session.removeAttribute("newReportCreated");
session.removeAttribute("detailPage");
setStaticDropdowns(session);
}
public void setCharacterizationTypeCharacterizations(HttpSession session)
throws Exception {
if (session.getServletContext().getAttribute(
"allCharacterizationTypeCharacterizations") == null) {
Map<String, String[]> charTypeChars = lookupService
.getCharacterizationTypeCharacterizations();
session.getServletContext().setAttribute(
"allCharacterizationTypeCharacterizations", charTypeChars);
}
}
public void setAllInstrumentTypes(HttpSession session) throws Exception {
if (session.getServletContext().getAttribute("allInstrumentTypes") == null) {
List<LabelValueBean> instrumentTypes = lookupService
.getAllInstrumentTypeAbbrs();
session.getServletContext().setAttribute("allInstrumentTypes",
instrumentTypes);
}
}
public void setAllInstrumentTypeManufacturers(HttpSession session)
throws Exception {
if (session.getServletContext().getAttribute(
"allInstrumentTypeManufacturers") == null) {
Map<String, SortedSet<String>> instrumentManufacturers = lookupService
.getAllInstrumentManufacturers();
session.getServletContext().setAttribute(
"allInstrumentTypeManufacturers", instrumentManufacturers);
}
}
public void setAllSizeDistributionGraphTypes(HttpSession session)
throws Exception {
if (session.getServletContext().getAttribute(
"allSizeDistributionGraphTypes") == null) {
String[] graphTypes = lookupService.getSizeDistributionGraphTypes();
session.getServletContext().setAttribute(
"allSizeDistributionGraphTypes", graphTypes);
}
}
public void setAllMolecularWeightDistributionGraphTypes(HttpSession session)
throws Exception {
if (session.getServletContext().getAttribute(
"allMolecularWeightDistributionGraphTypes") == null) {
String[] graphTypes = lookupService
.getMolecularWeightDistributionGraphTypes();
session.getServletContext().setAttribute(
"allMolecularWeightDistributionGraphTypes", graphTypes);
}
}
public void setAllMorphologyDistributionGraphTypes(HttpSession session)
throws Exception {
if (session.getServletContext().getAttribute(
"allMorphologyDistributionGraphTypes") == null) {
String[] graphTypes = lookupService
.getMorphologyDistributionGraphTypes();
session.getServletContext().setAttribute(
"allMorphologyDistributionGraphTypes", graphTypes);
}
}
public void setAllShapeDistributionGraphTypes(HttpSession session)
throws Exception {
if (session.getServletContext().getAttribute(
"allShapeDistributionGraphTypes") == null) {
String[] graphTypes = lookupService
.getShapeDistributionGraphTypes();
session.getServletContext().setAttribute(
"allShapeDistributionGraphTypes", graphTypes);
}
}
public void setAllStabilityDistributionGraphTypes(HttpSession session)
throws Exception {
if (session.getServletContext().getAttribute(
"allStabilityDistributionGraphTypes") == null) {
String[] graphTypes = lookupService
.getStabilityDistributionGraphTypes();
session.getServletContext().setAttribute(
"allStabilityDistributionGraphTypes", graphTypes);
}
}
public void setAllPurityDistributionGraphTypes(HttpSession session)
throws Exception {
if (session.getServletContext().getAttribute(
"allPurityDistributionGraphTypes") == null) {
String[] graphTypes = lookupService
.getPurityDistributionGraphTypes();
session.getServletContext().setAttribute(
"allPurityDistributionGraphTypes", graphTypes);
}
}
public void setAllSolubilityDistributionGraphTypes(HttpSession session)
throws Exception {
if (session.getServletContext().getAttribute(
"allSolubilityDistributionGraphTypes") == null) {
String[] graphTypes = lookupService
.getSolubilityDistributionGraphTypes();
session.getServletContext().setAttribute(
"allSolubilityDistributionGraphTypes", graphTypes);
}
}
public void setAllMorphologyTypes(HttpSession session) throws Exception {
if (session.getServletContext().getAttribute("allMorphologyTypes") == null) {
String[] morphologyTypes = lookupService.getAllMorphologyTypes();
session.getServletContext().setAttribute("allMorphologyTypes",
morphologyTypes);
}
}
public void setAllShapeTypes(HttpSession session) throws Exception {
if (session.getServletContext().getAttribute("allShapeTypes") == null) {
String[] shapeTypes = lookupService.getAllShapeTypes();
session.getServletContext().setAttribute("allShapeTypes",
shapeTypes);
}
}
public void setAllStressorTypes(HttpSession session) throws Exception {
if (session.getServletContext().getAttribute("allStessorTypes") == null) {
String[] stressorTypes = lookupService.getAllStressorTypes();
session.getServletContext().setAttribute("allStressorTypes",
stressorTypes);
}
}
public void setStaticDropdowns(HttpSession session) {
// set static boolean yes or no and characterization source choices
session.setAttribute("booleanChoices",
CaNanoLabConstants.BOOLEAN_CHOICES);
session.setAttribute("characterizationSources",
CaNanoLabConstants.CHARACTERIZATION_SOURCES);
session.setAttribute("allCarbonNanotubeWallTypes",
CaNanoLabConstants.CARBON_NANOTUBE_WALLTYPES);
if (session.getAttribute("allReportTypes") == null) {
String[] allReportTypes = lookupService.getAllReportTypes();
session.setAttribute("allReportTypes", allReportTypes);
}
session.setAttribute("allFunctionLinkageTypes",
CaNanoLabConstants.FUNCTION_LINKAGE_TYPES);
session.setAttribute("allFunctionAgentTypes",
CaNanoLabConstants.FUNCTION_AGENT_TYPES);
}
public void setProtocolSubmitPage(HttpSession session) throws Exception {
// set protocol types, and protocol names for all these types
List<String> protocolTypes = lookupService.getAllProtocolTypes();
for (int i = 0; i < CaNanoLabConstants.PROTOCOL_TYPES.length; i++){
if (!protocolTypes.contains(CaNanoLabConstants.PROTOCOL_TYPES[i]))
protocolTypes.add(CaNanoLabConstants.PROTOCOL_TYPES[i]);
}
session.setAttribute("protocolTypes", protocolTypes);
Map<String, List<String>> nameTypes = lookupService.getAllProtocolNameTypes();
for (String type : protocolTypes){
List<String> localList = nameTypes.get(type);
if (localList == null){
localList = new ArrayList<String>();
nameTypes.put(type, localList);
}
}
session.setAttribute("AllProtocolNameTypes", nameTypes);
session.setAttribute("protocolNames", new ArrayList<String>());
}
public void setAllProtocolNameVersionsByType(HttpSession session, String type) throws Exception {
// set protocol name and its versions for a given protocol type.
Map<ProtocolBean, List<String>> nameVersions = lookupService.getAllProtocolNameVersionByType(type);
Map<String, List<String>> tempMap = new HashMap<String, List<String>>();
Set keySet = nameVersions.keySet();
for (Iterator it = keySet.iterator(); it.hasNext();){
ProtocolBean pb = (ProtocolBean)it.next();
tempMap.put(pb.getId().toString(), nameVersions.get(pb));
}
session.setAttribute("AllProtocolNameVersionsByType", tempMap);
session.setAttribute("AllProtocolNameByType", new ArrayList<ProtocolBean>(nameVersions
.keySet()));
}
public void setAllProtocolNameVersion(HttpSession session) throws Exception {
// set protocol name and its versions for all protocol types.
Map<ProtocolBean, List<String>> nameVersions = lookupService.getAllProtocolNameVersion();
session.setAttribute("AllProtocolNameVersions", nameVersions);
}
public void setAllProtocolNamesWithVersion(HttpSession session) throws Exception {
// set protocol name and its versions for all protocol types.
Map<String, List<String>> nameVersions = lookupService.getAllProtocolNamesWithVersions();
session.setAttribute("AllProtocolNamesWithVersions", nameVersions);
}
public void setAllRunFiles(HttpSession session, String particleName)
throws Exception {
if (session.getAttribute("allRunFiles") == null
|| session.getAttribute("newParticleCreated") != null
|| session.getAttribute("newFileLoaded") != null) {
SubmitNanoparticleService service = new SubmitNanoparticleService();
List<LabFileBean> runFileBeans = service
.getAllRunFiles(particleName);
session.setAttribute("allRunFiles", runFileBeans);
}
session.removeAttribute("newParticleCreated");
session.removeAttribute("newFileLoaded");
}
public void setAllAreaMeasureUnits(HttpSession session) throws Exception {
if (session.getServletContext().getAttribute("allAreaMeasureUnits") == null) {
String[] areaUnits = lookupService.getAllAreaMeasureUnits();
session.getServletContext().setAttribute("allAreaMeasureUnits",
areaUnits);
}
}
public void setAllChargeMeasureUnits(HttpSession session) throws Exception {
if (session.getServletContext().getAttribute("allChargeMeasureUnits") == null) {
String[] chargeUnits = lookupService.getAllChargeMeasureUnits();
session.getServletContext().setAttribute("allChargeMeasureUnits",
chargeUnits);
}
}
public void setAllControlTypes(HttpSession session) throws Exception {
if (session.getServletContext().getAttribute("allControlTypes") == null) {
String[] controlTypes = lookupService.getAllControlTypes();
session.getServletContext().setAttribute("allControlTypes",
controlTypes);
}
}
public void setAllConditionTypes(HttpSession session) throws Exception {
if (session.getServletContext().getAttribute("allConditionTypes") == null) {
String[] conditionTypes = lookupService.getAllConditionTypes();
session.getServletContext().setAttribute("allConditionTypes",
conditionTypes);
}
}
public void setAllConditionUnits(HttpSession session) throws Exception {
if (session.getServletContext().getAttribute("allConditionTypeUnits") == null) {
Map<String, String[]> conditionTypeUnits = lookupService
.getAllConditionUnits();
session.getServletContext().setAttribute("allConditionTypeUnits",
conditionTypeUnits);
}
}
public void setAllAgentTypes(HttpSession session) throws Exception {
if (session.getServletContext().getAttribute("allAgentTypes") == null) {
Map<String, String[]> agentTypes = lookupService.getAllAgentTypes();
session.getServletContext().setAttribute("allAgentTypes",
agentTypes);
}
}
public void setAllAgentTargetTypes(HttpSession session) throws Exception {
if (session.getServletContext().getAttribute("allAgentTargetTypes") == null) {
Map<String, String[]> agentTargetTypes = lookupService
.getAllAgentTargetTypes();
session.getServletContext().setAttribute("allAgentTargetTypes",
agentTargetTypes);
}
}
public void setAllTimeUnits(HttpSession session) throws Exception {
if (session.getServletContext().getAttribute("allTimeUnits") == null) {
String[] timeUnits = lookupService.getAllTimeUnits();
session.getServletContext().setAttribute("allTimeUnits", timeUnits);
}
}
public void setAllConcentrationUnits(HttpSession session) throws Exception {
if (session.getServletContext().getAttribute("allConcentrationUnits") == null) {
String[] concentrationUnits = lookupService
.getAllConcentrationUnits();
session.getServletContext().setAttribute("allConcentrationUnits",
concentrationUnits);
}
}
public void setAllCellLines(HttpSession session) throws Exception {
if (session.getServletContext().getAttribute("allCellLines") == null) {
String[] cellLines = lookupService.getAllCellLines();
session.getServletContext().setAttribute("allCellLines", cellLines);
}
}
public void setAllActivationMethods(HttpSession session) throws Exception {
if (session.getServletContext().getAttribute("allActivationMethods") == null) {
String[] activationMethods = lookupService
.getAllActivationMethods();
session.getServletContext().setAttribute("allActivationMethods",
activationMethods);
}
}
public void setAllSpecies(HttpSession session) throws Exception {
if (session.getServletContext().getAttribute("allSpecies") == null) {
List<LabelValueBean> species = lookupService.getAllSpecies();
session.getServletContext().setAttribute("allSpecies", species);
}
}
public void setApplicationOwner(HttpSession session) {
if (session.getServletContext().getAttribute("applicationOwner") == null) {
session.getServletContext().setAttribute("applicationOwner",
CaNanoLabConstants.APP_OWNER);
}
}
// public void addCellLine(HttpSession session, String option) throws
// Exception {
// String[] cellLines = (String[])
// session.getServletContext().getAttribute("allCellLines");
// if (!StringHelper.contains(cellLines, option, true)) {
// session.getServletContext().setAttribute("allCellLines",
// StringHelper.add(cellLines, option));
/**
* Create default CSM groups for default visible groups and admin
*
*/
public void createDefaultCSMGroups() throws Exception {
for (String groupName : CaNanoLabConstants.VISIBLE_GROUPS) {
userService.createAGroup(groupName);
}
userService.createAGroup(CaNanoLabConstants.CSM_ADMIN);
}
} |
package gov.nih.nci.calab.ui.core;
import gov.nih.nci.calab.dto.characterization.CharacterizationBean;
import gov.nih.nci.calab.dto.characterization.CharacterizationTypeBean;
import gov.nih.nci.calab.dto.common.InstrumentBean;
import gov.nih.nci.calab.dto.common.LabFileBean;
import gov.nih.nci.calab.dto.common.ProtocolBean;
import gov.nih.nci.calab.dto.common.ProtocolFileBean;
import gov.nih.nci.calab.dto.common.UserBean;
import gov.nih.nci.calab.dto.function.FunctionBean;
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.remote.GridNodeBean;
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.search.GridSearchService;
import gov.nih.nci.calab.service.search.SearchNanoparticleService;
import gov.nih.nci.calab.service.search.SearchReportService;
import gov.nih.nci.calab.service.security.UserService;
import gov.nih.nci.calab.service.submit.SubmitNanoparticleService;
import gov.nih.nci.calab.service.util.CaNanoLabComparators;
import gov.nih.nci.calab.service.util.CaNanoLabConstants;
import gov.nih.nci.calab.service.util.StringUtils;
import gov.nih.nci.calab.service.workflow.ExecuteWorkflowService;
import gov.nih.nci.security.exceptions.CSException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.struts.util.LabelValueBean;
/**
* 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(CaNanoLabConstants.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("allSampleSourcesWithUnmaskedAliquots") == 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 CaNanoLabComparators.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("newSampleSourceCreated") != null) {
SortedSet<String> sampleSources = lookupService
.getAllSampleSources();
session.setAttribute("allSampleSources", sampleSources);
}
// clear the new sample created flag
session.removeAttribute("newSampleSourceCreated");
}
public void clearSampleSourcesSession(HttpSession session) {
session.removeAttribute("allSampleSources");
}
public void setAllSampleContainerTypes(HttpSession session)
throws Exception {
if (session.getAttribute("allSampleContainerTypes") == null
|| session.getAttribute("newSampleCreated") != null) {
SortedSet<String> 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(ServletContext appContext) throws Exception {
if (appContext.getAttribute("allSampleTypes") == null) {
List sampleTypes = lookupService.getAllSampleTypes();
appContext.setAttribute("allSampleTypes", sampleTypes);
}
}
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.getAttribute("sampleContainerInfo") == null
|| session.getAttribute("newSampleCreated") != null) {
ContainerInfoBean containerInfo = lookupService
.getSampleContainerInfo();
session.setAttribute("sampleContainerInfo", containerInfo);
}
// clear the new sample created flag
session.removeAttribute("newSampleCreated");
}
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(),
CaNanoLabConstants.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) {
SortedSet<String> containerTypes = lookupService
.getAllAliquotContainerTypes();
session.setAttribute("allAliquotContainerTypes", containerTypes);
}
session.removeAttribute("newAliquotCreated");
}
public void clearAliquotContainerTypesSession(HttpSession session) {
session.removeAttribute("allAliquotContainerTypes");
}
public void setAllAliquotContainerInfo(HttpSession session)
throws Exception {
if (session.getAttribute("aliquotContainerInfo") == null
|| session.getAttribute("newAliquotCreated") != null) {
ContainerInfoBean containerInfo = lookupService
.getAliquotContainerInfo();
session.setAttribute("aliquotContainerInfo", containerInfo);
}
session.removeAttribute("newAliquotCreated");
}
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 CaNanoLabComparators.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;
}
public boolean canUserExecuteClass(HttpSession session, Class classObj)
throws CSException {
UserBean user = (UserBean) session.getAttribute("user");
// assume the part of the package name containing the function domain
// is the same as the protection element defined in CSM
String[] nameStrs = classObj.getName().split("\\.");
String domain = nameStrs[nameStrs.length - 2];
return userService.checkExecutePermission(user, domain);
}
public void setParticleTypeParticles(HttpSession session) throws Exception {
if (session.getAttribute("particleTypeParticles") == null
|| session.getAttribute("newSampleCreated") != null
|| session.getAttribute("newParticleCreated") != null) {
Map<String, SortedSet<String>> particleTypeParticles = lookupService
.getAllParticleTypeParticles();
List<String> particleTypes = new ArrayList<String>(
particleTypeParticles.keySet());
Collections.sort(particleTypes);
session.setAttribute("allParticleTypeParticles",
particleTypeParticles);
session.setAttribute("allParticleTypes", particleTypes);
}
session.removeAttribute("newParticleCreated");
}
public void setAllVisibilityGroups(HttpSession session) throws Exception {
if (session.getAttribute("allVisibilityGroups") == null
|| session.getAttribute("newSampleCreated") != null) {
List<String> groupNames = userService.getAllVisibilityGroups();
session.setAttribute("allVisibilityGroups", groupNames);
}
session.removeAttribute("newSampleCreated");
}
public void setAllDendrimers(HttpSession session) throws Exception {
if ((session.getAttribute("allDendrimerCores") == null)
|| session.getAttribute("newDendrimerCreated") != null) {
SortedSet<String> dendrimerCores = lookupService
.getAllDendrimerCores();
session.setAttribute("allDendrimerCores", dendrimerCores);
}
if (session.getAttribute("allDendrimerSurfaceGroupNames") == null
|| session.getAttribute("newDendrimerCreated") != null) {
SortedSet<String> surfaceGroupNames = lookupService
.getAllDendrimerSurfaceGroupNames();
session.setAttribute("allDendrimerSurfaceGroupNames",
surfaceGroupNames);
}
if (session.getAttribute("allDendrimerBranches") == null
|| session.getAttribute("newDendrimerCreated") != null) {
SortedSet<String> branches = lookupService
.getAllDendrimerBranches();
session.setAttribute("allDendrimerBranches", branches);
}
if (session.getAttribute("allDendrimerGenerations") == null
|| session.getAttribute("newDendrimerCreated") != null) {
SortedSet<String> generations = lookupService
.getAllDendrimerGenerations();
session.setAttribute("allDendrimerGenerations", generations);
}
session.removeAttribute("newDendrimerCreated");
}
public void setAllMetalCompositions(HttpSession session) throws Exception {
if (session.getServletContext().getAttribute("allMetalCompositions") == null) {
String[] compositions = lookupService.getAllMetalCompositions();
session.getServletContext().setAttribute("allMetalCompositions",
compositions);
}
}
public void setAllPolymerInitiators(HttpSession session) throws Exception {
if ((session.getAttribute("allPolymerInitiators") == null)
|| (session.getAttribute("newPolymerCreated") != null)) {
SortedSet<String> initiators = lookupService
.getAllPolymerInitiators();
session.setAttribute("allPolymerInitiators", initiators);
}
session.removeAttribute("newPolymerCreated");
}
public void setAllParticleSources(HttpSession session) throws Exception {
if (session.getAttribute("allParticleSources") == null
|| session.getAttribute("newSampleCreated") != null) {
SortedSet<String> particleSources = lookupService
.getAllParticleSources();
session.setAttribute("allParticleSources", particleSources);
}
// clear the new sample created flag
session.removeAttribute("newSampleCreated");
}
public void setAllReports(HttpSession session, String particleName,
String particleType) throws Exception {
UserBean user = (UserBean) session.getAttribute("user");
SearchReportService searchReportService = new SearchReportService();
if (session.getAttribute("particleReports") == null
|| session.getAttribute("newReportCreated") != null
|| session.getAttribute("newParticleCreated") != null) {
List<LabFileBean> reportBeans = searchReportService
.getReportInfo(particleName, particleType,
CaNanoLabConstants.REPORT, user);
session.setAttribute("particleReports", reportBeans);
}
if (session.getAttribute("particleAssociatedFiles") == null
|| session.getAttribute("newReportCreated") != null
|| session.getAttribute("newParticleCreated") != null) {
List<LabFileBean> associatedBeans = searchReportService
.getReportInfo(particleName, particleType,
CaNanoLabConstants.ASSOCIATED_FILE, user);
session.setAttribute("particleAssociatedFiles", associatedBeans);
}
}
public void setSideParticleMenu(HttpServletRequest request,
String particleName, String particleType) throws Exception {
HttpSession session = request.getSession();
setAllReports(session, particleName, particleType);
// not part of the side menu, but need to up
// if (session.getAttribute("newParticleCreated") != null) {
// setParticleTypeParticles(session);
setStaticDropdowns(session);
setAllFunctionTypes(session);
setFunctionTypeFunctions(session, particleName, particleType);
setAllCharacterizations(session, particleName, particleType);
session.removeAttribute("newParticleCreated");
session.removeAttribute("newCharacterizationCreated");
session.removeAttribute("newReportCreated");
session.removeAttribute("newFunctionCreated");
session.removeAttribute("detailPage");
}
/**
* Set characterizations stored in the database
*
* @param session
* @param particleName
* @param particleType
* @throws Exception
*/
public void setAllCharacterizations(HttpSession session,
String particleName, String particleType) throws Exception {
setAllCharacterizationTypes(session);
Map<String, List<String>> charTypeChars = (Map<String, List<String>>) session
.getServletContext().getAttribute("allCharTypeChars");
if (session.getAttribute("allCharacterizations") == null
|| session.getAttribute("newCharacterizationCreated") != null
|| session.getAttribute("newParticleCreated") != null) {
SearchNanoparticleService service = new SearchNanoparticleService();
List<CharacterizationBean> charBeans = service
.getCharacterizationInfo(particleName, particleType);
Map<String, List<CharacterizationBean>> charMap = new HashMap<String, List<CharacterizationBean>>();
for (String charType : charTypeChars.keySet()) {
List<CharacterizationBean> newCharBeans = new ArrayList<CharacterizationBean>();
List<String> charList = (List<String>) charTypeChars
.get(charType);
for (CharacterizationBean charBean : charBeans) {
if (charList.contains(charBean.getName())) {
newCharBeans.add(charBean);
}
}
if (!newCharBeans.isEmpty()) {
charMap.put(charType, newCharBeans);
}
}
session.setAttribute("allCharacterizations", charMap);
}
}
public void setFunctionTypeFunctions(HttpSession session,
String particleName, String particleType) throws Exception {
if (session.getAttribute("allFuncTypeFuncs") == null
|| session.getAttribute("newFunctionCreated") != null) {
SearchNanoparticleService service = new SearchNanoparticleService();
Map<String, List<FunctionBean>> funcTypeFuncs = service
.getFunctionInfo(particleName, particleType);
session.setAttribute("allFuncTypeFuncs", funcTypeFuncs);
}
}
public void setRemoteSideParticleMenu(HttpServletRequest request,
String particleName, GridNodeBean gridNode) throws Exception {
HttpSession session = request.getSession();
GridSearchService service = new GridSearchService();
if (session.getAttribute("remoteCharTypeChars") == null
|| session.getAttribute("newCharacterizationCreated") != null
|| session.getAttribute("newRemoteParticleCreated") != null) {
Map<String, List<CharacterizationBean>> charTypeChars = service
.getRemoteCharacterizationMap(particleName, gridNode);
session.setAttribute("remoteCharTypeChars", charTypeChars);
}
if (session.getAttribute("remoteFuncTypeFuncs") == null
|| session.getAttribute("newFunctionCreated") != null
|| session.getAttribute("newRemoteParticleCreated") != null) {
Map<String, List<FunctionBean>> funcTypeFuncs = service
.getRemoteFunctionMap(particleName, gridNode);
session.setAttribute("remoteFuncTypeFuncs", funcTypeFuncs);
}
if (session.getAttribute("remoteParticleReports") == null
|| session.getAttribute("newReportCreated") != null
|| session.getAttribute("newRemoteParticleCreated") != null) {
List<LabFileBean> reportBeans = service.getRemoteReports(
particleName, gridNode);
session.setAttribute("remoteParticleReports", reportBeans);
}
if (session.getAttribute("remoteParticleAssociatedFiles") == null
|| session.getAttribute("newReportCreated") != null
|| session.getAttribute("newRemoteParticleCreated") != null) {
List<LabFileBean> associatedBeans = service
.getRemoteAssociatedFiles(particleName, gridNode);
session.setAttribute("remoteParticleAssociatedFiles",
associatedBeans);
}
// not part of the side menu, but need to up
if (session.getAttribute("newRemoteParticleCreated") != null) {
setParticleTypeParticles(session);
}
session.removeAttribute("newCharacterizationCreated");
session.removeAttribute("newFunctionCreated");
session.removeAttribute("newRemoteParticleCreated");
session.removeAttribute("newReportCreated");
session.removeAttribute("detailPage");
setStaticDropdowns(session);
}
public void setAllMorphologyTypes(HttpSession session) throws Exception {
if (session.getAttribute("allMorphologyTypes") == null
|| session.getAttribute("newMorphologyCreated") != null) {
SortedSet<String> morphologyTypes = lookupService
.getAllMorphologyTypes();
session.setAttribute("allMorphologyTypes", morphologyTypes);
}
session.removeAttribute("newMorphologyCreated");
}
public void setAllShapeTypes(HttpSession session) throws Exception {
if (session.getAttribute("allShapeTypes") == null
|| session.getAttribute("newShapeCreated") != null) {
SortedSet<String> shapeTypes = lookupService.getAllShapeTypes();
session.setAttribute("allShapeTypes", shapeTypes);
}
session.removeAttribute("newShapeCreated");
}
public void setStaticDropdowns(HttpSession session) {
// set static boolean yes or no and characterization source choices
session.setAttribute("booleanChoices",
CaNanoLabConstants.BOOLEAN_CHOICES);
session.setAttribute("allCarbonNanotubeWallTypes",
CaNanoLabConstants.CARBON_NANOTUBE_WALLTYPES);
if (session.getAttribute("allReportTypes") == null) {
String[] allReportTypes = lookupService.getAllReportTypes();
session.setAttribute("allReportTypes", allReportTypes);
}
session.setAttribute("allFunctionLinkageTypes",
CaNanoLabConstants.FUNCTION_LINKAGE_TYPES);
session.setAttribute("allFunctionAgentTypes",
CaNanoLabConstants.FUNCTION_AGENT_TYPES);
}
public void setProtocolType(HttpSession session) throws Exception {
// set protocol types, and protocol names for all these types
SortedSet<String> protocolTypes = lookupService.getAllProtocolTypes();
for (int i = 0; i < CaNanoLabConstants.PROTOCOL_TYPES.length; i++) {
if (!protocolTypes.contains(CaNanoLabConstants.PROTOCOL_TYPES[i]))
protocolTypes.add(CaNanoLabConstants.PROTOCOL_TYPES[i]);
}
session.setAttribute("protocolTypes", protocolTypes);
}
public void setProtocolSubmitPage(HttpSession session, UserBean user)
throws Exception {
// set protocol types, and protocol names for all these types
setProtocolType(session);
SortedSet<String> protocolTypes = (SortedSet<String>) session
.getAttribute("protocolTypes");
SortedSet<ProtocolBean> pbs = lookupService.getAllProtocols(user);
// Now generate two maps: one for type and nameList,
// and one for type and protocolIdList (for the protocol name dropdown
// box)
Map<String, List<String>> typeNamesMap = new HashMap<String, List<String>>();
Map<String, List<String>> typeIdsMap = new HashMap<String, List<String>>();
Map<String, List<String>> nameVersionsMap = new HashMap<String, List<String>>();
Map<String, List<String>> nameIdsMap = new HashMap<String, List<String>>();
for (String type : protocolTypes) {
for (ProtocolBean pb : pbs) {
if (type.equals(pb.getType())) {
List<String> nameList = typeNamesMap.get(type);
List<String> idList = typeIdsMap.get(type);
if (nameList == null) {
nameList = new ArrayList<String>();
nameList.add(pb.getName());
typeNamesMap.put(type, nameList);
} else {
nameList.add(pb.getName());
}
if (idList == null) {
idList = new ArrayList<String>();
idList.add(pb.getId().toString());
typeIdsMap.put(type, idList);
} else {
idList.add(pb.getId().toString());
}
}
}
}
for (ProtocolBean pb : pbs) {
String id = pb.getId();
List<String> versionList = new ArrayList<String>();
List<String> idList = new ArrayList<String>();
List<ProtocolFileBean> fileBeanList = pb.getFileBeanList();
Map<String, ProtocolFileBean> map = new HashMap<String, ProtocolFileBean>();
for (ProtocolFileBean fb : fileBeanList) {
versionList.add(fb.getVersion());
map.put(fb.getVersion(), fb);
}
String[] vlist = versionList.toArray(new String[0]);
Arrays.sort(vlist);
versionList.clear();
for (int i = 0; i < vlist.length; i++) {
ProtocolFileBean fb = map.get(vlist[i]);
versionList.add(fb.getVersion());
idList.add(fb.getId());
}
nameVersionsMap.put(id, versionList);
nameIdsMap.put(id, idList);
}
session.setAttribute("AllProtocolTypeNames", typeNamesMap);
session.setAttribute("AllProtocolTypeIds", typeIdsMap);
session.setAttribute("protocolNames", new ArrayList<String>());
session.setAttribute("AllProtocolNameVersions", nameVersionsMap);
session.setAttribute("AllProtocolNameFileIds", nameIdsMap);
session.setAttribute("protocolVersions", new ArrayList<String>());
}
public void setAllProtocolNameVersionsByType(HttpSession session,
String type) throws Exception {
// set protocol name and its versions for a given protocol type.
Map<ProtocolBean, List<ProtocolFileBean>> nameVersions = lookupService
.getAllProtocolNameVersionByType(type);
SortedSet<LabelValueBean> set = new TreeSet<LabelValueBean>();
Set keySet = nameVersions.keySet();
for (Iterator it = keySet.iterator(); it.hasNext();) {
ProtocolBean pb = (ProtocolBean) it.next();
List<ProtocolFileBean> fbList = nameVersions.get(pb);
for (ProtocolFileBean fb : fbList) {
set.add(new LabelValueBean(pb.getName() + " - "
+ fb.getVersion(), fb.getId()));
}
}
session.setAttribute("protocolNameVersionsByType", set);
}
public void setAllRunFiles(HttpSession session, String particleName)
throws Exception {
if (session.getAttribute("allRunFiles") == null
|| session.getAttribute("newParticleCreated") != null
|| session.getAttribute("newFileLoaded") != null) {
SubmitNanoparticleService service = new SubmitNanoparticleService();
List<LabFileBean> runFileBeans = service
.getAllRunFiles(particleName);
session.setAttribute("allRunFiles", runFileBeans);
}
session.removeAttribute("newParticleCreated");
session.removeAttribute("newFileLoaded");
}
public void setAllAreaMeasureUnits(HttpSession session) throws Exception {
if (session.getServletContext().getAttribute("allAreaMeasureUnits") == null) {
String[] areaUnits = lookupService.getAllAreaMeasureUnits();
session.getServletContext().setAttribute("allAreaMeasureUnits",
areaUnits);
}
}
public void setAllChargeMeasureUnits(HttpSession session) throws Exception {
if (session.getServletContext().getAttribute("allChargeMeasureUnits") == null) {
String[] chargeUnits = lookupService.getAllChargeMeasureUnits();
session.getServletContext().setAttribute("allChargeMeasureUnits",
chargeUnits);
}
}
public void setAllControlTypes(HttpSession session) throws Exception {
if (session.getServletContext().getAttribute("allControlTypes") == null) {
String[] controlTypes = lookupService.getAllControlTypes();
session.getServletContext().setAttribute("allControlTypes",
controlTypes);
}
}
public void setAllConditionTypes(HttpSession session) throws Exception {
if (session.getServletContext().getAttribute("allConditionTypes") == null) {
String[] conditionTypes = lookupService.getAllConditionTypes();
session.getServletContext().setAttribute("allConditionTypes",
conditionTypes);
}
}
public void setAllConditionUnits(HttpSession session) throws Exception {
if (session.getServletContext().getAttribute("allConditionTypeUnits") == null) {
Map<String, String[]> conditionTypeUnits = lookupService
.getAllConditionUnits();
session.getServletContext().setAttribute("allConditionTypeUnits",
conditionTypeUnits);
}
}
public void setAllAgentTypes(HttpSession session) throws Exception {
if (session.getServletContext().getAttribute("allAgentTypes") == null) {
Map<String, String[]> agentTypes = lookupService.getAllAgentTypes();
session.getServletContext().setAttribute("allAgentTypes",
agentTypes);
}
}
public void setAllAgentTargetTypes(HttpSession session) throws Exception {
if (session.getServletContext().getAttribute("allAgentTargetTypes") == null) {
String[] agentTargetTypes = lookupService.getAllAgentTargetTypes();
session.getServletContext().setAttribute("allAgentTargetTypes",
agentTargetTypes);
}
}
public void setAllTimeUnits(HttpSession session) throws Exception {
if (session.getServletContext().getAttribute("allTimeUnits") == null) {
String[] timeUnits = lookupService.getAllTimeUnits();
session.getServletContext().setAttribute("allTimeUnits", timeUnits);
}
}
public void setAllConcentrationUnits(HttpSession session) throws Exception {
if (session.getServletContext().getAttribute("allConcentrationUnits") == null) {
String[] concentrationUnits = lookupService
.getAllConcentrationUnits();
session.getServletContext().setAttribute("allConcentrationUnits",
concentrationUnits);
}
}
public void setAllCellLines(HttpSession session) throws Exception {
if (session.getAttribute("allCellLines") == null
|| session.getAttribute("newCellLineCreated") != null) {
SortedSet<String> cellLines = lookupService.getAllCellLines();
session.setAttribute("allCellLines", cellLines);
}
session.removeAttribute("newCellLineCreated");
}
public void setAllActivationMethods(HttpSession session) throws Exception {
if (session.getServletContext().getAttribute("allActivationMethods") == null) {
String[] activationMethods = lookupService
.getAllActivationMethods();
session.getServletContext().setAttribute("allActivationMethods",
activationMethods);
}
}
public void setAllSpecies(HttpSession session) throws Exception {
if (session.getServletContext().getAttribute("allSpecies") == null) {
List<LabelValueBean> species = lookupService.getAllSpecies();
session.getServletContext().setAttribute("allSpecies", species);
}
}
public void setApplicationOwner(HttpSession session) {
if (session.getServletContext().getAttribute("applicationOwner") == null) {
session.getServletContext().setAttribute("applicationOwner",
CaNanoLabConstants.APP_OWNER);
}
}
public void setAllCharacterizationSources(HttpSession session)
throws Exception {
if (session.getAttribute("characterizationSources") == null
|| session.getAttribute("newCharacterizationSourceCreated") != null) {
SortedSet<String> characterizationSources = lookupService
.getAllCharacterizationSources();
session.setAttribute("characterizationSources",
characterizationSources);
}
session.removeAttribute("newCharacterizationSourceCreated");
}
/**
* Create default CSM groups for default visible groups and admin
*
*/
public void createDefaultCSMGroups() throws Exception {
for (String groupName : CaNanoLabConstants.VISIBLE_GROUPS) {
userService.createAGroup(groupName);
}
userService.createAGroup(CaNanoLabConstants.CSM_ADMIN);
}
public void setAllInstruments(HttpSession session) throws Exception {
if (session.getAttribute("allInstruments") == null
|| session.getAttribute("newInstrumentCreated") != null) {
List<InstrumentBean> instruments = lookupService
.getAllInstruments();
SortedSet<String> instrumentTypes = new TreeSet<String>();
for (InstrumentBean instrument : instruments) {
instrumentTypes.add(instrument.getType());
}
SortedSet<String> manufacturers = lookupService
.getAllManufacturers();
session.setAttribute("allInstruments", instruments);
session.setAttribute("allInstrumentTypes", instrumentTypes);
session.setAttribute("allManufacturers", manufacturers);
}
session.removeAttribute("newInstrumentCreated");
}
public void setAllDerivedDataFileTypes(HttpSession session)
throws Exception {
if (session.getAttribute("allDerivedDataFileTypes") == null
|| session.getAttribute("newCharacterizationCreated") != null) {
SortedSet<String> fileTypes = lookupService
.getAllDerivedDataFileTypes();
session.setAttribute("allDerivedDataFileTypes", fileTypes);
}
session.removeAttribute("newCharacterizationCreated");
}
public void setAllFunctionTypes(HttpSession session) throws Exception {
// set in application context
if (session.getServletContext().getAttribute("allFunctionTypes") == null) {
List<String> types = lookupService.getAllFunctionTypes();
session.getServletContext().setAttribute("allFunctionTypes", types);
}
}
public void setAllCharacterizationTypes(HttpSession session)
throws Exception {
// set in application context
if (session.getServletContext()
.getAttribute("allCharacterizationTypes") == null) {
List<CharacterizationTypeBean> types = lookupService
.getAllCharacterizationTypes();
session.getServletContext().setAttribute(
"allCharacterizationTypes", types);
}
// set in application context mapping between characterization type and
// child characterization names
if (session.getServletContext().getAttribute("allCharTypeChars") == null) {
Map<String, List<String>> charTypeChars = lookupService
.getCharacterizationTypeCharacterizations();
session.getServletContext().setAttribute("allCharTypeChars",
charTypeChars);
}
}
public void setDerivedDataCategoriesDatumNames(HttpSession session,
String characterizationName) throws Exception {
SortedSet<String> categories = lookupService
.getDerivedDataCategories(characterizationName);
session.setAttribute("derivedDataCategories", categories);
SortedSet<String> datumNames = lookupService
.getDerivedDatumNames(characterizationName);
session.setAttribute("datumNames", datumNames);
}
public void setAllCharacterizationMeasureUnitsTypes(HttpSession session,
String charName) throws Exception {
Map<String, SortedSet<String>> unitMap = lookupService
.getAllMeasureUnits();
SortedSet<String> charUnits = unitMap.get(charName);
if (charUnits == null) {
charUnits = new TreeSet<String>();
charUnits.add("");// add an empty one to indicate no unit
}
SortedSet<String> types = lookupService.getAllMeasureTypes();
session.setAttribute("charMeasureUnits", charUnits);
session.setAttribute("charMeasureTypes", types);
}
public void updateEditableDropdown(HttpSession session,
String formAttribute, String sessionAttributeName) {
SortedSet<String> dropdown = (SortedSet<String>) session
.getAttribute(sessionAttributeName);
if (dropdown != null && formAttribute != null
&& formAttribute.length() > 0) {
dropdown.add(formAttribute);
}
}
} |
package gov.nih.nci.calab.ui.security;
import gov.nih.nci.calab.ui.core.AbstractBaseAction;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
/**
* This action logs user out of the current session
*
* @author pansn
*/
/* CVS $Id: */
public class LogoutAction extends AbstractBaseAction {
public ActionForward executeTask(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
ActionForward forward = null;
HttpSession session = request.getSession(false);
if (session != null) {
//invalidate the old one
session.invalidate();
//create a new one
session=request.getSession();
ActionMessages msgs = new ActionMessages();
ActionMessage error = new ActionMessage("msg.logout");
msgs.add("msg", error);
saveMessages(request, msgs);
}
forward = mapping.findForward("success");
return forward;
}
public boolean loginRequired() {
return false;
}
} |
package org.bbop.apollo.gwt.client;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.dom.client.NativeEvent;
import com.google.gwt.user.client.ui.*;
import com.google.gwt.user.client.Event.*;
import com.google.gwt.user.client.Window;
import org.bbop.apollo.gwt.client.rest.UserRestService;
// TODO: this needs to be moved into UIBinder into its own class
public class LoginDialog extends DialogBox {
// TODO: move to UIBinder
private VerticalPanel panel = new VerticalPanel();
private Grid grid = new Grid(2,2);
private Button okButton = new Button("Login");
private TextBox username = new TextBox();
private PasswordTextBox passwordTextBox = new PasswordTextBox();
private HorizontalPanel horizontalPanel = new HorizontalPanel();
private CheckBox rememberMeCheckBox = new CheckBox("Remember me");
public LoginDialog() {
// Set the dialog box's caption.
setText("Login");
// Enable animation.
setAnimationEnabled(true);
// Enable glass background.
setGlassEnabled(true);
grid.setHTML(0, 0, "Username");
grid.setWidget(0, 1, username);
grid.setHTML(1, 0, "Password");
grid.setWidget(1, 1, passwordTextBox);
panel.add(grid);
username.setFocus(true);
horizontalPanel.add(rememberMeCheckBox);
horizontalPanel.add(new HTML(" "));
horizontalPanel.add(okButton);
panel.add(horizontalPanel);
// DialogBox is a SimplePanel, so you have to set its widget property to
// whatever you want its contents to be.
okButton.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
doLogin(username.getText().trim(),passwordTextBox.getText(),rememberMeCheckBox.getValue());
}
});
setWidget(panel);
}
@Override
public void onPreviewNativeEvent(NativePreviewEvent e) {
NativeEvent nativeEvent = e.getNativeEvent();
if ("keydown".equals(nativeEvent.getType())) {
if (nativeEvent.getKeyCode() == KeyCodes.KEY_ENTER) {
doLogin(username.getText().trim(),passwordTextBox.getText(),rememberMeCheckBox.getValue());
}
}
}
public void doLogin(String username,String password,Boolean rememberMe){
UserRestService.login(username, password,rememberMe);
}
} |
package info.tregmine.database.db;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.dbcp.BasicDataSource;
import org.bukkit.configuration.file.FileConfiguration;
import com.mysql.jdbc.exceptions.jdbc4.CommunicationsException;
import info.tregmine.Tregmine;
import info.tregmine.database.DAOException;
import info.tregmine.database.IContext;
import info.tregmine.database.IContextFactory;
public class DBContextFactory implements IContextFactory {
private BasicDataSource ds;
private Map<String, LoggingConnection.LogEntry> queryLog;
private Tregmine plugin;
private String driver;
private String url;
private String user;
private String password;
public DBContextFactory(FileConfiguration config, Tregmine instance) {
queryLog = new HashMap<>();
String driver = config.getString("db.driver");
if (driver == null) {
driver = "com.mysql.jdbc.Driver";
}
try {
Class.forName(driver).newInstance();
} catch (ClassNotFoundException ex) {
throw new RuntimeException(ex);
} catch (IllegalAccessException ex) {
throw new RuntimeException(ex);
} catch (InstantiationException ex) {
throw new RuntimeException(ex);
}
String user = config.getString("db.user");
String password = config.getString("db.password");
String url = config.getString("db.url");
ds = new BasicDataSource();
ds.setDriverClassName(driver);
ds.setUrl(url);
ds.setUsername(user);
ds.setPassword(password);
ds.setMaxActive(5);
ds.setMaxIdle(5);
ds.setDefaultAutoCommit(true);
this.driver = driver;
this.url = url;
this.user = user;
this.password = password;
this.plugin = instance;
}
public void regenerate() throws DAOException{
try{
ds.close();
ds = null;
ds = new BasicDataSource();
ds.setDriverClassName(driver);
ds.setUrl(url);
ds.setUsername(user);
ds.setPassword(password);
ds.setMaxActive(5);
ds.setMaxIdle(5);
ds.setDefaultAutoCommit(true);
createTime = System.currentTimeMillis();
}catch(SQLException e){
throw new DAOException(e);
}
}
@Override
public IContext createContext() throws DAOException {
try {
// It's the responsibility of the context to make sure that the
// connection is correctly closed
Connection conn = ds.getConnection();
try (Statement stmt = conn.createStatement()) {
stmt.execute("SET NAMES latin1");
}
return new DBContext(new LoggingConnection(conn, queryLog), plugin);
} catch (SQLException e) {
throw new DAOException(e);
}
}
public Map<String, LoggingConnection.LogEntry> getLog() {
return queryLog;
}
} |
package com.tempoiq;
import java.io.File;
import java.io.FileInputStream;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.Interval;
import org.joda.time.Period;
import org.junit.*;
import static org.junit.Assert.*;
import static com.tempoiq.util.Preconditions.*;
public class ClientIT {
private static final Client client;
private static final Client invalidClient;
private static final DateTimeZone timezone = DateTimeZone.UTC;
private static final DateTime start = new DateTime(1500, 1, 1, 0, 0, 0, 0, timezone);
private static final DateTime end = new DateTime(3000, 1, 1, 0, 0, 0, 0, timezone);
private static final Interval interval = new Interval(start, end);
private static final int SLEEP = 5000;
static {
File credentials = new File("integration-credentials.properties");
if(!credentials.exists()) {
String message = "Missing credentials file for integration test.\n" +
"Please supply a file 'integration-credentials.properties' with the following format:\n" +
" database.id=<id>\n" +
" credentials.key=<key>\n" +
" credentials.secret=<secret>\n" +
" hostname=<hostname>\n" +
" port=<port>\n" +
" scheme=<scheme>\n";
System.exit(1);
}
client = getClient(credentials);
invalidClient = new Client(new Credentials("key", "secret"),
client.getHost(), client.getScheme());
}
static Client getClient(File propertiesFile) {
Properties properties = new Properties();
try {
properties.load(new FileInputStream(propertiesFile));
} catch (Exception e) {
throw new IllegalArgumentException("No credentials file", e);
}
String key = checkNotNull(properties.getProperty("credentials.key"));
String secret = checkNotNull(properties.getProperty("credentials.secret"));
String hostname = checkNotNull(properties.getProperty("hostname"));
int port = Integer.parseInt(checkNotNull(properties.getProperty("port")));
String scheme = checkNotNull(properties.getProperty("scheme"));
Credentials credentials = new Credentials(key, secret);
InetSocketAddress host = new InetSocketAddress(hostname, port);
return new Client(credentials, host, scheme);
}
@BeforeClass
static public void onetimeSetup() {
cleanup();
}
static public void cleanup() {
// /* Delete all devices */
Result<DeleteSummary> result = client.deleteAllDevices();
assertEquals(State.SUCCESS, result.getState());
}
static public Device createDevice() {
List<Sensor> sensors = new ArrayList<Sensor>();
sensors.add(new Sensor("key1"));
sensors.add(new Sensor("key2"));
Device device = new Device("create-device", "name", new HashMap<String, String>(), sensors);
Result<Device> result = client.createDevice(device);
return result.getValue();
}
@After
public void tearDown() { cleanup(); }
@Test
public void testInvalidCredentials() {
Device device = new Device();
Result<Device> result = invalidClient.createDevice(device);
Result<Device> expected = new Result<Device>(null, 403, "Forbidden");
assertEquals(expected, result);
}
@Test
public void testCreateDevices() {
Device device = new Device("create-device", "name", new HashMap<String, String>(), new ArrayList<Sensor>());
Result<Device> result = client.createDevice(device);
Result<Device> expected = new Result<Device>(device, 200, "OK");
assertEquals(expected, result);
}
@Test
public void testWriteDataPointBySensor() {
Device device = createDevice();
Map<String, Number> points = new HashMap<String, Number>();
points.put("sensor1", 1.23);
points.put("sensor2", 1.67);
MultiDataPoint mp = new MultiDataPoint(new DateTime(2012, 1, 1, 0, 0, 0, 0, timezone), points);
Result<Void> result = client.writeDataPoints(device, mp);
assertEquals(State.SUCCESS, result.getState());
}
@Test
public void testReadDataPoints() {
Device device = createDevice();
DateTime start = new DateTime(2012, 1, 1, 0, 0, 0, 0, timezone);
DateTime stop = new DateTime(2012, 1, 2, 0, 0, 0, 0, timezone);
Map<String, Number> points = new HashMap<String, Number>();
points.put("sensor1", 1.23);
points.put("sensor2", 1.67);
MultiDataPoint mp = new MultiDataPoint(new DateTime(2012, 1, 1, 0, 0, 0, 0, timezone), points);
Result<Void> result = client.writeDataPoints(device, mp);
Selection sel = new Selection().
addSelector(Selector.Type.DEVICES, Selector.key("key1"));
Cursor<Row> cursor = client.read(sel, start, stop);
for (Row row : cursor) {
assertEquals(1.23, row.getKey("key1", "sensor1").getValue());
assertEquals(1.67, row.getKey("key2", "sensor2").getValue());
}
}
// @Test
// public void testDeleteDataPointsBySensor() throws InterruptedException {
// // Write datapoints
// DataPoint dp = new DataPoint(new DateTime(2012, 1, 1, 0, 0, 0, 0, timezone), 12.34);
// Result<Void> result1 = client.writeDataPoints(new Sensor("key1"), Arrays.asList(dp));
// assertEquals(State.SUCCESS, result1.getState());
// Thread.sleep(SLEEP);
// // Read datapoints
// List<DataPoint> expected1 = Arrays.asList(dp);
// Cursor<DataPoint> cursor1 = client.readDataPoints(new Sensor("key1"), interval, timezone);
// assertEquals(expected1, toList(cursor1));
// // Delete datapoints
// Result<Void> result2 = client.deleteDataPoints(new Sensor("key1"), interval);
// assertEquals(new Result<Void>(null, 200, "OK"), result2);
// // Read datapoints again
// List<DataPoint> expected2 = new ArrayList<DataPoint>();
// Cursor<DataPoint> cursor2 = client.readDataPoints(new Sensor("key1"), interval, timezone);
// assertEquals(expected2, toList(cursor2));
// @Test
// public void testFindDataPointBySensor() throws InterruptedException {
// DataPoint dp1 = new DataPoint(new DateTime(2012, 1, 2, 0, 0 ,0, 0, timezone), 23.45);
// DataPoint dp2 = new DataPoint(new DateTime(2012, 1, 2, 1, 0 ,0, 0, timezone), 34.56);
// Result<Void> result = client.writeDataPoints(new Sensor("key-find"), Arrays.asList(dp1, dp2));
// assertEquals(State.SUCCESS, result.getState());
// Thread.sleep(SLEEP);
// DateTime start = new DateTime(2012, 1, 2, 0, 0, 0, 0, timezone);
// DateTime end = new DateTime(2012, 1, 3, 0, 0, 0, 0, timezone);
// Interval interval = new Interval(start, end);
// Predicate predicate = new Predicate(Period.days(1), "max");
// DataPointFound dpf1 = new DataPointFound(interval, dp2);
// List<DataPointFound> expected = Arrays.asList(dpf1);
// Cursor<DataPointFound> cursor = client.findDataPoints(new Sensor("key-find"), new Interval(start, end), predicate, timezone);
// assertEquals(expected, toList(cursor));
// @Test
// public void testReadDataPointByKey() throws InterruptedException {
// DataPoint dp1 = new DataPoint(new DateTime(2012, 1, 2, 0, 0 ,0, 0, timezone), 23.45);
// DataPoint dp2 = new DataPoint(new DateTime(2012, 1, 2, 1, 0 ,0, 0, timezone), 34.56);
// Result<Void> result = client.writeDataPoints(new Sensor("key1"), Arrays.asList(dp1, dp2));
// assertEquals(State.SUCCESS, result.getState());
// Thread.sleep(SLEEP);
// DateTime start = new DateTime(2012, 1, 2, 0, 0, 0, 0, timezone);
// DateTime end = new DateTime(2012, 1, 3, 0, 0, 0, 0, timezone);
// List<DataPoint> expected = Arrays.asList(dp1, dp2);
// Cursor<DataPoint> cursor = client.readDataPoints(new Sensor("key1"), new Interval(start, end), timezone);
// assertEquals(expected, toList(cursor));
// @Test
// public void testReadSingleValue() throws InterruptedException {
// DataPoint dp1 = new DataPoint(new DateTime(2012, 1, 2, 0, 0 ,0, 0, timezone), 23.45);
// DataPoint dp2 = new DataPoint(new DateTime(2012, 1, 2, 1, 0 ,0, 0, timezone), 34.56);
// Result<Void> result = client.writeDataPoints(new Sensor("key1"), Arrays.asList(dp1, dp2));
// assertEquals(State.SUCCESS, result.getState());
// Thread.sleep(SLEEP);
// DateTime ts = new DateTime(2012, 1, 2, 0, 0, 0, 0, timezone);
// SingleValue expected = new SingleValue(new Sensor("key1"), new DataPoint(ts, 23.45));
// Result<SingleValue> value = client.readSingleValue(new Sensor("key1"), ts, timezone, Direction.EXACT);
// assertEquals(expected, value.getValue());
// @Test
// public void testReadMultiDataPoints() throws InterruptedException {
// WriteRequest wr = new WriteRequest()
// .add(new Sensor("key1"), new DataPoint(new DateTime(2012, 1, 1, 0, 0, 0, 0, timezone), 5.0))
// .add(new Sensor("key2"), new DataPoint(new DateTime(2012, 1, 1, 0, 0, 0, 0, timezone), 6.0))
// .add(new Sensor("key1"), new DataPoint(new DateTime(2012, 1, 1, 0, 1, 0, 0, timezone), 7.0))
// .add(new Sensor("key2"), new DataPoint(new DateTime(2012, 1, 1, 0, 1, 0, 0, timezone), 8.0));
// Result<Void> result1 = client.writeDataPoints(wr);
// assertEquals(new Result<Void>(null, 200, "OK"), result1);
// Thread.sleep(SLEEP);
// Filter filter = new Filter();
// filter.addKey("key1");
// filter.addKey("key2");
// Cursor<MultiDataPoint> cursor = client.readMultiDataPoints(filter, interval, timezone);
// Map<String, Number> data1 = new HashMap<String, Number>();
// data1.put("key1", 5.0);
// data1.put("key2", 6.0);
// Map<String, Number> data2 = new HashMap<String, Number>();
// data2.put("key1", 7.0);
// data2.put("key2", 8.0);
// List<MultiDataPoint> expected = Arrays.asList(
// new MultiDataPoint(new DateTime(2012, 1, 1, 0, 0, 0, 0, timezone), data1),
// new MultiDataPoint(new DateTime(2012, 1, 1, 0, 1, 0, 0, timezone), data2)
// assertEquals(expected, toList(cursor));
// @Test
// public void testReadMultiRollupDataPointByKey() throws InterruptedException {
// DataPoint dp1 = new DataPoint(new DateTime(2012, 1, 2, 0, 0 ,0, 0, timezone), 23.45);
// DataPoint dp2 = new DataPoint(new DateTime(2012, 1, 2, 1, 0 ,0, 0, timezone), 34.56);
// Result<Void> result = client.writeDataPoints(new Sensor("key1"), Arrays.asList(dp1, dp2));
// assertEquals(State.SUCCESS, result.getState());
// Thread.sleep(SLEEP);
// DateTime start = new DateTime(2012, 1, 2, 0, 0, 0, 0, timezone);
// DateTime end = new DateTime(2012, 1, 3, 0, 0, 0, 0, timezone);
// MultiRollup rollup = new MultiRollup(Period.days(1), new Fold[] { Fold.MAX, Fold.MIN });
// Cursor<MultiDataPoint> cursor = client.readMultiRollupDataPoints(new Sensor("key1"), new Interval(start, end), timezone, rollup);
// Map<String, Number> data1 = new HashMap<String, Number>();
// data1.put("max", 34.56);
// data1.put("min", 23.45);
// MultiDataPoint mdp1 = new MultiDataPoint(new DateTime(2012, 1, 2, 0, 0, 0, 0, timezone), data1);
// List<MultiDataPoint> expected = Arrays.asList(mdp1);
// assertEquals(expected, toList(cursor));
// @Test
// public void testWriteDataPoints() throws InterruptedException {
// WriteRequest wr = new WriteRequest()
// .add(new Sensor("key1"), new DataPoint(new DateTime(2012, 1, 1, 0, 0, 0, 0, timezone), 5.0))
// .add(new Sensor("key2"), new DataPoint(new DateTime(2012, 1, 1, 0, 0, 0, 0, timezone), 6.0))
// .add(new Sensor("key1"), new DataPoint(new DateTime(2012, 1, 1, 0, 1, 0, 0, timezone), 7.0))
// .add(new Sensor("key2"), new DataPoint(new DateTime(2012, 1, 1, 0, 2, 0, 0, timezone), 8.0));
// Thread.sleep(SLEEP);
// Result<Void> result = client.writeDataPoints(wr);
// assertEquals(new Result<Void>(null, 200, "OK"), result);
// @Test
// public void testReadDataPoints() throws InterruptedException {
// WriteRequest wr = new WriteRequest()
// .add(new Sensor("key1"), new DataPoint(new DateTime(2012, 1, 1, 0, 0, 0, 0, timezone), 5.0))
// .add(new Sensor("key2"), new DataPoint(new DateTime(2012, 1, 1, 0, 0, 0, 0, timezone), 6.0))
// .add(new Sensor("key1"), new DataPoint(new DateTime(2012, 1, 1, 0, 1, 0, 0, timezone), 7.0))
// .add(new Sensor("key2"), new DataPoint(new DateTime(2012, 1, 1, 0, 1, 0, 0, timezone), 8.0));
// Result<Void> result1 = client.writeDataPoints(wr);
// assertEquals(new Result<Void>(null, 200, "OK"), result1);
// Thread.sleep(SLEEP);
// Filter filter = new Filter();
// filter.addKey("key1");
// filter.addKey("key2");
// Aggregation aggregation = new Aggregation(Fold.SUM);
// Cursor<DataPoint> cursor = client.readDataPoints(filter, interval, timezone, aggregation);
// DataPoint dp1 = new DataPoint(new DateTime(2012, 1, 1, 0, 0, 0, 0, timezone), 11.0);
// DataPoint dp2 = new DataPoint(new DateTime(2012, 1, 1, 0, 1, 0, 0, timezone), 15.0);
// List<DataPoint> expected = Arrays.asList(dp1, dp2);
// assertEquals(expected, toList(cursor));
// @Test
// public void testGetSensorByKey() {
// // Create a sensor
// HashMap<String, String> attributes = new HashMap<String, String>();
// attributes.put("txn", "/def ault");
// Result<Sensor> result1 = client.createSensor(sensor);
// // Get the sensor
// Result<Sensor> expected = new Result<Sensor>(sensor, 200, "OK");
// assertEquals(expected, result2);
// @Test
// public void testGetSensorByFilter() {
// // Create a sensor
// HashSet<String> tags = new HashSet<String>();
// tags.add("get-filter");
// Sensor sensor = new Sensor("create-sensor", "name", tags, new HashMap<String, String>());
// Result<Sensor> result1 = client.createSensor(sensor);
// // Get the sensor by filter
// Filter filter = new Filter();
// filter.addTag("get-filter");
// Cursor<Sensor> cursor = client.getSensor(filter);
// List<Sensor> expected = Arrays.asList(sensor);
// assertEquals(expected, toList(cursor));
// @Test
// public void testUpdateSensor() {
// // Create a sensor
// HashSet<String> tags = new HashSet<String>();
// tags.add("update");
// Sensor sensor = new Sensor("update-sensor", "name", tags, new HashMap<String, String>());
// Result<Sensor> result1 = client.createSensor(sensor);
// // Update the sensor
// sensor.getTags().add("update2");
// Result<Sensor> result2 = client.updateSensor(sensor);
// assertEquals(new Result<Sensor>(sensor, 200, "OK"), result2);
// // Get the sensor
// Result<Sensor> result3 = client.getSensor("update-sensor");
// Result<Sensor> expected = new Result<Sensor>(sensor, 200, "OK");
// assertEquals(expected, result3);
// @Test
// public void testDeleteSensor() {
// // Create a sensor
// HashSet<String> tags = new HashSet<String>();
// tags.add("delete");
// Sensor sensor = new Sensor("delete-sensor", "name", tags, new HashMap<String, String>());
// Result<Sensor> result1 = client.createSensor(sensor);
// // Delete the sensor
// Result<Void> result2 = client.deleteSensor(sensor);
// assertEquals(new Result<Void>(null, 200, "OK"), result2);
// // Get the sensor
// Result<Sensor> result3 = client.getSensor("delete-sensor");
// Result<Sensor> expected = new Result<Sensor>(null, 403, "Forbidden");
// assertEquals(expected, result3);
// @Test
// public void testDeleteSensorByFilter() {
// // Create a sensor
// HashSet<String> tags = new HashSet<String>();
// tags.add("delete-filter");
// Sensor sensor1 = new Sensor("delete-sensor", "name", tags, new HashMap<String, String>());
// Sensor sensor2 = new Sensor("delete-sensor2", "name", new HashSet<String>(), new HashMap<String, String>());
// Result<Sensor> result1 = client.createSensor(sensor1);
// Result<Sensor> result2 = client.createSensor(sensor2);
// // Get the sensor by filter
// Filter filter = new Filter();
// filter.addTag("delete-filter");
// Cursor<Sensor> cursor = client.getSensor(filter);
// List<Sensor> expected1 = Arrays.asList(sensor1);
// assertEquals(expected1, toList(cursor));
// // Delete the sensor by filter
// Result<DeleteSummary> result3 = client.deleteSensor(filter);
// assertEquals(new Result<DeleteSummary>(new DeleteSummary(1), 200, "OK"), result3);
// // Get the sensor by filter again
// Cursor<Sensor> cursor2 = client.getSensor(filter);
// List<Sensor> expected2 = Arrays.asList();
// assertEquals(expected2, toList(cursor2));
// private <T> List<T> toList(Cursor<T> cursor) {
// List<T> output = new ArrayList<T>();
// for(T dp : cursor) {
// output.add(dp);
// return output;
} |
package com.tempodb;
import java.io.File;
import java.io.FileInputStream;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.Interval;
import org.joda.time.Period;
import org.junit.*;
import static org.junit.Assert.*;
import static com.tempodb.util.Preconditions.*;
public class ClientIT {
private static final Client client;
private static final Client invalidClient;
private static final DateTimeZone timezone = DateTimeZone.UTC;
private static final DateTime start = new DateTime(1500, 1, 1, 0, 0, 0, 0, timezone);
private static final DateTime end = new DateTime(3000, 1, 1, 0, 0, 0, 0, timezone);
private static final Interval interval = new Interval(start, end);
private static final int SLEEP = 5000;
static {
File credentials = new File("integration-credentials.properties");
if(!credentials.exists()) {
String message = "Missing credentials file for integration test.\n" +
"Please supply a file 'integration-credentials.properties' with the following format:\n" +
" database.id=<id>\n" +
" credentials.key=<key>\n" +
" credentials.secret=<secret>\n" +
" hostname=<hostname>\n" +
" port=<port>\n" +
" scheme=<scheme>\n";
System.out.println(message);
System.exit(1);
}
client = getClient(credentials);
invalidClient = new Client(client.getDatabase(), new Credentials("key", "secret"),
client.getHost(), client.getScheme());
}
static Client getClient(File propertiesFile) {
Properties properties = new Properties();
try {
properties.load(new FileInputStream(propertiesFile));
} catch (Exception e) {
throw new IllegalArgumentException("No credentials file", e);
}
String id = checkNotNull(properties.getProperty("database.id"));
String key = checkNotNull(properties.getProperty("credentials.key"));
String secret = checkNotNull(properties.getProperty("credentials.secret"));
String hostname = checkNotNull(properties.getProperty("hostname"));
int port = Integer.parseInt(checkNotNull(properties.getProperty("port")));
String scheme = checkNotNull(properties.getProperty("scheme"));
Database database = new Database(id);
Credentials credentials = new Credentials(key, secret);
InetSocketAddress host = new InetSocketAddress(hostname, port);
return new Client(database, credentials, host, scheme);
}
@BeforeClass
static public void onetimeSetup() {
cleanup();
}
static public void cleanup() {
/* Delete all datapoints all series */
Cursor<Series> cursor = client.getSeries(new Filter());
for(Series series : cursor) {
Result<Nothing> result = client.deleteDataPoints(series, interval);
assertEquals(State.SUCCESS, result.getState());
}
/* Delete all series */
Result<DeleteSummary> result = client.deleteAllSeries();
assertEquals(State.SUCCESS, result.getState());
}
@After
public void tearDown() { cleanup(); }
@Test
public void testInvalidCredentials() {
Series series = new Series("key1", "", new HashSet<String>(), new HashMap<String, String>());
Result<Series> result = invalidClient.createSeries(series);
Result<Series> expected = new Result<Series>(null, 403, "Forbidden");
assertEquals(expected, result);
}
@Test
public void testCreateSeries() {
HashSet<String> tags = new HashSet<String>();
tags.add("create");
Series series = new Series("create-series", "name", tags, new HashMap<String, String>());
Result<Series> result = client.createSeries(series);
Result<Series> expected = new Result<Series>(series, 200, "OK");
assertEquals(expected, result);
}
@Test
public void testDeleteDataPointsBySeries() throws InterruptedException {
// Write datapoints
DataPoint dp = new DataPoint(new DateTime(2012, 1, 1, 0, 0, 0, 0, timezone), 12.34);
Result<Nothing> result1 = client.writeDataPoints(new Series("key1"), Arrays.asList(dp));
assertEquals(State.SUCCESS, result1.getState());
Thread.sleep(SLEEP);
// Read datapoints
List<DataPoint> expected1 = Arrays.asList(dp);
Cursor<DataPoint> cursor1 = client.readDataPoints(new Series("key1"), interval, timezone);
assertEquals(expected1, toList(cursor1));
// Delete datapoints
Result<Nothing> result2 = client.deleteDataPoints(new Series("key1"), interval);
assertEquals(new Result<Nothing>(new Nothing(), 200, "OK"), result2);
// Read datapoints again
List<DataPoint> expected2 = new ArrayList<DataPoint>();
Cursor<DataPoint> cursor2 = client.readDataPoints(new Series("key1"), interval, timezone);
assertEquals(expected2, toList(cursor2));
}
@Test
public void testWriteDataPointBySeries() {
DataPoint dp = new DataPoint(new DateTime(2012, 1, 1, 0, 0, 0, 0, timezone), 12.34);
Result<Nothing> result = client.writeDataPoints(new Series("key1"), Arrays.asList(dp));
assertEquals(State.SUCCESS, result.getState());
}
@Test
public void testFindDataPointBySeries() throws InterruptedException {
DataPoint dp1 = new DataPoint(new DateTime(2012, 1, 2, 0, 0 ,0, 0, timezone), 23.45);
DataPoint dp2 = new DataPoint(new DateTime(2012, 1, 2, 1, 0 ,0, 0, timezone), 34.56);
Result<Nothing> result = client.writeDataPoints(new Series("key-find"), Arrays.asList(dp1, dp2));
assertEquals(State.SUCCESS, result.getState());
Thread.sleep(SLEEP);
DateTime start = new DateTime(2012, 1, 2, 0, 0, 0, 0, timezone);
DateTime end = new DateTime(2012, 1, 3, 0, 0, 0, 0, timezone);
Interval interval = new Interval(start, end);
Predicate predicate = new Predicate(Period.days(1), "max");
DataPointFound dpf1 = new DataPointFound(interval, dp2);
List<DataPointFound> expected = Arrays.asList(dpf1);
Cursor<DataPointFound> cursor = client.findDataPoints(new Series("key-find"), new Interval(start, end), predicate, timezone);
assertEquals(expected, toList(cursor));
}
@Test
public void testReadDataPointByKey() throws InterruptedException {
DataPoint dp1 = new DataPoint(new DateTime(2012, 1, 2, 0, 0 ,0, 0, timezone), 23.45);
DataPoint dp2 = new DataPoint(new DateTime(2012, 1, 2, 1, 0 ,0, 0, timezone), 34.56);
Result<Nothing> result = client.writeDataPoints(new Series("key1"), Arrays.asList(dp1, dp2));
assertEquals(State.SUCCESS, result.getState());
Thread.sleep(SLEEP);
DateTime start = new DateTime(2012, 1, 2, 0, 0, 0, 0, timezone);
DateTime end = new DateTime(2012, 1, 3, 0, 0, 0, 0, timezone);
List<DataPoint> expected = Arrays.asList(dp1, dp2);
Cursor<DataPoint> cursor = client.readDataPoints(new Series("key1"), new Interval(start, end), timezone);
assertEquals(expected, toList(cursor));
}
@Test
public void testReadSingleValue() throws InterruptedException {
DataPoint dp1 = new DataPoint(new DateTime(2012, 1, 2, 0, 0 ,0, 0, timezone), 23.45);
DataPoint dp2 = new DataPoint(new DateTime(2012, 1, 2, 1, 0 ,0, 0, timezone), 34.56);
Result<Nothing> result = client.writeDataPoints(new Series("key1"), Arrays.asList(dp1, dp2));
assertEquals(State.SUCCESS, result.getState());
Thread.sleep(SLEEP);
DateTime ts = new DateTime(2012, 1, 2, 0, 0, 0, 0, timezone);
SingleValue expected = new SingleValue(new Series("key1"), new DataPoint(ts, 23.45));
Result<SingleValue> value = client.readSingleValue(new Series("key1"), ts, timezone, Direction.EXACT);
assertEquals(expected, value.getValue());
}
@Test
public void testReadMultiDataPoints() throws InterruptedException {
WriteRequest wr = new WriteRequest()
.add(new Series("key1"), new DataPoint(new DateTime(2012, 1, 1, 0, 0, 0, 0, timezone), 5.0))
.add(new Series("key2"), new DataPoint(new DateTime(2012, 1, 1, 0, 0, 0, 0, timezone), 6.0))
.add(new Series("key1"), new DataPoint(new DateTime(2012, 1, 1, 0, 1, 0, 0, timezone), 7.0))
.add(new Series("key2"), new DataPoint(new DateTime(2012, 1, 1, 0, 1, 0, 0, timezone), 8.0));
Result<Nothing> result1 = client.writeDataPoints(wr);
assertEquals(new Result<Nothing>(new Nothing(), 200, "OK"), result1);
Thread.sleep(SLEEP);
Filter filter = new Filter();
filter.addKey("key1");
filter.addKey("key2");
Cursor<MultiDataPoint> cursor = client.readMultiDataPoints(filter, interval, timezone);
Map<String, Number> data1 = new HashMap<String, Number>();
data1.put("key1", 5.0);
data1.put("key2", 6.0);
Map<String, Number> data2 = new HashMap<String, Number>();
data2.put("key1", 7.0);
data2.put("key2", 8.0);
List<MultiDataPoint> expected = Arrays.asList(
new MultiDataPoint(new DateTime(2012, 1, 1, 0, 0, 0, 0, timezone), data1),
new MultiDataPoint(new DateTime(2012, 1, 1, 0, 1, 0, 0, timezone), data2)
);
assertEquals(expected, toList(cursor));
}
@Test
public void testReadMultiRollupDataPointByKey() throws InterruptedException {
DataPoint dp1 = new DataPoint(new DateTime(2012, 1, 2, 0, 0 ,0, 0, timezone), 23.45);
DataPoint dp2 = new DataPoint(new DateTime(2012, 1, 2, 1, 0 ,0, 0, timezone), 34.56);
Result<Nothing> result = client.writeDataPoints(new Series("key1"), Arrays.asList(dp1, dp2));
assertEquals(State.SUCCESS, result.getState());
Thread.sleep(SLEEP);
DateTime start = new DateTime(2012, 1, 2, 0, 0, 0, 0, timezone);
DateTime end = new DateTime(2012, 1, 3, 0, 0, 0, 0, timezone);
Map<String, Number> data1 = new HashMap<String, Number>();
data1.put("max", 34.56);
data1.put("min", 23.45);
MultiDataPoint mdp1 = new MultiDataPoint(new DateTime(2012, 1, 2, 0, 0, 0, 0, timezone), data1);
List<MultiDataPoint> expected = Arrays.asList(mdp1);
Cursor<MultiDataPoint> cursor = client.readMultiRollupDataPoints(new Series("key1"), new Interval(start, end), new MultiRollup(Period.days(1), new Fold[] { Fold.MAX, Fold.MIN }), timezone);
assertEquals(expected, toList(cursor));
}
@Test
public void testWriteDataPoints() throws InterruptedException {
WriteRequest wr = new WriteRequest()
.add(new Series("key1"), new DataPoint(new DateTime(2012, 1, 1, 0, 0, 0, 0, timezone), 5.0))
.add(new Series("key2"), new DataPoint(new DateTime(2012, 1, 1, 0, 0, 0, 0, timezone), 6.0))
.add(new Series("key1"), new DataPoint(new DateTime(2012, 1, 1, 0, 1, 0, 0, timezone), 7.0))
.add(new Series("key2"), new DataPoint(new DateTime(2012, 1, 1, 0, 2, 0, 0, timezone), 8.0));
Thread.sleep(SLEEP);
Result<Nothing> result = client.writeDataPoints(wr);
assertEquals(new Result<Nothing>(new Nothing(), 200, "OK"), result);
}
@Test
public void testReadDataPoints() throws InterruptedException {
WriteRequest wr = new WriteRequest()
.add(new Series("key1"), new DataPoint(new DateTime(2012, 1, 1, 0, 0, 0, 0, timezone), 5.0))
.add(new Series("key2"), new DataPoint(new DateTime(2012, 1, 1, 0, 0, 0, 0, timezone), 6.0))
.add(new Series("key1"), new DataPoint(new DateTime(2012, 1, 1, 0, 1, 0, 0, timezone), 7.0))
.add(new Series("key2"), new DataPoint(new DateTime(2012, 1, 1, 0, 1, 0, 0, timezone), 8.0));
Result<Nothing> result1 = client.writeDataPoints(wr);
assertEquals(new Result<Nothing>(new Nothing(), 200, "OK"), result1);
Thread.sleep(SLEEP);
Filter filter = new Filter();
filter.addKey("key1");
filter.addKey("key2");
Aggregation aggregation = new Aggregation(Fold.SUM);
Cursor<DataPoint> cursor = client.readDataPoints(filter, interval, timezone, aggregation);
DataPoint dp1 = new DataPoint(new DateTime(2012, 1, 1, 0, 0, 0, 0, timezone), 11.0);
DataPoint dp2 = new DataPoint(new DateTime(2012, 1, 1, 0, 1, 0, 0, timezone), 15.0);
List<DataPoint> expected = Arrays.asList(dp1, dp2);
assertEquals(expected, toList(cursor));
}
@Test
public void testGetSeriesByKey() {
// Create a series
HashSet<String> tags = new HashSet<String>();
tags.add("create");
Series series = new Series("create-series", "name", tags, new HashMap<String, String>());
Result<Series> result1 = client.createSeries(series);
// Get the series
Result<Series> result2 = client.getSeries("create-series");
Result<Series> expected = new Result<Series>(series, 200, "OK");
assertEquals(expected, result2);
}
@Test
public void testGetSeriesByFilter() {
// Create a series
HashSet<String> tags = new HashSet<String>();
tags.add("get-filter");
Series series = new Series("create-series", "name", tags, new HashMap<String, String>());
Result<Series> result1 = client.createSeries(series);
// Get the series by filter
Filter filter = new Filter();
filter.addTag("get-filter");
Cursor<Series> cursor = client.getSeries(filter);
List<Series> expected = Arrays.asList(series);
assertEquals(expected, toList(cursor));
}
@Test
public void testUpdateSeries() {
// Create a series
HashSet<String> tags = new HashSet<String>();
tags.add("update");
Series series = new Series("update-series", "name", tags, new HashMap<String, String>());
Result<Series> result1 = client.createSeries(series);
// Update the series
series.getTags().add("update2");
Result<Series> result2 = client.updateSeries(series);
assertEquals(new Result<Series>(series, 200, "OK"), result2);
// Get the series
Result<Series> result3 = client.getSeries("update-series");
Result<Series> expected = new Result<Series>(series, 200, "OK");
assertEquals(expected, result3);
}
@Test
public void testDeleteSeries() {
// Create a series
HashSet<String> tags = new HashSet<String>();
tags.add("delete");
Series series = new Series("delete-series", "name", tags, new HashMap<String, String>());
Result<Series> result1 = client.createSeries(series);
// Delete the series
Result<Nothing> result2 = client.deleteSeries(series);
assertEquals(new Result<Nothing>(new Nothing(), 200, "OK"), result2);
// Get the series
Result<Series> result3 = client.getSeries("delete-series");
Result<Series> expected = new Result<Series>(null, 403, "Forbidden");
assertEquals(expected, result3);
}
@Test
public void testDeleteSeriesByFilter() {
// Create a series
HashSet<String> tags = new HashSet<String>();
tags.add("delete-filter");
Series series1 = new Series("delete-series", "name", tags, new HashMap<String, String>());
Series series2 = new Series("delete-series2", "name", new HashSet<String>(), new HashMap<String, String>());
Result<Series> result1 = client.createSeries(series1);
Result<Series> result2 = client.createSeries(series2);
// Get the series by filter
Filter filter = new Filter();
filter.addTag("delete-filter");
Cursor<Series> cursor = client.getSeries(filter);
List<Series> expected1 = Arrays.asList(series1);
assertEquals(expected1, toList(cursor));
// Delete the series by filter
Result<DeleteSummary> result3 = client.deleteSeries(filter);
assertEquals(new Result<DeleteSummary>(new DeleteSummary(1), 200, "OK"), result3);
// Get the series by filter again
Cursor<Series> cursor2 = client.getSeries(filter);
List<Series> expected2 = Arrays.asList();
assertEquals(expected2, toList(cursor2));
}
private <T> List<T> toList(Cursor<T> cursor) {
List<T> output = new ArrayList<T>();
for(T dp : cursor) {
output.add(dp);
}
return output;
}
} |
package org.postgresql.jdbc2;
import java.text.*;
import java.sql.*;
import java.util.*;
import java.math.BigDecimal;
import org.postgresql.Field;
import org.postgresql.util.*;
/*
* Array is used collect one column of query result data.
*
* <p>Read a field of type Array into either a natively-typed
* Java array object or a ResultSet. Accessor methods provide
* the ability to capture array slices.
*
* <p>Other than the constructor all methods are direct implementations
* of those specified for java.sql.Array. Please refer to the javadoc
* for java.sql.Array for detailed descriptions of the functionality
* and parameters of the methods of this class.
*
* @see ResultSet#getArray
*/
public class Array implements java.sql.Array
{
private org.postgresql.Connection conn = null;
private org.postgresql.Field field = null;
private org.postgresql.jdbc2.ResultSet rs = null;
private int idx = 0;
private String rawString = null;
/*
* Create a new Array
*
* @param conn a database connection
* @param idx 1-based index of the query field to load into this Array
* @param field the Field descriptor for the field to load into this Array
* @param rs the ResultSet from which to get the data for this Array
*/
public Array( org.postgresql.Connection conn, int idx, Field field, org.postgresql.jdbc2.ResultSet rs )
throws SQLException
{
this.conn = conn;
this.field = field;
this.rs = rs;
this.idx = idx;
this.rawString = rs.getFixedString(idx);
}
public Object getArray() throws SQLException
{
return getArray( 1, 0, null );
}
public Object getArray(long index, int count) throws SQLException
{
return getArray( index, count, null );
}
public Object getArray(Map map) throws SQLException
{
return getArray( 1, 0, map );
}
public Object getArray(long index, int count, Map map) throws SQLException
{
if ( map != null ) // For now maps aren't supported.
throw org.postgresql.Driver.notImplemented();
if (index < 1)
throw new PSQLException("postgresql.arr.range");
Object retVal = null;
ArrayList array = new ArrayList();
/* Check if the String is also not an empty array
* otherwise there will be an exception thrown below
* in the ResultSet.toX with an empty string.
* -- Doug Fields <dfields-pg-jdbc@pexicom.com> Feb 20, 2002 */
if ( rawString != null && !rawString.equals("{}") )
{
char[] chars = rawString.toCharArray();
StringBuffer sbuf = new StringBuffer();
boolean foundOpen = false;
boolean insideString = false;
for ( int i = 0; i < chars.length; i++ )
{
if ( chars[i] == '{' )
{
if ( foundOpen ) // Only supports 1-D arrays for now
throw org.postgresql.Driver.notImplemented();
foundOpen = true;
continue;
}
if ( chars[i] == '"' )
{
insideString = !insideString;
continue;
}
if ( (!insideString && chars[i] == ',') || chars[i] == '}' || i == chars.length - 1)
{
if ( chars[i] != '"' && chars[i] != '}' && chars[i] != ',' )
sbuf.append(chars[i]);
array.add( sbuf.toString() );
sbuf = new StringBuffer();
continue;
}
sbuf.append( chars[i] );
}
}
String[] arrayContents = (String[]) array.toArray( new String[array.size()] );
if ( count == 0 )
count = arrayContents.length;
index
if ( index + count > arrayContents.length )
throw new PSQLException("postgresql.arr.range");
int i = 0;
switch ( getBaseType() )
{
case Types.BIT:
retVal = new boolean[ count ];
for ( ; count > 0; count
((boolean[])retVal)[i++] = ResultSet.toBoolean( arrayContents[(int)index++] );
break;
case Types.SMALLINT:
case Types.INTEGER:
retVal = new int[ count ];
for ( ; count > 0; count
((int[])retVal)[i++] = ResultSet.toInt( arrayContents[(int)index++] );
break;
case Types.BIGINT:
retVal = new long[ count ];
for ( ; count > 0; count
((long[])retVal)[i++] = ResultSet.toLong( arrayContents[(int)index++] );
break;
case Types.NUMERIC:
retVal = new BigDecimal[ count ];
for ( ; count > 0; count
((BigDecimal[])retVal)[i++] = ResultSet.toBigDecimal( arrayContents[(int)index++], 0 );
break;
case Types.REAL:
retVal = new float[ count ];
for ( ; count > 0; count
((float[])retVal)[i++] = ResultSet.toFloat( arrayContents[(int)index++] );
break;
case Types.DOUBLE:
retVal = new double[ count ];
for ( ; count > 0; count
((double[])retVal)[i++] = ResultSet.toDouble( arrayContents[(int)index++] );
break;
case Types.CHAR:
case Types.VARCHAR:
retVal = new String[ count ];
for ( ; count > 0; count
((String[])retVal)[i++] = arrayContents[(int)index++];
break;
case Types.DATE:
retVal = new java.sql.Date[ count ];
for ( ; count > 0; count
((java.sql.Date[])retVal)[i++] = ResultSet.toDate( arrayContents[(int)index++] );
break;
case Types.TIME:
retVal = new java.sql.Time[ count ];
for ( ; count > 0; count
((java.sql.Time[])retVal)[i++] = ResultSet.toTime( arrayContents[(int)index++] );
break;
case Types.TIMESTAMP:
retVal = new Timestamp[ count ];
StringBuffer sbuf = null;
for ( ; count > 0; count
((java.sql.Timestamp[])retVal)[i++] = ResultSet.toTimestamp( arrayContents[(int)index++], rs );
break;
// Other datatypes not currently supported. If you are really using other types ask
// yourself if an array of non-trivial data types is really good database design.
default:
throw org.postgresql.Driver.notImplemented();
}
return retVal;
}
public int getBaseType() throws SQLException
{
return conn.getSQLType(getBaseTypeName());
}
public String getBaseTypeName() throws SQLException
{
String fType = field.getPGType();
if ( fType.charAt(0) == '_' )
fType = fType.substring(1);
return fType;
}
public java.sql.ResultSet getResultSet() throws SQLException
{
return getResultSet( 1, 0, null );
}
public java.sql.ResultSet getResultSet(long index, int count) throws SQLException
{
return getResultSet( index, count, null );
}
public java.sql.ResultSet getResultSet(Map map) throws SQLException
{
return getResultSet( 1, 0, map );
}
public java.sql.ResultSet getResultSet(long index, int count, java.util.Map map) throws SQLException
{
Object array = getArray( index, count, map );
Vector rows = new Vector();
Field[] fields = new Field[2];
fields[0] = new Field(conn, "INDEX", conn.getOID("int2"), 2);
switch ( getBaseType() )
{
case Types.BIT:
boolean[] booleanArray = (boolean[]) array;
fields[1] = new Field(conn, "VALUE", conn.getOID("bool"), 1);
for ( int i = 0; i < booleanArray.length; i++ )
{
byte[][] tuple = new byte[2][0];
tuple[0] = conn.getEncoding().encode( Integer.toString((int)index + i) ); // Index
tuple[1] = conn.getEncoding().encode( (booleanArray[i] ? "YES" : "NO") ); // Value
rows.addElement(tuple);
}
case Types.SMALLINT:
fields[1] = new Field(conn, "VALUE", conn.getOID("int2"), 2);
case Types.INTEGER:
int[] intArray = (int[]) array;
if ( fields[1] == null )
fields[1] = new Field(conn, "VALUE", conn.getOID("int4"), 4);
for ( int i = 0; i < intArray.length; i++ )
{
byte[][] tuple = new byte[2][0];
tuple[0] = conn.getEncoding().encode( Integer.toString((int)index + i) ); // Index
tuple[1] = conn.getEncoding().encode( Integer.toString(intArray[i]) ); // Value
rows.addElement(tuple);
}
break;
case Types.BIGINT:
long[] longArray = (long[]) array;
fields[1] = new Field(conn, "VALUE", conn.getOID("int8"), 8);
for ( int i = 0; i < longArray.length; i++ )
{
byte[][] tuple = new byte[2][0];
tuple[0] = conn.getEncoding().encode( Integer.toString((int)index + i) ); // Index
tuple[1] = conn.getEncoding().encode( Long.toString(longArray[i]) ); // Value
rows.addElement(tuple);
}
break;
case Types.NUMERIC:
BigDecimal[] bdArray = (BigDecimal[]) array;
fields[1] = new Field(conn, "VALUE", conn.getOID("numeric"), -1);
for ( int i = 0; i < bdArray.length; i++ )
{
byte[][] tuple = new byte[2][0];
tuple[0] = conn.getEncoding().encode( Integer.toString((int)index + i) ); // Index
tuple[1] = conn.getEncoding().encode( bdArray[i].toString() ); // Value
rows.addElement(tuple);
}
break;
case Types.REAL:
float[] floatArray = (float[]) array;
fields[1] = new Field(conn, "VALUE", conn.getOID("float4"), 4);
for ( int i = 0; i < floatArray.length; i++ )
{
byte[][] tuple = new byte[2][0];
tuple[0] = conn.getEncoding().encode( Integer.toString((int)index + i) ); // Index
tuple[1] = conn.getEncoding().encode( Float.toString(floatArray[i]) ); // Value
rows.addElement(tuple);
}
break;
case Types.DOUBLE:
double[] doubleArray = (double[]) array;
fields[1] = new Field(conn, "VALUE", conn.getOID("float8"), 8);
for ( int i = 0; i < doubleArray.length; i++ )
{
byte[][] tuple = new byte[2][0];
tuple[0] = conn.getEncoding().encode( Integer.toString((int)index + i) ); // Index
tuple[1] = conn.getEncoding().encode( Double.toString(doubleArray[i]) ); // Value
rows.addElement(tuple);
}
break;
case Types.CHAR:
fields[1] = new Field(conn, "VALUE", conn.getOID("char"), 1);
case Types.VARCHAR:
String[] strArray = (String[]) array;
if ( fields[1] == null )
fields[1] = new Field(conn, "VALUE", conn.getOID("varchar"), -1);
for ( int i = 0; i < strArray.length; i++ )
{
byte[][] tuple = new byte[2][0];
tuple[0] = conn.getEncoding().encode( Integer.toString((int)index + i) ); // Index
tuple[1] = conn.getEncoding().encode( strArray[i] ); // Value
rows.addElement(tuple);
}
break;
case Types.DATE:
java.sql.Date[] dateArray = (java.sql.Date[]) array;
fields[1] = new Field(conn, "VALUE", conn.getOID("date"), 4);
for ( int i = 0; i < dateArray.length; i++ )
{
byte[][] tuple = new byte[2][0];
tuple[0] = conn.getEncoding().encode( Integer.toString((int)index + i) ); // Index
tuple[1] = conn.getEncoding().encode( dateArray[i].toString() ); // Value
rows.addElement(tuple);
}
break;
case Types.TIME:
java.sql.Time[] timeArray = (java.sql.Time[]) array;
fields[1] = new Field(conn, "VALUE", conn.getOID("time"), 8);
for ( int i = 0; i < timeArray.length; i++ )
{
byte[][] tuple = new byte[2][0];
tuple[0] = conn.getEncoding().encode( Integer.toString((int)index + i) ); // Index
tuple[1] = conn.getEncoding().encode( timeArray[i].toString() ); // Value
rows.addElement(tuple);
}
break;
case Types.TIMESTAMP:
java.sql.Timestamp[] timestampArray = (java.sql.Timestamp[]) array;
fields[1] = new Field(conn, "VALUE", conn.getOID("timestamp"), 8);
for ( int i = 0; i < timestampArray.length; i++ )
{
byte[][] tuple = new byte[2][0];
tuple[0] = conn.getEncoding().encode( Integer.toString((int)index + i) ); // Index
tuple[1] = conn.getEncoding().encode( timestampArray[i].toString() ); // Value
rows.addElement(tuple);
}
break;
// Other datatypes not currently supported. If you are really using other types ask
// yourself if an array of non-trivial data types is really good database design.
default:
throw org.postgresql.Driver.notImplemented();
}
return new ResultSet((org.postgresql.jdbc2.Connection)conn, fields, rows, "OK", 1 );
}
public String toString()
{
return rawString;
}
} |
package it.feio.android.omninotes.utils;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import android.annotation.SuppressLint;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
public class FileHelper {
/**
* Get a file path from a Uri. This will get the the path for Storage Access
* Framework Documents, as well as the _data field for the MediaStore and
* other file-based ContentProviders.
*
* @param context
* The context.
* @param uri
* The Uri to query.
* @author paulburke
*/
@SuppressLint("NewApi")
public static String getPath(final Context context, final Uri uri) {
if (uri == null)
return null;
final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
// DocumentProvider
if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
// ExternalStorageProvider
if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
if ("primary".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/"
+ split[1];
}
// TODO handle non-primary volumes
}
// DownloadsProvider
else if (isDownloadsDocument(uri)) {
final String id = DocumentsContract.getDocumentId(uri);
final Uri contentUri = ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"),
Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
}
// MediaProvider
else if (isMediaDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
final String selection = "_id=?";
final String[] selectionArgs = new String[] { split[1] };
return getDataColumn(context, contentUri, selection,
selectionArgs);
}
}
// MediaStore (and general)
else if ("content".equalsIgnoreCase(uri.getScheme())) {
return getDataColumn(context, uri, null, null);
}
// File
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
/**
* Get the value of the data column for this Uri. This is useful for
* MediaStore Uris, and other file-based ContentProviders.
*
* @param context
* The context.
* @param uri
* The Uri to query.
* @param selection
* (Optional) Filter used in the query.
* @param selectionArgs
* (Optional) Selection arguments used in the query.
* @return The value of the _data column, which is typically a file path.
*/
public static String getDataColumn(Context context, Uri uri,
String selection, String[] selectionArgs) {
Cursor cursor = null;
final String column = "_data";
final String[] projection = { column };
try {
cursor = context.getContentResolver().query(uri, projection,
selection, selectionArgs, null);
if (cursor != null && cursor.moveToFirst()) {
final int column_index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(column_index);
}
} catch (Exception e) {
Log.e(Constants.TAG, "Error retrieving uri path", e);
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
/**
* @param uri
* The Uri to check.
* @return Whether the Uri authority is ExternalStorageProvider.
*/
public static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri
.getAuthority());
}
/**
* @param uri
* The Uri to check.
* @return Whether the Uri authority is DownloadsProvider.
*/
public static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri
.getAuthority());
}
/**
* @param uri
* The Uri to check.
* @return Whether the Uri authority is MediaProvider.
*/
public static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri
.getAuthority());
}
public static InputStream getInputStream(Context mContext, Uri mUri) {
InputStream inputStream;
try {
inputStream = mContext.getContentResolver().openInputStream(mUri);
inputStream.close();
return inputStream;
} catch (FileNotFoundException e) {
return null;
} catch (IOException e) {
return null;
}
}
// public static File getFileFromUri(Context mContext, Uri uri) {
// File f = null;
// try {
// InputStream is = mContext.getContentResolver().openInputStream(uri);
// f = getFileFromInputStream(mContext, is, getNameFromUri(mContext, uri));
// } catch (FileNotFoundException e) {
// Log.e(Constants.TAG, "Error creating InputStream", e);
// return f;
public static String getNameFromUri(Context mContext, Uri uri) {
String fileName = "";
// Trying to retrieve file name from content resolver
Cursor c = mContext.getContentResolver().query(uri, new String[]{"_display_name"}, null, null, null);
if (c != null) {
try {
if (c.moveToFirst()) {
fileName = c.getString(0);
}
} catch (Exception e) {}
} else {
fileName = uri.getLastPathSegment();
}
return fileName;
}
// public static File getFileFromInputStream(Context mContext, InputStream inputStream, String fileName) {
// File file = null;
// File f = null;
// try {
//// String name = !TextUtils.isEmpty(getFilePrefix(fileName)) ? getFilePrefix(fileName) : String
//// .valueOf(Calendar.getInstance().getTimeInMillis());
//// String extension = !TextUtils.isEmpty(getFileExtension(fileName)) ? getFileExtension(fileName) : "";
//// f = File.createTempFile(name, extension);
// f = new File(StorageManager.getCacheDir(mContext), fileName);
// f = StorageManager.createExternalStoragePrivateFile(mContext, uri, extension)
// f.deleteOnExit();
// } catch (IOException e1) {
// Log.e(Constants.TAG, "Error creating file from InputStream", e1);
// return file;
// OutputStream outputStream = null;
// try {
// outputStream = new FileOutputStream(f);
// int read = 0;
// byte[] bytes = new byte[1024];
// while ((read = inputStream.read(bytes)) != -1) {
// outputStream.write(bytes, 0, read);
// } catch (IOException e) {
// e.printStackTrace();
// } finally {
// if (inputStream != null) {
// try {
// inputStream.close();
// } catch (IOException e) {
// Log.e(Constants.TAG,
// "Error closing InputStream", e);
// if (outputStream != null) {
// try {
// // outputStream.flush();
// file = f;
// outputStream.close();
// } catch (IOException e) {
// Log.e(Constants.TAG,
// "Error closing OutputStream", e);
// return file;
public static String getFilePrefix(File file) {
return getFilePrefix(file.getName());
}
public static String getFilePrefix(String fileName) {
String prefix = fileName;
int index = fileName.indexOf(".");
if (index != -1) {
prefix = fileName.substring(0, index);
}
return prefix;
}
public static String getFileExtension(File file) {
return getFileExtension(file.getName());
}
public static String getFileExtension(String fileName) {
if (TextUtils.isEmpty(fileName)) return "";
String extension = "";
int index = fileName.lastIndexOf(".");
if (index != -1) {
extension = fileName.substring(index, fileName.length());
}
return extension;
}
} |
package org.apache.velocity.anakia;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.StringTokenizer;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.DirectoryScanner;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.MatchingTask;
import org.xml.sax.SAXParseException;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.apache.velocity.Template;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.util.StringUtils;
import org.apache.velocity.VelocityContext;
public class AnakiaTask extends MatchingTask
{
/** <code>{@link SAXBuilder}</code> instance to use */
private SAXBuilder builder;
/** the destination directory */
private File destDir = null;
/** the base directory */
private File baseDir = null;
/** the style= attribute */
private String style = null;
/** the File to the style file */
private File styleFile = null;
/** last modified of the style sheet */
private long styleSheetLastModified = 0;
/** the projectFile= attribute */
private String projectAttribute = null;
/** the File for the project.xml file */
private File projectFile = null;
/** last modified of the project file if it exists */
private long projectFileLastModified = 0;
/** check the last modified date on files. defaults to true */
private boolean lastModifiedCheck = true;
/** the default output extension is .html */
private String extension = ".html";
/** the template path */
private String templatePath = null;
/** the file to get the velocity properties file */
private File velocityPropertiesFile = null;
/** the VelocityEngine instance to use */
private VelocityEngine ve = new VelocityEngine();
/**
* Constructor creates the SAXBuilder.
*/
public AnakiaTask()
{
builder = new SAXBuilder();
builder.setFactory(new AnakiaJDOMFactory());
}
/**
* Set the base directory.
*/
public void setBasedir(File dir)
{
baseDir = dir;
}
/**
* Set the destination directory into which the VSL result
* files should be copied to
* @param dirName the name of the destination directory
*/
public void setDestdir(File dir)
{
destDir = dir;
}
/**
* Allow people to set the default output file extension
*/
public void setExtension(String extension)
{
this.extension = extension;
}
/**
* Allow people to set the path to the .vsl file
*/
public void setStyle(String style)
{
this.style = style;
}
/**
* Allow people to set the path to the project.xml file
*/
public void setProjectFile(String projectAttribute)
{
this.projectAttribute = projectAttribute;
}
/**
* Set the path to the templates.
* The way it works is this:
* If you have a Velocity.properties file defined, this method
* will <strong>override</strong> whatever is set in the
* Velocity.properties file. This allows one to not have to define
* a Velocity.properties file, therefore using Velocity's defaults
* only.
*/
public void setTemplatePath(File templatePath)
{
try
{
this.templatePath = templatePath.getCanonicalPath();
}
catch (java.io.IOException ioe)
{
throw new BuildException(ioe);
}
}
/**
* Allow people to set the path to the velocity.properties file
* This file is found relative to the path where the JVM was run.
* For example, if build.sh was executed in the ./build directory,
* then the path would be relative to this directory.
* This is optional based on the setting of setTemplatePath().
*/
public void setVelocityPropertiesFile(File velocityPropertiesFile)
{
this.velocityPropertiesFile = velocityPropertiesFile;
}
/**
* Turn on/off last modified checking. by default, it is on.
*/
public void setLastModifiedCheck(String lastmod)
{
if (lastmod.equalsIgnoreCase("false") || lastmod.equalsIgnoreCase("no")
|| lastmod.equalsIgnoreCase("off"))
{
this.lastModifiedCheck = false;
}
}
/**
* Main body of the application
*/
public void execute () throws BuildException
{
DirectoryScanner scanner;
String[] list;
String[] dirs;
if (baseDir == null)
{
baseDir = project.resolveFile(".");
}
if (destDir == null )
{
String msg = "destdir attribute must be set!";
throw new BuildException(msg);
}
if (style == null)
{
throw new BuildException("style attribute must be set!");
}
if (velocityPropertiesFile == null)
{
velocityPropertiesFile = new File("velocity.properties");
}
/*
* If the props file doesn't exist AND a templatePath hasn't
* been defined, then throw the exception.
*/
if ( !velocityPropertiesFile.exists() && templatePath == null )
{
throw new BuildException ("No template path and could not " +
"locate velocity.properties file: " +
velocityPropertiesFile.getAbsolutePath());
}
log("Transforming into: " + destDir.getAbsolutePath(), Project.MSG_INFO);
// projectFile relative to baseDir
if (projectAttribute != null && projectAttribute.length() > 0)
{
projectFile = new File(baseDir, projectAttribute);
if (projectFile.exists())
{
projectFileLastModified = projectFile.lastModified();
}
else
{
log ("Project file is defined, but could not be located: " +
projectFile.getAbsolutePath(), Project.MSG_INFO );
projectFile = null;
}
}
Document projectDocument = null;
try
{
if ( velocityPropertiesFile.exists() )
{
ve.init(velocityPropertiesFile.getAbsolutePath());
}
else if (templatePath != null && templatePath.length() > 0)
{
ve.setProperty( RuntimeConstants.FILE_RESOURCE_LOADER_PATH,
templatePath);
ve.init();
}
// get the last modification of the VSL stylesheet
styleSheetLastModified = ve.getTemplate( style ).getLastModified();
// Build the Project file document
if (projectFile != null)
{
projectDocument = builder.build(projectFile);
}
}
catch (Exception e)
{
log("Error: " + e.toString(), Project.MSG_INFO);
throw new BuildException(e);
}
// find the files/directories
scanner = getDirectoryScanner(baseDir);
// get a list of files to work on
list = scanner.getIncludedFiles();
for (int i = 0;i < list.length; ++i)
{
process( baseDir, list[i], destDir, projectDocument );
}
}
/**
* Process an XML file using Velocity
*/
private void process(File baseDir, String xmlFile, File destDir,
Document projectDocument)
throws BuildException
{
File outFile=null;
File inFile=null;
Writer writer = null;
try
{
// the current input file relative to the baseDir
inFile = new File(baseDir,xmlFile);
// the output file relative to basedir
outFile = new File(destDir,
xmlFile.substring(0,
xmlFile.lastIndexOf('.')) + extension);
// only process files that have changed
if (lastModifiedCheck == false ||
(inFile.lastModified() > outFile.lastModified() ||
styleSheetLastModified > outFile.lastModified() ||
projectFileLastModified > outFile.lastModified()))
{
ensureDirectoryFor( outFile );
//-- command line status
log("Input: " + xmlFile, Project.MSG_INFO );
// Build the JDOM Document
Document root = builder.build(inFile);
// Shove things into the Context
VelocityContext context = new VelocityContext();
/*
* get the property TEMPLATE_ENCODING
* we know it's a string...
*/
String encoding = (String) ve.getProperty( RuntimeConstants.OUTPUT_ENCODING );
if (encoding == null || encoding.length() == 0
|| encoding.equals("8859-1") || encoding.equals("8859_1"))
{
encoding = "ISO-8859-1";
}
OutputWrapper ow = new OutputWrapper();
ow.setEncoding (encoding);
context.put ("root", root.getRootElement());
context.put ("xmlout", ow );
context.put ("relativePath", getRelativePath(xmlFile));
context.put ("treeWalk", new TreeWalker());
context.put ("xpath", new XPathTool() );
context.put ("escape", new Escape() );
context.put ("date", new java.util.Date() );
// only put this into the context if it exists.
if (projectDocument != null)
{
context.put ("project", projectDocument.getRootElement());
}
// Process the VSL template with the context and write out
// the result as the outFile.
writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(outFile),
encoding));
// get the template to process
Template template = ve.getTemplate(style);
template.merge(context, writer);
log("Output: " + outFile, Project.MSG_INFO );
}
}
catch (JDOMException e)
{
if (outFile != null ) outFile.delete();
if (e.getRootCause() != null)
{
Throwable rootCause = e.getRootCause();
if (rootCause instanceof SAXParseException)
{
System.out.println("");
System.out.println("Error: " + rootCause.getMessage());
System.out.println(
" Line: " +
((SAXParseException)rootCause).getLineNumber() +
" Column: " +
((SAXParseException)rootCause).getColumnNumber());
System.out.println("");
}
else
{
rootCause.printStackTrace();
}
}
else
{
e.printStackTrace();
}
// log("Failed to process " + inFile, Project.MSG_INFO);
}
catch (Throwable e)
{
// log("Failed to process " + inFile, Project.MSG_INFO);
if (outFile != null)
{
outFile.delete();
}
e.printStackTrace();
}
finally
{
if (writer != null)
{
try
{
writer.flush();
writer.close();
}
catch (Exception e)
{
}
}
}
}
/**
* Hacky method to figure out the relative path
* that we are currently in. This is good for getting
* the relative path for images and anchor's.
*/
private String getRelativePath(String file)
{
if (file == null || file.length()==0)
return "";
StringTokenizer st = new StringTokenizer(file, "/\\");
// needs to be -1 cause ST returns 1 even if there are no matches. huh?
int slashCount = st.countTokens() - 1;
StringBuffer sb = new StringBuffer();
for (int i=0;i<slashCount ;i++ )
{
sb.append ("../");
}
if (sb.toString().length() > 0)
{
return StringUtils.chop(sb.toString(), 1);
}
else
{
return ".";
}
}
/**
* create directories as needed
*/
private void ensureDirectoryFor( File targetFile ) throws BuildException
{
File directory = new File( targetFile.getParent() );
if (!directory.exists())
{
if (!directory.mkdirs())
{
throw new BuildException("Unable to create directory: "
+ directory.getAbsolutePath() );
}
}
}
} |
package org.apache.velocity.context;
import java.util.HashMap;
import org.apache.velocity.runtime.RuntimeServices;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.directive.VMProxyArg;
import org.apache.velocity.util.introspection.IntrospectionCacheData;
import org.apache.velocity.runtime.resource.Resource;
import org.apache.velocity.app.event.EventCartridge;
/**
* This is a special, internal-use-only context implementation to be
* used for the new Velocimacro implementation.
*
* The main distinguishing feature is the management of the VMProxyArg objects
* in the put() and get() methods.
*
* Further, this context also supports the 'VM local context' mode, where
* any get() or put() of references that aren't args to the VM are considered
* local to the vm, protecting the global context.
*
* @author <a href="mailto:geirm@optonline.net">Geir Magnusson Jr.</a>
* @version $Id: VMContext.java,v 1.8 2001/08/07 22:21:51 geirm Exp $
*/
public class VMContext implements InternalContextAdapter
{
/** container for our VMProxy Objects */
HashMap vmproxyhash = new HashMap();
/** container for any local or constant VMProxy items */
HashMap localcontext = new HashMap();
/** the base context store. This is the 'global' context */
InternalContextAdapter innerContext = null;
/** context that we are wrapping */
InternalContextAdapter wrappedContext = null;
/** support for local context scope feature, where all references are local */
private boolean localcontextscope = true;
/**
* CTOR, wraps an ICA
*/
public VMContext( InternalContextAdapter inner, RuntimeServices rsvc )
{
localcontextscope = rsvc.getBoolean( RuntimeConstants.VM_CONTEXT_LOCALSCOPE, true );
wrappedContext = inner;
innerContext = inner.getBaseContext();
}
/**
* return the inner / user context
*/
public Context getInternalUserContext()
{
return innerContext.getInternalUserContext();
}
public InternalContextAdapter getBaseContext()
{
return innerContext.getBaseContext();
}
/**
* Used to put VMProxyArgs into this context. It separates
* the VMProxyArgs into constant and non-constant types
* pulling out the value of the constant types so they can
* be modified w/o damaging the VMProxyArg, and leaving the
* dynamic ones, as they modify context rather than their own
* state
* @param vmpa VMProxyArg to add
*/
public void addVMProxyArg( VMProxyArg vmpa )
{
/*
* ask if it's a constant : if so, get the value and put into the
* local context, otherwise, put the vmpa in our vmproxyhash
*/
String key = vmpa.getContextReference();
if ( vmpa.isConstant() )
{
localcontext.put( key, vmpa.getObject( wrappedContext ) );
}
else
{
vmproxyhash.put( key, vmpa );
}
}
/**
* Impl of the Context.put() method.
*
* @param key name of item to set
* @param value object to set to key
* @return old stored object
*/
public Object put(String key, Object value)
{
/*
* first see if this is a vmpa
*/
VMProxyArg vmpa = (VMProxyArg) vmproxyhash.get( key );
if( vmpa != null)
{
return vmpa.setObject( wrappedContext, value );
}
else
{
if(localcontextscope)
{
/*
* if we have localcontextscope mode, then just
* put in the local context
*/
return localcontext.put( key, value );
}
else
{
/*
* ok, how about the local context?
*/
if (localcontext.containsKey( key ))
{
return localcontext.put( key, value);
}
else
{
/*
* otherwise, let them push it into the 'global' context
*/
return innerContext.put( key, value );
}
}
}
}
/**
* Impl of the Context.gut() method.
*
* @param key name of item to get
* @return stored object or null
*/
public Object get( String key )
{
/*
* first, see if it's a VMPA
*/
Object o = null;
VMProxyArg vmpa = (VMProxyArg) vmproxyhash.get( key );
if( vmpa != null )
{
o = vmpa.getObject( wrappedContext );
}
else
{
if(localcontextscope)
{
/*
* if we have localcontextscope mode, then just
* put in the local context
*/
o = localcontext.get( key );
}
else
{
/*
* try the local context
*/
o = localcontext.get( key );
if ( o == null)
{
/*
* last chance
*/
o = innerContext.get( key );
}
}
}
return o;
}
/**
* not yet impl
*/
public boolean containsKey(Object key)
{
return false;
}
/**
* impl badly
*/
public Object[] getKeys()
{
return vmproxyhash.keySet().toArray();
}
/**
* impl badly
*/
public Object remove(Object key)
{
return vmproxyhash.remove( key );
}
public void pushCurrentTemplateName( String s )
{
innerContext.pushCurrentTemplateName( s );
}
public void popCurrentTemplateName()
{
innerContext.popCurrentTemplateName();
}
public String getCurrentTemplateName()
{
return innerContext.getCurrentTemplateName();
}
public Object[] getTemplateNameStack()
{
return innerContext.getTemplateNameStack();
}
public IntrospectionCacheData icacheGet( Object key )
{
return innerContext.icacheGet( key );
}
public void icachePut( Object key, IntrospectionCacheData o )
{
innerContext.icachePut( key, o );
}
public EventCartridge attachEventCartridge( EventCartridge ec )
{
return innerContext.attachEventCartridge( ec );
}
public EventCartridge getEventCartridge()
{
return innerContext.getEventCartridge();
}
public void setCurrentResource( Resource r )
{
innerContext.setCurrentResource( r );
}
public Resource getCurrentResource()
{
return innerContext.getCurrentResource();
}
} |
package org.jivesoftware;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.spark.ChatManager;
import org.jivesoftware.spark.SparkManager;
import org.jivesoftware.spark.UserManager;
import org.jivesoftware.spark.ui.ChatRoom;
import org.jivesoftware.spark.ui.conferences.ConferenceUtils;
import org.jivesoftware.spark.util.log.Log;
import org.jivesoftware.spark.util.StringUtils;
import org.jivesoftware.spark.util.Utilities;
/**
* Uses the Windows registry to perform URI XMPP mappings.
*
* @author Derek DeMoro
*/
public class SparkStartupListener implements com.install4j.api.launcher.StartupNotification.Listener {
public void startupPerformed(String string) {
if (string.indexOf("xmpp") == -1) {
return;
}
if (string.indexOf("?message") != -1) {
try {
handleJID(string);
}
catch (Exception e) {
Log.error(e);
}
}
else if (string.indexOf("?join") != -1) {
try {
handleConference(string);
}
catch (Exception e) {
Log.error(e);
}
}
else if (string.indexOf("?") == -1) {
// Then use the direct jid
int index = string.indexOf(":");
if (index != -1) {
String jid = string.substring(index + 1);
UserManager userManager = SparkManager.getUserManager();
String nickname = userManager.getUserNicknameFromJID(jid);
if (nickname == null) {
nickname = jid;
}
ChatManager chatManager = SparkManager.getChatManager();
ChatRoom chatRoom = chatManager.createChatRoom(jid, nickname, nickname);
chatManager.getChatContainer().activateChatRoom(chatRoom);
}
}
}
/**
* Factory method to handle different types of URI Mappings.
*
* @param uriMapping the uri mapping string.
* @throws Exception thrown if an exception occurs.
*/
public void handleJID(String uriMapping) throws Exception {
int index = uriMapping.indexOf("xmpp:");
int messageIndex = uriMapping.indexOf("?message");
int bodyIndex = uriMapping.indexOf("body=");
String jid = uriMapping.substring(index + 5, messageIndex);
String body = null;
// Find body
if (bodyIndex != -1) {
body = uriMapping.substring(bodyIndex + 5);
}
body = StringUtils.unescapeFromXML(body);
body = StringUtils.replace(body, "%20", " ");
UserManager userManager = SparkManager.getUserManager();
String nickname = userManager.getUserNicknameFromJID(jid);
if (nickname == null) {
nickname = jid;
}
ChatManager chatManager = SparkManager.getChatManager();
ChatRoom chatRoom = chatManager.createChatRoom(jid, nickname, nickname);
if (body != null) {
Message message = new Message();
message.setBody(body);
chatRoom.sendMessage(message);
}
chatManager.getChatContainer().activateChatRoom(chatRoom);
}
/**
* Handles the URI Mapping to join a conference room.
*
* @param uriMapping the uri mapping.
* @throws Exception thrown if the conference cannot be joined.
*/
public void handleConference(String uriMapping) throws Exception {
int index = uriMapping.indexOf("xmpp:");
int join = uriMapping.indexOf("?join");
String conference = uriMapping.substring(index + 5, join);
ConferenceUtils.autoJoinConferenceRoom(conference, conference, null);
}
public static void main(String args[]){
SparkStartupListener l = new SparkStartupListener();
l.startupPerformed("xmpp:jorge@jivesoftware.com?message;body=hello%20there");
}
} |
/* Generated By:JavaCC: Do not edit this line. ExpressionParser.java */
package org.relique.jdbc.csv;
import java.sql.Date;
import java.sql.Time;
import java.sql.Timestamp;
import java.math.BigInteger;
import java.math.BigDecimal;
import java.math.MathContext;
import java.util.Map;
import java.util.HashMap;
import java.util.List;
import java.util.LinkedList;
import org.relique.jdbc.csv.Expression;
class NumericConstant extends Expression{
Number value;
public NumericConstant(Number d){
value = d;
}
public Object eval(Map env){
return value;
}
public String toString(){
return value.toString();
}
public List usedColumns(){
return new LinkedList();
}
}
class StringConstant extends Expression{
String value;
public StringConstant(String s){
value = s;
}
public Object eval(Map env){
return value;
}
public String toString(){
return "'"+value+"'";
}
public List usedColumns(){
return new LinkedList();
}
}
class Placeholder extends Expression{
static int nextIndex = 1;
Integer index;
public Placeholder(){
index = Integer.valueOf(nextIndex);
nextIndex++;
}
public Object eval(Map env){
return env.get(index);
}
public String toString(){
return "?";
}
public List usedColumns(){
return new LinkedList();
}
}
class ColumnName extends Expression{
String columnName;
public ColumnName(String columnName){
this .columnName = columnName.toUpperCase();
}
public Object eval(Map env){
return env.get(columnName);
}
public String toString(){
return "["+columnName+"]";
}
public List usedColumns(){
List result = new LinkedList();
result.add(columnName);
return result;
}
}
class QueryEnvEntry extends Expression{
String key;
Expression expression;
public QueryEnvEntry(String fieldName){
this .key = fieldName.toUpperCase();
this .expression = new ColumnName(fieldName);
}
public QueryEnvEntry(String fieldName, Expression exp){
this .key = fieldName.toUpperCase();
this .expression = exp;
}
public Object eval(Map env){
return expression.eval(env);
}
public String toString(){
return key+": "+expression.toString();
}
}
class BinaryOperation extends Expression{
char op;
Expression left, right;
public BinaryOperation(char op, Expression left, Expression right){
this .op = op;
this .left = left;
this .right = right;
}
public Object eval(Map env){
Object leftEval = left.eval(env);
Object rightEval = right.eval(env);
try {
Integer leftInt = (Integer)leftEval;
BigInteger bil = new BigInteger(leftInt.toString());
Integer rightInt = (Integer)rightEval;
BigInteger bir = new BigInteger(rightInt.toString());
if (op == '+')return new Integer(bil.add(bir).toString());
if (op == '-')return new Integer(bil.subtract(bir).toString());
if (op == '*')return new Integer(bil.multiply(bir).toString());
if (op == '/')return new Integer(bil.divide(bir).toString());
}
catch (ClassCastException e){}try {
Number leftN = (Number)leftEval;
BigDecimal bdl = new BigDecimal(leftN.toString());
Number rightN = (Number)rightEval;
BigDecimal bdr = new BigDecimal(rightN.toString());
if (op == '+')return new Double(bdl.add(bdr).toString());
if (op == '-')return new Double(bdl.subtract(bdr).toString());
if (op == '*')return new Double(bdl.multiply(bdr).toString());
MathContext mc = new MathContext("precision=14 roundingMode=HALF_UP");
if (op == '/')return new Double(bdl.divide(bdr, mc.getPrecision(), mc.getRoundingMode()).toString());
}
catch (ClassCastException e){}try {
if (op == '+'){
Date leftD = (Date)leftEval;
Time rightT = (Time)rightEval;
Expression stringConverter = new ColumnName("@StringConverter");
StringConverter sc = (StringConverter) stringConverter.eval(env);
return sc.parseTimestamp(leftD.toString() + " " + rightT.toString());
}
}
catch (ClassCastException e){}try {
if (op == '+' || op == '-'){
Timestamp leftD = (Timestamp)leftEval;
long time = leftD.getTime();
Number rightN = (Number)rightEval;
BigDecimal bdr = new BigDecimal(rightN.toString());
if (op == '+')return new Timestamp(time + bdr.longValue());
if (op == '-')return new Timestamp(time - bdr.longValue());
}
}
catch (ClassCastException e){}
if(op == '+')return ""+leftEval+rightEval;
return null;
}
public String toString(){
return ""+op+" "+left+" "+right;
}
public List usedColumns(){
List result = new LinkedList();
result.addAll(left.usedColumns());
result.addAll(right.usedColumns());
return result;
}
}
abstract class LogicalExpression extends Expression{
public boolean isTrue(Map env){
return false;
}
}
class ParsedExpression extends LogicalExpression{
public Expression content;
public ParsedExpression(Expression left){
content = left;
}
public boolean isTrue(Map env){
return ((LogicalExpression)content).isTrue(env);
}
public Object eval(Map env){
return content.eval(env);
}
public String toString(){
return content.toString();
}
public List usedColumns(){
return content.usedColumns();
}
}
class NotExpression extends LogicalExpression{
LogicalExpression content;
public NotExpression(LogicalExpression arg){
this .content = arg;
}
public boolean isTrue(Map env){
return !content.isTrue(env);
}
public String toString(){
return "NOT "+content;
}
public List usedColumns(){
return content.usedColumns();
}
}
class OrExpression extends LogicalExpression{
LogicalExpression left, right;
public OrExpression(LogicalExpression left, LogicalExpression right){
this .left = left;
this .right = right;
}
public boolean isTrue(Map env){
return left.isTrue(env) || right.isTrue(env);
}
public String toString(){
return "OR "+left+" "+right;
}
public List usedColumns(){
List result = new LinkedList();
result.addAll(left.usedColumns());
result.addAll(right.usedColumns());
return result;
}
}
class AndExpression extends LogicalExpression{
LogicalExpression left, right;
public AndExpression(LogicalExpression left, LogicalExpression right){
this .left = left;
this .right = right;
}
public boolean isTrue(Map env){
return left.isTrue(env) && right.isTrue(env);
}
public String toString(){
return "AND "+left+" "+right;
}
public List usedColumns(){
List result = new LinkedList();
result.addAll(left.usedColumns());
result.addAll(right.usedColumns());
return result;
}
}
class RelopExpression extends LogicalExpression{
String op;
Expression left, right;
public RelopExpression(String op, Expression left, Expression right){
this .op = op;
this .left = left;
this .right = right;
}
public boolean isTrue(Map env){
Comparable leftValue = (Comparable)left.eval(env);
Comparable rightValue = (Comparable)right.eval(env);
boolean result = false;
Integer leftComparedToRightObj = null;
try {
leftComparedToRightObj = new Integer(leftValue.compareTo(rightValue));
}
catch (ClassCastException e){}try {
Double leftDouble = new Double(((Number)leftValue).toString());
Double rightDouble = new Double(((Number)rightValue).toString());
leftComparedToRightObj = new Integer(leftDouble.compareTo(rightDouble));
}
catch (ClassCastException e){}catch (NumberFormatException e){}if (leftComparedToRightObj != null){
int leftComparedToRight = leftComparedToRightObj.intValue();
if (leftValue != null && rightValue != null){
if (op.equals("=")){
result = leftComparedToRight == 0;
}
else if (op.equals("<>") || op.equals("!=")){
result = leftComparedToRight != 0;
}
else if (op.equals(">")){
result = leftComparedToRight>0;
}
else if (op.equals("<")){
result = leftComparedToRight<0;
}
else if (op.equals("<=") || op.equals("=<")){
result = leftComparedToRight <= 0;
}
else if (op.equals(">=") || op.equals("=>")){
result = leftComparedToRight >= 0;
}
}
}
return result;
}
public String toString(){
return op+" "+left+" "+right;
}
public List usedColumns(){
List result = new LinkedList();
result.addAll(left.usedColumns());
result.addAll(right.usedColumns());
return result;
}
}
class BetweenExpression extends LogicalExpression{
Expression obj, left, right;
public BetweenExpression(Expression obj, Expression left, Expression right){
this .obj = obj;
this .left = left;
this .right = right;
}
public boolean isTrue(Map env){
Comparable leftValue = (Comparable)left.eval(env);
Comparable rightValue = (Comparable)right.eval(env);
Comparable objValue = (Comparable)obj.eval(env);
boolean result = true;
try {
if (objValue.compareTo(leftValue)<0)result = false;
if (objValue.compareTo(rightValue)>0)result = false;
}
catch (ClassCastException e){}return result;
}
public String toString(){
return "B "+obj+" "+left+" "+right;
}
public List usedColumns(){
List result = new LinkedList();
result.addAll(obj.usedColumns());
result.addAll(left.usedColumns());
result.addAll(right.usedColumns());
return result;
}
}
class IsNullExpression extends LogicalExpression{
Expression arg;
public IsNullExpression(Expression arg){
this .arg = arg;
}
public boolean isTrue(Map env){
Object o = arg.eval(env);
return (o == null);
}
public String toString(){
return "N "+arg;
}
public List usedColumns(){
List result = new LinkedList();
result.addAll(arg.usedColumns());
return result;
}
}
class LikeExpression extends LogicalExpression{
Expression arg1, arg2;
public LikeExpression(Expression arg1, Expression arg2){
this .arg1 = arg1;
this .arg2 = arg2;
}
public boolean isTrue(Map env){
Object left = arg1.eval(env);
Object right = arg2.eval(env);
boolean result = false;
if (left != null && right != null)
result = LikePattern.matches(right.toString(), left.toString());
return result;
}
public String toString(){
return "L "+arg1+" "+arg2;
}
public List usedColumns(){
List result = new LinkedList();
result.addAll(arg1.usedColumns());
result.addAll(arg2.usedColumns());
return result;
}
}
public class ExpressionParser implements ExpressionParserConstants {
ParsedExpression content;
private Map placeholders;
public void parseLogicalExpression()throws ParseException{
Placeholder.nextIndex = 1;
placeholders = new HashMap();
content = logicalExpression();
}
public void parseQueryEnvEntry()throws ParseException{
content = queryEnvEntry();
}
public boolean isTrue(Map env){
if(placeholders != null) {
Map useThisEnv = new HashMap();
useThisEnv.putAll(env);
useThisEnv.putAll(placeholders);
env = useThisEnv;
}
return content.isTrue(env);
}
public Object eval(Map env){
if(placeholders != null) {
Map useThisEnv = new HashMap();
useThisEnv.putAll(env);
useThisEnv.putAll(placeholders);
env = useThisEnv;
}
return content.eval(env);
}
public String toString(){
return ""+content;
}
public List usedColumns(){
return content.usedColumns();
}
public int getPlaceholdersCount(){
return Placeholder.nextIndex - 1;
}
public void setPlaceholdersValues(Object[] values){
for(int i=1; i<values.length; i++){
placeholders.put(Integer.valueOf(i), values[i]);
}
}
final public ParsedExpression logicalExpression() throws ParseException {
LogicalExpression left;
left = logicalOrExpression();
jj_consume_token(0);
{if (true) return new ParsedExpression(left);}
throw new Error("Missing return statement in function");
}
final public ParsedExpression queryEnvEntry() throws ParseException {
Expression expression, alias, result;
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case UNSIGNEDNUMBER:
case NULL:
case PLACEHOLDER:
case NAME:
case STRING:
case MINUS:
result = null;
expression = binaryOperation();
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case AS:
case NAME:
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case AS:
jj_consume_token(AS);
break;
default:
jj_la1[0] = jj_gen;
;
}
alias = columnName();
result = new QueryEnvEntry(((ColumnName)alias).columnName, expression);
break;
default:
jj_la1[1] = jj_gen;
;
}
jj_consume_token(0);
if (result == null){
try {
result = new QueryEnvEntry(((ColumnName)expression).columnName, expression);
}
catch (ClassCastException e){
{if (true) throw new ParseException("can't accept expression '"+expression+"' without an alias");}
}
}
{if (true) return new ParsedExpression(result);}
break;
case ASTERISK:
jj_consume_token(ASTERISK);
{if (true) return null;}
break;
default:
jj_la1[2] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
throw new Error("Missing return statement in function");
}
final public LogicalExpression logicalOrExpression() throws ParseException {
LogicalExpression left, right;
left = logicalAndExpression();
label_1:
while (true) {
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case OR:
;
break;
default:
jj_la1[3] = jj_gen;
break label_1;
}
jj_consume_token(OR);
right = logicalAndExpression();
left = new OrExpression(left, right);
}
{if (true) return left;}
throw new Error("Missing return statement in function");
}
final public LogicalExpression logicalAndExpression() throws ParseException {
LogicalExpression left, right;
left = logicalUnaryExpression();
label_2:
while (true) {
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case AND:
;
break;
default:
jj_la1[4] = jj_gen;
break label_2;
}
jj_consume_token(AND);
right = logicalUnaryExpression();
left = new AndExpression(left, right);
}
{if (true) return left;}
throw new Error("Missing return statement in function");
}
final public LogicalExpression logicalUnaryExpression() throws ParseException {
LogicalExpression arg;
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case NOT:
jj_consume_token(NOT);
arg = logicalUnaryExpression();
{if (true) return new NotExpression(arg);}
break;
case 21:
jj_consume_token(21);
arg = logicalOrExpression();
jj_consume_token(22);
{if (true) return arg;}
break;
case UNSIGNEDNUMBER:
case NULL:
case PLACEHOLDER:
case NAME:
case STRING:
case MINUS:
arg = relationalExpression();
{if (true) return arg;}
break;
default:
jj_la1[5] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
throw new Error("Missing return statement in function");
}
final public LogicalExpression relationalExpression() throws ParseException {
Expression arg1, arg2, arg3;
String op;
Token t;
arg1 = simpleExpression();
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case RELOP:
op = relOp();
arg2 = simpleExpression();
{if (true) return new RelopExpression(op, arg1, arg2);}
break;
case BETWEEN:
jj_consume_token(BETWEEN);
arg2 = simpleExpression();
jj_consume_token(AND);
arg3 = simpleExpression();
{if (true) return new BetweenExpression(arg1, arg2, arg3);}
break;
case IS:
jj_consume_token(IS);
jj_consume_token(NULL);
{if (true) return new IsNullExpression(arg1);}
break;
case LIKE:
jj_consume_token(LIKE);
t = jj_consume_token(STRING);
{if (true) return new LikeExpression(arg1, new StringConstant(t.image.substring(1, t.image.length()-1)));}
break;
default:
jj_la1[6] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
throw new Error("Missing return statement in function");
}
final public String relOp() throws ParseException {
Token t;
t = jj_consume_token(RELOP);
{if (true) return new String(t.image);}
throw new Error("Missing return statement in function");
}
final public char binOp() throws ParseException {
Token t;
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case BINOP:
t = jj_consume_token(BINOP);
break;
case ASTERISK:
t = jj_consume_token(ASTERISK);
break;
case MINUS:
t = jj_consume_token(MINUS);
break;
default:
jj_la1[7] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
{if (true) return t.image.charAt(0);}
throw new Error("Missing return statement in function");
}
final public Expression binaryOperation() throws ParseException {
Expression left, right;
char op;
left = simpleExpression();
label_3:
while (true) {
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case ASTERISK:
case MINUS:
case BINOP:
;
break;
default:
jj_la1[8] = jj_gen;
break label_3;
}
op = binOp();
right = simpleExpression();
left = new BinaryOperation(op, left, right);
}
{if (true) return left;}
throw new Error("Missing return statement in function");
}
final public Expression simpleExpression() throws ParseException {
Expression arg;
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case NAME:
arg = columnName();
{if (true) return arg;}
break;
case UNSIGNEDNUMBER:
case MINUS:
arg = numericConstant();
{if (true) return arg;}
break;
case STRING:
arg = stringConstant();
{if (true) return arg;}
break;
case NULL:
jj_consume_token(NULL);
{if (true) return null;}
break;
case PLACEHOLDER:
jj_consume_token(PLACEHOLDER);
{if (true) return new Placeholder();}
break;
default:
jj_la1[9] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
throw new Error("Missing return statement in function");
}
final public Expression columnName() throws ParseException {
Token t;
t = jj_consume_token(NAME);
{if (true) return new ColumnName(t.image);}
throw new Error("Missing return statement in function");
}
final public Expression numericConstant() throws ParseException {
Token t;
String sign;
sign="";
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case MINUS:
t = jj_consume_token(MINUS);
sign=t.image;
break;
default:
jj_la1[10] = jj_gen;
;
}
t = jj_consume_token(UNSIGNEDNUMBER);
Number value = null;
try {
value = new Integer(sign+t.image);
}
catch (NumberFormatException e){
value = new Double(sign+t.image);
}
{if (true) return new NumericConstant(value);}
throw new Error("Missing return statement in function");
}
final public Expression stringConstant() throws ParseException {
String left, right;
left = stringConstantAtom();
label_4:
while (true) {
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case STRING:
;
break;
default:
jj_la1[11] = jj_gen;
break label_4;
}
right = stringConstantAtom();
left = left+"'"+right;
}
{if (true) return new StringConstant(left);}
throw new Error("Missing return statement in function");
}
final public String stringConstantAtom() throws ParseException {
Token t;
t = jj_consume_token(STRING);
{if (true) return t.image.substring(1, t.image.length()-1);}
throw new Error("Missing return statement in function");
}
/** Generated Token Manager. */
public ExpressionParserTokenManager token_source;
SimpleCharStream jj_input_stream;
/** Current token. */
public Token token;
/** Next token. */
public Token jj_nt;
private int jj_ntk;
private int jj_gen;
final private int[] jj_la1 = new int[12];
static private int[] jj_la1_0;
static {
jj_la1_init_0();
}
private static void jj_la1_init_0() {
jj_la1_0 = new int[] {0x800,0x8800,0xdc050,0x100,0x80,0x29c250,0x23400,0x1c0000,0x1c0000,0x9c050,0x80000,0x10000,};
}
/** Constructor with InputStream. */
public ExpressionParser(java.io.InputStream stream) {
this(stream, null);
}
/** Constructor with InputStream and supplied encoding */
public ExpressionParser(java.io.InputStream stream, String encoding) {
try { jj_input_stream = new SimpleCharStream(stream, encoding, 1, 1); } catch(java.io.UnsupportedEncodingException e) { throw new RuntimeException(e.getMessage()); }
token_source = new ExpressionParserTokenManager(jj_input_stream);
token = new Token();
jj_ntk = -1;
jj_gen = 0;
for (int i = 0; i < 12; i++) jj_la1[i] = -1;
}
/** Reinitialise. */
public void ReInit(java.io.InputStream stream) {
ReInit(stream, null);
}
/** Reinitialise. */
public void ReInit(java.io.InputStream stream, String encoding) {
try { jj_input_stream.ReInit(stream, encoding, 1, 1); } catch(java.io.UnsupportedEncodingException e) { throw new RuntimeException(e.getMessage()); }
token_source.ReInit(jj_input_stream);
token = new Token();
jj_ntk = -1;
jj_gen = 0;
for (int i = 0; i < 12; i++) jj_la1[i] = -1;
}
/** Constructor. */
public ExpressionParser(java.io.Reader stream) {
jj_input_stream = new SimpleCharStream(stream, 1, 1);
token_source = new ExpressionParserTokenManager(jj_input_stream);
token = new Token();
jj_ntk = -1;
jj_gen = 0;
for (int i = 0; i < 12; i++) jj_la1[i] = -1;
}
/** Reinitialise. */
public void ReInit(java.io.Reader stream) {
jj_input_stream.ReInit(stream, 1, 1);
token_source.ReInit(jj_input_stream);
token = new Token();
jj_ntk = -1;
jj_gen = 0;
for (int i = 0; i < 12; i++) jj_la1[i] = -1;
}
/** Constructor with generated Token Manager. */
public ExpressionParser(ExpressionParserTokenManager tm) {
token_source = tm;
token = new Token();
jj_ntk = -1;
jj_gen = 0;
for (int i = 0; i < 12; i++) jj_la1[i] = -1;
}
/** Reinitialise. */
public void ReInit(ExpressionParserTokenManager tm) {
token_source = tm;
token = new Token();
jj_ntk = -1;
jj_gen = 0;
for (int i = 0; i < 12; i++) jj_la1[i] = -1;
}
private Token jj_consume_token(int kind) throws ParseException {
Token oldToken;
if ((oldToken = token).next != null) token = token.next;
else token = token.next = token_source.getNextToken();
jj_ntk = -1;
if (token.kind == kind) {
jj_gen++;
return token;
}
token = oldToken;
jj_kind = kind;
throw generateParseException();
}
/** Get the next Token. */
final public Token getNextToken() {
if (token.next != null) token = token.next;
else token = token.next = token_source.getNextToken();
jj_ntk = -1;
jj_gen++;
return token;
}
/** Get the specific Token. */
final public Token getToken(int index) {
Token t = token;
for (int i = 0; i < index; i++) {
if (t.next != null) t = t.next;
else t = t.next = token_source.getNextToken();
}
return t;
}
private int jj_ntk() {
if ((jj_nt=token.next) == null)
return (jj_ntk = (token.next=token_source.getNextToken()).kind);
else
return (jj_ntk = jj_nt.kind);
}
private java.util.List jj_expentries = new java.util.ArrayList();
private int[] jj_expentry;
private int jj_kind = -1;
/** Generate ParseException. */
public ParseException generateParseException() {
jj_expentries.clear();
boolean[] la1tokens = new boolean[23];
if (jj_kind >= 0) {
la1tokens[jj_kind] = true;
jj_kind = -1;
}
for (int i = 0; i < 12; i++) {
if (jj_la1[i] == jj_gen) {
for (int j = 0; j < 32; j++) {
if ((jj_la1_0[i] & (1<<j)) != 0) {
la1tokens[j] = true;
}
}
}
}
for (int i = 0; i < 23; i++) {
if (la1tokens[i]) {
jj_expentry = new int[1];
jj_expentry[0] = i;
jj_expentries.add(jj_expentry);
}
}
int[][] exptokseq = new int[jj_expentries.size()][];
for (int i = 0; i < jj_expentries.size(); i++) {
exptokseq[i] = (int[])jj_expentries.get(i);
}
return new ParseException(token, exptokseq, tokenImage);
}
/** Enable tracing. */
final public void enable_tracing() {
}
/** Disable tracing. */
final public void disable_tracing() {
}
} |
package jsettlers.logic.algorithms.queue;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import jsettlers.common.map.shapes.MapCircle;
import jsettlers.common.position.ILocatable;
import jsettlers.common.position.ISPosition2D;
/**
* This is a queue that lets you define different slots. In each slot, the entries are processed in a fifo-principle, but it is not guaranteed that
* the first job is handled first, but it gets higher priority.
* <p>
* This queue is not thread safe.
*
* @param T
* the type of the slot identifiers. Should support equals
* @param E
* the type of elements in the queue.
* @author michael
*/
public class SlotQueue<T, E extends ILocatable> implements Serializable {
private static final long serialVersionUID = -5567867841476892036L;
private static final int ELEMENTS_TO_LOOK_AT = 15;
private static final int CONSIDER_MAX = 3; // < should be small
private T[] slotTypes;
private int[] slotPriority;
/**
* The head of the fifo queues
*/
private ElementHolder<E>[] slots;
/**
* The tail of the fifo queues
*/
private ElementHolder<E>[] tails;
private int[] count;
/**
* The permutation of the slots so that they are ordered by priority.
*/
private int[] slotOrder;
private void writeObject(ObjectOutputStream oos) throws IOException {
oos.writeObject(slotTypes);
oos.writeObject(slotPriority);
oos.writeObject(count);
oos.writeObject(slotOrder);
for (int i = 0; i < slotTypes.length; i++) {
ElementHolder<E> curr = slots[i];
while (curr != null) {
oos.writeObject(curr);
curr = curr.next;
}
oos.writeObject(null);
}
for (int i = 0; i < slotTypes.length; i++) {
ElementHolder<E> curr = tails[i];
while (curr != null) {
oos.writeObject(curr);
curr = curr.next;
}
oos.writeObject(null);
}
}
@SuppressWarnings("unchecked")
private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
slotTypes = (T[]) ois.readObject();
slotPriority = (int[]) ois.readObject();
count = (int[]) ois.readObject();
slotOrder = (int[]) ois.readObject();
slots = new ElementHolder[slotTypes.length];
for (int i = 0; i < slotTypes.length; i++) {
ElementHolder<E> curr = (ElementHolder<E>) ois.readObject();
slots[i] = curr;
ElementHolder<E> last = curr;
while (last != null) {
curr = (ElementHolder<E>) ois.readObject();
last.next = curr;
last = curr;
}
}
tails = new ElementHolder[slotTypes.length];
for (int i = 0; i < slotTypes.length; i++) {
ElementHolder<E> curr = (ElementHolder<E>) ois.readObject();
tails[i] = curr;
ElementHolder<E> last = curr;
while (last != null) {
curr = (ElementHolder<E>) ois.readObject();
last.next = curr;
last = curr;
}
}
}
@SuppressWarnings("unchecked")
public SlotQueue(T[] slottypes, int[] slotpriority) {
int slotCount = slotpriority.length;
if (slotCount != slottypes.length) {
throw new IllegalArgumentException();
}
this.slotTypes = slottypes;
this.slotPriority = slotpriority;
this.slots = new ElementHolder[slotCount];
this.tails = new ElementHolder[slotCount];
this.count = new int[slotCount];
this.slotOrder = new int[slotCount];
for (int i = 0; i < slotCount; i++) {
slotOrder[i] = i;
}
reorderSlots();
}
private void reorderSlots() {
int slotCount = slotOrder.length;
for (int i = 0; i < slotCount; i++) {
for (int j = i; j < slotCount; j++) {
if (slotPriority[slotOrder[i]] < slotPriority[slotOrder[j]]) {
int temp = slotOrder[i];
slotOrder[i] = slotOrder[j];
slotOrder[j] = temp;
}
}
}
}
/**
* Adds the element to the queue, if the given slot exists (otherwise: does nothing)
*
* @param slottype
* The slot to use
* @param element
* The element to add
*/
public void add(T slot, E element) {
ElementHolder<E> elementHolder = new ElementHolder<E>(element);
for (int i = 0; i < slots.length; i++) {
if (slotTypes[i].equals(slot)) {
if (tails[i] == null) {
slots[i] = elementHolder;
tails[i] = elementHolder;
} else {
tails[i].next = elementHolder;
tails[i] = elementHolder;
}
count[i]++;
break;
}
}
}
/**
* Pops a element from a specific slot.
*
* @param slot
* The slot to use
* @param pos
* The position to pop close to.
*/
public E pop(T slot, ISPosition2D pos) {
for (int slotNumber = 0; slotNumber < slots.length; slotNumber++) {
if (slotTypes[slotNumber].equals(slot)) {
return pop(pos, slotNumber);
}
}
return null;
}
private E pop(ISPosition2D pos, int slotNumber) {
if (slots[slotNumber] == null) {
return null;
} else {
ElementHolder<E> best = findBestFit(pos, slotNumber);
// remove best from the array.
removeFromSlot(slotNumber, best);
E e = best.element;
return e;
}
}
private ElementHolder<E> findBestFit(ISPosition2D pos, int slotNumber) {
ElementHolder<E> best = slots[slotNumber];
float bestDist = Float.POSITIVE_INFINITY;
ElementHolder<E> current = slots[slotNumber];
for (int cost = 0; cost < ELEMENTS_TO_LOOK_AT && current != null; cost++) {
float dist = MapCircle.getDistanceSquared(current.element.getPos(), pos);
if (dist < bestDist) {
best = current;
bestDist = dist;
}
cost += current.skipcost;
current = current.next;
}
return best;
}
/**
* Removes a element from a slot, rates the skip cost of all elements to skip up. Decreases the count for the slot by one.
*
* @param slotNumber
* @param toRemove
*/
private void removeFromSlot(int slotNumber, ElementHolder<E> toRemove) {
ElementHolder<E> current;
if (toRemove == slots[slotNumber]) {
slots[slotNumber] = toRemove.next;
if (slots[slotNumber] == null) {
tails[slotNumber] = null;
}
} else {
for (current = slots[slotNumber]; true /* uses break */; current = current.next) {
if (current.next == toRemove) {
current.next = toRemove.next;
if (toRemove.next == null) {
tails[slotNumber] = current;
}
break;
} else {
current.skipcost++;
}
}
}
count[slotNumber]
}
/**
* Pops a element. The position is taken into account when rating the possible pop slots.
*
* @param closeTo
* @return
*/
public E pop(ISPosition2D closeTo) {
float bestDistance = Float.POSITIVE_INFINITY;
ElementHolder<E> best = null;
int bestSlot = 0;
for (int i = 0, considered = 0; i < slotOrder.length && considered < CONSIDER_MAX; i++) {
int slotNumber = slotOrder[i];
ElementHolder<E> myBest = findBestFit(closeTo, slotNumber);
if (myBest != null) {
considered++;
float distance = MapCircle.getDistanceSquared(myBest.element.getPos(), closeTo);
if (distance < bestDistance) {
bestDistance = distance;
best = myBest;
bestSlot = slotNumber;
}
}
}
if (best != null) {
removeFromSlot(bestSlot, best);
return best.element;
} else {
return null;
}
}
/**
* Pops anything
*
* @return
*/
public E pop() {
for (int i = 0; i < slotOrder.length; i++) {
int slotNumber = slotOrder[i];
if (slots[slotNumber] != null) {
E e = slots[slotNumber].element;
slots[slotNumber] = slots[slotNumber].next;
if (slots[slotNumber] == null) {
tails[slotNumber] = null;
}
return e;
}
}
return null;
}
/**
* Pushes all items at the given position to the other queue.
*
* @param pos
* @param to
* @see #add(Object, ILocatable)
*/
public void moveItemsForPosition(ISPosition2D pos, SlotQueue<T, E> to) {
for (int i = 0; i < slots.length; i++) {
if (slots[i] == null) {
continue;
}
ElementHolder<E> current;
for (current = slots[i]; current.next != null;) {
if (current.next.element.getPos().equals(pos)) {
to.add(slotTypes[i], current.next.element);
current.next = current.next.next;
if (current.next == null) {
tails[i] = current;
}
} else {
current = current.next;
}
}
if (slots[i].element.getPos().equals(pos)) {
to.add(slotTypes[i], slots[i].element);
slots[i] = slots[i].next;
if (slots[i] == null) {
tails[i] = null;
}
}
}
}
private static class ElementHolder<E> implements Serializable {
private static final long serialVersionUID = 5419958157372923605L;
final E element;
ElementHolder<E> next = null;
int skipcost = 1;
public ElementHolder(E element) {
this.element = element;
}
}
public void addAll(SlotQueue<T, E> other) {
for (int i = 0; i < other.slots.length; i++) {
for (ElementHolder<E> current = other.slots[i]; current != null; current = current.next) {
add(other.slotTypes[i], current.element);
}
}
}
public void removeOfType(T type, ISPosition2D pos) {
for (int slotNumber = 0; slotNumber < slots.length; slotNumber++) {
if (slotTypes[slotNumber].equals(type) && slots[slotNumber] != null) {
removeFromPosition(pos, slotNumber);
}
}
}
private void removeFromPosition(ISPosition2D pos, int slotNumber) {
for (ElementHolder<E> current = slots[slotNumber]; current.next != null;) {
if (current.next.element.getPos().equals(pos)) {
current.next = current.next.next;
if (current.next == null) {
tails[slotNumber] = current;
}
} else {
current = current.next;
}
}
if (slots[slotNumber].element.getPos().equals(pos)) {
slots[slotNumber] = slots[slotNumber].next;
if (slots[slotNumber] == null) {
tails[slotNumber] = null;
}
}
}
} |
package jsettlers.main.swing;
import go.graphics.area.Area;
import go.graphics.nativegl.NativeAreaWindow;
import go.graphics.swing.AreaContainer;
import go.graphics.swing.sound.SwingSoundPlayer;
import java.awt.Dimension;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.JFrame;
import jsettlers.common.CommonConstants;
import jsettlers.common.resources.ResourceManager;
import jsettlers.common.utils.MainUtils;
import jsettlers.graphics.JSettlersScreen;
import jsettlers.graphics.startscreen.interfaces.IStartingGame;
import jsettlers.graphics.startscreen.progress.StartingGamePanel;
import jsettlers.graphics.swing.SwingResourceLoader;
import jsettlers.logic.LogicRevision;
import jsettlers.logic.constants.MatchConstants;
import jsettlers.logic.map.save.MapLoader;
import jsettlers.main.JSettlersGame;
import jsettlers.main.StartScreenConnector;
import networklib.client.OfflineNetworkConnector;
/**
*
* @author Andreas Eberle
* @author michael
*/
public class SwingManagedJSettlers {
/**
* @param args
* @throws FileNotFoundException
* @throws IOException
* @throws ClassNotFoundException
*/
public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
HashMap<String, String> argsMap = MainUtils.createArgumentsMap(args);
setupResourceManagers(argsMap, new File("config.prp"));
loadDebugSettings(argsMap);
JSettlersScreen content = startGui(argsMap);
generateContent(argsMap, content);
}
/**
* Sets up the {@link ResourceManager} by using a configuration file. <br>
* First it is checked, if the given argsMap contains a "configFile" parameter. If so, the path specified for this parameter is used to get the
* file. <br>
* If the parameter is not given, the defaultConfigFile is used.
*
* @param argsMap
* @param defaultConfigFile
* @throws FileNotFoundException
* @throws IOException
*/
public static void setupResourceManagers(HashMap<String, String> argsMap, File defaultConfigFile) throws FileNotFoundException, IOException {
File configFile;
if (argsMap.containsKey("configFile")) {
configFile = new File(argsMap.get("configFile"));
} else {
configFile = defaultConfigFile;
}
SwingResourceLoader.setupResourceManagersByConfigFile(configFile);
}
private static void loadDebugSettings(HashMap<String, String> argsMap) {
if (argsMap.containsKey("control-all")) {
CommonConstants.ENABLE_ALL_PLAYER_FOG_OF_WAR = true;
CommonConstants.ENABLE_ALL_PLAYER_SELECTION = true;
CommonConstants.ENABLE_FOG_OF_WAR_DISABLING = true;
}
if (argsMap.containsKey("localhost")) {
CommonConstants.DEFAULT_SERVER_ADDRESS = "localhost";
}
}
/**
* Creates a new SWING GUI for the game.
*
* @param argsList
* @return
* @throws IOException
* @throws FileNotFoundException
*/
public static JSettlersScreen startGui(HashMap<String, String> argsMap) {
Area area = new Area();
JSettlersScreen content = new JSettlersScreen(new StartScreenConnector(), new SwingSoundPlayer(), "r" + Revision.REVISION + " / r"
+ LogicRevision.REVISION);
area.add(content.getRegion());
if (argsMap.containsKey("force-jogl")) {
startJogl(area);
} else if (argsMap.containsKey("force-native")) {
startNative(area);
} else {
try {
startNative(area);
} catch (Throwable t) {
startJogl(area);
}
}
startRedrawTimer(content);
return content;
}
private static void generateContent(HashMap<String, String> argsMap, JSettlersScreen content) throws IOException {
String mapfile = null;
long randomSeed = 0;
File loadableReplayFile = null;
int targetGameTime = 0;
if (argsMap.containsKey("mapfile")) {
mapfile = argsMap.get("mapfile");
}
if (argsMap.containsKey("random")) {
randomSeed = Long.parseLong(argsMap.get("random"));
}
if (argsMap.containsKey("replayFile")) {
String loadableReplayFileString = argsMap.get("replayFile");
File replayFile = new File(loadableReplayFileString);
if (replayFile.exists()) {
loadableReplayFile = replayFile;
System.out.println("Found loadable replay file and loading it: " + loadableReplayFile);
} else {
System.err.println("Found replayFile parameter, but file can not be found!");
}
}
if (argsMap.containsKey("targetTime")) {
targetGameTime = Integer.valueOf(argsMap.get("targetTime")) * 60 * 1000;
}
if (mapfile != null || loadableReplayFile != null) {
IStartingGame game;
if (loadableReplayFile == null) {
MapLoader mapLoader = new MapLoader(new File(mapfile));
game = new JSettlersGame(mapLoader, randomSeed, (byte) 0).start();
} else {
game = JSettlersGame.loadFromReplayFile(loadableReplayFile, new OfflineNetworkConnector()).start();
}
StartingGamePanel toDisplay = new StartingGamePanel(game, content);
content.setContent(toDisplay);
if (targetGameTime > 0) {
while (!game.isStartupFinished()) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
}
MatchConstants.clock.fastForwardTo(targetGameTime);
}
} else {
content.goToStartScreen("");
}
}
private static void startRedrawTimer(final JSettlersScreen content) {
new Timer("opengl-redraw").schedule(new TimerTask() {
@Override
public void run() {
content.getRegion().requestRedraw();
}
}, 100, 25);
}
private static void startJogl(Area area) {
JFrame jsettlersWnd = new JFrame("JSettlers - Revision: " + Revision.REVISION + "/" + LogicRevision.REVISION);
AreaContainer panel = new AreaContainer(area);
panel.setPreferredSize(new Dimension(640, 480));
jsettlersWnd.add(panel);
panel.requestFocusInWindow();
jsettlersWnd.pack();
jsettlersWnd.setSize(1200, 800);
jsettlersWnd.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jsettlersWnd.setVisible(true);
jsettlersWnd.setLocationRelativeTo(null);
}
private static void startNative(Area area) {
new NativeAreaWindow(area);
}
} |
package java.awt;
import java.awt.peer.KeyboardFocusManagerPeer;
import java.awt.peer.RobotPeer;
import sun.awt.ComponentFactory;
import sun.awt.KeyboardFocusManagerPeerProvider;
import sun.awt.datatransfer.DataTransferer;
import java.awt.peer.BDFramePeer;
import java.awt.peer.BDKeyboardFocusManagerPeer;
import org.videolan.GUIManager;
import org.videolan.Logger;
public class BDToolkit extends BDToolkitBase
implements KeyboardFocusManagerPeerProvider, ComponentFactory {
private static final Logger logger = Logger.getLogger(BDToolkit.class.getName());
public BDToolkit () {
}
protected void shutdown() {
super.shutdown();
KeyboardFocusManager.getCurrentKeyboardFocusManager().clearGlobalFocusOwner();
KeyboardFocusManager.getCurrentKeyboardFocusManager().setGlobalCurrentFocusCycleRoot(null);
KeyboardFocusManager.getCurrentKeyboardFocusManager().setGlobalFocusedWindow(null);
KeyboardFocusManager.getCurrentKeyboardFocusManager().setGlobalActiveWindow(null);
KeyboardFocusManager.getCurrentKeyboardFocusManager().setGlobalPermanentFocusOwner(null);
BDKeyboardFocusManagerPeer.shutdown();
KeyboardFocusManager.setCurrentKeyboardFocusManager(null);
}
public static void setFocusedWindow(Window window) {
/* hook KeyboardFocusManagerPeer (not doing this leads to crash) */
BDKeyboardFocusManagerPeer.init(window);
}
// required by older Java 7 versions
public KeyboardFocusManagerPeer createKeyboardFocusManagerPeer(KeyboardFocusManager kfm)
{
return getKeyboardFocusManagerPeer();
}
public KeyboardFocusManagerPeer getKeyboardFocusManagerPeer()
{
return BDKeyboardFocusManagerPeer.getInstance();
}
public void sync() {
GUIManager.getInstance().sync();
}
public java.util.Map mapInputMethodHighlight(java.awt.im.InputMethodHighlight h) {
logger.unimplemented();
throw new Error("Not implemented");
}
public boolean isModalExclusionTypeSupported(Dialog.ModalExclusionType modalExclusionType) {
logger.unimplemented();
throw new Error("Not implemented");
}
public boolean isModalityTypeSupported(Dialog.ModalityType modalityType) {
logger.unimplemented();
throw new Error("Not implemented");
}
public java.awt.peer.FramePeer createFrame(Frame target) {
if (!(target instanceof BDRootWindow)) {
logger.error("createFrame(): not BDRootWindow");
throw new Error("Not implemented");
}
return new BDFramePeer(target, (BDRootWindow)target);
}
public java.awt.peer.ButtonPeer createButton(Button target) {
logger.unimplemented();
throw new Error("Not implemented");
}
public java.awt.peer.CanvasPeer createCanvas(Canvas target) {
logger.unimplemented();
throw new Error("Not implemented");
}
public java.awt.peer.CheckboxPeer createCheckbox(Checkbox target) {
logger.unimplemented();
throw new Error("Not implemented");
}
public java.awt.peer.CheckboxMenuItemPeer createCheckboxMenuItem(CheckboxMenuItem target) {
logger.unimplemented();
throw new Error("Not implemented");
}
public java.awt.peer.ChoicePeer createChoice(Choice target) {
logger.unimplemented();
throw new Error("Not implemented");
}
public java.awt.peer.DesktopPeer createDesktopPeer(Desktop target) {
logger.unimplemented();
throw new Error("Not implemented");
}
public java.awt.peer.DialogPeer createDialog(Dialog target) {
logger.unimplemented();
throw new Error("Not implemented");
}
public java.awt.dnd.peer.DragSourceContextPeer createDragSourceContextPeer(java.awt.dnd.DragGestureEvent dge) {
logger.unimplemented();
throw new Error("Not implemented");
}
public java.awt.peer.FileDialogPeer createFileDialog(FileDialog target) {
logger.unimplemented();
throw new Error("Not implemented");
}
public java.awt.peer.LabelPeer createLabel(Label target) {
logger.unimplemented();
throw new Error("Not implemented");
}
public java.awt.peer.ListPeer createList(List target) {
logger.unimplemented();
throw new Error("Not implemented");
}
public java.awt.peer.MenuPeer createMenu(Menu target) {
logger.unimplemented();
throw new Error("Not implemented");
}
public java.awt.peer.MenuBarPeer createMenuBar(MenuBar target) {
logger.unimplemented();
throw new Error("Not implemented");
}
public java.awt.peer.MenuItemPeer createMenuItem(MenuItem target) {
logger.unimplemented();
throw new Error("Not implemented");
}
public java.awt.peer.PanelPeer createPanel(Panel target) {
logger.unimplemented();
throw new Error("Not implemented");
}
public java.awt.peer.PopupMenuPeer createPopupMenu(PopupMenu target) {
logger.unimplemented();
throw new Error("Not implemented");
}
public java.awt.peer.ScrollbarPeer createScrollbar(Scrollbar target) {
logger.unimplemented();
throw new Error("Not implemented");
}
public java.awt.peer.ScrollPanePeer createScrollPane(ScrollPane target) {
logger.unimplemented();
throw new Error("Not implemented");
}
public java.awt.peer.TextAreaPeer createTextArea(TextArea target) {
logger.unimplemented();
throw new Error("Not implemented");
}
public java.awt.peer.TextFieldPeer createTextField(TextField target) {
logger.unimplemented();
throw new Error("Not implemented");
}
public java.awt.peer.WindowPeer createWindow(Window target) {
logger.unimplemented();
throw new Error("Not implemented");
}
public java.awt.datatransfer.Clipboard getSystemClipboard() {
logger.unimplemented();
throw new Error("Not implemented");
}
public PrintJob getPrintJob(Frame frame, String jobtitle, java.util.Properties props) {
logger.unimplemented();
throw new Error("Not implemented");
}
public java.awt.peer.FontPeer getFontPeer(String name, int style) {
logger.unimplemented();
throw new Error("Not implemented");
}
/* required for Java < 9 */
public DataTransferer getDataTransferer() {
return null;
}
public RobotPeer createRobot(Robot target, GraphicsDevice screen) {
logger.unimplemented();
throw new Error("Not implemented");
}
} |
package com.psddev.dari.db;
import java.io.ByteArrayInputStream;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.ref.WeakReference;
import java.sql.BatchUpdateException;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.SQLIntegrityConstraintViolationException;
import java.sql.SQLTimeoutException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import javax.sql.DataSource;
import org.iq80.snappy.Snappy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.jolbox.bonecp.BoneCPDataSource;
import com.psddev.dari.util.ObjectUtils;
import com.psddev.dari.util.PaginatedResult;
import com.psddev.dari.util.PeriodicValue;
import com.psddev.dari.util.Profiler;
import com.psddev.dari.util.PullThroughValue;
import com.psddev.dari.util.Settings;
import com.psddev.dari.util.SettingsException;
import com.psddev.dari.util.Stats;
import com.psddev.dari.util.StringUtils;
import com.psddev.dari.util.TypeDefinition;
/** Database backed by a SQL engine. */
public class SqlDatabase extends AbstractDatabase<Connection> {
public static final String DATA_SOURCE_SETTING = "dataSource";
public static final String JDBC_DRIVER_CLASS_SETTING = "jdbcDriverClass";
public static final String JDBC_URL_SETTING = "jdbcUrl";
public static final String JDBC_USER_SETTING = "jdbcUser";
public static final String JDBC_PASSWORD_SETTING = "jdbcPassword";
public static final String JDBC_POOL_SIZE_SETTING = "jdbcPoolSize";
public static final String READ_DATA_SOURCE_SETTING = "readDataSource";
public static final String READ_JDBC_DRIVER_CLASS_SETTING = "readJdbcDriverClass";
public static final String READ_JDBC_URL_SETTING = "readJdbcUrl";
public static final String READ_JDBC_USER_SETTING = "readJdbcUser";
public static final String READ_JDBC_PASSWORD_SETTING = "readJdbcPassword";
public static final String READ_JDBC_POOL_SIZE_SETTING = "readJdbcPoolSize";
public static final String VENDOR_CLASS_SETTING = "vendorClass";
public static final String COMPRESS_DATA_SUB_SETTING = "compressData";
public static final String CACHE_DATA_SUB_SETTING = "cacheData";
public static final String RECORD_TABLE = "Record";
public static final String RECORD_UPDATE_TABLE = "RecordUpdate";
public static final String SYMBOL_TABLE = "Symbol";
public static final String ID_COLUMN = "id";
public static final String TYPE_ID_COLUMN = "typeId";
public static final String IN_ROW_INDEX_COLUMN = "inRowIndex";
public static final String DATA_COLUMN = "data";
public static final String SYMBOL_ID_COLUMN = "symbolId";
public static final String UPDATE_DATE_COLUMN = "updateDate";
public static final String VALUE_COLUMN = "value";
public static final String CONNECTION_QUERY_OPTION = "sql.connection";
public static final String EXTRA_COLUMNS_QUERY_OPTION = "sql.extraColumns";
public static final String EXTRA_JOINS_QUERY_OPTION = "sql.extraJoins";
public static final String EXTRA_WHERE_QUERY_OPTION = "sql.extraWhere";
public static final String EXTRA_HAVING_QUERY_OPTION = "sql.extraHaving";
public static final String MYSQL_INDEX_HINT_QUERY_OPTION = "sql.mysqlIndexHint";
public static final String RETURN_ORIGINAL_DATA_QUERY_OPTION = "sql.returnOriginalData";
public static final String USE_JDBC_FETCH_SIZE_QUERY_OPTION = "sql.useJdbcFetchSize";
public static final String USE_READ_DATA_SOURCE_QUERY_OPTION = "sql.useReadDataSource";
public static final String SKIP_INDEX_STATE_EXTRA = "sql.skipIndex";
public static final String INDEX_TABLE_INDEX_OPTION = "sql.indexTable";
public static final String EXTRA_COLUMN_EXTRA_PREFIX = "sql.extraColumn.";
public static final String ORIGINAL_DATA_EXTRA = "sql.originalData";
private static final Logger LOGGER = LoggerFactory.getLogger(SqlDatabase.class);
private static final String SHORT_NAME = "SQL";
private static final Stats STATS = new Stats(SHORT_NAME);
private static final String QUERY_STATS_OPERATION = "Query";
private static final String UPDATE_STATS_OPERATION = "Update";
private static final String QUERY_PROFILER_EVENT = SHORT_NAME + " " + QUERY_STATS_OPERATION;
private static final String UPDATE_PROFILER_EVENT = SHORT_NAME + " " + UPDATE_STATS_OPERATION;
private final static List<SqlDatabase> INSTANCES = new ArrayList<SqlDatabase>();
{
INSTANCES.add(this);
}
private volatile DataSource dataSource;
private volatile DataSource readDataSource;
private volatile SqlVendor vendor;
private volatile boolean compressData;
private volatile boolean cacheData;
/**
* Quotes the given {@code identifier} so that it's safe to use
* in a SQL query.
*/
public static String quoteIdentifier(String identifier) {
return "\"" + StringUtils.replaceAll(identifier, "\\\\", "\\\\\\\\", "\"", "\"\"") + "\"";
}
/**
* Quotes the given {@code value} so that it's safe to use
* in a SQL query.
*/
public static String quoteValue(Object value) {
if (value == null) {
return "NULL";
} else if (value instanceof Number) {
return value.toString();
} else if (value instanceof byte[]) {
return "X'" + StringUtils.hex((byte[]) value) + "'";
} else {
return "'" + value.toString().replace("'", "''").replace("\\", "\\\\") + "'";
}
}
/** Closes all resources used by all instances. */
public static void closeAll() {
for (SqlDatabase database : INSTANCES) {
database.close();
}
INSTANCES.clear();
}
/**
* Creates an {@link SqlDatabaseException} that occurred during
* an execution of a query.
*/
private SqlDatabaseException createQueryException(
SQLException error,
String sqlQuery,
Query<?> query) {
String message = error.getMessage();
if (error instanceof SQLTimeoutException || message.contains("timeout")) {
return new SqlDatabaseException.ReadTimeout(this, error, sqlQuery, query);
} else {
return new SqlDatabaseException(this, error, sqlQuery, query);
}
}
/** Returns the JDBC data source used for general database operations. */
public DataSource getDataSource() {
return dataSource;
}
private static final Map<String, Class<? extends SqlVendor>> VENDOR_CLASSES; static {
Map<String, Class<? extends SqlVendor>> m = new HashMap<String, Class<? extends SqlVendor>>();
m.put("H2", SqlVendor.H2.class);
m.put("MySQL", SqlVendor.MySQL.class);
m.put("PostgreSQL", SqlVendor.PostgreSQL.class);
m.put("Oracle", SqlVendor.Oracle.class);
VENDOR_CLASSES = m;
}
/** Sets the JDBC data source used for general database operations. */
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
if (dataSource == null) {
return;
}
synchronized (this) {
try {
boolean writable = false;
if (vendor == null) {
Connection connection;
try {
connection = openConnection();
writable = true;
} catch (DatabaseException error) {
LOGGER.debug("Can't read vendor information from the writable server!", error);
connection = openReadConnection();
}
try {
DatabaseMetaData meta = connection.getMetaData();
String vendorName = meta.getDatabaseProductName();
Class<? extends SqlVendor> vendorClass = VENDOR_CLASSES.get(vendorName);
LOGGER.info(
"Initializing SQL vendor for [{}]: [{}] -> [{}]",
new Object[] { getName(), vendorName, vendorClass });
vendor = vendorClass != null ? TypeDefinition.getInstance(vendorClass).newInstance() : new SqlVendor();
vendor.setDatabase(this);
} finally {
closeConnection(connection);
}
}
tableNames.refresh();
symbols.invalidate();
if (writable) {
vendor.createRecord(this);
vendor.createRecordUpdate(this);
vendor.createSymbol(this);
for (SqlIndex index : SqlIndex.values()) {
if (index != SqlIndex.CUSTOM) {
vendor.createRecordIndex(
this,
index.getReadTable(this, null).getName(this, null),
index);
}
}
tableNames.refresh();
symbols.invalidate();
}
} catch (SQLException ex) {
throw new SqlDatabaseException(this, "Can't check for required tables!", ex);
}
}
}
/** Returns the JDBC data source used exclusively for read operations. */
public DataSource getReadDataSource() {
return this.readDataSource;
}
/** Sets the JDBC data source used exclusively for read operations. */
public void setReadDataSource(DataSource readDataSource) {
this.readDataSource = readDataSource;
}
/** Returns the vendor-specific SQL engine information. */
public SqlVendor getVendor() {
return vendor;
}
/** Sets the vendor-specific SQL engine information. */
public void setVendor(SqlVendor vendor) {
this.vendor = vendor;
}
/** Returns {@code true} if the data should be compressed. */
public boolean isCompressData() {
return compressData;
}
/** Sets whether the data should be compressed. */
public void setCompressData(boolean compressData) {
this.compressData = compressData;
}
public boolean isCacheData() {
return cacheData;
}
public void setCacheData(boolean cacheData) {
this.cacheData = cacheData;
}
/**
* Returns {@code true} if the {@link #RECORD_TABLE} in this database
* has the {@link #IN_ROW_INDEX_COLUMN}.
*/
public boolean hasInRowIndex() {
return hasInRowIndex;
}
/**
* Returns {@code true} if all comparisons executed in this database
* should ignore case by default.
*/
public boolean comparesIgnoreCase() {
return comparesIgnoreCase;
}
/**
* Returns {@code true} if this database contains a table with
* the given {@code name}.
*/
public boolean hasTable(String name) {
if (name == null) {
return false;
} else {
Set<String> names = tableNames.get();
return names != null && names.contains(name.toLowerCase());
}
}
private transient volatile boolean hasInRowIndex;
private transient volatile boolean comparesIgnoreCase;
private final transient PeriodicValue<Set<String>> tableNames = new PeriodicValue<Set<String>>(0.0, 60.0) {
@Override
protected Set<String> update() {
if (getDataSource() == null) {
return Collections.emptySet();
}
Connection connection;
try {
connection = openConnection();
} catch (DatabaseException error) {
LOGGER.debug("Can't read table names from the writable server!", error);
connection = openReadConnection();
}
try {
SqlVendor vendor = getVendor();
String recordTable = null;
int maxStringVersion = 0;
Set<String> loweredNames = new HashSet<String>();
for (String name : vendor.getTables(connection)) {
String loweredName = name.toLowerCase();
loweredNames.add(loweredName);
if ("record".equals(loweredName)) {
recordTable = name;
} else if (loweredName.startsWith("recordstring")) {
int version = ObjectUtils.to(int.class, loweredName.substring(12));
if (version > maxStringVersion) {
maxStringVersion = version;
}
}
}
if (recordTable != null) {
hasInRowIndex = vendor.hasInRowIndex(connection, recordTable);
}
comparesIgnoreCase = maxStringVersion >= 3;
return loweredNames;
} catch (SQLException error) {
LOGGER.error("Can't query table names!", error);
return get();
} finally {
closeConnection(connection);
}
}
};
/**
* Returns an unique numeric ID for the given {@code symbol}.
*/
public int getSymbolId(String symbol) {
Integer id = symbols.get().get(symbol);
if (id == null) {
SqlVendor vendor = getVendor();
Connection connection = openConnection();
try {
List<Object> parameters = new ArrayList<Object>();
StringBuilder insertBuilder = new StringBuilder();
insertBuilder.append("INSERT /*! IGNORE */ INTO ");
vendor.appendIdentifier(insertBuilder, SYMBOL_TABLE);
insertBuilder.append(" (");
vendor.appendIdentifier(insertBuilder, VALUE_COLUMN);
insertBuilder.append(") VALUES (");
vendor.appendBindValue(insertBuilder, symbol, parameters);
insertBuilder.append(")");
String insertSql = insertBuilder.toString();
try {
Static.executeUpdateWithList(connection, insertSql, parameters);
} catch (SQLException ex) {
if (!Static.isIntegrityConstraintViolation(ex)) {
throw createQueryException(ex, insertSql, null);
}
}
StringBuilder selectBuilder = new StringBuilder();
selectBuilder.append("SELECT ");
vendor.appendIdentifier(selectBuilder, SYMBOL_ID_COLUMN);
selectBuilder.append(" FROM ");
vendor.appendIdentifier(selectBuilder, SYMBOL_TABLE);
selectBuilder.append(" WHERE ");
vendor.appendIdentifier(selectBuilder, VALUE_COLUMN);
selectBuilder.append("=");
vendor.appendValue(selectBuilder, symbol);
String selectSql = selectBuilder.toString();
Statement statement = null;
ResultSet result = null;
try {
statement = connection.createStatement();
result = statement.executeQuery(selectSql);
result.next();
id = result.getInt(1);
symbols.get().put(symbol, id);
} catch (SQLException ex) {
throw createQueryException(ex, selectSql, null);
} finally {
closeResources(null, null, statement, result);
}
} finally {
closeConnection(connection);
}
}
return id;
}
// Cache of all internal symbols.
private transient PullThroughValue<Map<String, Integer>> symbols = new PullThroughValue<Map<String, Integer>>() {
@Override
protected Map<String, Integer> produce() {
SqlVendor vendor = getVendor();
StringBuilder selectBuilder = new StringBuilder();
selectBuilder.append("SELECT ");
vendor.appendIdentifier(selectBuilder, SYMBOL_ID_COLUMN);
selectBuilder.append(",");
vendor.appendIdentifier(selectBuilder, VALUE_COLUMN);
selectBuilder.append(" FROM ");
vendor.appendIdentifier(selectBuilder, SYMBOL_TABLE);
String selectSql = selectBuilder.toString();
Connection connection;
Statement statement = null;
ResultSet result = null;
try {
connection = openConnection();
} catch (DatabaseException error) {
LOGGER.debug("Can't read symbols from the writable server!", error);
connection = openReadConnection();
}
try {
statement = connection.createStatement();
result = statement.executeQuery(selectSql);
Map<String, Integer> symbols = new ConcurrentHashMap<String, Integer>();
while (result.next()) {
symbols.put(new String(result.getBytes(2), StringUtils.UTF_8), result.getInt(1));
}
return symbols;
} catch (SQLException ex) {
throw createQueryException(ex, selectSql, null);
} finally {
closeResources(null, connection, statement, result);
}
}
};
/**
* Returns the underlying JDBC connection.
*
* @deprecated Use {@link #openConnection} instead.
*/
@Deprecated
public Connection getConnection() {
return openConnection();
}
/** Closes any resources used by this database. */
public void close() {
DataSource dataSource = getDataSource();
if (dataSource instanceof BoneCPDataSource) {
LOGGER.info("Closing BoneCP data source in {}", getName());
((BoneCPDataSource) dataSource).close();
}
DataSource readDataSource = getReadDataSource();
if (readDataSource instanceof BoneCPDataSource) {
LOGGER.info("Closing BoneCP read data source in {}", getName());
((BoneCPDataSource) readDataSource).close();
}
setDataSource(null);
setReadDataSource(null);
}
/**
* Builds an SQL statement that can be used to get a count of all
* objects matching the given {@code query}.
*/
public String buildCountStatement(Query<?> query) {
return new SqlQuery(this, query).countStatement();
}
/**
* Builds an SQL statement that can be used to delete all rows
* matching the given {@code query}.
*/
public String buildDeleteStatement(Query<?> query) {
return new SqlQuery(this, query).deleteStatement();
}
/**
* Builds an SQL statement that can be used to get all objects
* grouped by the values of the given {@code groupFields}.
*/
public String buildGroupStatement(Query<?> query, String... groupFields) {
return new SqlQuery(this, query).groupStatement(groupFields);
}
public String buildGroupedMetricStatement(Query<?> query, String metricFieldName, String... groupFields) {
return new SqlQuery(this, query).groupedMetricSql(metricFieldName, groupFields);
}
/**
* Builds an SQL statement that can be used to get when the objects
* matching the given {@code query} were last updated.
*/
public String buildLastUpdateStatement(Query<?> query) {
return new SqlQuery(this, query).lastUpdateStatement();
}
/**
* Builds an SQL statement that can be used to list all rows
* matching the given {@code query}.
*/
public String buildSelectStatement(Query<?> query) {
return new SqlQuery(this, query).selectStatement();
}
/** Closes all the given SQL resources safely. */
private void closeResources(Query<?> query, Connection connection, Statement statement, ResultSet result) {
if (result != null) {
try {
result.close();
} catch (SQLException ex) {
}
}
if (statement != null) {
try {
statement.close();
} catch (SQLException ex) {
}
}
if (connection != null &&
(query == null ||
!connection.equals(query.getOptions().get(CONNECTION_QUERY_OPTION)))) {
try {
connection.close();
} catch (SQLException ex) {
}
}
}
private byte[] serializeState(State state) {
Map<String, Object> values = state.getSimpleValues();
for (Iterator<Map.Entry<String, Object>> i = values.entrySet().iterator(); i.hasNext(); ) {
Map.Entry<String, Object> entry = i.next();
ObjectField field = state.getField(entry.getKey());
if (field != null) {
if (field.as(FieldData.class).isIndexTableSourceFromAnywhere()) {
i.remove();
}
}
}
byte[] dataBytes = ObjectUtils.toJson(values).getBytes(StringUtils.UTF_8);
if (isCompressData()) {
byte[] compressed = new byte[Snappy.maxCompressedLength(dataBytes.length)];
int compressedLength = Snappy.compress(dataBytes, 0, dataBytes.length, compressed, 0);
dataBytes = new byte[compressedLength + 1];
dataBytes[0] = 's';
System.arraycopy(compressed, 0, dataBytes, 1, compressedLength);
}
return dataBytes;
}
@SuppressWarnings("unchecked")
private Map<String, Object> unserializeData(byte[] dataBytes) {
char format = '\0';
while (true) {
format = (char) dataBytes[0];
if (format == 's') {
dataBytes = Snappy.uncompress(dataBytes, 1, dataBytes.length - 1);
} else if (format == '{') {
return (Map<String, Object>) ObjectUtils.fromJson(new String(dataBytes, StringUtils.UTF_8));
} else {
break;
}
}
throw new IllegalStateException(String.format(
"Unknown format! ([%s])", format));
}
private final transient Cache<String, byte[]> dataCache = CacheBuilder.newBuilder().maximumSize(10000).build();
/**
* Creates a previously saved object using the given {@code resultSet}.
*/
private <T> T createSavedObjectWithResultSet(ResultSet resultSet, Query<T> query) throws SQLException {
T object = createSavedObject(resultSet.getObject(2), resultSet.getObject(1), query);
State objectState = State.getInstance(object);
if (!objectState.isReferenceOnly()) {
byte[] data = null;
if (isCacheData()) {
UUID id = objectState.getId();
String key = id + "/" + resultSet.getDouble(3);
data = dataCache.getIfPresent(key);
if (data == null) {
SqlVendor vendor = getVendor();
StringBuilder sqlQuery = new StringBuilder();
sqlQuery.append("SELECT r.");
vendor.appendIdentifier(sqlQuery, "data");
sqlQuery.append(", ru.");
vendor.appendIdentifier(sqlQuery, "updateDate");
sqlQuery.append(" FROM ");
vendor.appendIdentifier(sqlQuery, "Record");
sqlQuery.append(" AS r LEFT OUTER JOIN ");
vendor.appendIdentifier(sqlQuery, "RecordUpdate");
sqlQuery.append(" AS ru ON r.");
vendor.appendIdentifier(sqlQuery, "id");
sqlQuery.append(" = ru.");
vendor.appendIdentifier(sqlQuery, "id");
sqlQuery.append(" WHERE r.");
vendor.appendIdentifier(sqlQuery, "id");
sqlQuery.append(" = ");
vendor.appendUuid(sqlQuery, id);
Connection connection = null;
Statement statement = null;
ResultSet result = null;
try {
connection = openQueryConnection(query);
statement = connection.createStatement();
result = executeQueryBeforeTimeout(statement, sqlQuery.toString(), 0);
if (result.next()) {
data = result.getBytes(1);
dataCache.put(id + "/" + result.getDouble(2), data);
}
} catch (SQLException error) {
throw createQueryException(error, sqlQuery.toString(), query);
} finally {
closeResources(null, connection, statement, result);
}
}
} else {
data = resultSet.getBytes(3);
}
if (data != null) {
objectState.putAll(unserializeData(data));
Boolean returnOriginal = ObjectUtils.to(Boolean.class, query.getOptions().get(RETURN_ORIGINAL_DATA_QUERY_OPTION));
if (returnOriginal == null) {
returnOriginal = Boolean.FALSE;
}
if (returnOriginal) {
objectState.getExtras().put(ORIGINAL_DATA_EXTRA, data);
}
}
}
ResultSetMetaData meta = resultSet.getMetaData();
for (int i = 4, count = meta.getColumnCount(); i <= count; ++ i) {
String columnName = meta.getColumnLabel(i);
if (query.getExtraSourceColumns().containsKey(columnName)) {
objectState.put(query.getExtraSourceColumns().get(columnName), resultSet.getObject(i));
} else {
objectState.getExtras().put(EXTRA_COLUMN_EXTRA_PREFIX + meta.getColumnLabel(i), resultSet.getObject(i));
}
}
// Load some extra column from source index tables.
@SuppressWarnings("unchecked")
Set<UUID> unresolvedTypeIds = (Set<UUID>) query.getOptions().get(State.UNRESOLVED_TYPE_IDS_QUERY_OPTION);
Set<ObjectType> queryTypes = query.getConcreteTypes(getEnvironment());
ObjectType type = objectState.getType();
HashSet<ObjectField> loadExtraFields = new HashSet<ObjectField>();
if (type != null &&
(unresolvedTypeIds == null || !unresolvedTypeIds.contains(type.getId())) &&
!queryTypes.contains(type)) {
for (ObjectField field : type.getFields()) {
SqlDatabase.FieldData fieldData = field.as(SqlDatabase.FieldData.class);
Metric.FieldData metricFieldData = field.as(Metric.FieldData.class);
if (fieldData.isIndexTableSource() && metricFieldData.isMetricValue()) {
loadExtraFields.add(field);
}
}
}
if (loadExtraFields != null) {
Connection connection = openQueryConnection(query);
try {
for (ObjectField field : loadExtraFields) {
Statement extraStatement = null;
ResultSet extraResult = null;
try {
extraStatement = connection.createStatement();
extraResult = executeQueryBeforeTimeout(
extraStatement,
extraSourceSelectStatementById(field, objectState.getId(), objectState.getTypeId()),
getQueryReadTimeout(query));
if (extraResult.next()) {
meta = extraResult.getMetaData();
for (int i = 1, count = meta.getColumnCount(); i <= count; ++ i) {
objectState.put(meta.getColumnLabel(i), extraResult.getObject(i));
}
}
} finally {
closeResources(null, null, extraStatement, extraResult);
}
}
} finally {
closeResources(query, connection, null, null);
}
}
return swapObjectType(query, object);
}
// Creates an SQL statement to return a single row from a FieldIndexTable
// used as a source table.
// Maybe: move this to SqlQuery and use initializeClauses() and
// needsRecordTable=false instead of passing id to this method. Needs
// countperformance branch to do this.
private String extraSourceSelectStatementById(ObjectField field, UUID id, UUID typeId) {
FieldData fieldData = field.as(FieldData.class);
Metric.FieldData metricFieldData = field.as(Metric.FieldData.class);
ObjectType parentType = field.getParentType();
StringBuilder keyName = new StringBuilder(parentType.getInternalName());
keyName.append("/");
keyName.append(field.getInternalName());
Query<?> query = Query.fromType(parentType);
Query.MappedKey key = query.mapEmbeddedKey(getEnvironment(), keyName.toString());
ObjectIndex useIndex = null;
for (ObjectIndex index : key.getIndexes()) {
if (field.getInternalName().equals(index.getFields().get(0))) {
useIndex = index;
break;
}
}
SqlIndex useSqlIndex = SqlIndex.Static.getByIndex(useIndex);
SqlIndex.Table indexTable = useSqlIndex.getReadTable(this, useIndex);
String sourceTableName = fieldData.getIndexTable();
int symbolId = getSymbolId(key.getIndexKey(useIndex));
StringBuilder sql = new StringBuilder();
int fieldIndex = 0;
sql.append("SELECT ");
if (metricFieldData.isMetricValue()) {
String indexColumnName = indexTable.getValueField(this, useIndex, fieldIndex);
StringBuilder minData = new StringBuilder("MIN(");
vendor.appendIdentifier(minData, indexColumnName);
minData.append(")");
StringBuilder maxData = new StringBuilder("MAX(");
vendor.appendIdentifier(maxData, indexColumnName);
maxData.append(")");
Metric.Static.appendSelectCalculatedAmountSql(sql, vendor, minData.toString(), maxData.toString(), false);
sql.append(" AS ");
vendor.appendIdentifier(sql, field.getInternalName());
} else {
for (String indexFieldName : useIndex.getFields()) {
String indexColumnName = indexTable.getValueField(this, useIndex, fieldIndex);
++ fieldIndex;
vendor.appendIdentifier(sql, indexColumnName);
sql.append(" AS ");
vendor.appendIdentifier(sql, indexFieldName);
sql.append(", ");
}
sql.setLength(sql.length() - 2);
}
sql.append(" FROM ");
vendor.appendIdentifier(sql, sourceTableName);
sql.append(" WHERE ");
vendor.appendIdentifier(sql, "id");
sql.append(" = ");
vendor.appendValue(sql, id);
sql.append(" AND ");
vendor.appendIdentifier(sql, "symbolId");
sql.append(" = ");
sql.append(symbolId);
if (metricFieldData.isMetricValue()) {
sql.append(" AND ");
vendor.appendIdentifier(sql, "typeId");
sql.append(" = ");
vendor.appendValue(sql, typeId);
}
return sql.toString();
}
/**
* Executes the given read {@code statement} (created from the given
* {@code sqlQuery}) before the given {@code timeout} (in seconds).
*/
ResultSet executeQueryBeforeTimeout(
Statement statement,
String sqlQuery,
int timeout)
throws SQLException {
if (timeout > 0 && !(vendor instanceof SqlVendor.PostgreSQL)) {
statement.setQueryTimeout(timeout);
}
Stats.Timer timer = STATS.startTimer();
Profiler.Static.startThreadEvent(QUERY_PROFILER_EVENT);
try {
return statement.executeQuery(sqlQuery);
} finally {
double duration = timer.stop(QUERY_STATS_OPERATION);
Profiler.Static.stopThreadEvent(sqlQuery);
LOGGER.debug(
"Read from the SQL database using [{}] in [{}]ms",
sqlQuery, duration);
}
}
/**
* Selects the first object that matches the given {@code sqlQuery}
* with options from the given {@code query}.
*/
public <T> T selectFirstWithOptions(String sqlQuery, Query<T> query) {
sqlQuery = vendor.rewriteQueryWithLimitClause(sqlQuery, 1, 0);
Connection connection = null;
Statement statement = null;
ResultSet result = null;
try {
connection = openQueryConnection(query);
statement = connection.createStatement();
result = executeQueryBeforeTimeout(statement, sqlQuery, getQueryReadTimeout(query));
return result.next() ? createSavedObjectWithResultSet(result, query) : null;
} catch (SQLException ex) {
throw createQueryException(ex, sqlQuery, query);
} finally {
closeResources(query, connection, statement, result);
}
}
/**
* Selects the first object that matches the given {@code sqlQuery}
* without a timeout.
*/
public Object selectFirst(String sqlQuery) {
return selectFirstWithOptions(sqlQuery, null);
}
/**
* Selects a list of objects that match the given {@code sqlQuery}
* with options from the given {@code query}.
*/
public <T> List<T> selectListWithOptions(String sqlQuery, Query<T> query) {
Connection connection = null;
Statement statement = null;
ResultSet result = null;
List<T> objects = new ArrayList<T>();
int timeout = getQueryReadTimeout(query);
try {
connection = openQueryConnection(query);
statement = connection.createStatement();
result = executeQueryBeforeTimeout(statement, sqlQuery, timeout);
while (result.next()) {
objects.add(createSavedObjectWithResultSet(result, query));
}
return objects;
} catch (SQLException ex) {
throw createQueryException(ex, sqlQuery, query);
} finally {
closeResources(query, connection, statement, result);
}
}
/**
* Selects a list of objects that match the given {@code sqlQuery}
* without a timeout.
*/
public List<Object> selectList(String sqlQuery) {
return selectListWithOptions(sqlQuery, null);
}
/**
* Returns an iterable that selects all objects matching the given
* {@code sqlQuery} with options from the given {@code query}.
*/
public <T> Iterable<T> selectIterableWithOptions(
final String sqlQuery,
final int fetchSize,
final Query<T> query) {
return new Iterable<T>() {
@Override
public Iterator<T> iterator() {
return new SqlIterator<T>(sqlQuery, fetchSize, query);
}
};
}
private class SqlIterator<T> implements Iterator<T> {
private final String sqlQuery;
private final Query<T> query;
private final Connection connection;
private final Statement statement;
private final ResultSet result;
private boolean hasNext = true;
public SqlIterator(String initialSqlQuery, int fetchSize, Query<T> initialQuery) {
sqlQuery = initialSqlQuery;
query = initialQuery;
try {
connection = openReadConnection();
statement = connection.createStatement();
statement.setFetchSize(
getVendor() instanceof SqlVendor.MySQL ? Integer.MIN_VALUE :
fetchSize <= 0 ? 200 :
fetchSize);
result = statement.executeQuery(sqlQuery);
moveToNext();
} catch (SQLException ex) {
close();
throw createQueryException(ex, sqlQuery, query);
}
}
private void moveToNext() throws SQLException {
if (hasNext) {
hasNext = result.next();
if (!hasNext) {
close();
}
}
}
public void close() {
hasNext = false;
closeResources(query, connection, statement, result);
}
@Override
public boolean hasNext() {
return hasNext;
}
@Override
public T next() {
if (!hasNext) {
throw new NoSuchElementException();
}
try {
T object = createSavedObjectWithResultSet(result, query);
moveToNext();
return object;
} catch (SQLException ex) {
close();
throw createQueryException(ex, sqlQuery, query);
}
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
@Override
protected void finalize() {
close();
}
}
/**
* Fills the placeholders in the given {@code sqlQuery} with the given
* {@code parameters}.
*/
private static String fillPlaceholders(String sqlQuery, Object... parameters) {
StringBuilder filled = new StringBuilder();
int prevPh = 0;
for (int ph, index = 0; (ph = sqlQuery.indexOf('?', prevPh)) > -1; ++ index) {
filled.append(sqlQuery.substring(prevPh, ph));
prevPh = ph + 1;
filled.append(quoteValue(parameters[index]));
}
filled.append(sqlQuery.substring(prevPh));
return filled.toString();
}
/**
* Executes the given write {@code sqlQuery} with the given
* {@code parameters}.
*
* @deprecated Use {@link Static#executeUpdate} instead.
*/
@Deprecated
public int executeUpdate(String sqlQuery, Object... parameters) {
try {
return Static.executeUpdateWithArray(getConnection(), sqlQuery, parameters);
} catch (SQLException ex) {
throw createQueryException(ex, fillPlaceholders(sqlQuery, parameters), null);
}
}
/**
* Reads the given {@code resultSet} into a list of maps
* and closes it.
*/
public List<Map<String, Object>> readResultSet(ResultSet resultSet) throws SQLException {
try {
ResultSetMetaData meta = resultSet.getMetaData();
List<String> columnNames = new ArrayList<String>();
for (int i = 1, count = meta.getColumnCount(); i < count; ++ i) {
columnNames.add(meta.getColumnName(i));
}
List<Map<String, Object>> maps = new ArrayList<Map<String, Object>>();
while (resultSet.next()) {
Map<String, Object> map = new LinkedHashMap<String, Object>();
maps.add(map);
for (int i = 0, size = columnNames.size(); i < size; ++ i) {
map.put(columnNames.get(i), resultSet.getObject(i + 1));
}
}
return maps;
} finally {
resultSet.close();
}
}
@Override
public Connection openConnection() {
DataSource dataSource = getDataSource();
if (dataSource == null) {
throw new SqlDatabaseException(this, "No SQL data source!");
}
try {
Connection connection = dataSource.getConnection();
connection.setReadOnly(false);
return connection;
} catch (SQLException error) {
throw new SqlDatabaseException(this, "Can't connect to the SQL engine!", error);
}
}
@Override
protected Connection doOpenReadConnection() {
DataSource readDataSource = getReadDataSource();
if (readDataSource == null) {
readDataSource = getDataSource();
}
if (readDataSource == null) {
throw new SqlDatabaseException(this, "No SQL data source!");
}
try {
Connection connection = readDataSource.getConnection();
connection.setReadOnly(true);
return connection;
} catch (SQLException error) {
throw new SqlDatabaseException(this, "Can't connect to the SQL engine!", error);
}
}
// Opens a connection that should be used to execute the given query.
private Connection openQueryConnection(Query<?> query) {
if (query != null) {
Connection connection = (Connection) query.getOptions().get(CONNECTION_QUERY_OPTION);
if (connection != null) {
return connection;
}
Boolean useRead = ObjectUtils.to(Boolean.class, query.getOptions().get(USE_READ_DATA_SOURCE_QUERY_OPTION));
if (useRead == null) {
useRead = Boolean.TRUE;
}
if (!useRead) {
return openConnection();
}
}
return openReadConnection();
}
@Override
public void closeConnection(Connection connection) {
if (connection != null) {
try {
connection.close();
} catch (SQLException ex) {
}
}
}
@Override
protected boolean isRecoverableError(Exception error) {
if (error instanceof SQLException) {
SQLException sqlError = (SQLException) error;
return "40001".equals(sqlError.getSQLState());
}
return false;
}
@Override
protected void doInitialize(String settingsKey, Map<String, Object> settings) {
close();
setReadDataSource(createDataSource(
settings,
READ_DATA_SOURCE_SETTING,
READ_JDBC_DRIVER_CLASS_SETTING,
READ_JDBC_URL_SETTING,
READ_JDBC_USER_SETTING,
READ_JDBC_PASSWORD_SETTING,
READ_JDBC_POOL_SIZE_SETTING));
setDataSource(createDataSource(
settings,
DATA_SOURCE_SETTING,
JDBC_DRIVER_CLASS_SETTING,
JDBC_URL_SETTING,
JDBC_USER_SETTING,
JDBC_PASSWORD_SETTING,
JDBC_POOL_SIZE_SETTING));
String vendorClassName = ObjectUtils.to(String.class, settings.get(VENDOR_CLASS_SETTING));
Class<?> vendorClass = null;
if (vendorClassName != null) {
vendorClass = ObjectUtils.getClassByName(vendorClassName);
if (vendorClass == null) {
throw new SettingsException(
VENDOR_CLASS_SETTING,
String.format("Can't find [%s]!",
vendorClassName));
} else if (!SqlVendor.class.isAssignableFrom(vendorClass)) {
throw new SettingsException(
VENDOR_CLASS_SETTING,
String.format("[%s] doesn't implement [%s]!",
vendorClass, Driver.class));
}
}
if (vendorClass != null) {
setVendor((SqlVendor) TypeDefinition.getInstance(vendorClass).newInstance());
}
Boolean compressData = ObjectUtils.coalesce(
ObjectUtils.to(Boolean.class, settings.get(COMPRESS_DATA_SUB_SETTING)),
Settings.get(Boolean.class, "dari/isCompressSqlData"));
if (compressData != null) {
setCompressData(compressData);
}
setCacheData(ObjectUtils.to(boolean.class, settings.get(CACHE_DATA_SUB_SETTING)));
}
private static final Map<String, String> DRIVER_CLASS_NAMES; static {
Map<String, String> m = new HashMap<String, String>();
m.put("h2", "org.h2.Driver");
m.put("jtds", "net.sourceforge.jtds.jdbc.Driver");
m.put("mysql", "com.mysql.jdbc.Driver");
m.put("postgresql", "org.postgresql.Driver");
DRIVER_CLASS_NAMES = m;
}
private static final Set<WeakReference<Driver>> REGISTERED_DRIVERS = new HashSet<WeakReference<Driver>>();
private DataSource createDataSource(
Map<String, Object> settings,
String dataSourceSetting,
String jdbcDriverClassSetting,
String jdbcUrlSetting,
String jdbcUserSetting,
String jdbcPasswordSetting,
String jdbcPoolSizeSetting) {
Object dataSourceObject = settings.get(dataSourceSetting);
if (dataSourceObject instanceof DataSource) {
return (DataSource) dataSourceObject;
} else {
String url = ObjectUtils.to(String.class, settings.get(jdbcUrlSetting));
if (ObjectUtils.isBlank(url)) {
return null;
} else {
String driverClassName = ObjectUtils.to(String.class, settings.get(jdbcDriverClassSetting));
Class<?> driverClass = null;
if (driverClassName != null) {
driverClass = ObjectUtils.getClassByName(driverClassName);
if (driverClass == null) {
throw new SettingsException(
jdbcDriverClassSetting,
String.format("Can't find [%s]!",
driverClassName));
} else if (!Driver.class.isAssignableFrom(driverClass)) {
throw new SettingsException(
jdbcDriverClassSetting,
String.format("[%s] doesn't implement [%s]!",
driverClass, Driver.class));
}
} else {
int firstColonAt = url.indexOf(':');
if (firstColonAt > -1) {
++ firstColonAt;
int secondColonAt = url.indexOf(':', firstColonAt);
if (secondColonAt > -1) {
driverClass = ObjectUtils.getClassByName(DRIVER_CLASS_NAMES.get(url.substring(firstColonAt, secondColonAt)));
}
}
}
if (driverClass != null) {
Driver driver = null;
for (Enumeration<Driver> e = DriverManager.getDrivers(); e.hasMoreElements(); ) {
Driver d = e.nextElement();
if (driverClass.isInstance(d)) {
driver = d;
break;
}
}
if (driver == null) {
driver = (Driver) TypeDefinition.getInstance(driverClass).newInstance();
try {
LOGGER.info("Registering [{}]", driver);
DriverManager.registerDriver(driver);
} catch (SQLException ex) {
LOGGER.warn("Can't register [{}]!", driver);
}
}
if (driver != null) {
REGISTERED_DRIVERS.add(new WeakReference<Driver>(driver));
}
}
String user = ObjectUtils.to(String.class, settings.get(jdbcUserSetting));
String password = ObjectUtils.to(String.class, settings.get(jdbcPasswordSetting));
Integer poolSize = ObjectUtils.to(Integer.class, settings.get(jdbcPoolSizeSetting));
if (poolSize == null || poolSize <= 0) {
poolSize = 24;
}
int partitionCount = 3;
int connectionsPerPartition = poolSize / partitionCount;
LOGGER.info("Automatically creating BoneCP data source:" +
"\n\turl={}" +
"\n\tusername={}" +
"\n\tpoolSize={}" +
"\n\tconnectionsPerPartition={}" +
"\n\tpartitionCount={}", new Object[] {
url,
user,
poolSize,
connectionsPerPartition,
partitionCount
});
BoneCPDataSource bone = new BoneCPDataSource();
bone.setJdbcUrl(url);
bone.setUsername(user);
bone.setPassword(password);
bone.setMinConnectionsPerPartition(connectionsPerPartition);
bone.setMaxConnectionsPerPartition(connectionsPerPartition);
bone.setPartitionCount(partitionCount);
bone.setConnectionTimeoutInMs(5000L);
return bone;
}
}
}
/** Returns the read timeout associated with the given {@code query}. */
private int getQueryReadTimeout(Query<?> query) {
if (query != null) {
Double timeout = query.getTimeout();
if (timeout == null) {
timeout = getReadTimeout();
}
if (timeout > 0.0) {
return (int) Math.round(timeout);
}
}
return 0;
}
@Override
public <T> List<T> readAll(Query<T> query) {
return selectListWithOptions(buildSelectStatement(query), query);
}
@Override
public long readCount(Query<?> query) {
String sqlQuery = buildCountStatement(query);
Connection connection = null;
Statement statement = null;
ResultSet result = null;
try {
connection = openQueryConnection(query);
statement = connection.createStatement();
result = executeQueryBeforeTimeout(statement, sqlQuery, getQueryReadTimeout(query));
if (result.next()) {
Object countObj = result.getObject(1);
if (countObj instanceof Number) {
return ((Number) countObj).longValue();
}
}
return 0;
} catch (SQLException ex) {
throw createQueryException(ex, sqlQuery, query);
} finally {
closeResources(query, connection, statement, result);
}
}
@Override
public <T> T readFirst(Query<T> query) {
if (query.getSorters().isEmpty()) {
Predicate predicate = query.getPredicate();
if (predicate instanceof CompoundPredicate) {
CompoundPredicate compoundPredicate = (CompoundPredicate) predicate;
if (PredicateParser.OR_OPERATOR.equals(compoundPredicate.getOperator())) {
for (Predicate child : compoundPredicate.getChildren()) {
Query<T> childQuery = query.clone();
childQuery.setPredicate(child);
T first = readFirst(childQuery);
if (first != null) {
return first;
}
}
return null;
}
}
}
return selectFirstWithOptions(buildSelectStatement(query), query);
}
@Override
public <T> Iterable<T> readIterable(Query<T> query, int fetchSize) {
Boolean useJdbc = ObjectUtils.to(Boolean.class, query.getOptions().get(USE_JDBC_FETCH_SIZE_QUERY_OPTION));
if (useJdbc == null) {
useJdbc = Boolean.TRUE;
}
if (useJdbc) {
return selectIterableWithOptions(buildSelectStatement(query), fetchSize, query);
} else {
return new ByIdIterable<T>(query, fetchSize);
}
}
private static class ByIdIterable<T> implements Iterable<T> {
private final Query<T> query;
private final int fetchSize;
public ByIdIterable(Query<T> query, int fetchSize) {
this.query = query;
this.fetchSize = fetchSize;
}
@Override
public Iterator<T> iterator() {
return new ByIdIterator<T>(query, fetchSize);
}
}
private static class ByIdIterator<T> implements Iterator<T> {
private final Query<T> query;
private final int fetchSize;
private UUID lastTypeId;
private UUID lastId;
private List<T> items;
private int index;
public ByIdIterator(Query<T> query, int fetchSize) {
if (!query.getSorters().isEmpty()) {
throw new IllegalArgumentException("Can't iterate over a query that has sorters!");
}
this.query = query.clone().timeout(0.0).sortAscending("_type").sortAscending("_id");
this.fetchSize = fetchSize > 0 ? fetchSize : 200;
}
@Override
public boolean hasNext() {
if (items != null && items.isEmpty()) {
return false;
}
if (items == null || index >= items.size()) {
Query<T> nextQuery = query.clone();
if (lastTypeId != null) {
nextQuery.and("_type = ? and _id > ?", lastTypeId, lastId);
}
items = nextQuery.select(0, fetchSize).getItems();
int size = items.size();
if (size < 1) {
if (lastTypeId == null) {
return false;
} else {
nextQuery = query.clone().and("_type > ?", lastTypeId);
items = nextQuery.select(0, fetchSize).getItems();
size = items.size();
if (size < 1) {
return false;
}
}
}
State lastState = State.getInstance(items.get(size - 1));
lastTypeId = lastState.getTypeId();
lastId = lastState.getId();
index = 0;
}
return true;
}
@Override
public T next() {
if (hasNext()) {
T object = items.get(index);
++ index;
return object;
} else {
throw new NoSuchElementException();
}
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
@Override
public Date readLastUpdate(Query<?> query) {
String sqlQuery = buildLastUpdateStatement(query);
Connection connection = null;
Statement statement = null;
ResultSet result = null;
try {
connection = openQueryConnection(query);
statement = connection.createStatement();
result = executeQueryBeforeTimeout(statement, sqlQuery, getQueryReadTimeout(query));
if (result.next()) {
Double date = result.getDouble(1);
if (date != null) {
return new Date((long) (date * 1000L));
}
}
return null;
} catch (SQLException ex) {
throw createQueryException(ex, sqlQuery, query);
} finally {
closeResources(query, connection, statement, result);
}
}
@Override
public <T> PaginatedResult<T> readPartial(final Query<T> query, long offset, int limit) {
List<T> objects = selectListWithOptions(
vendor.rewriteQueryWithLimitClause(buildSelectStatement(query), limit + 1, offset),
query);
int size = objects.size();
if (size <= limit) {
return new PaginatedResult<T>(offset, limit, offset + size, objects);
} else {
objects.remove(size - 1);
return new PaginatedResult<T>(offset, limit, 0, objects) {
private Long count;
@Override
public long getCount() {
if (count == null) {
count = readCount(query);
}
return count;
}
@Override
public boolean hasNext() {
return true;
}
};
}
}
@Override
public <T> PaginatedResult<Grouping<T>> readPartialGrouped(Query<T> query, long offset, int limit, String... fields) {
List<Grouping<T>> groupings = new ArrayList<Grouping<T>>();
String sqlQuery = buildGroupStatement(query, fields);
Connection connection = null;
Statement statement = null;
ResultSet result = null;
try {
connection = openQueryConnection(query);
statement = connection.createStatement();
result = executeQueryBeforeTimeout(statement, sqlQuery, getQueryReadTimeout(query));
int fieldsLength = fields.length;
int groupingsCount = 0;
for (int i = 0, last = (int) offset + limit; result.next(); ++ i, ++ groupingsCount) {
if (i < offset || i >= last) {
continue;
}
List<Object> keys = new ArrayList<Object>();
SqlGrouping<T> grouping;
ResultSetMetaData meta = result.getMetaData();
String aggregateColumnName = meta.getColumnName(1);
if (aggregateColumnName.equals("_count")) {
long count = ObjectUtils.to(long.class, result.getObject(1));
for (int j = 0; j < fieldsLength; ++ j) {
keys.add(result.getObject(j + 2));
}
grouping = new SqlGrouping<T>(keys, query, fields, count, groupings);
} else {
Double amount = ObjectUtils.to(Double.class, result.getObject(1));
for (int j = 0; j < fieldsLength; ++ j) {
keys.add(result.getObject(j + 3));
}
long count = 0L;
if (meta.getColumnName(2).equals("_count")) {
count = ObjectUtils.to(long.class, result.getObject(2));
}
grouping = new SqlGrouping<T>(keys, query, fields, count, groupings);
if (amount == null) amount = 0d;
grouping.setSum(aggregateColumnName, amount);
}
groupings.add(grouping);
}
int groupingsSize = groupings.size();
for (int i = 0; i < fieldsLength; ++ i) {
ObjectField field = query.mapEmbeddedKey(getEnvironment(), fields[i]).getField();
if (field != null) {
Map<String, Object> rawKeys = new HashMap<String, Object>();
for (int j = 0; j < groupingsSize; ++ j) {
rawKeys.put(String.valueOf(j), groupings.get(j).getKeys().get(i));
}
String itemType = field.getInternalItemType();
if (ObjectField.RECORD_TYPE.equals(itemType)) {
for (Map.Entry<String, Object> entry : rawKeys.entrySet()) {
Map<String, Object> ref = new HashMap<String, Object>();
ref.put(StateValueUtils.REFERENCE_KEY, entry.getValue());
entry.setValue(ref);
}
}
Map<?, ?> convertedKeys = (Map<?, ?>) StateValueUtils.toJavaValue(query.getDatabase(), null, field, "map/" + itemType, rawKeys);
for (int j = 0; j < groupingsSize; ++ j) {
groupings.get(j).getKeys().set(i, convertedKeys.get(String.valueOf(j)));
}
}
}
return new PaginatedResult<Grouping<T>>(offset, limit, groupingsCount, groupings);
} catch (SQLException ex) {
throw createQueryException(ex, sqlQuery, query);
} finally {
closeResources(query, connection, statement, result);
}
}
/** SQL-specific implementation of {@link Grouping}. */
private class SqlGrouping<T> extends AbstractGrouping<T> {
private long count;
private final Map<String,Double> metricSums = new HashMap<String,Double>();
private final List<Grouping<T>> groupings;
public SqlGrouping(List<Object> keys, Query<T> query, String[] fields, long count, List<Grouping<T>> groupings) {
super(keys, query, fields);
this.count = count;
this.groupings = groupings;
}
@Override
public double getSum(String field) {
Query.MappedKey mappedKey = this.query.mapEmbeddedKey(getEnvironment(), field);
ObjectField sumField = mappedKey.getField();
if (sumField.as(Metric.FieldData.class).isMetricValue()) {
if (! metricSums.containsKey(field)) {
String sqlQuery = buildGroupedMetricStatement(query, field, fields);
Connection connection = null;
Statement statement = null;
ResultSet result = null;
try {
connection = openQueryConnection(query);
statement = connection.createStatement();
result = executeQueryBeforeTimeout(statement, sqlQuery, getQueryReadTimeout(query));
if (this.getKeys().size() == 0) {
// Special case for .groupby() without any fields
if (this.groupings.size() != 1) throw new RuntimeException("There should only be one grouping when grouping by nothing. Something went wrong internally.");
if (result.next() && result.getBytes(1) != null) {
this.setSum(field, result.getDouble(1));
} else {
this.setSum(field, 0);
}
} else {
// Find the ObjectFields for the specified fields
List<ObjectField> objectFields = new ArrayList<ObjectField>();
for (String fieldName : fields) {
objectFields.add(query.mapEmbeddedKey(getEnvironment(), fieldName).getField());
}
// index the groupings by their keys
Map<List<Object>, SqlGrouping<T>> groupingMap = new HashMap<List<Object>, SqlGrouping<T>>();
for (Grouping<T> grouping : groupings) {
if (grouping instanceof SqlGrouping) {
((SqlGrouping<T>) grouping).setSum(field, 0);
groupingMap.put(grouping.getKeys(), (SqlGrouping<T>) grouping);
}
}
// Find the sums and set them on each grouping
while (result.next()) {
// TODO: limit/offset
List<Object> keys = new ArrayList<Object>();
for (int j = 0; j < objectFields.size(); ++ j) {
keys.add(StateValueUtils.toJavaValue(query.getDatabase(), null, objectFields.get(j), objectFields.get(j).getInternalItemType(), result.getObject(j+3))); // 3 because _count and amount
}
if (groupingMap.containsKey(keys)) {
if (result.getBytes(1) != null) {
groupingMap.get(keys).setSum(field, result.getDouble(1));
} else {
groupingMap.get(keys).setSum(field, 0);
}
}
}
}
} catch (SQLException ex) {
throw createQueryException(ex, sqlQuery, query);
} finally {
closeResources(query, connection, statement, result);
}
}
if (metricSums.containsKey(field))
return metricSums.get(field);
else
return 0;
} else {
// If it's not a MetricValue, we don't need to override it.
return super.getSum(field);
}
}
private void setSum(String field, double sum) {
metricSums.put(field, sum);
}
@Override
protected Aggregate createAggregate(String field) {
throw new UnsupportedOperationException();
}
@Override
public long getCount() {
return count;
}
}
@Override
protected void beginTransaction(Connection connection, boolean isImmediate) throws SQLException {
connection.setAutoCommit(false);
}
@Override
protected void commitTransaction(Connection connection, boolean isImmediate) throws SQLException {
connection.commit();
}
@Override
protected void rollbackTransaction(Connection connection, boolean isImmediate) throws SQLException {
connection.rollback();
}
@Override
protected void endTransaction(Connection connection, boolean isImmediate) throws SQLException {
connection.setAutoCommit(true);
}
@Override
protected void doSaves(Connection connection, boolean isImmediate, List<State> states) throws SQLException {
List<State> indexStates = null;
for (State state1 : states) {
if (Boolean.TRUE.equals(state1.getExtra(SKIP_INDEX_STATE_EXTRA))) {
indexStates = new ArrayList<State>();
for (State state2 : states) {
if (!Boolean.TRUE.equals(state2.getExtra(SKIP_INDEX_STATE_EXTRA))) {
indexStates.add(state2);
}
}
break;
}
}
if (indexStates == null) {
indexStates = states;
}
SqlIndex.Static.deleteByStates(this, connection, indexStates);
Map<State, String> inRowIndexes = SqlIndex.Static.insertByStates(this, connection, indexStates);
boolean hasInRowIndex = hasInRowIndex();
SqlVendor vendor = getVendor();
double now = System.currentTimeMillis() / 1000.0;
for (State state : states) {
boolean isNew = state.isNew();
boolean saveInRowIndex = hasInRowIndex && !Boolean.TRUE.equals(state.getExtra(SKIP_INDEX_STATE_EXTRA));
UUID id = state.getId();
UUID typeId = state.getVisibilityAwareTypeId();
byte[] dataBytes = null;
String inRowIndex = inRowIndexes.get(state);
byte[] inRowIndexBytes = inRowIndex != null ? inRowIndex.getBytes(StringUtils.UTF_8) : new byte[0];
while (true) {
if (isNew) {
try {
if (dataBytes == null) {
dataBytes = serializeState(state);
}
List<Object> parameters = new ArrayList<Object>();
StringBuilder insertBuilder = new StringBuilder();
insertBuilder.append("INSERT INTO ");
vendor.appendIdentifier(insertBuilder, RECORD_TABLE);
insertBuilder.append(" (");
vendor.appendIdentifier(insertBuilder, ID_COLUMN);
insertBuilder.append(",");
vendor.appendIdentifier(insertBuilder, TYPE_ID_COLUMN);
insertBuilder.append(",");
vendor.appendIdentifier(insertBuilder, DATA_COLUMN);
if (saveInRowIndex) {
insertBuilder.append(",");
vendor.appendIdentifier(insertBuilder, IN_ROW_INDEX_COLUMN);
}
insertBuilder.append(") VALUES (");
vendor.appendBindValue(insertBuilder, id, parameters);
insertBuilder.append(",");
vendor.appendBindValue(insertBuilder, typeId, parameters);
insertBuilder.append(",");
vendor.appendBindValue(insertBuilder, dataBytes, parameters);
if (saveInRowIndex) {
insertBuilder.append(",");
vendor.appendBindValue(insertBuilder, inRowIndexBytes, parameters);
}
insertBuilder.append(")");
Static.executeUpdateWithList(connection, insertBuilder.toString(), parameters);
} catch (SQLException ex) {
if (Static.isIntegrityConstraintViolation(ex)) {
isNew = false;
continue;
} else {
throw ex;
}
}
} else {
List<AtomicOperation> atomicOperations = state.getAtomicOperations();
if (atomicOperations.isEmpty()) {
if (dataBytes == null) {
dataBytes = serializeState(state);
}
List<Object> parameters = new ArrayList<Object>();
StringBuilder updateBuilder = new StringBuilder();
updateBuilder.append("UPDATE ");
vendor.appendIdentifier(updateBuilder, RECORD_TABLE);
updateBuilder.append(" SET ");
vendor.appendIdentifier(updateBuilder, TYPE_ID_COLUMN);
updateBuilder.append("=");
vendor.appendBindValue(updateBuilder, typeId, parameters);
updateBuilder.append(",");
if (saveInRowIndex) {
vendor.appendIdentifier(updateBuilder, IN_ROW_INDEX_COLUMN);
updateBuilder.append("=");
vendor.appendBindValue(updateBuilder, inRowIndexBytes, parameters);
updateBuilder.append(",");
}
vendor.appendIdentifier(updateBuilder, DATA_COLUMN);
updateBuilder.append("=");
vendor.appendBindValue(updateBuilder, dataBytes, parameters);
updateBuilder.append(" WHERE ");
vendor.appendIdentifier(updateBuilder, ID_COLUMN);
updateBuilder.append("=");
vendor.appendBindValue(updateBuilder, id, parameters);
if (Static.executeUpdateWithList(connection, updateBuilder.toString(), parameters) < 1) {
isNew = true;
continue;
}
} else {
Object oldObject = Query.
from(Object.class).
where("_id = ?", id).
using(this).
option(CONNECTION_QUERY_OPTION, connection).
option(RETURN_ORIGINAL_DATA_QUERY_OPTION, Boolean.TRUE).
option(USE_READ_DATA_SOURCE_QUERY_OPTION, Boolean.FALSE).
first();
if (oldObject == null) {
retryWrites();
break;
}
State oldState = State.getInstance(oldObject);
UUID oldTypeId = oldState.getVisibilityAwareTypeId();
byte[] oldData = Static.getOriginalData(oldObject);
state.setValues(oldState.getValues());
for (AtomicOperation operation : atomicOperations) {
String field = operation.getField();
state.putValue(field, oldState.getValue(field));
}
for (AtomicOperation operation : atomicOperations) {
operation.execute(state);
}
dataBytes = serializeState(state);
List<Object> parameters = new ArrayList<Object>();
StringBuilder updateBuilder = new StringBuilder();
updateBuilder.append("UPDATE ");
vendor.appendIdentifier(updateBuilder, RECORD_TABLE);
updateBuilder.append(" SET ");
vendor.appendIdentifier(updateBuilder, TYPE_ID_COLUMN);
updateBuilder.append("=");
vendor.appendBindValue(updateBuilder, typeId, parameters);
if (saveInRowIndex) {
updateBuilder.append(",");
vendor.appendIdentifier(updateBuilder, IN_ROW_INDEX_COLUMN);
updateBuilder.append("=");
vendor.appendBindValue(updateBuilder, inRowIndexBytes, parameters);
}
updateBuilder.append(",");
vendor.appendIdentifier(updateBuilder, DATA_COLUMN);
updateBuilder.append("=");
vendor.appendBindValue(updateBuilder, dataBytes, parameters);
updateBuilder.append(" WHERE ");
vendor.appendIdentifier(updateBuilder, ID_COLUMN);
updateBuilder.append("=");
vendor.appendBindValue(updateBuilder, id, parameters);
updateBuilder.append(" AND ");
vendor.appendIdentifier(updateBuilder, TYPE_ID_COLUMN);
updateBuilder.append("=");
vendor.appendBindValue(updateBuilder, oldTypeId, parameters);
updateBuilder.append(" AND ");
vendor.appendIdentifier(updateBuilder, DATA_COLUMN);
updateBuilder.append("=");
vendor.appendBindValue(updateBuilder, oldData, parameters);
if (Static.executeUpdateWithList(connection, updateBuilder.toString(), parameters) < 1) {
retryWrites();
break;
}
}
}
break;
}
while (true) {
if (isNew) {
List<Object> parameters = new ArrayList<Object>();
StringBuilder insertBuilder = new StringBuilder();
insertBuilder.append("INSERT INTO ");
vendor.appendIdentifier(insertBuilder, RECORD_UPDATE_TABLE);
insertBuilder.append(" (");
vendor.appendIdentifier(insertBuilder, ID_COLUMN);
insertBuilder.append(",");
vendor.appendIdentifier(insertBuilder, TYPE_ID_COLUMN);
insertBuilder.append(",");
vendor.appendIdentifier(insertBuilder, UPDATE_DATE_COLUMN);
insertBuilder.append(") VALUES (");
vendor.appendBindValue(insertBuilder, id, parameters);
insertBuilder.append(",");
vendor.appendBindValue(insertBuilder, typeId, parameters);
insertBuilder.append(",");
vendor.appendBindValue(insertBuilder, now, parameters);
insertBuilder.append(")");
try {
Static.executeUpdateWithList(connection, insertBuilder.toString(), parameters);
} catch (SQLException ex) {
if (Static.isIntegrityConstraintViolation(ex)) {
isNew = false;
continue;
} else {
throw ex;
}
}
} else {
List<Object> parameters = new ArrayList<Object>();
StringBuilder updateBuilder = new StringBuilder();
updateBuilder.append("UPDATE ");
vendor.appendIdentifier(updateBuilder, RECORD_UPDATE_TABLE);
updateBuilder.append(" SET ");
vendor.appendIdentifier(updateBuilder, TYPE_ID_COLUMN);
updateBuilder.append("=");
vendor.appendBindValue(updateBuilder, typeId, parameters);
updateBuilder.append(",");
vendor.appendIdentifier(updateBuilder, UPDATE_DATE_COLUMN);
updateBuilder.append("=");
vendor.appendBindValue(updateBuilder, now, parameters);
updateBuilder.append(" WHERE ");
vendor.appendIdentifier(updateBuilder, ID_COLUMN);
updateBuilder.append("=");
vendor.appendBindValue(updateBuilder, id, parameters);
if (Static.executeUpdateWithList(connection, updateBuilder.toString(), parameters) < 1) {
isNew = true;
continue;
}
}
break;
}
}
}
@Override
protected void doIndexes(Connection connection, boolean isImmediate, List<State> states) throws SQLException {
SqlIndex.Static.deleteByStates(this, connection, states);
Map<State, String> inRowIndexes = SqlIndex.Static.insertByStates(this, connection, states);
if (!hasInRowIndex()) {
return;
}
SqlVendor vendor = getVendor();
for (Map.Entry<State, String> entry : inRowIndexes.entrySet()) {
StringBuilder updateBuilder = new StringBuilder();
updateBuilder.append("UPDATE ");
vendor.appendIdentifier(updateBuilder, RECORD_TABLE);
updateBuilder.append(" SET ");
vendor.appendIdentifier(updateBuilder, IN_ROW_INDEX_COLUMN);
updateBuilder.append("=");
vendor.appendValue(updateBuilder, entry.getValue());
updateBuilder.append(" WHERE ");
vendor.appendIdentifier(updateBuilder, ID_COLUMN);
updateBuilder.append("=");
vendor.appendValue(updateBuilder, entry.getKey().getId());
Static.executeUpdateWithArray(connection, updateBuilder.toString());
}
}
/** @deprecated Use {@link #index} instead. */
@Deprecated
public void fixIndexes(List<State> states) {
Connection connection = openConnection();
try {
doIndexes(connection, true, states);
} catch (SQLException ex) {
List<UUID> ids = new ArrayList<UUID>();
for (State state : states) {
ids.add(state.getId());
}
throw new SqlDatabaseException(this, String.format(
"Can't index states! (%s)", ids));
} finally {
closeConnection(connection);
}
}
@Override
protected void doDeletes(Connection connection, boolean isImmediate, List<State> states) throws SQLException {
SqlVendor vendor = getVendor();
StringBuilder whereBuilder = new StringBuilder();
whereBuilder.append(" WHERE ");
vendor.appendIdentifier(whereBuilder, ID_COLUMN);
whereBuilder.append(" IN (");
for (State state : states) {
vendor.appendValue(whereBuilder, state.getId());
whereBuilder.append(",");
}
whereBuilder.setCharAt(whereBuilder.length() - 1, ')');
StringBuilder deleteBuilder = new StringBuilder();
deleteBuilder.append("DELETE FROM ");
vendor.appendIdentifier(deleteBuilder, RECORD_TABLE);
deleteBuilder.append(whereBuilder);
Static.executeUpdateWithArray(connection, deleteBuilder.toString());
SqlIndex.Static.deleteByStates(this, connection, states);
StringBuilder updateBuilder = new StringBuilder();
updateBuilder.append("UPDATE ");
vendor.appendIdentifier(updateBuilder, RECORD_UPDATE_TABLE);
updateBuilder.append(" SET ");
vendor.appendIdentifier(updateBuilder, UPDATE_DATE_COLUMN);
updateBuilder.append("=");
vendor.appendValue(updateBuilder, System.currentTimeMillis() / 1000.0);
updateBuilder.append(whereBuilder);
Static.executeUpdateWithArray(connection, updateBuilder.toString());
}
@FieldData.FieldInternalNamePrefix("sql.")
public static class FieldData extends Modification<ObjectField> {
private String indexTable;
private String indexTableColumnName;
private boolean indexTableReadOnly;
private boolean indexTableSameColumnNames;
private boolean indexTableSource;
public String getIndexTable() {
return indexTable;
}
public void setIndexTable(String indexTable) {
this.indexTable = indexTable;
}
public boolean isIndexTableReadOnly() {
return indexTableReadOnly;
}
public void setIndexTableReadOnly(boolean indexTableReadOnly) {
this.indexTableReadOnly = indexTableReadOnly;
}
public boolean isIndexTableSameColumnNames() {
return indexTableSameColumnNames;
}
public void setIndexTableSameColumnNames(boolean indexTableSameColumnNames) {
this.indexTableSameColumnNames = indexTableSameColumnNames;
}
public void setIndexTableColumnName(String indexTableColumnName) {
this.indexTableColumnName = indexTableColumnName;
}
public String getIndexTableColumnName() {
return this.indexTableColumnName;
}
public boolean isIndexTableSource() {
return indexTableSource;
}
public void setIndexTableSource(boolean indexTableSource) {
this.indexTableSource = indexTableSource;
}
public boolean isIndexTableSourceFromAnywhere() {
if (isIndexTableSource()) {
return true;
}
ObjectField field = getOriginalObject();
ObjectStruct parent = field.getParent();
String fieldName = field.getInternalName();
for (ObjectIndex index : parent.getIndexes()) {
List<String> indexFieldNames = index.getFields();
if (!indexFieldNames.isEmpty() &&
indexFieldNames.contains(fieldName)) {
String firstIndexFieldName = indexFieldNames.get(0);
if (!fieldName.equals(firstIndexFieldName)) {
ObjectField firstIndexField = parent.getField(firstIndexFieldName);
if (firstIndexField != null) {
return firstIndexField.as(FieldData.class).isIndexTableSource();
}
}
}
}
return false;
}
}
/** Specifies the name of the table for storing target field values. */
@Documented
@ObjectField.AnnotationProcessorClass(FieldIndexTableProcessor.class)
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface FieldIndexTable {
String value();
boolean readOnly() default false;
boolean sameColumnNames() default false;
boolean source() default false;
}
private static class FieldIndexTableProcessor implements ObjectField.AnnotationProcessor<FieldIndexTable> {
@Override
public void process(ObjectType type, ObjectField field, FieldIndexTable annotation) {
FieldData data = field.as(FieldData.class);
data.setIndexTable(annotation.value());
data.setIndexTableSameColumnNames(annotation.sameColumnNames());
data.setIndexTableSource(annotation.source());
data.setIndexTableReadOnly(annotation.readOnly());
}
}
/** {@link SqlDatabase} utility methods. */
public static final class Static {
private Static() {
}
public static List<SqlDatabase> getAll() {
return INSTANCES;
}
public static void deregisterAllDrivers() {
for (WeakReference<Driver> driverRef : REGISTERED_DRIVERS) {
Driver driver = driverRef.get();
if (driver != null) {
LOGGER.info("Deregistering [{}]", driver);
try {
DriverManager.deregisterDriver(driver);
} catch (SQLException ex) {
LOGGER.warn("Can't deregister [{}]!", driver);
}
}
}
}
/**
* Log a batch update exception with values.
*/
static void logBatchUpdateException(BatchUpdateException bue, String sqlQuery, List<? extends List<?>> parameters) {
int i = 0;
int failureOffset = bue.getUpdateCounts().length;
List<?> rowData = parameters.get(failureOffset);
StringBuilder errorBuilder = new StringBuilder();
errorBuilder.append("Batch update failed with query '");
errorBuilder.append(sqlQuery);
errorBuilder.append("' with values (");
for (Object value : rowData) {
if (i++ != 0) {
errorBuilder.append(", ");
}
if (value instanceof byte[]) {
errorBuilder.append(StringUtils.hex((byte[]) value));
} else {
errorBuilder.append(value);
}
}
errorBuilder.append(")");
Exception ex = bue.getNextException() != null ? bue.getNextException() : bue;
LOGGER.error(errorBuilder.toString(), ex);
}
static void logUpdateException(String sqlQuery, List<?> parameters) {
int i = 0;
StringBuilder errorBuilder = new StringBuilder();
errorBuilder.append("Batch update failed with query '");
errorBuilder.append(sqlQuery);
errorBuilder.append("' with values (");
for (Object value : parameters) {
if (i++ != 0) {
errorBuilder.append(", ");
}
if (value instanceof byte[]) {
errorBuilder.append(StringUtils.hex((byte[]) value));
} else {
errorBuilder.append(value);
}
}
errorBuilder.append(")");
LOGGER.error(errorBuilder.toString());
}
// Safely binds the given parameter to the given statement at the
// given index.
private static void bindParameter(PreparedStatement statement, int index, Object parameter) throws SQLException {
if (parameter instanceof String) {
parameter = ((String) parameter).getBytes(StringUtils.UTF_8);
}
if (parameter instanceof byte[]) {
byte[] parameterBytes = (byte[]) parameter;
int parameterBytesLength = parameterBytes.length;
if (parameterBytesLength > 2000) {
statement.setBinaryStream(index, new ByteArrayInputStream(parameterBytes), parameterBytesLength);
return;
}
}
statement.setObject(index, parameter);
}
/**
* Executes the given batch update {@code sqlQuery} with the given
* list of {@code parameters} within the given {@code connection}.
*
* @return Array of number of rows affected by the update query.
*/
public static int[] executeBatchUpdate(
Connection connection,
String sqlQuery,
List<? extends List<?>> parameters) throws SQLException {
PreparedStatement prepared = connection.prepareStatement(sqlQuery);
List<?> currentRow = null;
try {
for (List<?> row : parameters) {
currentRow = row;
int columnIndex = 1;
for (Object parameter : row) {
bindParameter(prepared, columnIndex, parameter);
columnIndex++;
}
prepared.addBatch();
}
int[] affected = null;
Stats.Timer timer = STATS.startTimer();
Profiler.Static.startThreadEvent(UPDATE_PROFILER_EVENT);
try {
return (affected = prepared.executeBatch());
} finally {
double time = timer.stop(UPDATE_STATS_OPERATION);
Profiler.Static.stopThreadEvent(sqlQuery);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(
"SQL batch update: [{}], Parameters: {}, Affected: {}, Time: [{}]ms",
new Object[] { sqlQuery, parameters, affected != null ? Arrays.toString(affected) : "[]", time });
}
}
} catch (SQLException error) {
logUpdateException(sqlQuery, currentRow);
throw error;
} finally {
try {
prepared.close();
} catch (SQLException error) {
}
}
}
/**
* Executes the given update {@code sqlQuery} with the given
* {@code parameters} within the given {@code connection}.
*
* @return Number of rows affected by the update query.
*/
public static int executeUpdateWithList(
Connection connection,
String sqlQuery,
List<?> parameters)
throws SQLException {
if (parameters == null) {
return executeUpdateWithArray(connection, sqlQuery);
} else {
Object[] array = parameters.toArray(new Object[parameters.size()]);
return executeUpdateWithArray(connection, sqlQuery, array);
}
}
/**
* Executes the given update {@code sqlQuery} with the given
* {@code parameters} within the given {@code connection}.
*
* @return Number of rows affected by the update query.
*/
public static int executeUpdateWithArray(
Connection connection,
String sqlQuery,
Object... parameters)
throws SQLException {
boolean hasParameters = parameters != null && parameters.length > 0;
PreparedStatement prepared;
Statement statement;
if (hasParameters) {
prepared = connection.prepareStatement(sqlQuery);
statement = prepared;
} else {
prepared = null;
statement = connection.createStatement();
}
try {
if (hasParameters) {
for (int i = 0; i < parameters.length; i++) {
bindParameter(prepared, i + 1, parameters[i]);
}
}
Integer affected = null;
Stats.Timer timer = STATS.startTimer();
Profiler.Static.startThreadEvent(UPDATE_PROFILER_EVENT);
try {
return (affected = hasParameters ?
prepared.executeUpdate() :
statement.executeUpdate(sqlQuery));
} finally {
double time = timer.stop(UPDATE_STATS_OPERATION);
Profiler.Static.stopThreadEvent(sqlQuery);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(
"SQL update: [{}], Affected: [{}], Time: [{}]ms",
new Object[] { fillPlaceholders(sqlQuery, parameters), affected, time });
}
}
} finally {
try {
statement.close();
} catch (SQLException ex) {
}
}
}
/**
* Returns {@code true} if the given {@code error} looks like a
* {@link SQLIntegrityConstraintViolationException}.
*/
public static boolean isIntegrityConstraintViolation(SQLException error) {
if (error instanceof SQLIntegrityConstraintViolationException) {
return true;
} else {
String state = error.getSQLState();
return state != null && state.startsWith("23");
}
}
/**
* Returns the name of the table for storing the values of the
* given {@code index}.
*/
public static String getIndexTable(ObjectIndex index) {
return ObjectUtils.to(String.class, index.getOptions().get(INDEX_TABLE_INDEX_OPTION));
}
/**
* Sets the name of the table for storing the values of the
* given {@code index}.
*/
public static void setIndexTable(ObjectIndex index, String table) {
index.getOptions().put(INDEX_TABLE_INDEX_OPTION, table);
}
public static Object getExtraColumn(Object object, String name) {
return State.getInstance(object).getExtra(EXTRA_COLUMN_EXTRA_PREFIX + name);
}
public static byte[] getOriginalData(Object object) {
return (byte[]) State.getInstance(object).getExtra(ORIGINAL_DATA_EXTRA);
}
/** @deprecated Use {@link #executeUpdateWithArray} instead. */
@Deprecated
public static int executeUpdate(
Connection connection,
String sqlQuery,
Object... parameters)
throws SQLException {
return executeUpdateWithArray(connection, sqlQuery, parameters);
}
}
/** @deprecated No replacement. */
@Deprecated
public void beginThreadLocalReadConnection() {
}
/** @deprecated No replacement. */
@Deprecated
public void endThreadLocalReadConnection() {
}
} |
package com.psddev.dari.db;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.ref.WeakReference;
import java.nio.charset.StandardCharsets;
import java.sql.BatchUpdateException;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.SQLIntegrityConstraintViolationException;
import java.sql.SQLRecoverableException;
import java.sql.SQLTimeoutException;
import java.sql.Savepoint;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import javax.sql.DataSource;
import com.zaxxer.hikari.HikariDataSource;
import org.iq80.snappy.Snappy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Supplier;
import com.google.common.base.Suppliers;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.util.concurrent.UncheckedExecutionException;
import com.psddev.dari.util.CompactMap;
import com.psddev.dari.util.Lazy;
import com.psddev.dari.util.ObjectUtils;
import com.psddev.dari.util.PaginatedResult;
import com.psddev.dari.util.PeriodicValue;
import com.psddev.dari.util.Profiler;
import com.psddev.dari.util.Settings;
import com.psddev.dari.util.SettingsException;
import com.psddev.dari.util.Stats;
import com.psddev.dari.util.StringUtils;
import com.psddev.dari.util.TypeDefinition;
import com.psddev.dari.util.UuidUtils;
/** Database backed by a SQL engine. */
public class SqlDatabase extends AbstractDatabase<Connection> {
public static final String DATA_SOURCE_SETTING = "dataSource";
public static final String JDBC_DRIVER_CLASS_SETTING = "jdbcDriverClass";
public static final String JDBC_URL_SETTING = "jdbcUrl";
public static final String JDBC_USER_SETTING = "jdbcUser";
public static final String JDBC_PASSWORD_SETTING = "jdbcPassword";
public static final String JDBC_POOL_SIZE_SETTING = "jdbcPoolSize";
public static final String READ_DATA_SOURCE_SETTING = "readDataSource";
public static final String READ_JDBC_DRIVER_CLASS_SETTING = "readJdbcDriverClass";
public static final String READ_JDBC_URL_SETTING = "readJdbcUrl";
public static final String READ_JDBC_USER_SETTING = "readJdbcUser";
public static final String READ_JDBC_PASSWORD_SETTING = "readJdbcPassword";
public static final String READ_JDBC_POOL_SIZE_SETTING = "readJdbcPoolSize";
public static final String CATALOG_SUB_SETTING = "catalog";
public static final String METRIC_CATALOG_SUB_SETTING = "metricCatalog";
public static final String VENDOR_CLASS_SETTING = "vendorClass";
public static final String COMPRESS_DATA_SUB_SETTING = "compressData";
@Deprecated
public static final String CACHE_DATA_SUB_SETTING = "cacheData";
@Deprecated
public static final String DATA_CACHE_SIZE_SUB_SETTING = "dataCacheSize";
public static final String ENABLE_REPLICATION_CACHE_SUB_SETTING = "enableReplicationCache";
public static final String ENABLE_FUNNEL_CACHE_SUB_SETTING = "enableFunnelCache";
public static final String REPLICATION_CACHE_SIZE_SUB_SETTING = "replicationCacheSize";
public static final String RECORD_TABLE = "Record";
public static final String RECORD_UPDATE_TABLE = "RecordUpdate";
public static final String SYMBOL_TABLE = "Symbol";
public static final String ID_COLUMN = "id";
public static final String TYPE_ID_COLUMN = "typeId";
public static final String IN_ROW_INDEX_COLUMN = "inRowIndex";
public static final String DATA_COLUMN = "data";
public static final String SYMBOL_ID_COLUMN = "symbolId";
public static final String UPDATE_DATE_COLUMN = "updateDate";
public static final String VALUE_COLUMN = "value";
public static final String CONNECTION_QUERY_OPTION = "sql.connection";
public static final String EXTRA_COLUMNS_QUERY_OPTION = "sql.extraColumns";
public static final String EXTRA_JOINS_QUERY_OPTION = "sql.extraJoins";
public static final String EXTRA_WHERE_QUERY_OPTION = "sql.extraWhere";
public static final String EXTRA_HAVING_QUERY_OPTION = "sql.extraHaving";
public static final String MYSQL_INDEX_HINT_QUERY_OPTION = "sql.mysqlIndexHint";
public static final String RETURN_ORIGINAL_DATA_QUERY_OPTION = "sql.returnOriginalData";
public static final String USE_JDBC_FETCH_SIZE_QUERY_OPTION = "sql.useJdbcFetchSize";
public static final String USE_READ_DATA_SOURCE_QUERY_OPTION = "sql.useReadDataSource";
public static final String DISABLE_REPLICATION_CACHE_QUERY_OPTION = "sql.disableReplicationCache";
public static final String SKIP_INDEX_STATE_EXTRA = "sql.skipIndex";
public static final String INDEX_TABLE_INDEX_OPTION = "sql.indexTable";
public static final String EXTRA_COLUMN_EXTRA_PREFIX = "sql.extraColumn.";
public static final String ORIGINAL_DATA_EXTRA = "sql.originalData";
public static final String SUB_DATA_COLUMN_ALIAS_PREFIX = "subData_";
private static final Logger LOGGER = LoggerFactory.getLogger(SqlDatabase.class);
private static final String SHORT_NAME = "SQL";
private static final Stats STATS = new Stats(SHORT_NAME);
private static final String CONNECTION_ERROR_STATS_OPERATION = "Connection Error";
private static final String QUERY_STATS_OPERATION = "Query";
private static final String UPDATE_STATS_OPERATION = "Update";
private static final String QUERY_PROFILER_EVENT = SHORT_NAME + " " + QUERY_STATS_OPERATION;
private static final String UPDATE_PROFILER_EVENT = SHORT_NAME + " " + UPDATE_STATS_OPERATION;
private static final String REPLICATION_CACHE_GET_PROFILER_EVENT = SHORT_NAME + " Replication Cache Get";
private static final String REPLICATION_CACHE_PUT_PROFILER_EVENT = SHORT_NAME + " Replication Cache Put";
private static final String FUNNEL_CACHE_GET_PROFILER_EVENT = SHORT_NAME + " Funnel Cache Get";
private static final String FUNNEL_CACHE_PUT_PROFILER_EVENT = SHORT_NAME + " Funnel Cache Put";
private static final long NOW_EXPIRATION_SECONDS = 300;
public static final long DEFAULT_REPLICATION_CACHE_SIZE = 10000L;
public static final long DEFAULT_DATA_CACHE_SIZE = 10000L;
private static final List<SqlDatabase> INSTANCES = new ArrayList<SqlDatabase>();
{
INSTANCES.add(this);
}
private volatile DataSource dataSource;
private volatile DataSource readDataSource;
private volatile String catalog;
private volatile String metricCatalog;
private transient volatile String defaultCatalog;
private volatile SqlVendor vendor;
private volatile boolean compressData;
private volatile boolean enableReplicationCache;
private volatile boolean enableFunnelCache;
private volatile long replicationCacheMaximumSize;
private final transient ConcurrentMap<Class<?>, UUID> singletonIds = new ConcurrentHashMap<>();
private transient volatile Cache<UUID, Object[]> replicationCache;
private transient volatile MySQLBinaryLogReader mysqlBinaryLogReader;
private transient volatile FunnelCache<SqlDatabase> funnelCache;
/**
* Quotes the given {@code identifier} so that it's safe to use
* in a SQL query.
*/
public static String quoteIdentifier(String identifier) {
return "\"" + StringUtils.replaceAll(identifier, "\\\\", "\\\\\\\\", "\"", "\"\"") + "\"";
}
/**
* Quotes the given {@code value} so that it's safe to use
* in a SQL query.
*/
public static String quoteValue(Object value) {
if (value == null) {
return "NULL";
} else if (value instanceof Number) {
return value.toString();
} else if (value instanceof byte[]) {
return "X'" + StringUtils.hex((byte[]) value) + "'";
} else {
return "'" + value.toString().replace("'", "''").replace("\\", "\\\\") + "'";
}
}
/** Closes all resources used by all instances. */
public static void closeAll() {
for (SqlDatabase database : INSTANCES) {
database.close();
}
INSTANCES.clear();
}
/**
* Creates an {@link SqlDatabaseException} that occurred during
* an execution of a query.
*/
private SqlDatabaseException createQueryException(
SQLException error,
String sqlQuery,
Query<?> query) {
String message = error.getMessage();
if (error instanceof SQLTimeoutException || message.contains("timeout")) {
return new SqlDatabaseException.ReadTimeout(this, error, sqlQuery, query);
} else {
return new SqlDatabaseException(this, error, sqlQuery, query);
}
}
/** Returns the JDBC data source used for general database operations. */
public DataSource getDataSource() {
return dataSource;
}
private static final Map<String, Class<? extends SqlVendor>> VENDOR_CLASSES; static {
Map<String, Class<? extends SqlVendor>> m = new HashMap<String, Class<? extends SqlVendor>>();
m.put("H2", SqlVendor.H2.class);
m.put("MySQL", SqlVendor.MySQL.class);
m.put("PostgreSQL", SqlVendor.PostgreSQL.class);
m.put("Oracle", SqlVendor.Oracle.class);
VENDOR_CLASSES = m;
}
/** Sets the JDBC data source used for general database operations. */
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
if (dataSource == null) {
return;
}
synchronized (this) {
try {
boolean writable = false;
if (vendor == null) {
Connection connection;
try {
connection = openConnection();
writable = true;
} catch (DatabaseException error) {
LOGGER.debug("Can't read vendor information from the writable server!", error);
connection = openReadConnection();
}
try {
defaultCatalog = connection.getCatalog();
DatabaseMetaData meta = connection.getMetaData();
String vendorName = meta.getDatabaseProductName();
Class<? extends SqlVendor> vendorClass = VENDOR_CLASSES.get(vendorName);
LOGGER.info(
"Initializing SQL vendor for [{}]: [{}] -> [{}]",
new Object[] { getName(), vendorName, vendorClass });
vendor = vendorClass != null ? TypeDefinition.getInstance(vendorClass).newInstance() : new SqlVendor();
vendor.setDatabase(this);
} finally {
closeConnection(connection);
}
}
tableColumnNames.refresh();
symbols.reset();
if (writable) {
vendor.setUp(this);
tableColumnNames.refresh();
symbols.reset();
}
} catch (IOException error) {
throw new IllegalStateException(error);
} catch (SQLException error) {
throw new SqlDatabaseException(this, "Can't check for required tables!", error);
}
}
}
/** Returns the JDBC data source used exclusively for read operations. */
public DataSource getReadDataSource() {
return this.readDataSource;
}
/** Sets the JDBC data source used exclusively for read operations. */
public void setReadDataSource(DataSource readDataSource) {
this.readDataSource = readDataSource;
}
public String getCatalog() {
return catalog;
}
public void setCatalog(String catalog) {
this.catalog = catalog;
try {
getVendor().setUp(this);
tableColumnNames.refresh();
symbols.reset();
} catch (IOException error) {
throw new IllegalStateException(error);
} catch (SQLException error) {
throw new SqlDatabaseException(this, "Can't check for required tables!", error);
}
}
/** Returns the catalog that contains the Metric table.
*
* @return May be {@code null}.
*
**/
public String getMetricCatalog() {
return metricCatalog;
}
public void setMetricCatalog(String metricCatalog) {
if (ObjectUtils.isBlank(metricCatalog)) {
this.metricCatalog = null;
} else {
StringBuilder str = new StringBuilder();
vendor.appendIdentifier(str, metricCatalog);
str.append(".");
vendor.appendIdentifier(str, MetricAccess.METRIC_TABLE);
if (getVendor().checkTableExists(str.toString())) {
this.metricCatalog = metricCatalog;
} else {
LOGGER.error("SqlDatabase#setMetricCatalog error: " + str.toString() + " does not exist or is not accessible. Falling back to default catalog.");
this.metricCatalog = null;
}
}
}
/** Returns the vendor-specific SQL engine information. */
public SqlVendor getVendor() {
return vendor;
}
/** Sets the vendor-specific SQL engine information. */
public void setVendor(SqlVendor vendor) {
this.vendor = vendor;
}
/** Returns {@code true} if the data should be compressed. */
public boolean isCompressData() {
return compressData;
}
/** Sets whether the data should be compressed. */
public void setCompressData(boolean compressData) {
this.compressData = compressData;
}
@Deprecated
public boolean isCacheData() {
return false;
}
@Deprecated
public void setCacheData(boolean cacheData) {
}
@Deprecated
public long getDataCacheMaximumSize() {
return 0L;
}
@Deprecated
public void setDataCacheMaximumSize(long dataCacheMaximumSize) {
}
public boolean isEnableReplicationCache() {
return enableReplicationCache;
}
public void setEnableReplicationCache(boolean enableReplicationCache) {
this.enableReplicationCache = enableReplicationCache;
}
public boolean isEnableFunnelCache() {
return enableFunnelCache;
}
public void setEnableFunnelCache(boolean enableFunnelCache) {
this.enableFunnelCache = enableFunnelCache;
}
public void setReplicationCacheMaximumSize(long replicationCacheMaximumSize) {
this.replicationCacheMaximumSize = replicationCacheMaximumSize;
}
public long getReplicationCacheMaximumSize() {
return this.replicationCacheMaximumSize;
}
/**
* Returns {@code true} if the {@link #RECORD_TABLE} in this database
* has the {@link #IN_ROW_INDEX_COLUMN}.
*/
public boolean hasInRowIndex() {
return hasInRowIndex;
}
/**
* Returns {@code true} if all comparisons executed in this database
* should ignore case by default.
*/
public boolean comparesIgnoreCase() {
return comparesIgnoreCase;
}
/**
* Returns {@code true} if this database contains a table with
* the given {@code name}.
*/
public boolean hasTable(String name) {
if (name == null) {
return false;
} else {
Set<String> names = tableColumnNames.get().keySet();
return names != null && names.contains(name.toLowerCase(Locale.ENGLISH));
}
}
/**
* Returns {@code true} if the given {@code table} in this database
* contains the given {@code column}.
*
* @param table If {@code null}, always returns {@code false}.
* @param column If {@code null}, always returns {@code false}.
*/
public boolean hasColumn(String table, String column) {
if (table == null || column == null) {
return false;
} else {
Set<String> columnNames = tableColumnNames.get().get(table.toLowerCase(Locale.ENGLISH));
return columnNames != null && columnNames.contains(column.toLowerCase(Locale.ENGLISH));
}
}
private transient volatile boolean hasInRowIndex;
private transient volatile boolean comparesIgnoreCase;
private final transient PeriodicValue<Map<String, Set<String>>> tableColumnNames = new PeriodicValue<Map<String, Set<String>>>(0.0, 60.0) {
@Override
protected Map<String, Set<String>> update() {
if (getDataSource() == null) {
return Collections.emptyMap();
}
Connection connection;
try {
connection = openConnection();
} catch (DatabaseException error) {
LOGGER.debug("Can't read table names from the writable server!", error);
connection = openReadConnection();
}
try {
SqlVendor vendor = getVendor();
String recordTable = null;
int maxStringVersion = 0;
Map<String, Set<String>> loweredNames = new HashMap<String, Set<String>>();
for (String name : vendor.getTables(connection)) {
String loweredName = name.toLowerCase(Locale.ENGLISH);
Set<String> loweredColumnNames = new HashSet<String>();
for (String columnName : vendor.getColumns(connection, name)) {
loweredColumnNames.add(columnName.toLowerCase(Locale.ENGLISH));
}
loweredNames.put(loweredName, loweredColumnNames);
if ("record".equals(loweredName)) {
recordTable = name;
} else if (loweredName.startsWith("recordstring")) {
int version = ObjectUtils.to(int.class, loweredName.substring(12));
if (version > maxStringVersion) {
maxStringVersion = version;
}
}
}
if (recordTable != null) {
hasInRowIndex = vendor.hasInRowIndex(connection, recordTable);
}
comparesIgnoreCase = maxStringVersion >= 3;
return loweredNames;
} catch (SQLException error) {
LOGGER.error("Can't query table names!", error);
return get();
} finally {
closeConnection(connection);
}
}
};
/**
* Returns an unique numeric ID for the given {@code symbol}.
*/
public int getSymbolId(String symbol) {
Integer id = symbols.get().get(symbol);
if (id == null) {
SqlVendor vendor = getVendor();
Connection connection = openConnection();
try {
List<Object> parameters = new ArrayList<Object>();
StringBuilder insertBuilder = new StringBuilder();
insertBuilder.append("INSERT /*! IGNORE */ INTO ");
vendor.appendIdentifier(insertBuilder, SYMBOL_TABLE);
insertBuilder.append(" (");
vendor.appendIdentifier(insertBuilder, VALUE_COLUMN);
insertBuilder.append(") VALUES (");
vendor.appendBindValue(insertBuilder, symbol, parameters);
insertBuilder.append(')');
String insertSql = insertBuilder.toString();
try {
Static.executeUpdateWithList(connection, insertSql, parameters);
} catch (SQLException ex) {
if (!Static.isIntegrityConstraintViolation(ex)) {
throw createQueryException(ex, insertSql, null);
}
}
StringBuilder selectBuilder = new StringBuilder();
selectBuilder.append("SELECT ");
vendor.appendIdentifier(selectBuilder, SYMBOL_ID_COLUMN);
selectBuilder.append(" FROM ");
vendor.appendIdentifier(selectBuilder, SYMBOL_TABLE);
selectBuilder.append(" WHERE ");
vendor.appendIdentifier(selectBuilder, VALUE_COLUMN);
selectBuilder.append('=');
vendor.appendValue(selectBuilder, symbol);
String selectSql = selectBuilder.toString();
Statement statement = null;
ResultSet result = null;
try {
statement = connection.createStatement();
result = statement.executeQuery(selectSql);
result.next();
id = result.getInt(1);
symbols.get().put(symbol, id);
} catch (SQLException ex) {
throw createQueryException(ex, selectSql, null);
} finally {
closeResources(null, null, statement, result);
}
} finally {
closeConnection(connection);
}
}
return id;
}
private final Supplier<Long> nowOffset = Suppliers.memoizeWithExpiration(new Supplier<Long>() {
@Override
public Long get() {
String selectSql = getVendor().getSelectTimestampMillisSql();
Connection connection;
Statement statement = null;
ResultSet result = null;
Long nowOffsetMillis = 0L;
if (selectSql != null) {
try {
connection = openConnection();
} catch (DatabaseException error) {
LOGGER.debug("Can't read timestamp from the writable server!", error);
connection = openReadConnection();
}
try {
statement = connection.createStatement();
result = statement.executeQuery(selectSql);
if (result.next()) {
nowOffsetMillis = System.currentTimeMillis() - result.getLong(1);
}
} catch (SQLException ex) {
throw createQueryException(ex, selectSql, null);
} finally {
closeResources(null, connection, statement, result);
}
}
return nowOffsetMillis;
}
}, NOW_EXPIRATION_SECONDS, TimeUnit.SECONDS);
@Override
public long now() {
return System.currentTimeMillis() - nowOffset.get();
}
// Cache of all internal symbols.
private final transient Lazy<Map<String, Integer>> symbols = new Lazy<Map<String, Integer>>() {
@Override
protected Map<String, Integer> create() {
SqlVendor vendor = getVendor();
StringBuilder selectBuilder = new StringBuilder();
selectBuilder.append("SELECT ");
vendor.appendIdentifier(selectBuilder, SYMBOL_ID_COLUMN);
selectBuilder.append(',');
vendor.appendIdentifier(selectBuilder, VALUE_COLUMN);
selectBuilder.append(" FROM ");
vendor.appendIdentifier(selectBuilder, SYMBOL_TABLE);
String selectSql = selectBuilder.toString();
Connection connection;
Statement statement = null;
ResultSet result = null;
try {
connection = openConnection();
} catch (DatabaseException error) {
LOGGER.debug("Can't read symbols from the writable server!", error);
connection = openReadConnection();
}
try {
statement = connection.createStatement();
result = statement.executeQuery(selectSql);
Map<String, Integer> symbols = new ConcurrentHashMap<String, Integer>();
while (result.next()) {
symbols.put(new String(result.getBytes(2), StandardCharsets.UTF_8), result.getInt(1));
}
return symbols;
} catch (SQLException ex) {
throw createQueryException(ex, selectSql, null);
} finally {
closeResources(null, connection, statement, result);
}
}
};
/**
* Returns the underlying JDBC connection.
*
* @deprecated Use {@link #openConnection} instead.
*/
@Deprecated
public Connection getConnection() {
return openConnection();
}
/** Closes any resources used by this database. */
public void close() {
DataSource dataSource = getDataSource();
if (dataSource instanceof HikariDataSource) {
LOGGER.info("Closing connection pool in {}", getName());
((HikariDataSource) dataSource).close();
}
DataSource readDataSource = getReadDataSource();
if (readDataSource instanceof HikariDataSource) {
LOGGER.info("Closing read connection pool in {}", getName());
((HikariDataSource) readDataSource).close();
}
setDataSource(null);
setReadDataSource(null);
if (mysqlBinaryLogReader != null) {
LOGGER.info("Stopping MySQL binary log reader");
mysqlBinaryLogReader.stop();
mysqlBinaryLogReader = null;
}
}
/**
* Builds an SQL statement that can be used to get a count of all
* objects matching the given {@code query}.
*/
public String buildCountStatement(Query<?> query) {
return new SqlQuery(this, query).countStatement();
}
/**
* Builds an SQL statement that can be used to delete all rows
* matching the given {@code query}.
*/
public String buildDeleteStatement(Query<?> query) {
return new SqlQuery(this, query).deleteStatement();
}
/**
* Builds an SQL statement that can be used to get all objects
* grouped by the values of the given {@code groupFields}.
*/
public String buildGroupStatement(Query<?> query, String... groupFields) {
return new SqlQuery(this, query).groupStatement(groupFields);
}
public String buildGroupedMetricStatement(Query<?> query, String metricFieldName, String... groupFields) {
return new SqlQuery(this, query).groupedMetricSql(metricFieldName, groupFields);
}
/**
* Builds an SQL statement that can be used to get when the objects
* matching the given {@code query} were last updated.
*/
public String buildLastUpdateStatement(Query<?> query) {
return new SqlQuery(this, query).lastUpdateStatement();
}
/**
* Maintains a cache of Querys to SQL select statements.
*/
private final LoadingCache<Query<?>, String> sqlQueryCache = CacheBuilder
.newBuilder()
.maximumSize(5000)
.concurrencyLevel(20)
.build(new CacheLoader<Query<?>, String>() {
@Override
public String load(Query<?> query) throws Exception {
return new SqlQuery(SqlDatabase.this, query).selectStatement();
}
});
/**
* Builds an SQL statement that can be used to list all rows
* matching the given {@code query}.
*/
public String buildSelectStatement(Query<?> query) {
try {
Query<?> strippedQuery = query.clone();
// Remove any possibility that multiple CachingDatabases will be cached in the sqlQueryCache.
strippedQuery.setDatabase(this);
return sqlQueryCache.getUnchecked(strippedQuery);
} catch (UncheckedExecutionException e) {
Throwable cause = e.getCause();
if (cause instanceof RuntimeException) {
throw (RuntimeException) cause;
} else {
throw new DatabaseException(this, cause);
}
}
}
// Closes all the given SQL resources safely.
protected void closeResources(Query<?> query, Connection connection, Statement statement, ResultSet result) {
if (result != null) {
try {
result.close();
} catch (SQLException error) {
// Not likely and probably harmless.
}
}
if (statement != null) {
try {
statement.close();
} catch (SQLException error) {
// Not likely and probably harmless.
}
}
Object queryConnection;
if (connection != null
&& (query == null
|| (queryConnection = query.getOptions().get(CONNECTION_QUERY_OPTION)) == null
|| !connection.equals(queryConnection))) {
try {
if (!connection.isClosed()) {
connection.close();
}
} catch (SQLException ex) {
// Not likely and probably harmless.
}
}
}
private byte[] serializeState(State state) {
Map<String, Object> values = state.getSimpleValues();
for (Iterator<Map.Entry<String, Object>> i = values.entrySet().iterator(); i.hasNext();) {
Map.Entry<String, Object> entry = i.next();
ObjectField field = state.getField(entry.getKey());
if (field != null) {
if (field.as(FieldData.class).isIndexTableSourceFromAnywhere()) {
i.remove();
}
}
}
byte[] dataBytes = ObjectUtils.toJson(values).getBytes(StandardCharsets.UTF_8);
if (isCompressData()) {
byte[] compressed = new byte[Snappy.maxCompressedLength(dataBytes.length)];
int compressedLength = Snappy.compress(dataBytes, 0, dataBytes.length, compressed, 0);
dataBytes = new byte[compressedLength + 1];
dataBytes[0] = 's';
System.arraycopy(compressed, 0, dataBytes, 1, compressedLength);
}
return dataBytes;
}
@SuppressWarnings("unchecked")
protected static Map<String, Object> unserializeData(byte[] dataBytes) {
char format = '\0';
while (true) {
format = (char) dataBytes[0];
if (format == 's') {
dataBytes = Snappy.uncompress(dataBytes, 1, dataBytes.length - 1);
} else if (format == '{') {
return (Map<String, Object>) ObjectUtils.fromJson(dataBytes);
} else {
break;
}
}
throw new IllegalStateException(String.format(
"Unknown format! ([%s])", format));
}
private class ConnectionRef {
private Connection connection;
public Connection getOrOpen(Query<?> query) {
if (connection == null) {
connection = SqlDatabase.super.openQueryConnection(query);
}
return connection;
}
public void close() {
if (connection != null) {
try {
if (!connection.isClosed()) {
connection.close();
}
} catch (SQLException error) {
// Not likely and probably harmless.
}
}
}
}
// Creates a previously saved object using the given resultSet.
private <T> T createSavedObjectWithResultSet(
ResultSet resultSet,
Query<T> query,
ConnectionRef extraConnectionRef)
throws SQLException {
T object = createSavedObject(resultSet.getObject(2), resultSet.getObject(1), query);
State objectState = State.getInstance(object);
if (object instanceof Singleton) {
singletonIds.put(object.getClass(), objectState.getId());
}
if (!objectState.isReferenceOnly()) {
byte[] data = resultSet.getBytes(3);
if (data != null) {
objectState.setValues(unserializeData(data));
Boolean returnOriginal = ObjectUtils.to(Boolean.class, query.getOptions().get(RETURN_ORIGINAL_DATA_QUERY_OPTION));
if (returnOriginal == null) {
returnOriginal = Boolean.FALSE;
}
if (returnOriginal) {
objectState.getExtras().put(ORIGINAL_DATA_EXTRA, data);
}
}
}
ResultSetMetaData meta = resultSet.getMetaData();
Object subId = null, subTypeId = null;
byte[] subData;
for (int i = 4, count = meta.getColumnCount(); i <= count; ++ i) {
String columnName = meta.getColumnLabel(i);
if (columnName.startsWith(SUB_DATA_COLUMN_ALIAS_PREFIX)) {
if (columnName.endsWith("_" + ID_COLUMN)) {
subId = resultSet.getObject(i);
} else if (columnName.endsWith("_" + TYPE_ID_COLUMN)) {
subTypeId = resultSet.getObject(i);
} else if (columnName.endsWith("_" + DATA_COLUMN)) {
subData = resultSet.getBytes(i);
if (subId != null && subTypeId != null && subData != null && !subId.equals(objectState.getId())) {
Object subObject = createSavedObject(subTypeId, subId, query);
State subObjectState = State.getInstance(subObject);
subObjectState.setValues(unserializeData(subData));
subObject = swapObjectType(null, subObject);
subId = null;
subTypeId = null;
subData = null;
objectState.getExtras().put(State.SUB_DATA_STATE_EXTRA_PREFIX + subObjectState.getId(), subObject);
}
}
} else if (query.getExtraSourceColumns().containsKey(columnName)) {
objectState.put(query.getExtraSourceColumns().get(columnName), resultSet.getObject(i));
} else {
objectState.getExtras().put(EXTRA_COLUMN_EXTRA_PREFIX + meta.getColumnLabel(i), resultSet.getObject(i));
}
}
// Load some extra column from source index tables.
@SuppressWarnings("unchecked")
Set<UUID> unresolvedTypeIds = (Set<UUID>) query.getOptions().get(State.UNRESOLVED_TYPE_IDS_QUERY_OPTION);
Set<ObjectType> queryTypes = query.getConcreteTypes(getEnvironment());
ObjectType type = objectState.getType();
HashSet<ObjectField> loadExtraFields = new HashSet<ObjectField>();
if (type != null) {
if ((unresolvedTypeIds == null || !unresolvedTypeIds.contains(type.getId()))
&& !queryTypes.contains(type)) {
for (ObjectField field : type.getFields()) {
SqlDatabase.FieldData fieldData = field.as(SqlDatabase.FieldData.class);
if (fieldData.isIndexTableSource() && !field.isMetric()) {
loadExtraFields.add(field);
}
}
}
}
if (!loadExtraFields.isEmpty()) {
Connection connection = extraConnectionRef.getOrOpen(query);
for (ObjectField field : loadExtraFields) {
Statement extraStatement = null;
ResultSet extraResult = null;
try {
extraStatement = connection.createStatement();
extraResult = executeQueryBeforeTimeout(
extraStatement,
extraSourceSelectStatementById(field, objectState.getId(), objectState.getTypeId()),
getQueryReadTimeout(query));
if (extraResult.next()) {
meta = extraResult.getMetaData();
for (int i = 1, count = meta.getColumnCount(); i <= count; ++ i) {
objectState.put(meta.getColumnLabel(i), extraResult.getObject(i));
}
}
} finally {
closeResources(null, null, extraStatement, extraResult);
}
}
}
return swapObjectType(query, object);
}
// Creates an SQL statement to return a single row from a FieldIndexTable
// used as a source table.
// Maybe: move this to SqlQuery and use initializeClauses() and
// needsRecordTable=false instead of passing id to this method. Needs
// countperformance branch to do this.
private String extraSourceSelectStatementById(ObjectField field, UUID id, UUID typeId) {
FieldData fieldData = field.as(FieldData.class);
ObjectType parentType = field.getParentType();
StringBuilder keyName = new StringBuilder(parentType.getInternalName());
keyName.append('/');
keyName.append(field.getInternalName());
Query<?> query = Query.fromType(parentType);
Query.MappedKey key = query.mapEmbeddedKey(getEnvironment(), keyName.toString());
ObjectIndex useIndex = null;
for (ObjectIndex index : key.getIndexes()) {
if (field.getInternalName().equals(index.getFields().get(0))) {
useIndex = index;
break;
}
}
SqlIndex useSqlIndex = SqlIndex.Static.getByIndex(useIndex);
SqlIndex.Table indexTable = useSqlIndex.getReadTable(this, useIndex);
String sourceTableName = fieldData.getIndexTable();
int symbolId = getSymbolId(key.getIndexKey(useIndex));
StringBuilder sql = new StringBuilder();
int fieldIndex = 0;
sql.append("SELECT ");
for (String indexFieldName : useIndex.getFields()) {
String indexColumnName = indexTable.getValueField(this, useIndex, fieldIndex);
++ fieldIndex;
vendor.appendIdentifier(sql, indexColumnName);
sql.append(" AS ");
vendor.appendIdentifier(sql, indexFieldName);
sql.append(", ");
}
sql.setLength(sql.length() - 2);
sql.append(" FROM ");
vendor.appendIdentifier(sql, sourceTableName);
sql.append(" WHERE ");
vendor.appendIdentifier(sql, "id");
sql.append(" = ");
vendor.appendValue(sql, id);
sql.append(" AND ");
vendor.appendIdentifier(sql, "symbolId");
sql.append(" = ");
sql.append(symbolId);
return sql.toString();
}
/**
* Executes the given read {@code statement} (created from the given
* {@code sqlQuery}) before the given {@code timeout} (in seconds).
*/
ResultSet executeQueryBeforeTimeout(
Statement statement,
String sqlQuery,
int timeout)
throws SQLException {
if (timeout > 0 && !(vendor instanceof SqlVendor.PostgreSQL)) {
statement.setQueryTimeout(timeout);
}
Stats.Timer timer = STATS.startTimer();
Profiler.Static.startThreadEvent(QUERY_PROFILER_EVENT);
try {
return statement.executeQuery(sqlQuery);
} finally {
double duration = timer.stop(QUERY_STATS_OPERATION);
Profiler.Static.stopThreadEvent(sqlQuery);
LOGGER.debug(
"Read from the SQL database using [{}] in [{}]ms",
sqlQuery, duration * 1000.0);
}
}
// Creates a previously saved object from the replication cache.
private <T> T createSavedObjectFromReplicationCache(byte[] typeId, UUID id, byte[] data, Map<String, Object> dataJson, Query<T> query) {
T object = createSavedObject(typeId, id, query);
State objectState = State.getInstance(object);
objectState.setValues(cloneDataJson(dataJson));
Boolean returnOriginal = query != null ? ObjectUtils.to(Boolean.class, query.getOptions().get(RETURN_ORIGINAL_DATA_QUERY_OPTION)) : null;
if (returnOriginal == null) {
returnOriginal = Boolean.FALSE;
}
if (returnOriginal) {
objectState.getExtras().put(ORIGINAL_DATA_EXTRA, data);
}
return swapObjectType(query, object);
}
@SuppressWarnings("unchecked")
private static Map<String, Object> cloneDataJson(Map<String, Object> dataJson) {
return (Map<String, Object>) cloneDataJsonRecursively(dataJson);
}
private static Object cloneDataJsonRecursively(Object object) {
if (object instanceof Map) {
Map<?, ?> objectMap = (Map<?, ?>) object;
int objectMapSize = objectMap.size();
Map<String, Object> clone = objectMapSize <= 8
? new CompactMap<String, Object>()
: new LinkedHashMap<String, Object>(objectMapSize);
for (Map.Entry<?, ?> entry : objectMap.entrySet()) {
clone.put((String) entry.getKey(), cloneDataJsonRecursively(entry.getValue()));
}
return clone;
} else if (object instanceof List) {
List<?> objectList = (List<?>) object;
List<Object> clone = new ArrayList<Object>(objectList.size());
for (Object item : objectList) {
clone.add(cloneDataJsonRecursively(item));
}
return clone;
} else {
return object;
}
}
// Tries to find objects by the given ids from the replication cache.
// If not found, execute the given query to populate it.
private <T> List<T> findObjectsFromReplicationCache(List<Object> ids, Query<T> query) {
List<T> objects = null;
if (ids == null || ids.isEmpty()) {
return objects;
}
List<UUID> missingIds = null;
Profiler.Static.startThreadEvent(REPLICATION_CACHE_GET_PROFILER_EVENT);
String queryGroup = query != null ? query.getGroup() : null;
Class queryObjectClass = query != null ? query.getObjectClass() : null;
try {
for (Object idObject : ids) {
UUID id = ObjectUtils.to(UUID.class, idObject);
if (id == null) {
continue;
}
Object[] value = replicationCache.getIfPresent(id);
if (value == null) {
if (missingIds == null) {
missingIds = new ArrayList<UUID>();
}
missingIds.add(id);
continue;
}
UUID typeId = ObjectUtils.to(UUID.class, (byte[]) value[0]);
ObjectType type = typeId != null ? ObjectType.getInstance(typeId) : null;
// Restrict objects based on the class provided to the Query
if (type != null && queryObjectClass != null && !query.getObjectClass().isAssignableFrom(type.getObjectClass())) {
continue;
}
// Restrict objects based on the group provided to the Query
if (type != null && queryGroup != null && !type.getGroups().contains(queryGroup)) {
continue;
}
@SuppressWarnings("unchecked")
T object = createSavedObjectFromReplicationCache((byte[]) value[0], id, (byte[]) value[1], (Map<String, Object>) value[2], query);
if (object != null) {
if (objects == null) {
objects = new ArrayList<T>();
}
objects.add(object);
}
}
} finally {
Profiler.Static.stopThreadEvent((objects != null ? objects.size() : 0) + " Objects");
}
if (missingIds != null && !missingIds.isEmpty()) {
Profiler.Static.startThreadEvent(REPLICATION_CACHE_PUT_PROFILER_EVENT);
try {
SqlVendor vendor = getVendor();
StringBuilder sqlQuery = new StringBuilder();
sqlQuery.append("SELECT ");
vendor.appendIdentifier(sqlQuery, TYPE_ID_COLUMN);
sqlQuery.append(", ");
vendor.appendIdentifier(sqlQuery, DATA_COLUMN);
sqlQuery.append(", ");
vendor.appendIdentifier(sqlQuery, ID_COLUMN);
sqlQuery.append(" FROM ");
vendor.appendIdentifier(sqlQuery, RECORD_TABLE);
sqlQuery.append(" WHERE ");
vendor.appendIdentifier(sqlQuery, ID_COLUMN);
sqlQuery.append(" IN (");
for (UUID missingId : missingIds) {
vendor.appendUuid(sqlQuery, missingId);
sqlQuery.append(", ");
}
sqlQuery.setLength(sqlQuery.length() - 2);
sqlQuery.append(")");
Connection connection = null;
ConnectionRef extraConnectionRef = new ConnectionRef();
Statement statement = null;
ResultSet result = null;
try {
connection = extraConnectionRef.getOrOpen(query);
statement = connection.createStatement();
result = executeQueryBeforeTimeout(statement, sqlQuery.toString(), 0);
while (result.next()) {
UUID id = ObjectUtils.to(UUID.class, result.getBytes(3));
byte[] data = result.getBytes(2);
Map<String, Object> dataJson = unserializeData(data);
byte[] typeIdBytes = UuidUtils.toBytes(ObjectUtils.to(UUID.class, dataJson.get(StateValueUtils.TYPE_KEY)));
if (!Arrays.equals(typeIdBytes, UuidUtils.ZERO_BYTES) && id != null) {
replicationCache.put(id, new Object[] { typeIdBytes, data, dataJson });
}
UUID typeId = ObjectUtils.to(UUID.class, typeIdBytes);
ObjectType type = typeId != null ? ObjectType.getInstance(typeId) : null;
// Restrict objects based on the class provided to the Query
if (type != null && queryObjectClass != null && !query.getObjectClass().isAssignableFrom(type.getObjectClass())) {
continue;
}
// Restrict objects based on the group provided to the Query
if (type != null && queryGroup != null && !type.getGroups().contains(queryGroup)) {
continue;
}
T object = createSavedObjectFromReplicationCache(typeIdBytes, id, data, dataJson, query);
if (object != null) {
if (objects == null) {
objects = new ArrayList<T>();
}
objects.add(object);
}
}
} catch (SQLException error) {
throw createQueryException(error, sqlQuery.toString(), query);
} finally {
closeResources(query, connection, statement, result);
extraConnectionRef.close();
}
} finally {
Profiler.Static.stopThreadEvent(missingIds.size() + " Objects");
}
}
return objects;
}
private <T> List<T> findObjectsFromFunnelCache(String sqlQuery, Query<T> query) {
List<T> objects = new ArrayList<T>();
Profiler.Static.startThreadEvent(FUNNEL_CACHE_GET_PROFILER_EVENT);
try {
List<FunnelCachedObject> cachedObjects = funnelCache.get(new FunnelCacheProducer(sqlQuery, query));
if (cachedObjects != null) {
for (FunnelCachedObject cachedObj : cachedObjects) {
T savedObj = createSavedObjectFromReplicationCache(UuidUtils.toBytes(cachedObj.getTypeId()), cachedObj.getId(), null, cachedObj.getValues(), query);
if (cachedObj.getExtras() != null && !cachedObj.getExtras().isEmpty()) {
State.getInstance(savedObj).getExtras().putAll(cachedObj.getExtras());
}
objects.add(savedObj);
}
}
return objects;
} finally {
Profiler.Static.stopThreadEvent(objects);
}
}
/**
* Selects the first object that matches the given {@code sqlQuery}
* with options from the given {@code query}.
*/
public <T> T selectFirstWithOptions(String sqlQuery, Query<T> query) {
sqlQuery = vendor.rewriteQueryWithLimitClause(sqlQuery, 1, 0);
if (checkFunnelCache(query)) {
List<T> objects = findObjectsFromFunnelCache(sqlQuery, query);
if (objects != null) {
return objects.isEmpty() ? null : objects.get(0);
}
}
ConnectionRef extraConnectionRef = new ConnectionRef();
Connection connection = null;
Statement statement = null;
ResultSet result = null;
try {
connection = openQueryConnection(query);
statement = connection.createStatement();
result = executeQueryBeforeTimeout(statement, sqlQuery, getQueryReadTimeout(query));
return result.next() ? createSavedObjectWithResultSet(result, query, extraConnectionRef) : null;
} catch (SQLException ex) {
throw createQueryException(ex, sqlQuery, query);
} finally {
closeResources(query, connection, statement, result);
extraConnectionRef.close();
}
}
/**
* Selects the first object that matches the given {@code sqlQuery}
* without a timeout.
*/
public Object selectFirst(String sqlQuery) {
return selectFirstWithOptions(sqlQuery, null);
}
/**
* Selects a list of objects that match the given {@code sqlQuery}
* with options from the given {@code query}.
*/
public <T> List<T> selectListWithOptions(String sqlQuery, Query<T> query) {
if (checkFunnelCache(query)) {
List<T> objects = findObjectsFromFunnelCache(sqlQuery, query);
if (objects != null) {
return objects;
}
}
ConnectionRef extraConnectionRef = new ConnectionRef();
Connection connection = null;
Statement statement = null;
ResultSet result = null;
List<T> objects = new ArrayList<T>();
int timeout = getQueryReadTimeout(query);
try {
connection = openQueryConnection(query);
statement = connection.createStatement();
result = executeQueryBeforeTimeout(statement, sqlQuery, timeout);
while (result.next()) {
objects.add(createSavedObjectWithResultSet(result, query, extraConnectionRef));
}
return objects;
} catch (SQLException ex) {
throw createQueryException(ex, sqlQuery, query);
} finally {
closeResources(query, connection, statement, result);
extraConnectionRef.close();
}
}
/**
* Selects a list of objects that match the given {@code sqlQuery}
* without a timeout.
*/
public List<Object> selectList(String sqlQuery) {
return selectListWithOptions(sqlQuery, null);
}
/**
* Returns an iterable that selects all objects matching the given
* {@code sqlQuery} with options from the given {@code query}.
*/
public <T> Iterable<T> selectIterableWithOptions(
final String sqlQuery,
final int fetchSize,
final Query<T> query) {
return new Iterable<T>() {
@Override
public Iterator<T> iterator() {
return new SqlIterator<T>(sqlQuery, fetchSize, query);
}
};
}
private class SqlIterator<T> implements java.io.Closeable, Iterator<T> {
private final String sqlQuery;
private final Query<T> query;
private final ConnectionRef extraConnectionRef;
private final Connection connection;
private final Statement statement;
private final ResultSet result;
private boolean hasNext = true;
public SqlIterator(String initialSqlQuery, int fetchSize, Query<T> initialQuery) {
sqlQuery = initialSqlQuery;
query = initialQuery;
extraConnectionRef = new ConnectionRef();
try {
connection = openQueryConnection(query);
statement = connection.createStatement();
statement.setFetchSize(getVendor() instanceof SqlVendor.MySQL ? Integer.MIN_VALUE
: fetchSize <= 0 ? 200
: fetchSize);
result = statement.executeQuery(sqlQuery);
moveToNext();
} catch (SQLException ex) {
close();
throw createQueryException(ex, sqlQuery, query);
}
}
private void moveToNext() throws SQLException {
if (hasNext) {
hasNext = result.next();
if (!hasNext) {
close();
}
}
}
@Override
public void close() {
hasNext = false;
closeResources(query, connection, statement, result);
extraConnectionRef.close();
}
@Override
public boolean hasNext() {
return hasNext;
}
@Override
public T next() {
if (!hasNext) {
throw new NoSuchElementException();
}
try {
T object = createSavedObjectWithResultSet(result, query, extraConnectionRef);
moveToNext();
return object;
} catch (SQLException ex) {
close();
throw createQueryException(ex, sqlQuery, query);
}
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
@Override
protected void finalize() {
close();
}
}
/**
* Fills the placeholders in the given {@code sqlQuery} with the given
* {@code parameters}.
*/
private static String fillPlaceholders(String sqlQuery, Object... parameters) {
StringBuilder filled = new StringBuilder();
int prevPh = 0;
for (int ph, index = 0; (ph = sqlQuery.indexOf('?', prevPh)) > -1; ++ index) {
filled.append(sqlQuery.substring(prevPh, ph));
prevPh = ph + 1;
filled.append(quoteValue(parameters[index]));
}
filled.append(sqlQuery.substring(prevPh));
return filled.toString();
}
/**
* Executes the given write {@code sqlQuery} with the given
* {@code parameters}.
*
* @deprecated Use {@link Static#executeUpdate} instead.
*/
@Deprecated
public int executeUpdate(String sqlQuery, Object... parameters) {
try {
return Static.executeUpdateWithArray(getConnection(), sqlQuery, parameters);
} catch (SQLException ex) {
throw createQueryException(ex, fillPlaceholders(sqlQuery, parameters), null);
}
}
/**
* Reads the given {@code resultSet} into a list of maps
* and closes it.
*/
public List<Map<String, Object>> readResultSet(ResultSet resultSet) throws SQLException {
try {
ResultSetMetaData meta = resultSet.getMetaData();
List<String> columnNames = new ArrayList<String>();
for (int i = 1, count = meta.getColumnCount(); i < count; ++ i) {
columnNames.add(meta.getColumnName(i));
}
List<Map<String, Object>> maps = new ArrayList<Map<String, Object>>();
while (resultSet.next()) {
Map<String, Object> map = new LinkedHashMap<String, Object>();
maps.add(map);
for (int i = 0, size = columnNames.size(); i < size; ++ i) {
map.put(columnNames.get(i), resultSet.getObject(i + 1));
}
}
return maps;
} finally {
resultSet.close();
}
}
@Override
public Connection openConnection() {
DataSource dataSource = getDataSource();
if (dataSource == null) {
throw new SqlDatabaseException(this, "No SQL data source!");
}
try {
Connection connection = getConnectionFromDataSource(dataSource);
connection.setReadOnly(false);
if (vendor != null) {
vendor.setTransactionIsolation(connection);
}
return connection;
} catch (SQLException error) {
throw new SqlDatabaseException(this, "Can't connect to the SQL engine!", error);
}
}
private Connection getConnectionFromDataSource(DataSource dataSource) throws SQLException {
int limit = Settings.getOrDefault(int.class, "dari/sqlConnectionRetryLimit", 5);
while (true) {
try {
Connection connection = dataSource.getConnection();
String catalog = getCatalog();
if (catalog != null) {
connection.setCatalog(catalog);
}
return connection;
} catch (SQLException error) {
if (error instanceof SQLRecoverableException) {
-- limit;
if (limit >= 0) {
Stats.Timer timer = STATS.startTimer();
try {
Thread.sleep(ObjectUtils.jitter(10L, 0.5));
} catch (InterruptedException ignore) {
// Ignore and keep retrying.
} finally {
timer.stop(CONNECTION_ERROR_STATS_OPERATION);
}
continue;
}
}
throw error;
}
}
}
@Override
protected Connection doOpenReadConnection() {
DataSource readDataSource = getReadDataSource();
if (readDataSource == null) {
readDataSource = getDataSource();
}
if (readDataSource == null) {
throw new SqlDatabaseException(this, "No SQL data source!");
}
try {
Connection connection = getConnectionFromDataSource(readDataSource);
connection.setReadOnly(true);
return connection;
} catch (SQLException error) {
throw new SqlDatabaseException(this, "Can't connect to the SQL engine!", error);
}
}
@Override
public Connection openQueryConnection(Query<?> query) {
if (query != null) {
Connection connection = (Connection) query.getOptions().get(CONNECTION_QUERY_OPTION);
if (connection != null) {
return connection;
}
Boolean useRead = ObjectUtils.to(Boolean.class, query.getOptions().get(USE_READ_DATA_SOURCE_QUERY_OPTION));
if (useRead == null) {
useRead = Boolean.TRUE;
}
if (!useRead) {
return openConnection();
}
}
return super.openQueryConnection(query);
}
@Override
public void closeConnection(Connection connection) {
if (connection != null) {
try {
if (defaultCatalog != null) {
String catalog = getCatalog();
if (catalog != null) {
connection.setCatalog(defaultCatalog);
}
}
if (!connection.isClosed()) {
connection.close();
}
} catch (SQLException error) {
// Not likely and probably harmless.
}
}
}
@Override
protected boolean isRecoverableError(Exception error) {
if (error instanceof SQLException) {
SQLException sqlError = (SQLException) error;
return "40001".equals(sqlError.getSQLState());
}
return false;
}
@Override
protected void doInitialize(String settingsKey, Map<String, Object> settings) {
close();
setReadDataSource(createDataSource(
settings,
READ_DATA_SOURCE_SETTING,
READ_JDBC_DRIVER_CLASS_SETTING,
READ_JDBC_URL_SETTING,
READ_JDBC_USER_SETTING,
READ_JDBC_PASSWORD_SETTING,
READ_JDBC_POOL_SIZE_SETTING));
setDataSource(createDataSource(
settings,
DATA_SOURCE_SETTING,
JDBC_DRIVER_CLASS_SETTING,
JDBC_URL_SETTING,
JDBC_USER_SETTING,
JDBC_PASSWORD_SETTING,
JDBC_POOL_SIZE_SETTING));
setCatalog(ObjectUtils.to(String.class, settings.get(CATALOG_SUB_SETTING)));
setMetricCatalog(ObjectUtils.to(String.class, settings.get(METRIC_CATALOG_SUB_SETTING)));
String vendorClassName = ObjectUtils.to(String.class, settings.get(VENDOR_CLASS_SETTING));
Class<?> vendorClass = null;
if (vendorClassName != null) {
vendorClass = ObjectUtils.getClassByName(vendorClassName);
if (vendorClass == null) {
throw new SettingsException(
VENDOR_CLASS_SETTING,
String.format("Can't find [%s]!",
vendorClassName));
} else if (!SqlVendor.class.isAssignableFrom(vendorClass)) {
throw new SettingsException(
VENDOR_CLASS_SETTING,
String.format("[%s] doesn't implement [%s]!",
vendorClass, Driver.class));
}
}
if (vendorClass != null) {
setVendor((SqlVendor) TypeDefinition.getInstance(vendorClass).newInstance());
}
Boolean compressData = ObjectUtils.firstNonNull(
ObjectUtils.to(Boolean.class, settings.get(COMPRESS_DATA_SUB_SETTING)),
Settings.get(Boolean.class, "dari/isCompressSqlData"));
if (compressData != null) {
setCompressData(compressData);
}
setEnableReplicationCache(ObjectUtils.to(boolean.class, settings.get(ENABLE_REPLICATION_CACHE_SUB_SETTING)));
setEnableFunnelCache(ObjectUtils.to(boolean.class, settings.get(ENABLE_FUNNEL_CACHE_SUB_SETTING)));
Long replicationCacheMaxSize = ObjectUtils.to(Long.class, settings.get(REPLICATION_CACHE_SIZE_SUB_SETTING));
setReplicationCacheMaximumSize(replicationCacheMaxSize != null ? replicationCacheMaxSize : DEFAULT_REPLICATION_CACHE_SIZE);
if (isEnableReplicationCache()
&& vendor instanceof SqlVendor.MySQL
&& (mysqlBinaryLogReader == null
|| !mysqlBinaryLogReader.isRunning())) {
replicationCache = CacheBuilder.newBuilder().maximumSize(getReplicationCacheMaximumSize()).build();
try {
LOGGER.info("Starting MySQL binary log reader");
mysqlBinaryLogReader = new MySQLBinaryLogReader(replicationCache, ObjectUtils.firstNonNull(getReadDataSource(), getDataSource()));
mysqlBinaryLogReader.start();
} catch (IllegalArgumentException error) {
setEnableReplicationCache(false);
LOGGER.warn("Can't start MySQL binary log reader!", error);
}
}
if (isEnableFunnelCache()) {
funnelCache = new FunnelCache<SqlDatabase>(this, settings);
}
}
private static final Map<String, String> DRIVER_CLASS_NAMES; static {
Map<String, String> m = new HashMap<String, String>();
m.put("h2", "org.h2.Driver");
m.put("jtds", "net.sourceforge.jtds.jdbc.Driver");
m.put("mysql", "com.mysql.jdbc.Driver");
m.put("postgresql", "org.postgresql.Driver");
DRIVER_CLASS_NAMES = m;
}
private static final Set<WeakReference<Driver>> REGISTERED_DRIVERS = new HashSet<WeakReference<Driver>>();
private DataSource createDataSource(
Map<String, Object> settings,
String dataSourceSetting,
String jdbcDriverClassSetting,
String jdbcUrlSetting,
String jdbcUserSetting,
String jdbcPasswordSetting,
String jdbcPoolSizeSetting) {
Object dataSourceObject = settings.get(dataSourceSetting);
if (dataSourceObject instanceof DataSource) {
return (DataSource) dataSourceObject;
} else {
String url = ObjectUtils.to(String.class, settings.get(jdbcUrlSetting));
if (ObjectUtils.isBlank(url)) {
return null;
} else {
String driverClassName = ObjectUtils.to(String.class, settings.get(jdbcDriverClassSetting));
Class<?> driverClass = null;
if (driverClassName != null) {
driverClass = ObjectUtils.getClassByName(driverClassName);
if (driverClass == null) {
throw new SettingsException(
jdbcDriverClassSetting,
String.format("Can't find [%s]!",
driverClassName));
} else if (!Driver.class.isAssignableFrom(driverClass)) {
throw new SettingsException(
jdbcDriverClassSetting,
String.format("[%s] doesn't implement [%s]!",
driverClass, Driver.class));
}
} else {
int firstColonAt = url.indexOf(':');
if (firstColonAt > -1) {
++ firstColonAt;
int secondColonAt = url.indexOf(':', firstColonAt);
if (secondColonAt > -1) {
driverClass = ObjectUtils.getClassByName(DRIVER_CLASS_NAMES.get(url.substring(firstColonAt, secondColonAt)));
}
}
}
if (driverClass != null) {
Driver driver = null;
for (Enumeration<Driver> e = DriverManager.getDrivers(); e.hasMoreElements();) {
Driver d = e.nextElement();
if (driverClass.isInstance(d)) {
driver = d;
break;
}
}
if (driver == null) {
driver = (Driver) TypeDefinition.getInstance(driverClass).newInstance();
try {
LOGGER.info("Registering [{}]", driver);
DriverManager.registerDriver(driver);
} catch (SQLException ex) {
LOGGER.warn("Can't register [{}]!", driver);
}
}
if (driver != null) {
REGISTERED_DRIVERS.add(new WeakReference<Driver>(driver));
}
}
String user = ObjectUtils.to(String.class, settings.get(jdbcUserSetting));
String password = ObjectUtils.to(String.class, settings.get(jdbcPasswordSetting));
Integer poolSize = ObjectUtils.to(Integer.class, settings.get(jdbcPoolSizeSetting));
if (poolSize == null || poolSize <= 0) {
poolSize = 24;
}
LOGGER.info(
"Automatically creating connection pool:"
+ "\n\turl={}"
+ "\n\tusername={}"
+ "\n\tpoolSize={}",
url,
user,
poolSize);
HikariDataSource ds = new HikariDataSource();
ds.setJdbcUrl(url);
ds.setUsername(user);
ds.setPassword(password);
ds.setMaximumPoolSize(poolSize);
return ds;
}
}
}
/** Returns the read timeout associated with the given {@code query}. */
private int getQueryReadTimeout(Query<?> query) {
if (query != null) {
Double timeout = query.getTimeout();
if (timeout == null) {
timeout = getReadTimeout();
}
if (timeout > 0.0) {
return (int) Math.round(timeout);
}
}
return 0;
}
private boolean checkReplicationCache(Query<?> query) {
return query.isCache()
&& isEnableReplicationCache()
&& !Boolean.TRUE.equals(query.getOptions().get(DISABLE_REPLICATION_CACHE_QUERY_OPTION))
&& mysqlBinaryLogReader != null
&& mysqlBinaryLogReader.isConnected();
}
private boolean checkFunnelCache(Query<?> query) {
return query.isCache()
&& !query.isReferenceOnly()
&& isEnableFunnelCache()
&& !Boolean.TRUE.equals(query.getOptions().get(Database.DISABLE_FUNNEL_CACHE_QUERY_OPTION))
&& funnelCache != null;
}
@Override
public <T> List<T> readAll(Query<T> query) {
if (checkReplicationCache(query)) {
List<Object> ids = query.findIdOnlyQueryValues();
if (ids != null && !ids.isEmpty()) {
List<T> objects = findObjectsFromReplicationCache(ids, query);
return objects != null ? objects : new ArrayList<T>();
}
}
return selectListWithOptions(buildSelectStatement(query), query);
}
@Override
public long readCount(Query<?> query) {
String sqlQuery = buildCountStatement(query);
Connection connection = null;
Statement statement = null;
ResultSet result = null;
try {
connection = openQueryConnection(query);
statement = connection.createStatement();
result = executeQueryBeforeTimeout(statement, sqlQuery, getQueryReadTimeout(query));
if (result.next()) {
Object countObj = result.getObject(1);
if (countObj instanceof Number) {
return ((Number) countObj).longValue();
}
}
return 0;
} catch (SQLException ex) {
throw createQueryException(ex, sqlQuery, query);
} finally {
closeResources(query, connection, statement, result);
}
}
@Override
public <T> T readFirst(Query<T> query) {
if (query.getSorters().isEmpty()) {
Predicate predicate = query.getPredicate();
if (predicate instanceof CompoundPredicate) {
CompoundPredicate compoundPredicate = (CompoundPredicate) predicate;
if (PredicateParser.OR_OPERATOR.equals(compoundPredicate.getOperator())) {
for (Predicate child : compoundPredicate.getChildren()) {
Query<T> childQuery = query.clone();
childQuery.setPredicate(child);
T first = readFirst(childQuery);
if (first != null) {
return first;
}
}
return null;
}
}
}
if (checkReplicationCache(query)) {
Class<?> objectClass = query.getObjectClass();
List<Object> ids;
if (objectClass != null
&& Singleton.class.isAssignableFrom(objectClass)
&& query.getPredicate() == null) {
UUID id = singletonIds.get(objectClass);
ids = id != null ? Collections.singletonList(id) : null;
} else {
ids = query.findIdOnlyQueryValues();
}
if (ids != null && !ids.isEmpty()) {
List<T> objects = findObjectsFromReplicationCache(ids, query);
return objects == null || objects.isEmpty() ? null : objects.get(0);
}
}
return selectFirstWithOptions(buildSelectStatement(query), query);
}
@Override
public <T> Iterable<T> readIterable(Query<T> query, int fetchSize) {
Boolean useJdbc = ObjectUtils.to(Boolean.class, query.getOptions().get(USE_JDBC_FETCH_SIZE_QUERY_OPTION));
if (useJdbc == null) {
useJdbc = Boolean.TRUE;
}
if (useJdbc) {
return selectIterableWithOptions(buildSelectStatement(query), fetchSize, query);
} else {
return new ByIdIterable<T>(query, fetchSize);
}
}
private static class ByIdIterable<T> implements Iterable<T> {
private final Query<T> query;
private final int fetchSize;
public ByIdIterable(Query<T> query, int fetchSize) {
this.query = query;
this.fetchSize = fetchSize;
}
@Override
public Iterator<T> iterator() {
return new ByIdIterator<T>(query, fetchSize);
}
}
private static class ByIdIterator<T> implements Iterator<T> {
private final Query<T> query;
private final int fetchSize;
private UUID lastTypeId;
private UUID lastId;
private List<T> items;
private int index;
public ByIdIterator(Query<T> query, int fetchSize) {
if (!query.getSorters().isEmpty()) {
throw new IllegalArgumentException("Can't iterate over a query that has sorters!");
}
this.query = query.clone().timeout(0.0).sortAscending("_type").sortAscending("_id");
this.fetchSize = fetchSize > 0 ? fetchSize : 200;
}
@Override
public boolean hasNext() {
if (items != null && items.isEmpty()) {
return false;
}
if (items == null || index >= items.size()) {
Query<T> nextQuery = query.clone();
if (lastTypeId != null) {
nextQuery.and("_type = ? and _id > ?", lastTypeId, lastId);
}
items = nextQuery.select(0, fetchSize).getItems();
int size = items.size();
if (size < 1) {
if (lastTypeId == null) {
return false;
} else {
nextQuery = query.clone().and("_type > ?", lastTypeId);
items = nextQuery.select(0, fetchSize).getItems();
size = items.size();
if (size < 1) {
return false;
}
}
}
State lastState = State.getInstance(items.get(size - 1));
lastTypeId = lastState.getVisibilityAwareTypeId();
lastId = lastState.getId();
index = 0;
}
return true;
}
@Override
public T next() {
if (hasNext()) {
T object = items.get(index);
++ index;
return object;
} else {
throw new NoSuchElementException();
}
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
@Override
public Date readLastUpdate(Query<?> query) {
String sqlQuery = buildLastUpdateStatement(query);
Connection connection = null;
Statement statement = null;
ResultSet result = null;
try {
connection = openQueryConnection(query);
statement = connection.createStatement();
result = executeQueryBeforeTimeout(statement, sqlQuery, getQueryReadTimeout(query));
if (result.next()) {
Double date = ObjectUtils.to(Double.class, result.getObject(1));
if (date != null) {
return new Date((long) (date * 1000L));
}
}
return null;
} catch (SQLException ex) {
throw createQueryException(ex, sqlQuery, query);
} finally {
closeResources(query, connection, statement, result);
}
}
@Override
public <T> PaginatedResult<T> readPartial(final Query<T> query, long offset, int limit) {
// Guard against integer overflow
if (limit == Integer.MAX_VALUE) {
limit
}
List<T> objects = selectListWithOptions(
vendor.rewriteQueryWithLimitClause(buildSelectStatement(query), limit + 1, offset),
query);
int size = objects.size();
if (size <= limit) {
return new PaginatedResult<T>(offset, limit, offset + size, objects);
} else {
objects.remove(size - 1);
return new PaginatedResult<T>(offset, limit, 0, objects) {
private Long count;
@Override
public long getCount() {
if (count == null) {
count = readCount(query);
}
return count;
}
@Override
public boolean hasNext() {
return true;
}
};
}
}
@Override
public <T> PaginatedResult<Grouping<T>> readPartialGrouped(Query<T> query, long offset, int limit, String... fields) {
for (String field : fields) {
Matcher groupingMatcher = Query.RANGE_PATTERN.matcher(field);
if (groupingMatcher.find()) {
throw new UnsupportedOperationException("SqlDatabase does not support group by numeric range");
}
}
List<Grouping<T>> groupings = new ArrayList<Grouping<T>>();
String sqlQuery = buildGroupStatement(query, fields);
Connection connection = null;
Statement statement = null;
ResultSet result = null;
try {
connection = openQueryConnection(query);
statement = connection.createStatement();
result = executeQueryBeforeTimeout(statement, sqlQuery, getQueryReadTimeout(query));
int fieldsLength = fields.length;
int groupingsCount = 0;
for (int i = 0, last = (int) offset + limit; result.next(); ++ i, ++ groupingsCount) {
if (i < offset || i >= last) {
continue;
}
List<Object> keys = new ArrayList<Object>();
SqlGrouping<T> grouping;
ResultSetMetaData meta = result.getMetaData();
String aggregateColumnName = meta.getColumnName(1);
if ("_count".equals(aggregateColumnName)) {
long count = ObjectUtils.to(long.class, result.getObject(1));
for (int j = 0; j < fieldsLength; ++ j) {
keys.add(result.getObject(j + 2));
}
grouping = new SqlGrouping<T>(keys, query, fields, count, groupings);
} else {
Double amount = ObjectUtils.to(Double.class, result.getObject(1));
for (int j = 0; j < fieldsLength; ++ j) {
keys.add(result.getObject(j + 3));
}
long count = 0L;
if (meta.getColumnName(2).equals("_count")) {
count = ObjectUtils.to(long.class, result.getObject(2));
}
grouping = new SqlGrouping<T>(keys, query, fields, count, groupings);
if (amount == null) {
amount = 0d;
}
grouping.setSum(aggregateColumnName, amount);
}
groupings.add(grouping);
}
int groupingsSize = groupings.size();
List<Integer> removes = new ArrayList<Integer>();
for (int i = 0; i < fieldsLength; ++ i) {
Query.MappedKey key = query.mapEmbeddedKey(getEnvironment(), fields[i]);
ObjectField field = key.getSubQueryKeyField();
if (field == null) {
field = key.getField();
}
if (field != null) {
Map<String, Object> rawKeys = new HashMap<String, Object>();
for (int j = 0; j < groupingsSize; ++ j) {
rawKeys.put(String.valueOf(j), groupings.get(j).getKeys().get(i));
}
String itemType = field.getInternalItemType();
if (ObjectField.RECORD_TYPE.equals(itemType)) {
for (Map.Entry<String, Object> entry : rawKeys.entrySet()) {
Map<String, Object> ref = new HashMap<String, Object>();
ref.put(StateValueUtils.REFERENCE_KEY, entry.getValue());
entry.setValue(ref);
}
}
Map<String, Object> rawKeysCopy = new HashMap<String, Object>(rawKeys);
Map<?, ?> convertedKeys = (Map<?, ?>) StateValueUtils.toJavaValue(query.getDatabase(), null, field, "map/" + itemType, rawKeys);
for (int j = 0; j < groupingsSize; ++ j) {
String jString = String.valueOf(j);
Object convertedKey = convertedKeys.get(jString);
if (convertedKey == null
&& rawKeysCopy.get(jString) != null) {
removes.add(j - removes.size());
}
groupings.get(j).getKeys().set(i, convertedKey);
}
}
}
for (Integer i : removes) {
groupings.remove((int) i);
}
return new PaginatedResult<Grouping<T>>(offset, limit, groupingsCount - removes.size(), groupings);
} catch (SQLException ex) {
throw createQueryException(ex, sqlQuery, query);
} finally {
closeResources(query, connection, statement, result);
}
}
/** SQL-specific implementation of {@link Grouping}. */
private class SqlGrouping<T> extends AbstractGrouping<T> {
private final long count;
private final Map<String, Double> metricSums = new HashMap<String, Double>();
private final List<Grouping<T>> groupings;
public SqlGrouping(List<Object> keys, Query<T> query, String[] fields, long count, List<Grouping<T>> groupings) {
super(keys, query, fields);
this.count = count;
this.groupings = groupings;
}
@Override
public double getSum(String field) {
Query.MappedKey mappedKey = this.query.mapEmbeddedKey(getEnvironment(), field);
ObjectField sumField = mappedKey.getField();
if (sumField.isMetric()) {
if (!metricSums.containsKey(field)) {
String sqlQuery = buildGroupedMetricStatement(query, field, fields);
Connection connection = null;
Statement statement = null;
ResultSet result = null;
try {
connection = openQueryConnection(query);
statement = connection.createStatement();
result = executeQueryBeforeTimeout(statement, sqlQuery, getQueryReadTimeout(query));
if (this.getKeys().size() == 0) {
// Special case for .groupby() without any fields
if (this.groupings.size() != 1) {
throw new RuntimeException("There should only be one grouping when grouping by nothing. Something went wrong internally.");
}
if (result.next() && result.getBytes(1) != null) {
this.setSum(field, result.getDouble(1));
} else {
this.setSum(field, 0);
}
} else {
// Find the ObjectFields for the specified fields
List<ObjectField> objectFields = new ArrayList<ObjectField>();
for (String fieldName : fields) {
objectFields.add(query.mapEmbeddedKey(getEnvironment(), fieldName).getField());
}
// index the groupings by their keys
Map<List<Object>, SqlGrouping<T>> groupingMap = new HashMap<List<Object>, SqlGrouping<T>>();
for (Grouping<T> grouping : groupings) {
if (grouping instanceof SqlGrouping) {
((SqlGrouping<T>) grouping).setSum(field, 0);
groupingMap.put(grouping.getKeys(), (SqlGrouping<T>) grouping);
}
}
// Find the sums and set them on each grouping
while (result.next()) {
// TODO: limit/offset
List<Object> keys = new ArrayList<Object>();
for (int j = 0; j < objectFields.size(); ++ j) {
keys.add(StateValueUtils.toJavaValue(query.getDatabase(), null, objectFields.get(j), objectFields.get(j).getInternalItemType(), result.getObject(j + 3))); // 3 because _count and amount
}
if (groupingMap.containsKey(keys)) {
if (result.getBytes(1) != null) {
groupingMap.get(keys).setSum(field, result.getDouble(1));
} else {
groupingMap.get(keys).setSum(field, 0);
}
}
}
}
} catch (SQLException ex) {
throw createQueryException(ex, sqlQuery, query);
} finally {
closeResources(query, connection, statement, result);
}
}
if (metricSums.containsKey(field)) {
return metricSums.get(field);
} else {
return 0;
}
} else {
// If it's not a MetricValue, we don't need to override it.
return super.getSum(field);
}
}
private void setSum(String field, double sum) {
metricSums.put(field, sum);
}
@Override
protected Aggregate createAggregate(String field) {
throw new UnsupportedOperationException();
}
@Override
public long getCount() {
return count;
}
}
/**
* Invalidates all entries in the replication cache.
*/
public void invalidateReplicationCache() {
replicationCache.invalidateAll();
}
@Override
protected void beginTransaction(Connection connection, boolean isImmediate) throws SQLException {
connection.setAutoCommit(false);
}
@Override
protected void commitTransaction(Connection connection, boolean isImmediate) throws SQLException {
connection.commit();
}
@Override
protected void rollbackTransaction(Connection connection, boolean isImmediate) throws SQLException {
connection.rollback();
}
@Override
protected void endTransaction(Connection connection, boolean isImmediate) throws SQLException {
connection.setAutoCommit(true);
}
@Override
protected void doSaves(Connection connection, boolean isImmediate, List<State> states) throws SQLException {
List<State> indexStates = null;
for (State state1 : states) {
if (Boolean.TRUE.equals(state1.getExtra(SKIP_INDEX_STATE_EXTRA))) {
indexStates = new ArrayList<State>();
for (State state2 : states) {
if (!Boolean.TRUE.equals(state2.getExtra(SKIP_INDEX_STATE_EXTRA))) {
indexStates.add(state2);
}
}
break;
}
}
if (indexStates == null) {
indexStates = states;
}
SqlIndex.Static.deleteByStates(this, connection, indexStates);
Map<State, String> inRowIndexes = SqlIndex.Static.insertByStates(this, connection, indexStates);
boolean hasInRowIndex = hasInRowIndex();
SqlVendor vendor = getVendor();
double now = System.currentTimeMillis() / 1000.0;
for (State state : states) {
boolean isNew = state.isNew();
boolean saveInRowIndex = hasInRowIndex && !Boolean.TRUE.equals(state.getExtra(SKIP_INDEX_STATE_EXTRA));
UUID id = state.getId();
UUID typeId = state.getVisibilityAwareTypeId();
byte[] dataBytes = null;
String inRowIndex = inRowIndexes.get(state);
byte[] inRowIndexBytes = inRowIndex != null ? inRowIndex.getBytes(StandardCharsets.UTF_8) : new byte[0];
while (true) {
if (isNew) {
try {
if (dataBytes == null) {
dataBytes = serializeState(state);
}
List<Object> parameters = new ArrayList<Object>();
StringBuilder insertBuilder = new StringBuilder();
insertBuilder.append("INSERT INTO ");
vendor.appendIdentifier(insertBuilder, RECORD_TABLE);
insertBuilder.append(" (");
vendor.appendIdentifier(insertBuilder, ID_COLUMN);
insertBuilder.append(',');
vendor.appendIdentifier(insertBuilder, TYPE_ID_COLUMN);
insertBuilder.append(',');
vendor.appendIdentifier(insertBuilder, DATA_COLUMN);
if (saveInRowIndex) {
insertBuilder.append(',');
vendor.appendIdentifier(insertBuilder, IN_ROW_INDEX_COLUMN);
}
insertBuilder.append(") VALUES (");
vendor.appendBindValue(insertBuilder, id, parameters);
insertBuilder.append(',');
vendor.appendBindValue(insertBuilder, typeId, parameters);
insertBuilder.append(',');
vendor.appendBindValue(insertBuilder, dataBytes, parameters);
if (saveInRowIndex) {
insertBuilder.append(',');
vendor.appendBindValue(insertBuilder, inRowIndexBytes, parameters);
}
insertBuilder.append(')');
Static.executeUpdateWithList(connection, insertBuilder.toString(), parameters);
} catch (SQLException ex) {
if (Static.isIntegrityConstraintViolation(ex)) {
isNew = false;
continue;
} else {
throw ex;
}
}
} else {
List<AtomicOperation> atomicOperations = state.getAtomicOperations();
if (atomicOperations.isEmpty()) {
if (dataBytes == null) {
dataBytes = serializeState(state);
}
List<Object> parameters = new ArrayList<Object>();
StringBuilder updateBuilder = new StringBuilder();
updateBuilder.append("UPDATE ");
vendor.appendIdentifier(updateBuilder, RECORD_TABLE);
updateBuilder.append(" SET ");
vendor.appendIdentifier(updateBuilder, TYPE_ID_COLUMN);
updateBuilder.append('=');
vendor.appendBindValue(updateBuilder, typeId, parameters);
updateBuilder.append(',');
if (saveInRowIndex) {
vendor.appendIdentifier(updateBuilder, IN_ROW_INDEX_COLUMN);
updateBuilder.append('=');
vendor.appendBindValue(updateBuilder, inRowIndexBytes, parameters);
updateBuilder.append(',');
}
vendor.appendIdentifier(updateBuilder, DATA_COLUMN);
updateBuilder.append('=');
vendor.appendBindValue(updateBuilder, dataBytes, parameters);
updateBuilder.append(" WHERE ");
vendor.appendIdentifier(updateBuilder, ID_COLUMN);
updateBuilder.append('=');
vendor.appendBindValue(updateBuilder, id, parameters);
if (Static.executeUpdateWithList(connection, updateBuilder.toString(), parameters) < 1) {
isNew = true;
continue;
}
} else {
Object oldObject = Query
.from(Object.class)
.where("_id = ?", id)
.using(this)
.option(CONNECTION_QUERY_OPTION, connection)
.option(RETURN_ORIGINAL_DATA_QUERY_OPTION, Boolean.TRUE)
.option(USE_READ_DATA_SOURCE_QUERY_OPTION, Boolean.FALSE)
.first();
if (oldObject == null) {
retryWrites();
break;
}
State oldState = State.getInstance(oldObject);
UUID oldTypeId = oldState.getVisibilityAwareTypeId();
byte[] oldData = Static.getOriginalData(oldObject);
state.setValues(oldState.getValues());
for (AtomicOperation operation : atomicOperations) {
String field = operation.getField();
state.putByPath(field, oldState.getByPath(field));
}
for (AtomicOperation operation : atomicOperations) {
operation.execute(state);
}
dataBytes = serializeState(state);
List<Object> parameters = new ArrayList<Object>();
StringBuilder updateBuilder = new StringBuilder();
updateBuilder.append("UPDATE ");
vendor.appendIdentifier(updateBuilder, RECORD_TABLE);
updateBuilder.append(" SET ");
vendor.appendIdentifier(updateBuilder, TYPE_ID_COLUMN);
updateBuilder.append('=');
vendor.appendBindValue(updateBuilder, typeId, parameters);
if (saveInRowIndex) {
updateBuilder.append(',');
vendor.appendIdentifier(updateBuilder, IN_ROW_INDEX_COLUMN);
updateBuilder.append('=');
vendor.appendBindValue(updateBuilder, inRowIndexBytes, parameters);
}
updateBuilder.append(',');
vendor.appendIdentifier(updateBuilder, DATA_COLUMN);
updateBuilder.append('=');
vendor.appendBindValue(updateBuilder, dataBytes, parameters);
updateBuilder.append(" WHERE ");
vendor.appendIdentifier(updateBuilder, ID_COLUMN);
updateBuilder.append('=');
vendor.appendBindValue(updateBuilder, id, parameters);
updateBuilder.append(" AND ");
vendor.appendIdentifier(updateBuilder, TYPE_ID_COLUMN);
updateBuilder.append('=');
vendor.appendBindValue(updateBuilder, oldTypeId, parameters);
updateBuilder.append(" AND ");
vendor.appendIdentifier(updateBuilder, DATA_COLUMN);
updateBuilder.append('=');
vendor.appendBindValue(updateBuilder, oldData, parameters);
if (Static.executeUpdateWithList(connection, updateBuilder.toString(), parameters) < 1) {
retryWrites();
break;
}
}
}
break;
}
while (true) {
if (isNew) {
List<Object> parameters = new ArrayList<Object>();
StringBuilder insertBuilder = new StringBuilder();
insertBuilder.append("INSERT INTO ");
vendor.appendIdentifier(insertBuilder, RECORD_UPDATE_TABLE);
insertBuilder.append(" (");
vendor.appendIdentifier(insertBuilder, ID_COLUMN);
insertBuilder.append(',');
vendor.appendIdentifier(insertBuilder, TYPE_ID_COLUMN);
insertBuilder.append(',');
vendor.appendIdentifier(insertBuilder, UPDATE_DATE_COLUMN);
insertBuilder.append(") VALUES (");
vendor.appendBindValue(insertBuilder, id, parameters);
insertBuilder.append(',');
vendor.appendBindValue(insertBuilder, typeId, parameters);
insertBuilder.append(',');
vendor.appendBindValue(insertBuilder, now, parameters);
insertBuilder.append(')');
try {
Static.executeUpdateWithList(connection, insertBuilder.toString(), parameters);
} catch (SQLException ex) {
if (Static.isIntegrityConstraintViolation(ex)) {
isNew = false;
continue;
} else {
throw ex;
}
}
} else {
List<Object> parameters = new ArrayList<Object>();
StringBuilder updateBuilder = new StringBuilder();
updateBuilder.append("UPDATE ");
vendor.appendIdentifier(updateBuilder, RECORD_UPDATE_TABLE);
updateBuilder.append(" SET ");
vendor.appendIdentifier(updateBuilder, TYPE_ID_COLUMN);
updateBuilder.append('=');
vendor.appendBindValue(updateBuilder, typeId, parameters);
updateBuilder.append(',');
vendor.appendIdentifier(updateBuilder, UPDATE_DATE_COLUMN);
updateBuilder.append('=');
vendor.appendBindValue(updateBuilder, now, parameters);
updateBuilder.append(" WHERE ");
vendor.appendIdentifier(updateBuilder, ID_COLUMN);
updateBuilder.append('=');
vendor.appendBindValue(updateBuilder, id, parameters);
if (Static.executeUpdateWithList(connection, updateBuilder.toString(), parameters) < 1) {
isNew = true;
continue;
}
}
break;
}
}
}
@Override
protected void doIndexes(Connection connection, boolean isImmediate, List<State> states) throws SQLException {
SqlIndex.Static.deleteByStates(this, connection, states);
Map<State, String> inRowIndexes = SqlIndex.Static.insertByStates(this, connection, states);
if (!hasInRowIndex()) {
return;
}
SqlVendor vendor = getVendor();
for (Map.Entry<State, String> entry : inRowIndexes.entrySet()) {
StringBuilder updateBuilder = new StringBuilder();
updateBuilder.append("UPDATE ");
vendor.appendIdentifier(updateBuilder, RECORD_TABLE);
updateBuilder.append(" SET ");
vendor.appendIdentifier(updateBuilder, IN_ROW_INDEX_COLUMN);
updateBuilder.append('=');
vendor.appendValue(updateBuilder, entry.getValue());
updateBuilder.append(" WHERE ");
vendor.appendIdentifier(updateBuilder, ID_COLUMN);
updateBuilder.append('=');
vendor.appendValue(updateBuilder, entry.getKey().getId());
Static.executeUpdateWithArray(connection, updateBuilder.toString());
}
}
@Override
public void doRecalculations(Connection connection, boolean isImmediate, ObjectIndex index, List<State> states) throws SQLException {
SqlIndex.Static.updateByStates(this, connection, index, states);
}
/** @deprecated Use {@link #index} instead. */
@Deprecated
public void fixIndexes(List<State> states) {
Connection connection = openConnection();
try {
doIndexes(connection, true, states);
} catch (SQLException ex) {
List<UUID> ids = new ArrayList<UUID>();
for (State state : states) {
ids.add(state.getId());
}
throw new SqlDatabaseException(this, String.format(
"Can't index states! (%s)", ids));
} finally {
closeConnection(connection);
}
}
@Override
protected void doDeletes(Connection connection, boolean isImmediate, List<State> states) throws SQLException {
SqlVendor vendor = getVendor();
StringBuilder whereBuilder = new StringBuilder();
whereBuilder.append(" WHERE ");
vendor.appendIdentifier(whereBuilder, ID_COLUMN);
whereBuilder.append(" IN (");
for (State state : states) {
vendor.appendValue(whereBuilder, state.getId());
whereBuilder.append(',');
}
whereBuilder.setCharAt(whereBuilder.length() - 1, ')');
StringBuilder deleteBuilder = new StringBuilder();
deleteBuilder.append("DELETE FROM ");
vendor.appendIdentifier(deleteBuilder, RECORD_TABLE);
deleteBuilder.append(whereBuilder);
Static.executeUpdateWithArray(connection, deleteBuilder.toString());
SqlIndex.Static.deleteByStates(this, connection, states);
StringBuilder updateBuilder = new StringBuilder();
updateBuilder.append("UPDATE ");
vendor.appendIdentifier(updateBuilder, RECORD_UPDATE_TABLE);
updateBuilder.append(" SET ");
vendor.appendIdentifier(updateBuilder, UPDATE_DATE_COLUMN);
updateBuilder.append('=');
vendor.appendValue(updateBuilder, System.currentTimeMillis() / 1000.0);
updateBuilder.append(whereBuilder);
Static.executeUpdateWithArray(connection, updateBuilder.toString());
}
@FieldData.FieldInternalNamePrefix("sql.")
public static class FieldData extends Modification<ObjectField> {
private String indexTable;
private String indexTableColumnName;
private boolean indexTableReadOnly;
private boolean indexTableSameColumnNames;
private boolean indexTableSource;
public String getIndexTable() {
return indexTable;
}
public void setIndexTable(String indexTable) {
this.indexTable = indexTable;
}
public boolean isIndexTableReadOnly() {
return indexTableReadOnly;
}
public void setIndexTableReadOnly(boolean indexTableReadOnly) {
this.indexTableReadOnly = indexTableReadOnly;
}
public boolean isIndexTableSameColumnNames() {
return indexTableSameColumnNames;
}
public void setIndexTableSameColumnNames(boolean indexTableSameColumnNames) {
this.indexTableSameColumnNames = indexTableSameColumnNames;
}
public void setIndexTableColumnName(String indexTableColumnName) {
this.indexTableColumnName = indexTableColumnName;
}
public String getIndexTableColumnName() {
return this.indexTableColumnName;
}
public boolean isIndexTableSource() {
return indexTableSource;
}
public void setIndexTableSource(boolean indexTableSource) {
this.indexTableSource = indexTableSource;
}
public boolean isIndexTableSourceFromAnywhere() {
if (isIndexTableSource()) {
return true;
}
ObjectField field = getOriginalObject();
ObjectStruct parent = field.getParent();
String fieldName = field.getInternalName();
for (ObjectIndex index : parent.getIndexes()) {
List<String> indexFieldNames = index.getFields();
if (!indexFieldNames.isEmpty()
&& indexFieldNames.contains(fieldName)) {
String firstIndexFieldName = indexFieldNames.get(0);
if (!fieldName.equals(firstIndexFieldName)) {
ObjectField firstIndexField = parent.getField(firstIndexFieldName);
if (firstIndexField != null) {
return firstIndexField.as(FieldData.class).isIndexTableSource();
}
}
}
}
return false;
}
}
/** Specifies the name of the table for storing target field values. */
@Documented
@ObjectField.AnnotationProcessorClass(FieldIndexTableProcessor.class)
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface FieldIndexTable {
String value();
boolean readOnly() default false;
boolean sameColumnNames() default false;
boolean source() default false;
}
private static class FieldIndexTableProcessor implements ObjectField.AnnotationProcessor<FieldIndexTable> {
@Override
public void process(ObjectType type, ObjectField field, FieldIndexTable annotation) {
FieldData data = field.as(FieldData.class);
data.setIndexTable(annotation.value());
data.setIndexTableSameColumnNames(annotation.sameColumnNames());
data.setIndexTableSource(annotation.source());
data.setIndexTableReadOnly(annotation.readOnly());
}
}
private static final class FunnelCacheProducer implements FunnelCachedObjectProducer<SqlDatabase> {
private final String sqlQuery;
private final Query<?> query;
private FunnelCacheProducer(String sqlQuery, Query<?> query) {
this.query = query;
this.sqlQuery = sqlQuery;
}
@Override
public boolean equals(Object other) {
if (!(other instanceof FunnelCacheProducer)) {
return false;
}
FunnelCacheProducer otherProducer = (FunnelCacheProducer) other;
return (otherProducer.sqlQuery + otherProducer.query.getOptions().get(RETURN_ORIGINAL_DATA_QUERY_OPTION))
.equals(sqlQuery + query.getOptions().get(RETURN_ORIGINAL_DATA_QUERY_OPTION));
}
@Override
public int hashCode() {
return sqlQuery.hashCode();
}
@Override
public List<FunnelCachedObject> produce(SqlDatabase db) {
ConnectionRef extraConnectionRef = db.new ConnectionRef();
Connection connection = null;
Statement statement = null;
ResultSet result = null;
List<FunnelCachedObject> objects = new ArrayList<FunnelCachedObject>();
int timeout = db.getQueryReadTimeout(query);
Profiler.Static.startThreadEvent(FUNNEL_CACHE_PUT_PROFILER_EVENT);
try {
connection = db.openQueryConnection(query);
statement = connection.createStatement();
result = db.executeQueryBeforeTimeout(statement, sqlQuery, timeout);
while (result.next()) {
UUID id = ObjectUtils.to(UUID.class, result.getObject(1));
UUID typeId = ObjectUtils.to(UUID.class, result.getObject(2));
byte[] data = result.getBytes(3);
Map<String, Object> dataJson = unserializeData(data);
Map<String, Object> extras = null;
if (Boolean.TRUE.equals(ObjectUtils.to(Boolean.class, query.getOptions().get(RETURN_ORIGINAL_DATA_QUERY_OPTION)))) {
extras = new CompactMap<String, Object>();
extras.put(ORIGINAL_DATA_EXTRA, data);
}
objects.add(new FunnelCachedObject(id, typeId, dataJson, extras));
}
return objects;
} catch (SQLException ex) {
throw db.createQueryException(ex, sqlQuery, query);
} finally {
Profiler.Static.stopThreadEvent(objects);
db.closeResources(query, connection, statement, result);
extraConnectionRef.close();
}
}
@Override
public String toString() {
return sqlQuery;
}
}
/** {@link SqlDatabase} utility methods. */
public static final class Static {
public static List<SqlDatabase> getAll() {
return INSTANCES;
}
public static void deregisterAllDrivers() {
for (WeakReference<Driver> driverRef : REGISTERED_DRIVERS) {
Driver driver = driverRef.get();
if (driver != null) {
LOGGER.info("Deregistering [{}]", driver);
try {
DriverManager.deregisterDriver(driver);
} catch (SQLException ex) {
LOGGER.warn("Can't deregister [{}]!", driver);
}
}
}
}
/**
* Log a batch update exception with values.
*/
static void logBatchUpdateException(BatchUpdateException bue, String sqlQuery, List<? extends List<?>> parameters) {
int i = 0;
StringBuilder errorBuilder = new StringBuilder();
for (int code : bue.getUpdateCounts()) {
if (code == Statement.EXECUTE_FAILED) {
List<?> rowData = parameters.get(i);
errorBuilder.append("Batch update failed with query '");
errorBuilder.append(sqlQuery);
errorBuilder.append("' with values (");
int o = 0;
for (Object value : rowData) {
if (o++ != 0) {
errorBuilder.append(", ");
}
if (value instanceof byte[]) {
errorBuilder.append(StringUtils.hex((byte[]) value));
} else {
errorBuilder.append(value);
}
}
errorBuilder.append(')');
}
i++;
}
Exception ex = bue.getNextException() != null ? bue.getNextException() : bue;
LOGGER.error(errorBuilder.toString(), ex);
}
static void logUpdateException(String sqlQuery, List<?> parameters) {
int i = 0;
StringBuilder errorBuilder = new StringBuilder();
errorBuilder.append("Batch update failed with query '");
errorBuilder.append(sqlQuery);
errorBuilder.append("' with values (");
for (Object value : parameters) {
if (i++ != 0) {
errorBuilder.append(", ");
}
if (value instanceof byte[]) {
errorBuilder.append(StringUtils.hex((byte[]) value));
} else {
errorBuilder.append(value);
}
}
errorBuilder.append(')');
LOGGER.error(errorBuilder.toString());
}
// Safely binds the given parameter to the given statement at the
// given index.
private static void bindParameter(PreparedStatement statement, int index, Object parameter) throws SQLException {
if (parameter instanceof String) {
parameter = ((String) parameter).getBytes(StandardCharsets.UTF_8);
}
if (parameter instanceof StringBuilder) {
parameter = ((StringBuilder) parameter).toString();
}
if (parameter instanceof byte[]) {
byte[] parameterBytes = (byte[]) parameter;
int parameterBytesLength = parameterBytes.length;
if (parameterBytesLength > 2000) {
statement.setBinaryStream(index, new ByteArrayInputStream(parameterBytes), parameterBytesLength);
return;
}
}
statement.setObject(index, parameter);
}
/**
* Executes the given batch update {@code sqlQuery} with the given
* list of {@code parameters} within the given {@code connection}.
*
* @return Array of number of rows affected by the update query.
*/
public static int[] executeBatchUpdate(
Connection connection,
String sqlQuery,
List<? extends List<?>> parameters) throws SQLException {
PreparedStatement prepared = connection.prepareStatement(sqlQuery);
List<?> currentRow = null;
try {
for (List<?> row : parameters) {
currentRow = row;
int columnIndex = 1;
for (Object parameter : row) {
bindParameter(prepared, columnIndex, parameter);
columnIndex++;
}
prepared.addBatch();
}
int[] affected = null;
Stats.Timer timer = STATS.startTimer();
Profiler.Static.startThreadEvent(UPDATE_PROFILER_EVENT);
try {
affected = prepared.executeBatch();
return affected;
} finally {
double time = timer.stop(UPDATE_STATS_OPERATION);
Profiler.Static.stopThreadEvent(sqlQuery);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(
"SQL batch update: [{}], Parameters: {}, Affected: {}, Time: [{}]ms",
new Object[] { sqlQuery, parameters, affected != null ? Arrays.toString(affected) : "[]", time * 1000.0 });
}
}
} catch (SQLException error) {
logUpdateException(sqlQuery, currentRow);
throw error;
} finally {
try {
prepared.close();
} catch (SQLException error) {
// Not likely and probably harmless.
}
}
}
/**
* Executes the given update {@code sqlQuery} with the given
* {@code parameters} within the given {@code connection}.
*
* @return Number of rows affected by the update query.
*/
public static int executeUpdateWithList(
Connection connection,
String sqlQuery,
List<?> parameters)
throws SQLException {
if (parameters == null) {
return executeUpdateWithArray(connection, sqlQuery);
} else {
Object[] array = parameters.toArray(new Object[parameters.size()]);
return executeUpdateWithArray(connection, sqlQuery, array);
}
}
/**
* Executes the given update {@code sqlQuery} with the given
* {@code parameters} within the given {@code connection}.
*
* @return Number of rows affected by the update query.
*/
public static int executeUpdateWithArray(
Connection connection,
String sqlQuery,
Object... parameters)
throws SQLException {
boolean hasParameters = parameters != null && parameters.length > 0;
PreparedStatement prepared;
Statement statement;
if (hasParameters) {
prepared = connection.prepareStatement(sqlQuery);
statement = prepared;
} else {
prepared = null;
statement = connection.createStatement();
}
try {
if (hasParameters) {
for (int i = 0; i < parameters.length; i++) {
bindParameter(prepared, i + 1, parameters[i]);
}
}
Integer affected = null;
Stats.Timer timer = STATS.startTimer();
Profiler.Static.startThreadEvent(UPDATE_PROFILER_EVENT);
Savepoint savePoint = null;
try {
if (!connection.getAutoCommit()) {
savePoint = connection.setSavepoint();
}
affected = hasParameters
? prepared.executeUpdate()
: statement.executeUpdate(sqlQuery);
return affected;
} catch (SQLException sqlEx) {
if (savePoint != null) {
connection.rollback(savePoint);
}
throw sqlEx;
} finally {
if (savePoint != null) {
connection.releaseSavepoint(savePoint);
}
double time = timer.stop(UPDATE_STATS_OPERATION);
Profiler.Static.stopThreadEvent(sqlQuery);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(
"SQL update: [{}], Affected: [{}], Time: [{}]ms",
new Object[] { fillPlaceholders(sqlQuery, parameters), affected, time * 1000.0 });
}
}
} finally {
try {
statement.close();
} catch (SQLException error) {
// Not likely and probably harmless.
}
}
}
/**
* Returns {@code true} if the given {@code error} looks like a
* {@link SQLIntegrityConstraintViolationException}.
*/
public static boolean isIntegrityConstraintViolation(SQLException error) {
if (error instanceof SQLIntegrityConstraintViolationException) {
return true;
} else {
String state = error.getSQLState();
return state != null && state.startsWith("23");
}
}
/**
* Returns the name of the table for storing the values of the
* given {@code index}.
*/
public static String getIndexTable(ObjectIndex index) {
return ObjectUtils.to(String.class, index.getOptions().get(INDEX_TABLE_INDEX_OPTION));
}
/**
* Sets the name of the table for storing the values of the
* given {@code index}.
*/
public static void setIndexTable(ObjectIndex index, String table) {
index.getOptions().put(INDEX_TABLE_INDEX_OPTION, table);
}
public static Object getExtraColumn(Object object, String name) {
return State.getInstance(object).getExtra(EXTRA_COLUMN_EXTRA_PREFIX + name);
}
public static byte[] getOriginalData(Object object) {
return (byte[]) State.getInstance(object).getExtra(ORIGINAL_DATA_EXTRA);
}
/** @deprecated Use {@link #executeUpdateWithArray} instead. */
@Deprecated
public static int executeUpdate(
Connection connection,
String sqlQuery,
Object... parameters)
throws SQLException {
return executeUpdateWithArray(connection, sqlQuery, parameters);
}
}
/** @deprecated No replacement. */
@Deprecated
public void beginThreadLocalReadConnection() {
}
/** @deprecated No replacement. */
@Deprecated
public void endThreadLocalReadConnection() {
}
} |
package add;
import imagej.ops.Function;
import imagej.ops.Op;
import net.imglib2.Cursor;
import net.imglib2.IterableInterval;
import net.imglib2.RandomAccess;
import net.imglib2.RandomAccessibleInterval;
import net.imglib2.type.numeric.NumericType;
import org.scijava.Priority;
import org.scijava.plugin.Parameter;
import org.scijava.plugin.Plugin;
@Plugin(type = Op.class, name = "add", priority = Priority.VERY_LOW_PRIORITY)
public class AddConstantToImageFunctional<T extends NumericType<T>> extends
Function<IterableInterval<T>, RandomAccessibleInterval<T>>
{
@Parameter
private T value;
@Override
public RandomAccessibleInterval<T> compute(final IterableInterval<T> input,
final RandomAccessibleInterval<T> output)
{
final Cursor<T> c = input.localizingCursor();
final RandomAccess<T> ra = output.randomAccess();
while (c.hasNext()) {
final T in = c.next();
ra.setPosition(c);
final T out = ra.get();
out.set(in);
out.add(value);
}
return output;
}
} |
package biweekly.property;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import biweekly.component.ICalComponent;
public class RecurrenceRule extends ICalProperty {
private Frequency frequency;
private Integer interval;
private Integer count;
private Date until;
private boolean untilHasTime;
private List<Integer> bySecond = new ArrayList<Integer>();
private List<Integer> byMinute = new ArrayList<Integer>();
private List<Integer> byHour = new ArrayList<Integer>();
private List<Integer> byMonthDay = new ArrayList<Integer>();
private List<Integer> byYearDay = new ArrayList<Integer>();
private List<Integer> byWeekNo = new ArrayList<Integer>();
private List<Integer> byMonth = new ArrayList<Integer>();
private List<Integer> bySetPos = new ArrayList<Integer>();
private List<DayOfWeek> byDay = new ArrayList<DayOfWeek>();
private List<Integer> byDayPrefixes = new ArrayList<Integer>();
private DayOfWeek workweekStarts;
/**
* Creates a new recurrence rule property.
* @param frequency the frequency of the recurrence rule
*/
public RecurrenceRule(Frequency frequency) {
setFrequency(frequency);
}
public Frequency getFrequency() {
return frequency;
}
public void setFrequency(Frequency frequency) {
this.frequency = frequency;
}
public Date getUntil() {
return until;
}
public void setUntil(Date until) {
setUntil(until, true);
}
public void setUntil(Date until, boolean hasTime) {
this.until = until;
untilHasTime = hasTime;
}
public boolean hasTimeUntilDate() {
return untilHasTime;
}
public Integer getCount() {
return count;
}
public void setCount(Integer count) {
this.count = count;
}
public Integer getInterval() {
return interval;
}
public void setInterval(Integer interval) {
this.interval = interval;
}
public List<Integer> getBySecond() {
return bySecond;
}
public void addBySecond(Integer bySecond) {
this.bySecond.add(bySecond);
}
public void setBySecond(List<Integer> bySecond) {
this.bySecond = bySecond;
}
public List<Integer> getByMinute() {
return byMinute;
}
public void addByMinute(Integer byMinute) {
this.byMinute.add(byMinute);
}
public void setByMinute(List<Integer> byMinute) {
this.byMinute = byMinute;
}
public List<Integer> getByHour() {
return byHour;
}
public void addByHour(Integer byHour) {
this.byHour.add(byHour);
}
public void setByHour(List<Integer> byHour) {
this.byHour = byHour;
}
public void addByDay(DayOfWeek day) {
addByDay(null, day);
}
public void addByDay(Integer prefix, DayOfWeek day) {
byDayPrefixes.add(prefix);
byDay.add(day);
}
public List<DayOfWeek> getByDay() {
return byDay;
}
public List<Integer> getByDayPrefixes() {
return byDayPrefixes;
}
public List<Integer> getByMonthDay() {
return byMonthDay;
}
public void addMonthDay(Integer byMonthDay) {
this.byMonthDay.add(byMonthDay);
}
public void setByMonthDay(List<Integer> byMonthDay) {
this.byMonthDay = byMonthDay;
}
public List<Integer> getByYearDay() {
return byYearDay;
}
public void addByYearDay(Integer byYearDay) {
this.byYearDay.add(byYearDay);
}
public void setByYearDay(List<Integer> byYearDay) {
this.byYearDay = byYearDay;
}
public List<Integer> getByWeekNo() {
return byWeekNo;
}
public void addByWeekNo(Integer byWeekNo) {
this.byWeekNo.add(byWeekNo);
}
public void setByWeekNo(List<Integer> byWeekNo) {
this.byWeekNo = byWeekNo;
}
public List<Integer> getByMonth() {
return byMonth;
}
public void addByMonth(Integer byMonth) {
this.byMonth.add(byMonth);
}
public void setByMonth(List<Integer> byMonth) {
this.byMonth = byMonth;
}
public List<Integer> getBySetPos() {
return bySetPos;
}
public void addBySetPos(Integer bySetPos) {
this.bySetPos.add(bySetPos);
}
public void setBySetPos(List<Integer> bySetPos) {
this.bySetPos = bySetPos;
}
public DayOfWeek getWorkweekStarts() {
return workweekStarts;
}
public void setWorkweekStarts(DayOfWeek workweekStarts) {
this.workweekStarts = workweekStarts;
}
@Override
protected void validate(List<ICalComponent> components, List<String> warnings) {
if (frequency == null) {
warnings.add("Frequency is not set (it is a required field).");
}
if (until != null && count != null) {
warnings.add("\"Until\" and \"count\" cannot both be set.");
}
}
/**
* Represents the frequency at which the recurrence rule repeats itself.
* @author Michael Angstadt
*/
public static enum Frequency {
SECONDLY, MINUTELY, HOURLY, DAILY, WEEKLY, MONTHLY, YEARLY
}
/**
* Represents each of the seven days of the week.
* @author Michael Angstadt
*/
public static enum DayOfWeek {
MONDAY("MO"), TUESDAY("TU"), WEDNESDAY("WE"), THURSDAY("TH"), FRIDAY("FR"), SATURDAY("SA"), SUNDAY("SU");
private final String abbr;
private DayOfWeek(String abbr) {
this.abbr = abbr;
}
/**
* Gets the day's abbreviation.
* @return the abbreviation (e.g. "MO" for Monday)
*/
public String getAbbr() {
return abbr;
}
/**
* Gets a day by its abbreviation.
* @param abbr the abbreviation (case-insensitive, e.g. "MO" for Monday)
* @return the day or null if not found
*/
public static DayOfWeek valueOfAbbr(String abbr) {
for (DayOfWeek day : values()) {
if (day.abbr.equalsIgnoreCase(abbr)) {
return day;
}
}
return null;
}
}
} |
package br.uff.ic.utility;
import br.uff.ic.provviewer.VariableNames;
import br.uff.ic.utility.graph.Edge;
import br.uff.ic.utility.graph.GraphVertex;
import edu.uci.ics.jung.graph.DirectedSparseMultigraph;
import java.util.Collection;
import java.util.logging.Logger;
import edu.uci.ics.jung.graph.Graph;
import edu.uci.ics.jung.graph.util.Pair;
import java.util.HashMap;
import java.util.Map;
public class GraphCollapser {
private static final Logger logger = Logger.getLogger(GraphCollapser.class.getClass().getName());
private Graph originalGraph;
boolean considerEdgeLabelForMerge;
public GraphCollapser(Graph originalGraph, boolean considerEdgeLabelForMerge) {
this.originalGraph = originalGraph;
this.considerEdgeLabelForMerge = considerEdgeLabelForMerge;
}
Graph createGraph() throws InstantiationException, IllegalAccessException {
return (Graph) originalGraph.getClass().newInstance();
}
/**
* Method to collapse vertices into a single graph-vertex. It also collapses the edges, summarizing them
* @param inGraph
* @param clusterGraph
* @return the collapsed graph
*/
public Graph collapse(Graph inGraph, GraphVertex clusterGraph) {
if (clusterGraph.clusterGraph.getVertexCount() < 2) {
return inGraph;
}
Graph<Object, Object> graph = new DirectedSparseMultigraph<>();
try {
graph = createGraph();
} catch (Exception ex) {
ex.printStackTrace();
}
Collection cluster = clusterGraph.clusterGraph.getVertices();
Map<String, Object> collapsedEdges = new HashMap<>();
Map<String, Object> mergedEdges = new HashMap<>();
// add all vertices in the delegate, unless the vertex is in the
// cluster.
for (Object v : inGraph.getVertices()) {
if (cluster.contains(v) == false) {
graph.addVertex(v);
}
}
// add the clusterGraph as a vertex
// GraphVertex gv = GraphUtils.CreateVertexGraph(clusterGraph);
// graph.addVertex(gv);
graph.addVertex(clusterGraph);
//add all edges from the inGraph, unless both endpoints of
// the edge are in the cluster
for (Object e : (Collection<?>) inGraph.getEdges()) {
Pair endpoints = inGraph.getEndpoints(e);
// don't add edges whose endpoints are both in the cluster
if (cluster.containsAll(endpoints) == false) {
if (cluster.contains(endpoints.getFirst())) {
Object edge = hasEdge(clusterGraph.getID(), collapsedEdges, mergedEdges, e, ((Edge)e).getLabel(), ((Edge)e).getType(), cluster.hashCode(), endpoints.getSecond().hashCode());
graph.addEdge(edge, clusterGraph, endpoints.getSecond(), inGraph.getEdgeType(e));
graph.addEdge(e, clusterGraph, endpoints.getSecond(), inGraph.getEdgeType(e));
} else if (cluster.contains(endpoints.getSecond())) {
Object edge = hasEdge(clusterGraph.getID(), collapsedEdges, mergedEdges, e, ((Edge)e).getLabel(), ((Edge)e).getType(), endpoints.getFirst().hashCode(), cluster.hashCode());
graph.addEdge(edge, endpoints.getFirst(), clusterGraph, inGraph.getEdgeType(e));
graph.addEdge(e, endpoints.getFirst(), clusterGraph, inGraph.getEdgeType(e));
} else {
graph.addEdge(e, endpoints.getFirst(), endpoints.getSecond(), inGraph.getEdgeType(e));
}
}
}
return graph;
}
/**
* Method to determine if there are other edges from the same type that goes to a cluster vertex. If there are any, then it will create a summarized edge and hide the original edges
* @param collapsedEdges is a map that contains the processed edges
* @param mergedEdges is a map that contains the summarized edges
* @param e is the current edge
* @param type is the edge type
* @param source is the source hashcode
* @param target is the target hashcode
* @return the edge to be added in the graph
*/
private Object hasEdge(String clusterID, Map<String, Object> collapsedEdges, Map<String, Object> mergedEdges, Object e, String label, String type, int source, int target) {
String key;
if(considerEdgeLabelForMerge)
key = label + " " + type + " " + source + " " + target;
else
key = type + " " + source + " " + target;
if(collapsedEdges.containsKey(key)) {
((Edge)e).setHide(true);
Object edge = collapsedEdges.get(key);
((Edge)edge).setHide(true);
// If first time, create the edge
if(!mergedEdges.containsKey(key)) {
Edge newEdge = new Edge(((Edge)edge).getID(), ((Edge)edge).getType(), ((Edge)edge).getStringValue(), ((Edge)edge).getLabel(), ((Edge)edge).attributes, ((Edge)edge).getTarget(), ((Edge)edge).getSource());
newEdge = newEdge.merge((Edge) e, clusterID);
mergedEdges.put(key, newEdge);
return newEdge;
}
else {
// Else update it
Edge newEdge = ((Edge)mergedEdges.get(key)).merge((Edge) e, clusterID);
mergedEdges.put(key, newEdge);
return newEdge;
}
}
else {
collapsedEdges.put(key, e);
return e;
}
}
/**
* Method to expand the cluster-vertex
* @param inGraph
* @param clusterGraph
* @return the graph without the selected cluster-vertex
*/
public Graph expand(Graph inGraph, GraphVertex clusterGraph) {
Graph<Object, Object> graph = new DirectedSparseMultigraph<>();
try {
graph = createGraph();
} catch (Exception ex) {
ex.printStackTrace();
}
Collection cluster = clusterGraph.clusterGraph.getVertices();
logger.fine("cluster to expand is " + cluster);
// put all clusterGraph vertices and edges into the new Graph
for (Object v : cluster) {
graph.addVertex(v);
for (Object edge : clusterGraph.clusterGraph.getIncidentEdges(v)) {
Pair endpoints = clusterGraph.clusterGraph.getEndpoints(edge);
graph.addEdge(edge, endpoints.getFirst(), endpoints.getSecond(), clusterGraph.clusterGraph.getEdgeType(edge));
}
}
// add all the vertices from the current graph except for
// the cluster we are expanding
for (Object v : inGraph.getVertices()) {
if (v.equals(clusterGraph) == false) {
graph.addVertex(v);
}
}
// now that all vertices have been added, add the edges,
// ensuring that no edge contains a vertex that has not
// already been added
for (Object v : inGraph.getVertices()) {
if (v.equals(clusterGraph) == false) {
for (Object edge : inGraph.getIncidentEdges(v)) {
Pair endpoints = inGraph.getEndpoints(edge);
Object v1 = endpoints.getFirst();
Object v2 = endpoints.getSecond();
if (cluster.containsAll(endpoints) == false) {
if (clusterGraph.equals(v1)) {
if(!((Edge)edge).hasAttribute(VariableNames.MergedEdgeAttribute)) {
// i need a new v1
// Object originalV1 = originalGraph.getEndpoints(edge).getFirst();
Object originalV1 = ((Edge)edge).getSource();
Object newV1 = findVertex(graph, originalV1);
assert newV1 != null : "newV1 for " + originalV1 + " was not found!";
((Edge)edge).setHide(false);
graph.addEdge(edge, newV1, v2, inGraph.getEdgeType(edge));
}
} else if (clusterGraph.equals(v2)) {
if(!((Edge)edge).hasAttribute(VariableNames.MergedEdgeAttribute)) {
// i need a new v2
// Object originalV2 = originalGraph.getEndpoints(edge).getSecond();
Object originalV2 = ((Edge)edge).getTarget();
Object newV2 = findVertex(graph, originalV2);
assert newV2 != null : "newV2 for " + originalV2 + " was not found!";
((Edge)edge).setHide(false);
graph.addEdge(edge, v1, newV2, inGraph.getEdgeType(edge));
}
} else {
graph.addEdge(edge, v1, v2, inGraph.getEdgeType(edge));
}
}
}
}
}
return graph;
}
Object findVertex(Graph inGraph, Object vertex) {
Collection vertices = inGraph.getVertices();
if (vertices.contains(vertex)) {
return vertex;
}
for (Object v : vertices) {
if (v instanceof GraphVertex) {
GraphVertex g = (GraphVertex) v;
if (contains(g.clusterGraph, vertex)) {
return v;
}
}
}
return null;
}
private boolean contains(Graph inGraph, Object vertex) {
boolean contained = false;
if (inGraph.getVertices().contains(vertex)) {
return true;
}
for (Object v : inGraph.getVertices()) {
if (v instanceof GraphVertex) {
contained |= contains((Graph) ((GraphVertex)v).clusterGraph, vertex);
}
}
return contained;
}
public GraphVertex getClusterGraph(Graph inGraph, Collection picked) {
Graph clusterGraph;
try {
clusterGraph = createGraph();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
for (Object v : picked) {
clusterGraph.addVertex(v);
Collection edges = inGraph.getIncidentEdges(v);
for (Object edge : edges) {
Pair endpoints = inGraph.getEndpoints(edge);
Object v1 = endpoints.getFirst();
Object v2 = endpoints.getSecond();
if (picked.containsAll(endpoints)) {
clusterGraph.addEdge(edge, v1, v2, inGraph.getEdgeType(edge));
}
}
}
GraphVertex gv = GraphUtils.CreateVertexGraph(clusterGraph);
return gv;
}
} |
package ch.tkuhn.nanopub.server;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
public class MainPage extends Page {
public static void show(ServerRequest req, HttpServletResponse httpResp) throws IOException {
MainPage obj = new MainPage(req, httpResp);
obj.show();
}
public MainPage(ServerRequest req, HttpServletResponse httpResp) {
super(req, httpResp);
}
public void show() throws IOException {
String format;
String ext = getReq().getExtension();
if ("json".equals(ext)) {
format = "application/json";
} else if (ext == null || "html".equals(ext)) {
String suppFormats = "application/json,text/html";
format = Utils.getMimeType(getHttpReq(), suppFormats);
} else {
getResp().sendError(400, "Invalid request: " + getReq().getFullRequest());
return;
}
if ("application/json".equals(format)) {
println(ServerConf.getInfo().asJson());
} else {
printHtmlHeader("Nanopub Server");
println("<h1>Nanopub Server</h1>");
String url = ServerConf.getInfo().getPublicUrl();
if (url == null || url.isEmpty()) {
url = "<em>(unknown)</em>";
} else {
url = "<a href=\"" + url + "\">" + url + "</a>";
}
println("<p>Public URL: <span class=\"code\">" + url + "</span></p>");
String admin = ServerConf.getInfo().getAdmin();
if (admin == null || admin.isEmpty()) {
admin = "<em>(unknown)</em>";
} else {
admin = escapeHtml(admin);
}
println("<p>Administrator: " + admin + "</p>");
println("<p>Content:");
println("<ul>");
long npc = NanopubDb.get().getNanopubCollection().count();
println("<li><a href=\"+\">Nanopubs: " + npc + "</a></li>");
long peerc = NanopubDb.get().getPeerCollection().count();
println("<li><a href=\"peers\">Peers: " + peerc + "</a></li>");
println("</ul>");
println("<p>Actions:");
println("<ul>");
ServerInfo i = ServerConf.getInfo();
println("<li>Post nanopubs: <em>" + (i.isPostNanopubsEnabled() ? "" : "not") + " supported</em></li>");
println("<li>Post peers: <em>" + (i.isPostPeersEnabled() ? "" : "not") + " supported</em></li>");
println("</ul>");
println("<p>[ <a href=\".json\">json</a> ]</p>");
printHtmlFooter();
}
getResp().setContentType(format);
}
} |
package com.aol.cyclops.data.async;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import com.aol.cyclops.control.ReactiveSeq;
import com.aol.cyclops.data.async.AdaptersModule.ClosingSpliterator;
import com.aol.cyclops.data.async.AdaptersModule.QueueToBlockingQueueWrapper;
import com.aol.cyclops.data.async.AdaptersModule.SingleContinuation;
import com.aol.cyclops.data.async.AdaptersModule.StreamOfContinuations;
import com.aol.cyclops.data.async.wait.DirectWaitStrategy;
import com.aol.cyclops.data.async.wait.WaitStrategy;
import com.aol.cyclops.internal.react.exceptions.SimpleReactProcessingException;
import com.aol.cyclops.react.async.subscription.AlwaysContinue;
import com.aol.cyclops.react.async.subscription.Continueable;
import com.aol.cyclops.types.futurestream.Continuation;
import com.aol.cyclops.util.ExceptionSoftener;
import com.aol.cyclops.util.SimpleTimer;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import lombok.experimental.Wither;
/**
* Inspired by scalaz-streams async.Queue (functionally similar, but wraps a JDK Queue - wait-free or Blocking)
*
* A Queue that takes data from one or more input Streams and provides them to
* one or more output Streams
*
* Interface specifies a BlockingQueue, but non-BlockingQueues (such as ConcurrentLinkedQueue can be used
* in conjunction with an implementation of the Continuation interface
* @see QueueFactories#unboundedNonBlockingQueue() )
*
*
* Example transfering data using a Queue between two streams
* <pre>
* {@code
* Queue<String> transferQueue = QueueFactories.<String>boundedQueue(4)
.build();
new LazyReact(Executors.newFixedThreadPool(4)).generate(()->"data")
.map(d->"produced on " + Thread.currentThread().getId())
.peek(System.out::println)
.peek(d->transferQueue.offer(d))
.run();
transferQueue.stream()
.map(e->"Consumed on " + Thread.currentThread().getId())
.futureOperations(Executors.newFixedThreadPool(1))
.forEach(System.out::println);
while(true){
// System.out.println(inputQueue.size());
}
*
*
* }
* </pre>
*
*
*
* @author johnmcclean, thomas kountis
*
* @param <T>
* Type of data stored in Queue
*/
@Wither
@AllArgsConstructor
public class Queue<T> implements Adapter<T> {
private final static PoisonPill POISON_PILL = new PoisonPill();
private final static PoisonPill CLEAR_PILL = new PoisonPill();
private volatile boolean open = true;
private final AtomicInteger listeningStreams = new AtomicInteger();
private final int timeout;
private final TimeUnit timeUnit;
private final long offerTimeout;
private final TimeUnit offerTimeUnit;
private final int maxPoisonPills;
@Getter(AccessLevel.PACKAGE)
private final BlockingQueue<T> queue;
private final WaitStrategy<T> consumerWait;
private final WaitStrategy<T> producerWait;
@Getter
@Setter
private volatile Signal<Integer> sizeSignal;
private volatile Continueable sub;
private ContinuationStrategy continuationStrategy;
private volatile boolean shuttingDown = false;
/**
* Construct a Queue backed by a LinkedBlockingQueue
*/
public Queue() {
this(new LinkedBlockingQueue<>());
}
/**
* Construct an async.Queue backed by a JDK Queue from the provided QueueFactory
*
* @param factory QueueFactory to extract JDK Queue from
*/
public Queue(final QueueFactory<T> factory) {
final Queue<T> q = factory.build();
this.queue = q.queue;
timeout = q.timeout;
timeUnit = q.timeUnit;
maxPoisonPills = q.maxPoisonPills;
offerTimeout = q.offerTimeout;
offerTimeUnit = q.offerTimeUnit;
this.consumerWait = q.consumerWait;
this.producerWait = q.producerWait;
}
Queue(final BlockingQueue<T> queue, final WaitStrategy<T> consumer, final WaitStrategy<T> producer) {
this.queue = queue;
timeout = -1;
timeUnit = TimeUnit.MILLISECONDS;
maxPoisonPills = 90000;
offerTimeout = Integer.MAX_VALUE;
offerTimeUnit = TimeUnit.DAYS;
this.consumerWait = consumer;
this.producerWait = producer;
}
/**
* Queue accepts a BlockingQueue to make use of Blocking semantics
*
*
* @param queue
* BlockingQueue to back this Queue
*/
public Queue(final BlockingQueue<T> queue) {
this(queue, new DirectWaitStrategy<T>(), new DirectWaitStrategy<T>());
}
Queue(final BlockingQueue<T> queue, final Signal<Integer> sizeSignal) {
this(queue, new DirectWaitStrategy<T>(), new DirectWaitStrategy<T>());
}
public Queue(final java.util.Queue<T> q, final WaitStrategy<T> consumer, final WaitStrategy<T> producer) {
this(new QueueToBlockingQueueWrapper(
q),
consumer, producer);
}
public static <T> Queue<T> createMergeQueue() {
final Queue<T> q = new Queue<>();
q.continuationStrategy = new StreamOfContinuations(
q);
return q;
}
/**
* @return Sequential Infinite (until Queue is closed) Stream of data from
* this Queue
*
*/
@Override
public ReactiveSeq<T> stream() {
listeningStreams.incrementAndGet(); //assumes all Streams that ever connected, remain connected
return ReactiveSeq.fromStream(closingStream(this::get, new AlwaysContinue()));
}
/**
* Return a standard (unextended) JDK Stream connected to this Queue
* To disconnect cleanly close the queue
*
* <pre>
* {@code
* use queue.stream().parallel() to convert to a parallel Stream
* }
* </pre>
*
* @param closeScalingFactor Scaling factor for Queue closed messages to propagate to connected parallel Streams
*
* @return Java 8 Stream connnected to this Queue
*/
public Stream<T> jdkStream(int closeScalingFactor){
int cores = Runtime.getRuntime().availableProcessors();
String par = System.getProperty("java.util.concurrent.ForkJoinPool.common.parallelism");
int connected = par !=null ? Integer.valueOf(par) : cores;
for(int i=0;i<connected*closeScalingFactor;i++){
listeningStreams.incrementAndGet();
}
return closingStream(this::get, new AlwaysContinue());
}
/**
* Return a standard (unextended) JDK Stream connected to this Queue
* To disconnect cleanly close the queue
*
* <pre>
* {@code
* use queue.stream().parallel() to convert to a parallel Stream
* }
* </pre>
*
* @return Java 8 Stream connnected to this Queue
*/
public Stream<T> jdkStream() {
return jdkStream(8);
}
@Override
public ReactiveSeq<T> stream(final Continueable s) {
this.sub = s;
listeningStreams.incrementAndGet(); //assumes all Streams that ever connected, remain connected
return ReactiveSeq.fromStream(closingStream(this::get, s));
}
public ReactiveSeq<Collection<T>> streamBatchNoTimeout(final Continueable s, final Function<Supplier<T>, Supplier<Collection<T>>> batcher) {
this.sub = s;
listeningStreams.incrementAndGet(); //assumes all Streams that ever connected, remain connected
return ReactiveSeq.fromStream(closingStreamBatch(batcher.apply(() -> ensureOpen(this.timeout, this.timeUnit)), s));
}
public ReactiveSeq<Collection<T>> streamBatch(final Continueable s,
final Function<BiFunction<Long, TimeUnit, T>, Supplier<Collection<T>>> batcher) {
this.sub = s;
listeningStreams.incrementAndGet(); //assumes all Streams that ever connected, remain connected
return ReactiveSeq.fromStream(closingStreamBatch(batcher.apply((timeout, timeUnit) -> ensureOpen(timeout, timeUnit)), s));
}
public ReactiveSeq<T> streamControl(final Continueable s, final Function<Supplier<T>, Supplier<T>> batcher) {
listeningStreams.incrementAndGet(); //assumes all Streams that ever connected, remain connected
return ReactiveSeq.fromStream(closingStream(batcher.apply(() -> ensureOpen(this.timeout, this.timeUnit)), s));
}
public ReactiveSeq<CompletableFuture<T>> streamControlFutures(final Continueable s, final Function<Supplier<T>, CompletableFuture<T>> batcher) {
this.sub = s;
listeningStreams.incrementAndGet(); //assumes all Streams that ever connected, remain connected
return ReactiveSeq.fromStream(closingStreamFutures(() -> batcher.apply(() -> ensureOpen(this.timeout, this.timeUnit)), s));
}
private Stream<Collection<T>> closingStreamBatch(final Supplier<Collection<T>> s, final Continueable sub) {
final Stream<Collection<T>> st = StreamSupport.stream(new ClosingSpliterator<>(
Long.MAX_VALUE, s, sub, this),
false);
return st;
}
private Stream<T> closingStream(final Supplier<T> s, final Continueable sub) {
final Stream<T> st = StreamSupport.stream(new ClosingSpliterator<T>(
Long.MAX_VALUE, s, sub, this),
false);
return st;
}
private Stream<CompletableFuture<T>> closingStreamFutures(final Supplier<CompletableFuture<T>> s, final Continueable sub) {
final Stream<CompletableFuture<T>> st = StreamSupport.stream(new ClosingSpliterator<>(
Long.MAX_VALUE, s, sub, this),
false);
return st;
}
/**
* @return Infinite (until Queue is closed) Stream of CompletableFutures
* that can be used as input into a SimpleReact concurrent dataflow
*
* This Stream itself is Sequential, SimpleReact will apply
* concurrency / parralellism via the constituent CompletableFutures
*
*/
@Override
public ReactiveSeq<CompletableFuture<T>> streamCompletableFutures() {
return stream().map(CompletableFuture::completedFuture);
}
/**
* @param stream
* Input data from provided Stream
*/
@Override
public boolean fromStream(final Stream<T> stream) {
stream.collect(Collectors.toCollection(() -> queue));
return true;
}
private T ensureOpen(final long timeout, final TimeUnit timeUnit) {
if (!open && queue.size() == 0)
throw new ClosedQueueException();
final SimpleTimer timer = new SimpleTimer();
final long timeoutNanos = timeUnit.toNanos(timeout);
T data = null;
try {
if (this.continuationStrategy != null) {
while (open && (data = ensureClear(queue.poll())) == null) {
this.continuationStrategy.handleContinuation();
if (timeout != -1)
handleTimeout(timer, timeoutNanos);
}
if (data != null)
return (T) nillSafe(ensureNotPoisonPill(ensureClear(data)));
}
if (!open && queue.size() == 0)
throw new ClosedQueueException();
if (timeout == -1) {
if (this.sub != null && this.sub.timeLimit() > -1) {
data = ensureClear(consumerWait.take(() -> queue.poll(sub.timeLimit(), TimeUnit.NANOSECONDS)));
if (data == null)
throw new QueueTimeoutException();
}
else
data = ensureClear(consumerWait.take(() -> queue.take()));
} else {
data = ensureClear(consumerWait.take(() -> queue.poll(timeout, timeUnit)));
if (data == null)
throw new QueueTimeoutException();
}
} catch (final InterruptedException e) {
Thread.currentThread()
.interrupt();
throw ExceptionSoftener.throwSoftenedException(e);
}
ensureNotPoisonPill(data);
if (sizeSignal != null)
this.sizeSignal.set(queue.size());
return (T) nillSafe(data);
}
private void handleTimeout(final SimpleTimer timer, final long timeout) {
if (timer.getElapsedNanoseconds() > timeout) {
throw new QueueTimeoutException();
}
}
private T ensureClear(T poll) {
if (CLEAR_PILL == poll) {
if (queue.size() > 0)
poll = ensureClear(queue.poll());
this.queue.clear();
}
return poll;
}
private T ensureNotPoisonPill(final T data) {
if (data instanceof PoisonPill) {
throw new ClosedQueueException();
}
return data;
}
/**
* Exception thrown if Queue closed
*
* @author johnmcclean
*
*/
@AllArgsConstructor
public static class ClosedQueueException extends SimpleReactProcessingException {
private static final long serialVersionUID = 1L;
@Getter
private final List currentData;
public ClosedQueueException() {
currentData = null;
}
public boolean isDataPresent() {
return currentData != null;
}
@Override
public Throwable fillInStackTrace() {
return this;
}
}
/**
* Exception thrown if Queue polling timesout
*
* @author johnmcclean
*
*/
public static class QueueTimeoutException extends SimpleReactProcessingException {
@Override
public Throwable fillInStackTrace() {
return this;
}
private static final long serialVersionUID = 1L;
}
private static class PoisonPill {
}
public T poll(final long time, final TimeUnit unit) throws QueueTimeoutException {
return this.ensureOpen(time, unit);
}
public T get() {
return ensureOpen(this.timeout, this.timeUnit);
}
/**
* Add a single data point to the queue
*
* If the queue is a bounded queue and is full, will return false
*
* @param data Data to add
* @return true if successfully added.
*/
public boolean add(final T data) {
try {
final boolean result = queue.add((T) nullSafe(data));
if (result) {
if (sizeSignal != null)
this.sizeSignal.set(queue.size());
}
return result;
} catch (final IllegalStateException e) {
return false;
}
}
/**
* Offer a single datapoint to this Queue
*
* If the queue is a bounded queue and is full it will block until space comes available or until
* offer time out is reached (default is Integer.MAX_VALUE DAYS).
*
* @param data
* data to add
* @return self
*/
@Override
public boolean offer(final T data) {
if (!open)
throw new ClosedQueueException();
try {
final boolean result = producerWait.offer(() -> this.queue.offer((T) nullSafe(data), this.offerTimeout, this.offerTimeUnit));
if (sizeSignal != null)
this.sizeSignal.set(queue.size());
return result;
} catch (final InterruptedException e) {
Thread.currentThread()
.interrupt();
throw ExceptionSoftener.throwSoftenedException(e);
}
}
private boolean timeout(final SimpleTimer timer) {
if (timer.getElapsedNanoseconds() >= offerTimeUnit.toNanos(this.offerTimeout))
return true;
return false;
}
private Object nillSafe(final T data) {
if (NILL == data)
return null;
else
return data;
}
private Object nullSafe(final T data) {
if (data == null)
return NILL;
else
return data;
}
/**
* Close this Queue
*
* @return true if closed
*/
@Override
public boolean close() {
this.open = false;
if (this.queue.remainingCapacity() > 0) {
for (int i = 0; i < Math.min(maxPoisonPills, listeningStreams.get()); i++) {
add((T) POISON_PILL);
}
}
return true;
}
public void closeAndClear() {
this.open = false;
add((T) CLEAR_PILL);
}
public static final NIL NILL = new NIL();
public static class NIL {
}
@AllArgsConstructor
public static class QueueReader<T> {
@Getter
Queue<T> queue;
public boolean notEmpty() {
return queue.queue.size() != 0;
}
@Getter
private volatile T last = null;
private int size() {
return queue.queue.size();
}
public T next() {
last = queue.ensureOpen(queue.timeout, queue.timeUnit);
return last;
}
public boolean isOpen() {
return queue.open || notEmpty();
}
public Collection<T> drainToOrBlock() {
final Collection<T> result = new ArrayList<>();
if (size() > 0)
queue.queue.drainTo(result);
else {
try {
result.add(queue.ensureOpen(queue.timeout, queue.timeUnit));
} catch (final ClosedQueueException e) {
queue.open = false;
throw e;
}
}
return result.stream()
.filter(it -> it != POISON_PILL)
.collect(Collectors.toList());
}
}
public int size() {
return queue.size();
}
public boolean isOpen() {
return this.open;
}
public void addContinuation(final Continuation c) {
if (this.continuationStrategy == null)
continuationStrategy = new SingleContinuation(
this);
this.continuationStrategy.addContinuation(c);
}
@Override
public <R> R visit(final Function<? super Queue<T>, ? extends R> caseQueue, final Function<? super Topic<T>, ? extends R> caseTopic) {
return caseQueue.apply(this);
}
} |
package com.atlassian.rstocker.cm;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Locale;
import java.util.function.Function;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Common {
private static final String ENTITY = "&(?:#x[a-f0-9]{1,8}|#[0-9]{1,8}|[a-z][a-z0-9]{1,31});";
// foo: not sure about [ in [
static final String ESCAPABLE = "[!\"
// foo: not sure about the backslashes here
private static final Pattern reBackslashOrAmp = Pattern.compile("[\\\\&]");
// foo: had flags 'gi' before
private static final Pattern reEntityOrEscapedChar =
Pattern.compile("\\\\" + ESCAPABLE + '|' + ENTITY, Pattern.CASE_INSENSITIVE);
private static final String XMLSPECIAL = "[&<>\"]";
// foo: had flags 'g' before
private static final Pattern reXmlSpecial = Pattern.compile(XMLSPECIAL);
// foo: had flags 'gi' before
private static final Pattern reXmlSpecialOrEntity = Pattern.compile(ENTITY + '|' + XMLSPECIAL,
Pattern.CASE_INSENSITIVE);
static String unescapeChar(String s) {
if (s.charAt(0) == '\\') {
return s.substring(1);
} else {
return Html5Entities.entityToString(s);
}
}
// Replace entities and backslash escapes with literal characters.
public static String unescapeString(String s) {
if (reBackslashOrAmp.matcher(s).find()) {
return replaceAll(reEntityOrEscapedChar, s, match -> unescapeChar(match));
} else {
return s;
}
}
public static String normalizeURI(String uri) {
try {
// foo: equivalent to encodeURI(decodeURI(uri))?
uri = uri.replaceAll(" ", "%20");
uri = uri.replaceAll("\\\\", "%5C");
uri = uri.replaceAll("`", "%60");
return new URI(uri).toASCIIString();
} catch (URISyntaxException e) {
return uri;
}
}
private static Pattern whitespace = Pattern.compile("[ \t\r\n]+");
public static String normalizeReference(String input) {
// foo: is this the same as JS?
return whitespace.matcher(input.toLowerCase(Locale.ROOT)).replaceAll(" ");
}
public static Escaper XML_ESCAPER = (s, preserveEntities) -> {
Pattern p = preserveEntities ? reXmlSpecialOrEntity : reXmlSpecial;
return replaceAll(p, s, match -> replaceUnsafeChar(match));
};
private static String replaceUnsafeChar(String s) {
switch (s) {
case "&":
return "&";
case "<":
return "<";
case ">":
return ">";
case "\"":
return """;
default:
return s;
}
}
private static String replaceAll(Pattern p, String s,
Function<String, String> replacer) {
Matcher matcher = p.matcher(s);
if (!matcher.find()) {
return s;
}
StringBuilder sb = new StringBuilder(s.length() + 16);
int lastEnd = 0;
do {
sb.append(s, lastEnd, matcher.start());
String replaced = replacer.apply(matcher.group());
sb.append(replaced);
lastEnd = matcher.end();
} while (matcher.find());
if (lastEnd != s.length()) {
sb.append(s, lastEnd, s.length());
}
return sb.toString();
}
} |
package com.couchbase.lite.router;
import com.couchbase.lite.AsyncTask;
import com.couchbase.lite.Attachment;
import com.couchbase.lite.ChangesOptions;
import com.couchbase.lite.CouchbaseLiteException;
import com.couchbase.lite.Database;
import com.couchbase.lite.Database.TDContentOptions;
import com.couchbase.lite.DocumentChange;
import com.couchbase.lite.Manager;
import com.couchbase.lite.Misc;
import com.couchbase.lite.QueryOptions;
import com.couchbase.lite.QueryRow;
import com.couchbase.lite.Reducer;
import com.couchbase.lite.ReplicationFilter;
import com.couchbase.lite.Mapper;
import com.couchbase.lite.RevisionList;
import com.couchbase.lite.Status;
import com.couchbase.lite.View;
import com.couchbase.lite.View.TDViewCollation;
import com.couchbase.lite.auth.FacebookAuthorizer;
import com.couchbase.lite.auth.PersonaAuthorizer;
import com.couchbase.lite.internal.Body;
import com.couchbase.lite.internal.RevisionInternal;
import com.couchbase.lite.replicator.Replication;
import com.couchbase.lite.util.Log;
import org.apache.http.client.HttpResponseException;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
public class Router implements Database.ChangeListener {
private Manager manager;
private Database db;
private URLConnection connection;
private Map<String,String> queries;
private boolean changesIncludesDocs = false;
private RouterCallbackBlock callbackBlock;
private boolean responseSent = false;
private boolean waiting = false;
private ReplicationFilter changesFilter;
private boolean longpoll = false;
public static String getVersionString() {
return Manager.VERSION;
}
public Router(Manager manager, URLConnection connection) {
this.manager = manager;
this.connection = connection;
}
public void setCallbackBlock(RouterCallbackBlock callbackBlock) {
this.callbackBlock = callbackBlock;
}
public Map<String,String> getQueries() {
if(queries == null) {
String queryString = connection.getURL().getQuery();
if(queryString != null && queryString.length() > 0) {
queries = new HashMap<String,String>();
for (String component : queryString.split("&")) {
int location = component.indexOf('=');
if(location > 0) {
String key = component.substring(0, location);
String value = component.substring(location + 1);
queries.put(key, value);
}
}
}
}
return queries;
}
public boolean getBooleanValueFromBody(String paramName, Map<String, Object> bodyDict, boolean defaultVal) {
boolean value = defaultVal;
if (bodyDict.containsKey(paramName)) {
value = Boolean.TRUE.equals(bodyDict.get(paramName));
}
return value;
}
public String getQuery(String param) {
Map<String,String> queries = getQueries();
if(queries != null) {
String value = queries.get(param);
if(value != null) {
return URLDecoder.decode(value);
}
}
return null;
}
public boolean getBooleanQuery(String param) {
String value = getQuery(param);
return (value != null) && !"false".equals(value) && !"0".equals(value);
}
public int getIntQuery(String param, int defaultValue) {
int result = defaultValue;
String value = getQuery(param);
if(value != null) {
try {
result = Integer.parseInt(value);
} catch (NumberFormatException e) {
//ignore, will return default value
}
}
return result;
}
public Object getJSONQuery(String param) {
String value = getQuery(param);
if(value == null) {
return null;
}
Object result = null;
try {
result = Manager.getObjectMapper().readValue(value, Object.class);
} catch (Exception e) {
Log.w("Unable to parse JSON Query", e);
}
return result;
}
public boolean cacheWithEtag(String etag) {
String eTag = String.format("\"%s\"", etag);
connection.getResHeader().add("Etag", eTag);
String requestIfNoneMatch = connection.getRequestProperty("If-None-Match");
return eTag.equals(requestIfNoneMatch);
}
public Map<String,Object> getBodyAsDictionary() {
try {
InputStream contentStream = connection.getRequestInputStream();
Map<String,Object> bodyMap = Manager.getObjectMapper().readValue(contentStream, Map.class);
return bodyMap;
} catch (IOException e) {
Log.w(Database.TAG, "WARNING: Exception parsing body into dictionary", e);
return null;
}
}
public EnumSet<TDContentOptions> getContentOptions() {
EnumSet<TDContentOptions> result = EnumSet.noneOf(TDContentOptions.class);
if(getBooleanQuery("attachments")) {
result.add(TDContentOptions.TDIncludeAttachments);
}
if(getBooleanQuery("local_seq")) {
result.add(TDContentOptions.TDIncludeLocalSeq);
}
if(getBooleanQuery("conflicts")) {
result.add(TDContentOptions.TDIncludeConflicts);
}
if(getBooleanQuery("revs")) {
result.add(TDContentOptions.TDIncludeRevs);
}
if(getBooleanQuery("revs_info")) {
result.add(TDContentOptions.TDIncludeRevsInfo);
}
return result;
}
public boolean getQueryOptions(QueryOptions options) {
// http://wiki.apache.org/couchdb/HTTP_view_API#Querying_Options
options.setSkip(getIntQuery("skip", options.getSkip()));
options.setLimit(getIntQuery("limit", options.getLimit()));
options.setGroupLevel(getIntQuery("group_level", options.getGroupLevel()));
options.setDescending(getBooleanQuery("descending"));
options.setIncludeDocs(getBooleanQuery("include_docs"));
options.setUpdateSeq(getBooleanQuery("update_seq"));
if(getQuery("inclusive_end") != null) {
options.setInclusiveEnd(getBooleanQuery("inclusive_end"));
}
if(getQuery("reduce") != null) {
options.setReduce(getBooleanQuery("reduce"));
}
options.setGroup(getBooleanQuery("group"));
options.setContentOptions(getContentOptions());
List<Object> keys;
Object keysParam = getJSONQuery("keys");
if (keysParam != null && !(keysParam instanceof List)) {
return false;
}
else {
keys = ( List<Object>) keysParam;
}
if (keys == null) {
Object key = getJSONQuery("key");
if(key != null) {
keys = new ArrayList<Object>();
keys.add(key);
}
}
if (keys != null) {
options.setKeys(keys);
}
else {
options.setStartKey(getJSONQuery("startkey"));
options.setEndKey(getJSONQuery("endkey"));
}
return true;
}
public String getMultipartRequestType() {
String accept = connection.getRequestProperty("Accept");
if(accept.startsWith("multipart/")) {
return accept;
}
return null;
}
public Status openDB() {
if(db == null) {
return new Status(Status.INTERNAL_SERVER_ERROR);
}
if(!db.exists()) {
return new Status(Status.NOT_FOUND);
}
if(!db.open()) {
return new Status(Status.INTERNAL_SERVER_ERROR);
}
return new Status(Status.OK);
}
public static List<String> splitPath(URL url) {
String pathString = url.getPath();
if(pathString.startsWith("/")) {
pathString = pathString.substring(1);
}
List<String> result = new ArrayList<String>();
//we want empty string to return empty list
if(pathString.length() == 0) {
return result;
}
for (String component : pathString.split("/")) {
result.add(URLDecoder.decode(component));
}
return result;
}
public void sendResponse() {
if(!responseSent) {
responseSent = true;
if(callbackBlock != null) {
callbackBlock.onResponseReady();
}
}
}
public void start() {
// We're going to map the request into a method call using reflection based on the method and path.
// Accumulate the method name into the string 'message':
String method = connection.getRequestMethod();
if("HEAD".equals(method)) {
method = "GET";
}
String message = String.format("do_%s", method);
// First interpret the components of the request:
List<String> path = splitPath(connection.getURL());
if(path == null) {
connection.setResponseCode(Status.BAD_REQUEST);
try {
connection.getResponseOutputStream().close();
} catch (IOException e) {
Log.e(Database.TAG, "Error closing empty output stream");
}
sendResponse();
return;
}
int pathLen = path.size();
if(pathLen > 0) {
String dbName = path.get(0);
if(dbName.startsWith("_")) {
message += dbName; // special root path, like /_all_dbs
} else {
message += "_Database";
if (!Manager.isValidDatabaseName(dbName)) {
Header resHeader = connection.getResHeader();
if (resHeader != null) {
resHeader.add("Content-Type", "application/json");
}
Map<String, Object> result = new HashMap<String, Object>();
result.put("error", "Invalid database");
result.put("status", Status.BAD_REQUEST );
connection.setResponseBody(new Body(result));
ByteArrayInputStream bais = new ByteArrayInputStream(connection.getResponseBody().getJson());
connection.setResponseInputStream(bais);
connection.setResponseCode(Status.BAD_REQUEST);
try {
connection.getResponseOutputStream().close();
} catch (IOException e) {
Log.e(Database.TAG, "Error closing empty output stream");
}
sendResponse();
return;
}
else {
boolean mustExist = false;
db = manager.getDatabaseWithoutOpening(dbName, mustExist);
if(db == null) {
connection.setResponseCode(Status.BAD_REQUEST);
try {
connection.getResponseOutputStream().close();
} catch (IOException e) {
Log.e(Database.TAG, "Error closing empty output stream");
}
sendResponse();
return;
}
}
}
} else {
message += "Root";
}
String docID = null;
if(db != null && pathLen > 1) {
message = message.replaceFirst("_Database", "_Document");
// Make sure database exists, then interpret doc name:
Status status = openDB();
if(!status.isSuccessful()) {
connection.setResponseCode(status.getCode());
try {
connection.getResponseOutputStream().close();
} catch (IOException e) {
Log.e(Database.TAG, "Error closing empty output stream");
}
sendResponse();
return;
}
String name = path.get(1);
if(!name.startsWith("_")) {
// Regular document
if(!Database.isValidDocumentId(name)) {
connection.setResponseCode(Status.BAD_REQUEST);
try {
connection.getResponseOutputStream().close();
} catch (IOException e) {
Log.e(Database.TAG, "Error closing empty output stream");
}
sendResponse();
return;
}
docID = name;
} else if("_design".equals(name) || "_local".equals(name)) {
if(pathLen <= 2) {
connection.setResponseCode(Status.NOT_FOUND);
try {
connection.getResponseOutputStream().close();
} catch (IOException e) {
Log.e(Database.TAG, "Error closing empty output stream");
}
sendResponse();
return;
}
docID = name + "/" + path.get(2);
path.set(1, docID);
path.remove(2);
pathLen
} else if(name.startsWith("_design") || name.startsWith("_local")) {
// This is also a document, just with a URL-encoded "/"
docID = name;
} else {
// Special document name like "_all_docs":
message += name;
if(pathLen > 2) {
List<String> subList = path.subList(2, pathLen-1);
StringBuilder sb = new StringBuilder();
Iterator<String> iter = subList.iterator();
while(iter.hasNext()) {
sb.append(iter.next());
if(iter.hasNext()) {
sb.append("/");
}
}
docID = sb.toString();
}
}
}
String attachmentName = null;
if(docID != null && pathLen > 2) {
message = message.replaceFirst("_Document", "_Attachment");
// Interpret attachment name:
attachmentName = path.get(2);
if(attachmentName.startsWith("_") && docID.startsWith("_design")) {
// Design-doc attribute like _info or _view
message = message.replaceFirst("_Attachment", "_DesignDocument");
docID = docID.substring(8); // strip the "_design/" prefix
attachmentName = pathLen > 3 ? path.get(3) : null;
} else {
if (pathLen > 3) {
List<String> subList = path.subList(2, pathLen);
StringBuilder sb = new StringBuilder();
Iterator<String> iter = subList.iterator();
while(iter.hasNext()) {
sb.append(iter.next());
if(iter.hasNext()) {
//sb.append("%2F");
sb.append("/");
}
}
attachmentName = sb.toString();
}
}
}
//Log.d(TAG, "path: " + path + " message: " + message + " docID: " + docID + " attachmentName: " + attachmentName);
// Send myself a message based on the components:
Status status = null;
try {
Method m = Router.class.getMethod(message, Database.class, String.class, String.class);
status = (Status)m.invoke(this, db, docID, attachmentName);
} catch (NoSuchMethodException msme) {
try {
String errorMessage = "Router unable to route request to " + message;
Log.e(Database.TAG, errorMessage);
Map<String, Object> result = new HashMap<String, Object>();
result.put("error", "not_found");
result.put("reason", errorMessage);
connection.setResponseBody(new Body(result));
Method m = Router.class.getMethod("do_UNKNOWN", Database.class, String.class, String.class);
status = (Status)m.invoke(this, db, docID, attachmentName);
} catch (Exception e) {
//default status is internal server error
Log.e(Database.TAG, "Router attempted do_UNKNWON fallback, but that threw an exception", e);
Map<String, Object> result = new HashMap<String, Object>();
result.put("error", "not_found");
result.put("reason", "Router unable to route request");
connection.setResponseBody(new Body(result));
status = new Status(Status.NOT_FOUND);
}
} catch (Exception e) {
String errorMessage = "Router unable to route request to " + message;
Log.e(Database.TAG, errorMessage, e);
Map<String, Object> result = new HashMap<String, Object>();
result.put("error", "not_found");
result.put("reason", errorMessage + e.toString());
connection.setResponseBody(new Body(result));
if (e instanceof CouchbaseLiteException) {
status = ((CouchbaseLiteException)e).getCBLStatus();
}
else {
status = new Status(Status.NOT_FOUND);
}
}
// Configure response headers:
if(status.isSuccessful() && connection.getResponseBody() == null && connection.getHeaderField("Content-Type") == null) {
connection.setResponseBody(new Body("{\"ok\":true}".getBytes()));
}
if (status.isSuccessful() == false && connection.getResponseBody() == null) {
Map<String, Object> result = new HashMap<String, Object>();
result.put("status", status.getCode());
connection.setResponseBody(new Body(result));
}
if(connection.getResponseBody() != null && connection.getResponseBody().isValidJSON()) {
Header resHeader = connection.getResHeader();
if (resHeader != null) {
resHeader.add("Content-Type", "application/json");
}
else {
Log.w(Database.TAG, "Cannot add Content-Type header because getResHeader() returned null");
}
}
// Check for a mismatch between the Accept request header and the response type:
String accept = connection.getRequestProperty("Accept");
if(accept != null && !"*/*".equals(accept)) {
String responseType = connection.getBaseContentType();
if(responseType != null && accept.indexOf(responseType) < 0) {
Log.e(Database.TAG, String.format("Error 406: Can't satisfy request Accept: %s", accept));
status = new Status(Status.NOT_ACCEPTABLE);
}
}
connection.getResHeader().add("Server", String.format("Couchbase Lite %s", getVersionString()));
// If response is ready (nonzero status), tell my client about it:
if(status.getCode() != 0) {
connection.setResponseCode(status.getCode());
if(connection.getResponseBody() != null) {
ByteArrayInputStream bais = new ByteArrayInputStream(connection.getResponseBody().getJson());
connection.setResponseInputStream(bais);
} else {
try {
connection.getResponseOutputStream().close();
} catch (IOException e) {
Log.e(Database.TAG, "Error closing empty output stream");
}
}
sendResponse();
}
}
public void stop() {
callbackBlock = null;
if(db != null) {
db.removeChangeListener(this);
}
}
public Status do_UNKNOWN(Database db, String docID, String attachmentName) {
return new Status(Status.BAD_REQUEST);
}
/*** Router+Handlers ***/
public void setResponseLocation(URL url) {
String location = url.toExternalForm();
String query = url.getQuery();
if(query != null) {
int startOfQuery = location.indexOf(query);
if(startOfQuery > 0) {
location = location.substring(0, startOfQuery);
}
}
connection.getResHeader().add("Location", location);
}
/** SERVER REQUESTS: **/
public Status do_GETRoot(Database _db, String _docID, String _attachmentName) {
Map<String,Object> info = new HashMap<String,Object>();
info.put("CBLite", "Welcome");
info.put("couchdb", "Welcome"); // for compatibility
info.put("version", getVersionString());
connection.setResponseBody(new Body(info));
return new Status(Status.OK);
}
public Status do_GET_all_dbs(Database _db, String _docID, String _attachmentName) {
List<String> dbs = manager.getAllDatabaseNames();
connection.setResponseBody(new Body(dbs));
return new Status(Status.OK);
}
public Status do_GET_session(Database _db, String _docID, String _attachmentName) {
// Send back an "Admin Party"-like response
Map<String,Object> session= new HashMap<String,Object>();
Map<String,Object> userCtx = new HashMap<String,Object>();
String[] roles = {"_admin"};
session.put("ok", true);
userCtx.put("name", null);
userCtx.put("roles", roles);
session.put("userCtx", userCtx);
connection.setResponseBody(new Body(session));
return new Status(Status.OK);
}
public Status do_POST_replicate(Database _db, String _docID, String _attachmentName) {
Replication replicator;
// Extract the parameters from the JSON request body:
Map<String,Object> body = getBodyAsDictionary();
if(body == null) {
return new Status(Status.BAD_REQUEST);
}
try {
replicator = manager.getReplicator(body);
} catch (CouchbaseLiteException e) {
Map<String, Object> result = new HashMap<String, Object>();
result.put("error", e.toString());
connection.setResponseBody(new Body(result));
return e.getCBLStatus();
}
Boolean cancelBoolean = (Boolean)body.get("cancel");
boolean cancel = (cancelBoolean != null && cancelBoolean.booleanValue());
if(!cancel) {
replicator.start();
Map<String,Object> result = new HashMap<String,Object>();
result.put("session_id", replicator.getSessionID());
connection.setResponseBody(new Body(result));
} else {
// Cancel replication:
replicator.stop();
}
return new Status(Status.OK);
}
public Status do_GET_uuids(Database _db, String _docID, String _attachmentName) {
int count = Math.min(1000, getIntQuery("count", 1));
List<String> uuids = new ArrayList<String>(count);
for(int i=0; i<count; i++) {
uuids.add(Database.generateDocumentId());
}
Map<String,Object> result = new HashMap<String,Object>();
result.put("uuids", uuids);
connection.setResponseBody(new Body(result));
return new Status(Status.OK);
}
public Status do_GET_active_tasks(Database _db, String _docID, String _attachmentName) {
List<Map<String,Object>> activities = new ArrayList<Map<String,Object>>();
for (Database db : manager.allOpenDatabases()) {
List<Replication> activeReplicators = db.getActiveReplications();
if(activeReplicators != null) {
for (Replication replicator : activeReplicators) {
String source = replicator.getRemoteUrl().toExternalForm();
String target = db.getName();
if(!replicator.isPull()) {
String tmp = source;
source = target;
target = tmp;
}
int processed = replicator.getCompletedChangesCount();
int total = replicator.getChangesCount();
String status = String.format("Processed %d / %d changes", processed, total);
int progress = (total > 0) ? Math.round(100 * processed / (float)total) : 0;
Map<String,Object> activity = new HashMap<String,Object>();
activity.put("type", "Replication");
activity.put("task", replicator.getSessionID());
activity.put("source", source);
activity.put("target", target);
activity.put("status", status);
activity.put("progress", progress);
if (replicator.getLastError() != null) {
String msg = String.format("Replicator error: %s. Repl: %s. Source: %s, Target: %s",
replicator.getLastError(), replicator, source, target);
Log.e(Database.TAG, msg);
Throwable error = replicator.getLastError();
int statusCode = 400;
if (error instanceof HttpResponseException) {
statusCode = ((HttpResponseException)error).getStatusCode();
}
Object[] errorObjects = new Object[]{ statusCode, replicator.getLastError().toString() };
activity.put("error", errorObjects);
}
activities.add(activity);
}
}
}
connection.setResponseBody(new Body(activities));
return new Status(Status.OK);
}
/** DATABASE REQUESTS: **/
public Status do_GET_Database(Database _db, String _docID, String _attachmentName) {
// http://wiki.apache.org/couchdb/HTTP_database_API#Database_Information
Status status = openDB();
if(!status.isSuccessful()) {
return status;
}
int num_docs = db.getDocumentCount();
long update_seq = db.getLastSequenceNumber();
long instanceStartTimeMicroseconds = db.getStartTime() * 1000;
Map<String, Object> result = new HashMap<String,Object>();
result.put("db_name", db.getName());
result.put("db_uuid", db.publicUUID());
result.put("doc_count", num_docs);
result.put("update_seq", update_seq);
result.put("disk_size", db.totalDataSize());
result.put("instance_start_time", instanceStartTimeMicroseconds);
connection.setResponseBody(new Body(result));
return new Status(Status.OK);
}
public Status do_PUT_Database(Database _db, String _docID, String _attachmentName) {
if(db.exists()) {
return new Status(Status.PRECONDITION_FAILED);
}
if(!db.open()) {
return new Status(Status.INTERNAL_SERVER_ERROR);
}
setResponseLocation(connection.getURL());
return new Status(Status.CREATED);
}
public Status do_DELETE_Database(Database _db, String _docID, String _attachmentName) throws CouchbaseLiteException {
if(getQuery("rev") != null) {
return new Status(Status.BAD_REQUEST); // CouchDB checks for this; probably meant to be a document deletion
}
db.delete();
return new Status(Status.OK);
}
/**
* This is a hack to deal with the fact that there is currently no custom
* serializer for QueryRow. Instead, just convert everything to generic Maps.
*/
private void convertCBLQueryRowsToMaps(Map<String,Object> allDocsResult) {
List<Map<String, Object>> rowsAsMaps = new ArrayList<Map<String, Object>>();
List<QueryRow> rows = (List<QueryRow>) allDocsResult.get("rows");
for (QueryRow row : rows) {
rowsAsMaps.add(row.asJSONDictionary());
}
allDocsResult.put("rows", rowsAsMaps);
}
public Status do_POST_Database(Database _db, String _docID, String _attachmentName) {
Status status = openDB();
if(!status.isSuccessful()) {
return status;
}
return update(db, null, getBodyAsDictionary(), false);
}
public Status do_GET_Document_all_docs(Database _db, String _docID, String _attachmentName) throws CouchbaseLiteException {
QueryOptions options = new QueryOptions();
if(!getQueryOptions(options)) {
return new Status(Status.BAD_REQUEST);
}
Map<String,Object> result = db.getAllDocs(options);
convertCBLQueryRowsToMaps(result);
if(result == null) {
return new Status(Status.INTERNAL_SERVER_ERROR);
}
connection.setResponseBody(new Body(result));
return new Status(Status.OK);
}
public Status do_POST_Document_all_docs(Database _db, String _docID, String _attachmentName) throws CouchbaseLiteException {
QueryOptions options = new QueryOptions();
if (!getQueryOptions(options)) {
return new Status(Status.BAD_REQUEST);
}
Map<String, Object> body = getBodyAsDictionary();
if (body == null) {
return new Status(Status.BAD_REQUEST);
}
List<Object> keys = (List<Object>) body.get("keys");
options.setKeys(keys);
Map<String, Object> result = null;
result = db.getAllDocs(options);
convertCBLQueryRowsToMaps(result);
if (result == null) {
return new Status(Status.INTERNAL_SERVER_ERROR);
}
connection.setResponseBody(new Body(result));
return new Status(Status.OK);
}
public Status do_POST_facebook_token(Database _db, String _docID, String _attachmentName) {
Map<String, Object> body = getBodyAsDictionary();
if (body == null) {
return new Status(Status.BAD_REQUEST);
}
String email = (String) body.get("email");
String remoteUrl = (String) body.get("remote_url");
String accessToken = (String) body.get("access_token");
if (email != null && remoteUrl != null && accessToken != null) {
try {
URL siteUrl = new URL(remoteUrl);
} catch (MalformedURLException e) {
Map<String, Object> result = new HashMap<String, Object>();
result.put("error", "invalid remote_url: " + e.getLocalizedMessage());
connection.setResponseBody(new Body(result));
return new Status(Status.BAD_REQUEST);
}
try {
FacebookAuthorizer.registerAccessToken(accessToken, email, remoteUrl);
} catch (Exception e) {
Map<String, Object> result = new HashMap<String, Object>();
result.put("error", "error registering access token: " + e.getLocalizedMessage());
connection.setResponseBody(new Body(result));
return new Status(Status.BAD_REQUEST);
}
Map<String, Object> result = new HashMap<String, Object>();
result.put("ok", "registered");
connection.setResponseBody(new Body(result));
return new Status(Status.OK);
}
else {
Map<String, Object> result = new HashMap<String, Object>();
result.put("error", "required fields: access_token, email, remote_url");
connection.setResponseBody(new Body(result));
return new Status(Status.BAD_REQUEST);
}
}
public Status do_POST_persona_assertion(Database _db, String _docID, String _attachmentName) {
Map<String, Object> body = getBodyAsDictionary();
if (body == null) {
return new Status(Status.BAD_REQUEST);
}
String assertion = (String) body.get("assertion");
if (assertion == null) {
Map<String, Object> result = new HashMap<String, Object>();
result.put("error", "required fields: assertion");
connection.setResponseBody(new Body(result));
return new Status(Status.BAD_REQUEST);
}
try {
String email = PersonaAuthorizer.registerAssertion(assertion);
Map<String, Object> result = new HashMap<String, Object>();
result.put("ok", "registered");
result.put("email", email);
connection.setResponseBody(new Body(result));
return new Status(Status.OK);
} catch (Exception e) {
Map<String, Object> result = new HashMap<String, Object>();
result.put("error", "error registering persona assertion: " + e.getLocalizedMessage());
connection.setResponseBody(new Body(result));
return new Status(Status.BAD_REQUEST);
}
}
public Status do_POST_Document_bulk_docs(Database _db, String _docID, String _attachmentName) {
Map<String,Object> bodyDict = getBodyAsDictionary();
if(bodyDict == null) {
return new Status(Status.BAD_REQUEST);
}
List<Map<String,Object>> docs = (List<Map<String, Object>>) bodyDict.get("docs");
boolean noNewEdits = getBooleanValueFromBody("new_edits", bodyDict, true) == false;
boolean allOrNothing = getBooleanValueFromBody("all_or_nothing", bodyDict, false);
boolean ok = false;
db.beginTransaction();
List<Map<String,Object>> results = new ArrayList<Map<String,Object>>();
try {
for (Map<String, Object> doc : docs) {
String docID = (String) doc.get("_id");
RevisionInternal rev = null;
Status status = new Status(Status.OK);
Body docBody = new Body(doc);
if (noNewEdits) {
rev = new RevisionInternal(docBody, db);
if(rev.getRevId() == null || rev.getDocId() == null || !rev.getDocId().equals(docID)) {
status = new Status(Status.BAD_REQUEST);
} else {
List<String> history = Database.parseCouchDBRevisionHistory(doc);
db.forceInsert(rev, history, null);
}
} else {
Status outStatus = new Status();
rev = update(db, docID, docBody, false, allOrNothing, outStatus);
status.setCode(outStatus.getCode());
}
Map<String, Object> result = null;
if(status.isSuccessful()) {
result = new HashMap<String, Object>();
result.put("ok", true);
result.put("id", docID);
if (rev != null) {
result.put("rev", rev.getRevId());
}
} else if(allOrNothing) {
return status; // all_or_nothing backs out if there's any error
} else if(status.getCode() == Status.FORBIDDEN) {
result = new HashMap<String, Object>();
result.put("error", "validation failed");
result.put("id", docID);
} else if(status.getCode() == Status.CONFLICT) {
result = new HashMap<String, Object>();
result.put("error", "conflict");
result.put("id", docID);
} else {
return status; // abort the whole thing if something goes badly wrong
}
if(result != null) {
results.add(result);
}
}
Log.w(Database.TAG, String.format("%s finished inserting %d revisions in bulk", this, docs.size()));
ok = true;
} catch (Exception e) {
Log.e(Database.TAG, String.format("%s: Exception inserting revisions in bulk", this), e);
} finally {
db.endTransaction(ok);
}
Log.d(Database.TAG, "results: " + results.toString());
connection.setResponseBody(new Body(results));
return new Status(Status.CREATED);
}
public Status do_POST_Document_revs_diff(Database _db, String _docID, String _attachmentName) {
// Collect all of the input doc/revision IDs as TDRevisions:
RevisionList revs = new RevisionList();
Map<String, Object> body = getBodyAsDictionary();
if(body == null) {
return new Status(Status.BAD_JSON);
}
for (String docID : body.keySet()) {
List<String> revIDs = (List<String>)body.get(docID);
for (String revID : revIDs) {
RevisionInternal rev = new RevisionInternal(docID, revID, false, db);
revs.add(rev);
}
}
// Look them up, removing the existing ones from revs:
if(!db.findMissingRevisions(revs)) {
return new Status(Status.DB_ERROR);
}
// Return the missing revs in a somewhat different format:
Map<String, Object> diffs = new HashMap<String, Object>();
for (RevisionInternal rev : revs) {
String docID = rev.getDocId();
List<String> missingRevs = null;
Map<String, Object> idObj = (Map<String, Object>)diffs.get(docID);
if(idObj != null) {
missingRevs = (List<String>)idObj.get("missing");
} else {
idObj = new HashMap<String, Object>();
}
if(missingRevs == null) {
missingRevs = new ArrayList<String>();
idObj.put("missing", missingRevs);
diffs.put(docID, idObj);
}
missingRevs.add(rev.getRevId());
}
// FIXME add support for possible_ancestors
connection.setResponseBody(new Body(diffs));
return new Status(Status.OK);
}
public Status do_POST_Document_compact(Database _db, String _docID, String _attachmentName) {
Status status = new Status(Status.OK);
try {
_db.compact();
} catch (CouchbaseLiteException e) {
status = e.getCBLStatus();
}
if (status.getCode() < 300) {
Status outStatus = new Status();
outStatus.setCode(202); // CouchDB returns 202 'cause it's an async operation
return outStatus;
} else {
return status;
}
}
public Status do_POST_Document_purge(Database _db, String ignored1, String ignored2) {
Map<String,Object> body = getBodyAsDictionary();
if(body == null) {
return new Status(Status.BAD_REQUEST);
}
// convert from Map<String,Object> -> Map<String, List<String>> - is there a cleaner way?
final Map<String, List<String>> docsToRevs = new HashMap<String, List<String>>();
for (String key : body.keySet()) {
Object val = body.get(key);
if (val instanceof List) {
docsToRevs.put(key, (List<String>)val);
}
}
final List<Map<String, Object>> asyncApiCallResponse = new ArrayList<Map<String, Object>>();
// this is run in an async db task to fix the following race condition
// found in issue
// replicator thread: call db.loadRevisionBody for doc1
// liteserv thread: call db.purge on doc1
// replicator thread: call db.getRevisionHistory for doc1, which returns empty history since it was purged
Future future = db.runAsync(new AsyncTask() {
@Override
public void run(Database database) {
Map<String, Object> purgedRevisions = db.purgeRevisions(docsToRevs);
asyncApiCallResponse.add(purgedRevisions);
}
});
try {
future.get(60, TimeUnit.SECONDS);
} catch (InterruptedException e) {
Log.e(Database.TAG, "Exception waiting for future", e);
return new Status(Status.INTERNAL_SERVER_ERROR);
} catch (ExecutionException e) {
Log.e(Database.TAG, "Exception waiting for future", e);
return new Status(Status.INTERNAL_SERVER_ERROR);
} catch (TimeoutException e) {
Log.e(Database.TAG, "Exception waiting for future", e);
return new Status(Status.INTERNAL_SERVER_ERROR);
}
Map<String, Object> purgedRevisions = asyncApiCallResponse.get(0);
Map<String, Object> responseMap = new HashMap<String, Object>();
responseMap.put("purged", purgedRevisions);
Body responseBody = new Body(responseMap);
connection.setResponseBody(responseBody);
return new Status(Status.OK);
}
public Status do_POST_Document_ensure_full_commit(Database _db, String _docID, String _attachmentName) {
return new Status(Status.OK);
}
/** CHANGES: **/
public Map<String,Object> changesDictForRevision(RevisionInternal rev) {
Map<String,Object> changesDict = new HashMap<String, Object>();
changesDict.put("rev", rev.getRevId());
List<Map<String,Object>> changes = new ArrayList<Map<String,Object>>();
changes.add(changesDict);
Map<String,Object> result = new HashMap<String,Object>();
result.put("seq", rev.getSequence());
result.put("id", rev.getDocId());
result.put("changes", changes);
if(rev.isDeleted()) {
result.put("deleted", true);
}
if(changesIncludesDocs) {
result.put("doc", rev.getProperties());
}
return result;
}
public Map<String,Object> responseBodyForChanges(List<RevisionInternal> changes, long since) {
List<Map<String,Object>> results = new ArrayList<Map<String,Object>>();
for (RevisionInternal rev : changes) {
Map<String,Object> changeDict = changesDictForRevision(rev);
results.add(changeDict);
}
if(changes.size() > 0) {
since = changes.get(changes.size() - 1).getSequence();
}
Map<String,Object> result = new HashMap<String,Object>();
result.put("results", results);
result.put("last_seq", since);
return result;
}
public Map<String, Object> responseBodyForChangesWithConflicts(List<RevisionInternal> changes, long since) {
// Assumes the changes are grouped by docID so that conflicts will be adjacent.
List<Map<String,Object>> entries = new ArrayList<Map<String, Object>>();
String lastDocID = null;
Map<String, Object> lastEntry = null;
for (RevisionInternal rev : changes) {
String docID = rev.getDocId();
if(docID.equals(lastDocID)) {
Map<String,Object> changesDict = new HashMap<String, Object>();
changesDict.put("rev", rev.getRevId());
List<Map<String,Object>> inchanges = (List<Map<String,Object>>)lastEntry.get("changes");
inchanges.add(changesDict);
} else {
lastEntry = changesDictForRevision(rev);
entries.add(lastEntry);
lastDocID = docID;
}
}
// After collecting revisions, sort by sequence:
Collections.sort(entries, new Comparator<Map<String,Object>>() {
public int compare(Map<String,Object> e1, Map<String,Object> e2) {
return Misc.TDSequenceCompare((Long) e1.get("seq"), (Long) e2.get("seq"));
}
});
Long lastSeq = (Long)entries.get(entries.size() - 1).get("seq");
if(lastSeq == null) {
lastSeq = since;
}
Map<String,Object> result = new HashMap<String,Object>();
result.put("results", entries);
result.put("last_seq", lastSeq);
return result;
}
public void sendContinuousChange(RevisionInternal rev) {
Map<String,Object> changeDict = changesDictForRevision(rev);
try {
String jsonString = Manager.getObjectMapper().writeValueAsString(changeDict);
if(callbackBlock != null) {
byte[] json = (jsonString + "\n").getBytes();
OutputStream os = connection.getResponseOutputStream();
try {
os.write(json);
os.flush();
} catch (Exception e) {
Log.e(Database.TAG, "IOException writing to internal streams", e);
}
}
} catch (Exception e) {
Log.w("Unable to serialize change to JSON", e);
}
}
@Override
public void changed(Database.ChangeEvent event) {
List<DocumentChange> changes = event.getChanges();
for (DocumentChange change : changes) {
RevisionInternal rev = change.getAddedRevision();
Map<String, Object> paramsFixMe = null; // TODO: these should not be null
final boolean allowRevision = event.getSource().runFilter(changesFilter, paramsFixMe, rev);
if (!allowRevision) {
return;
}
if(longpoll) {
Log.w(Database.TAG, "Router: Sending longpoll response");
sendResponse();
List<RevisionInternal> revs = new ArrayList<RevisionInternal>();
revs.add(rev);
Map<String,Object> body = responseBodyForChanges(revs, 0);
if(callbackBlock != null) {
byte[] data = null;
try {
data = Manager.getObjectMapper().writeValueAsBytes(body);
} catch (Exception e) {
Log.w(Database.TAG, "Error serializing JSON", e);
}
OutputStream os = connection.getResponseOutputStream();
try {
os.write(data);
os.close();
} catch (IOException e) {
Log.e(Database.TAG, "IOException writing to internal streams", e);
}
}
} else {
Log.w(Database.TAG, "Router: Sending continous change chunk");
sendContinuousChange(rev);
}
}
}
public Status do_GET_Document_changes(Database _db, String docID, String _attachmentName) {
// http://wiki.apache.org/couchdb/HTTP_database_API#Changes
ChangesOptions options = new ChangesOptions();
changesIncludesDocs = getBooleanQuery("include_docs");
options.setIncludeDocs(changesIncludesDocs);
String style = getQuery("style");
if(style != null && style.equals("all_docs")) {
options.setIncludeConflicts(true);
}
options.setContentOptions(getContentOptions());
options.setSortBySequence(!options.isIncludeConflicts());
options.setLimit(getIntQuery("limit", options.getLimit()));
int since = getIntQuery("since", 0);
String filterName = getQuery("filter");
if(filterName != null) {
changesFilter = db.getFilter(filterName);
if(changesFilter == null) {
return new Status(Status.NOT_FOUND);
}
}
RevisionList changes = db.changesSince(since, options, changesFilter);
if(changes == null) {
return new Status(Status.INTERNAL_SERVER_ERROR);
}
String feed = getQuery("feed");
longpoll = "longpoll".equals(feed);
boolean continuous = !longpoll && "continuous".equals(feed);
if(continuous || (longpoll && changes.size() == 0)) {
connection.setChunked(true);
connection.setResponseCode(Status.OK);
sendResponse();
if(continuous) {
for (RevisionInternal rev : changes) {
sendContinuousChange(rev);
}
}
db.addChangeListener(this);
// Don't close connection; more data to come
return new Status(0);
} else {
if(options.isIncludeConflicts()) {
connection.setResponseBody(new Body(responseBodyForChangesWithConflicts(changes, since)));
} else {
connection.setResponseBody(new Body(responseBodyForChanges(changes, since)));
}
return new Status(Status.OK);
}
}
/** DOCUMENT REQUESTS: **/
public String getRevIDFromIfMatchHeader() {
String ifMatch = connection.getRequestProperty("If-Match");
if(ifMatch == null) {
return null;
}
// Value of If-Match is an ETag, so have to trim the quotes around it:
if(ifMatch.length() > 2 && ifMatch.startsWith("\"") && ifMatch.endsWith("\"")) {
return ifMatch.substring(1,ifMatch.length() - 2);
} else {
return null;
}
}
public String setResponseEtag(RevisionInternal rev) {
String eTag = String.format("\"%s\"", rev.getRevId());
connection.getResHeader().add("Etag", eTag);
return eTag;
}
public Status do_GET_Document(Database _db, String docID, String _attachmentName) {
try {
// http://wiki.apache.org/couchdb/HTTP_Document_API#GET
boolean isLocalDoc = docID.startsWith("_local");
EnumSet<TDContentOptions> options = getContentOptions();
String openRevsParam = getQuery("open_revs");
if(openRevsParam == null || isLocalDoc) {
// Regular GET:
String revID = getQuery("rev"); // often null
RevisionInternal rev = null;
if(isLocalDoc) {
rev = db.getLocalDocument(docID, revID);
} else {
rev = db.getDocumentWithIDAndRev(docID, revID, options);
// Handle ?atts_since query by stubbing out older attachments:
//?atts_since parameter - value is a (URL-encoded) JSON array of one or more revision IDs.
// The response will include the content of only those attachments that changed since the given revision(s).
//(You can ask for this either in the default JSON or as multipart/related, as previously described.)
List<String> attsSince = (List<String>)getJSONQuery("atts_since");
if (attsSince != null) {
String ancestorId = db.findCommonAncestorOf(rev, attsSince);
if (ancestorId != null) {
int generation = RevisionInternal.generationFromRevID(ancestorId);
db.stubOutAttachmentsIn(rev, generation + 1);
}
}
}
if(rev == null) {
return new Status(Status.NOT_FOUND);
}
if(cacheWithEtag(rev.getRevId())) {
return new Status(Status.NOT_MODIFIED); // set ETag and check conditional GET
}
connection.setResponseBody(rev.getBody());
} else {
List<Map<String,Object>> result = null;
if(openRevsParam.equals("all")) {
// Get all conflicting revisions:
RevisionList allRevs = db.getAllRevisionsOfDocumentID(docID, true);
result = new ArrayList<Map<String,Object>>(allRevs.size());
for (RevisionInternal rev : allRevs) {
try {
db.loadRevisionBody(rev, options);
} catch (CouchbaseLiteException e) {
if (e.getCBLStatus().getCode() != Status.INTERNAL_SERVER_ERROR) {
Map<String, Object> dict = new HashMap<String,Object>();
dict.put("missing", rev.getRevId());
result.add(dict);
}
else {
throw e;
}
}
Map<String, Object> dict = new HashMap<String,Object>();
dict.put("ok", rev.getProperties());
result.add(dict);
}
} else {
// ?open_revs=[...] returns an array of revisions of the document:
List<String> openRevs = (List<String>)getJSONQuery("open_revs");
if(openRevs == null) {
return new Status(Status.BAD_REQUEST);
}
result = new ArrayList<Map<String,Object>>(openRevs.size());
for (String revID : openRevs) {
RevisionInternal rev = db.getDocumentWithIDAndRev(docID, revID, options);
if(rev != null) {
Map<String, Object> dict = new HashMap<String,Object>();
dict.put("ok", rev.getProperties());
result.add(dict);
} else {
Map<String, Object> dict = new HashMap<String,Object>();
dict.put("missing", revID);
result.add(dict);
}
}
}
String acceptMultipart = getMultipartRequestType();
if(acceptMultipart != null) {
//FIXME figure out support for multipart
throw new UnsupportedOperationException();
} else {
connection.setResponseBody(new Body(result));
}
}
return new Status(Status.OK);
} catch (CouchbaseLiteException e) {
return e.getCBLStatus();
}
}
public Status do_GET_Attachment(Database _db, String docID, String _attachmentName) {
try {
// http://wiki.apache.org/couchdb/HTTP_Document_API#GET
EnumSet<TDContentOptions> options = getContentOptions();
options.add(TDContentOptions.TDNoBody);
String revID = getQuery("rev"); // often null
RevisionInternal rev = db.getDocumentWithIDAndRev(docID, revID, options);
if(rev == null) {
return new Status(Status.NOT_FOUND);
}
if(cacheWithEtag(rev.getRevId())) {
return new Status(Status.NOT_MODIFIED); // set ETag and check conditional GET
}
String type = null;
String acceptEncoding = connection.getRequestProperty("accept-encoding");
Attachment contents = db.getAttachmentForSequence(rev.getSequence(), _attachmentName);
if (contents == null) {
return new Status(Status.NOT_FOUND);
}
type = contents.getContentType();
if (type != null) {
connection.getResHeader().add("Content-Type", type);
}
if (acceptEncoding != null && acceptEncoding.contains("gzip") && contents.getGZipped()) {
connection.getResHeader().add("Content-Encoding", "gzip");
}
connection.setResponseInputStream(contents.getContent());
return new Status(Status.OK);
} catch (CouchbaseLiteException e) {
return e.getCBLStatus();
}
}
/**
* NOTE this departs from the iOS version, returning revision, passing status back by reference
*/
public RevisionInternal update(Database _db, String docID, Body body, boolean deleting, boolean allowConflict, Status outStatus) {
boolean isLocalDoc = docID != null && docID.startsWith(("_local"));
String prevRevID = null;
if(!deleting) {
Boolean deletingBoolean = (Boolean)body.getPropertyForKey("_deleted");
deleting = (deletingBoolean != null && deletingBoolean.booleanValue());
if(docID == null) {
if(isLocalDoc) {
outStatus.setCode(Status.METHOD_NOT_ALLOWED);
return null;
}
// POST's doc ID may come from the _id field of the JSON body, else generate a random one.
docID = (String)body.getPropertyForKey("_id");
if(docID == null) {
if(deleting) {
outStatus.setCode(Status.BAD_REQUEST);
return null;
}
docID = Database.generateDocumentId();
}
}
// PUT's revision ID comes from the JSON body.
prevRevID = (String)body.getPropertyForKey("_rev");
} else {
// DELETE's revision ID comes from the ?rev= query param
prevRevID = getQuery("rev");
}
// A backup source of revision ID is an If-Match header:
if(prevRevID == null) {
prevRevID = getRevIDFromIfMatchHeader();
}
RevisionInternal rev = new RevisionInternal(docID, null, deleting, db);
rev.setBody(body);
RevisionInternal result = null;
try {
if(isLocalDoc) {
result = _db.putLocalRevision(rev, prevRevID);
} else {
result = _db.putRevision(rev, prevRevID, allowConflict);
}
if(deleting){
outStatus.setCode(Status.OK);
} else{
outStatus.setCode(Status.CREATED);
}
} catch (CouchbaseLiteException e) {
e.printStackTrace();
Log.e(Database.TAG, e.toString());
outStatus.setCode(e.getCBLStatus().getCode());
}
return result;
}
public Status update(Database _db, String docID, Map<String,Object> bodyDict, boolean deleting) {
Body body = new Body(bodyDict);
Status status = new Status();
if (docID != null && docID.isEmpty() == false) {
// On PUT/DELETE, get revision ID from either ?rev= query or doc body:
String revParam = getQuery("rev");
if (revParam != null && bodyDict != null && bodyDict.size() > 0) {
String revProp = (String) bodyDict.get("_rev");
if (revProp == null) {
// No _rev property in body, so use ?rev= query param instead:
bodyDict.put("_rev", revParam);
body = new Body(bodyDict);
} else if (!revParam.equals(revProp)) {
throw new IllegalArgumentException("Mismatch between _rev and rev");
}
}
}
RevisionInternal rev = update(_db, docID, body, deleting, false, status);
if(status.isSuccessful()) {
cacheWithEtag(rev.getRevId()); // set ETag
if(!deleting) {
URL url = connection.getURL();
String urlString = url.toExternalForm();
if(docID != null) {
urlString += "/" + rev.getDocId();
try {
url = new URL(urlString);
} catch (MalformedURLException e) {
Log.w("Malformed URL", e);
}
}
setResponseLocation(url);
}
Map<String, Object> result = new HashMap<String, Object>();
result.put("ok", true);
result.put("id", rev.getDocId());
result.put("rev", rev.getRevId());
connection.setResponseBody(new Body(result));
}
return status;
}
public Status do_PUT_Document(Database _db, String docID, String _attachmentName) throws CouchbaseLiteException {
Status status = new Status(Status.CREATED);
Map<String,Object> bodyDict = getBodyAsDictionary();
if(bodyDict == null) {
throw new CouchbaseLiteException(Status.BAD_REQUEST);
}
if(getQuery("new_edits") == null || (getQuery("new_edits") != null && (new Boolean(getQuery("new_edits"))))) {
// Regular PUT
status = update(_db, docID, bodyDict, false);
} else {
// PUT with new_edits=false -- forcible insertion of existing revision:
Body body = new Body(bodyDict);
RevisionInternal rev = new RevisionInternal(body, _db);
if(rev.getRevId() == null || rev.getDocId() == null || !rev.getDocId().equals(docID)) {
throw new CouchbaseLiteException(Status.BAD_REQUEST);
}
List<String> history = Database.parseCouchDBRevisionHistory(body.getProperties());
db.forceInsert(rev, history, null);
}
return status;
}
public Status do_DELETE_Document(Database _db, String docID, String _attachmentName) {
return update(_db, docID, null, true);
}
public Status updateAttachment(String attachment, String docID, InputStream contentStream) throws CouchbaseLiteException {
Status status = new Status(Status.OK);
String revID = getQuery("rev");
if(revID == null) {
revID = getRevIDFromIfMatchHeader();
}
RevisionInternal rev = db.updateAttachment(attachment, contentStream, connection.getRequestProperty("content-type"),
docID, revID);
Map<String, Object> resultDict = new HashMap<String, Object>();
resultDict.put("ok", true);
resultDict.put("id", rev.getDocId());
resultDict.put("rev", rev.getRevId());
connection.setResponseBody(new Body(resultDict));
cacheWithEtag(rev.getRevId());
if(contentStream != null) {
setResponseLocation(connection.getURL());
}
return status;
}
public Status do_PUT_Attachment(Database _db, String docID, String _attachmentName) throws CouchbaseLiteException {
return updateAttachment(_attachmentName, docID, connection.getRequestInputStream());
}
public Status do_DELETE_Attachment(Database _db, String docID, String _attachmentName) throws CouchbaseLiteException {
return updateAttachment(_attachmentName, docID, null);
}
/** VIEW QUERIES: **/
public View compileView(String viewName, Map<String,Object> viewProps) {
String language = (String)viewProps.get("language");
if(language == null) {
language = "javascript";
}
String mapSource = (String)viewProps.get("map");
if(mapSource == null) {
return null;
}
Mapper mapBlock = View.getCompiler().compileMap(mapSource, language);
if(mapBlock == null) {
Log.w(Database.TAG, String.format("View %s has unknown map function: %s", viewName, mapSource));
return null;
}
String reduceSource = (String)viewProps.get("reduce");
Reducer reduceBlock = null;
if(reduceSource != null) {
reduceBlock = View.getCompiler().compileReduce(reduceSource, language);
if(reduceBlock == null) {
Log.w(Database.TAG, String.format("View %s has unknown reduce function: %s", viewName, reduceBlock));
return null;
}
}
View view = db.getView(viewName);
view.setMapReduce(mapBlock, reduceBlock, "1");
String collation = (String)viewProps.get("collation");
if("raw".equals(collation)) {
view.setCollation(TDViewCollation.TDViewCollationRaw);
}
return view;
}
public Status queryDesignDoc(String designDoc, String viewName, List<Object> keys) throws CouchbaseLiteException {
String tdViewName = String.format("%s/%s", designDoc, viewName);
View view = db.getExistingView(tdViewName);
if(view == null || view.getMap() == null) {
// No TouchDB view is defined, or it hasn't had a map block assigned;
// see if there's a CouchDB view definition we can compile:
RevisionInternal rev = db.getDocumentWithIDAndRev(String.format("_design/%s", designDoc), null, EnumSet.noneOf(TDContentOptions.class));
if(rev == null) {
return new Status(Status.NOT_FOUND);
}
Map<String,Object> views = (Map<String,Object>)rev.getProperties().get("views");
Map<String,Object> viewProps = (Map<String,Object>)views.get(viewName);
if(viewProps == null) {
return new Status(Status.NOT_FOUND);
}
// If there is a CouchDB view, see if it can be compiled from source:
view = compileView(tdViewName, viewProps);
if(view == null) {
return new Status(Status.INTERNAL_SERVER_ERROR);
}
}
QueryOptions options = new QueryOptions();
//if the view contains a reduce block, it should default to reduce=true
if(view.getReduce() != null) {
options.setReduce(true);
}
if(!getQueryOptions(options)) {
return new Status(Status.BAD_REQUEST);
}
if(keys != null) {
options.setKeys(keys);
}
view.updateIndex();
long lastSequenceIndexed = view.getLastSequenceIndexed();
// Check for conditional GET and set response Etag header:
if(keys == null) {
long eTag = options.isIncludeDocs() ? db.getLastSequenceNumber() : lastSequenceIndexed;
if(cacheWithEtag(String.format("%d", eTag))) {
return new Status(Status.NOT_MODIFIED);
}
}
// convert from QueryRow -> Map
List<QueryRow> queryRows = view.queryWithOptions(options);
List<Map<String,Object>> rows = new ArrayList<Map<String,Object>>();
for (QueryRow queryRow : queryRows) {
rows.add(queryRow.asJSONDictionary());
}
Map<String,Object> responseBody = new HashMap<String,Object>();
responseBody.put("rows", rows);
responseBody.put("total_rows", rows.size());
responseBody.put("offset", options.getSkip());
if(options.isUpdateSeq()) {
responseBody.put("update_seq", lastSequenceIndexed);
}
connection.setResponseBody(new Body(responseBody));
return new Status(Status.OK);
}
public Status do_GET_DesignDocument(Database _db, String designDocID, String viewName) throws CouchbaseLiteException {
return queryDesignDoc(designDocID, viewName, null);
}
public Status do_POST_DesignDocument(Database _db, String designDocID, String viewName) throws CouchbaseLiteException {
Map<String,Object> bodyDict = getBodyAsDictionary();
if(bodyDict == null) {
return new Status(Status.BAD_REQUEST);
}
List<Object> keys = (List<Object>) bodyDict.get("keys");
return queryDesignDoc(designDocID, viewName, keys);
}
@Override
public String toString() {
String url = "Unknown";
if(connection != null && connection.getURL() != null) {
url = connection.getURL().toExternalForm();
}
return String.format("Router [%s]", url);
}
} |
package com.ctrip.zeus.task;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.IOException;
public abstract class AbstractTask implements Task {
@Resource
private TaskManager taskManager2;
@PostConstruct
private void init() {
start();
taskManager2.add(this);
}
public abstract void start();
@Override
public String getName() {
return getClass().getSimpleName();
}
@Override
public long getInterval() {
return 60000;
}
public abstract void run() throws Exception;
@Override
public void shutDown() {
stop();
taskManager2.remove(this);
taskManager2 = null;
}
public abstract void stop();
} |
package com.ee.apiary.sql.core;
import com.ee.apiary.sql.hibernate.entities.DirectManager;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.SortedMap;
import java.util.TreeMap;
public class MainClass {
private static final int LEVEL_ONE = 1;
private static final int LEVEL_TWO = 2;
private static final int LEVEL_THREE = 3;
private static final int LEVEL_FOUR = 4;
private static final int LEVEL_FIVE = 5;
private static final int LEVEL_SIX = 6;
private static final int LEVEL_SEVEN = 7;
private static final int LEVEL_EIGHT = 8;
private static final int LEVEL_NINE = 9;
private static final int LEVEL_TEN = 10;
private static final int LEVEL_ELEVEN = 11;
private static final int LEVEL_TWELVE = 12;
private static final int LEVEL_THIRTEEN = 13;
private static final int LEVEL_FOURTEEN = 14;
private static final int LEVEL_FIFTEEN = 15;
private static final int LEVEL_SIXTEEN = 16;
private static final int LEVEL_SEVENTEEN = 17;
private static final int LEVEL_EIGHTEEN = 18;
private static final int LEVEL_NINETEEN = 19;
private static final int LEVEL_TWENTY = 20;
private static final int DIRECTLY_MANAGES_LIMIT_LEVEL_ONE = 5;
private static final int DIRECTLY_MANAGES_LIMIT_LEVEL_TWO = 5;
private static final int DIRECTLY_MANAGES_LIMIT_LEVEL_THREE = 5;
private static final int DIRECTLY_MANAGES_LIMIT_LEVEL_FOUR = 5;
private static final int DIRECTLY_MANAGES_LIMIT_LEVEL_FIVE = 5;
private static final int DIRECTLY_MANAGES_LIMIT_LEVEL_SIX = 5;
private static final int DIRECTLY_MANAGES_LIMIT_LEVEL_SEVEN = 5;
private static final int DIRECTLY_MANAGES_LIMIT_LEVEL_EIGHT = 5;
private static final int DIRECTLY_MANAGES_LIMIT_LEVEL_NINE = 5;
private static final int DIRECTLY_MANAGES_LIMIT_LEVEL_TEN = 5;
private static final int DIRECTLY_MANAGES_LIMIT_LEVEL_ELEVEN = 5;
private static final int DIRECTLY_MANAGES_LIMIT_LEVEL_TWELVE = 5;
private static final int DIRECTLY_MANAGES_LIMIT_LEVEL_THIRTEEN = 5;
private static final int DIRECTLY_MANAGES_LIMIT_LEVEL_FOURTEEN = 5;
private static final int DIRECTLY_MANAGES_LIMIT_LEVEL_FIFTEEN = 5;
private static final int DIRECTLY_MANAGES_LIMIT_LEVEL_SIXTEEN = 10;
private static final int DIRECTLY_MANAGES_LIMIT_LEVEL_SEVENTEEN = 10;
private static final int DIRECTLY_MANAGES_LIMIT_LEVEL_EIGHTEEN = 10;
private static final int DIRECTLY_MANAGES_LIMIT_LEVEL_NINETEEN = 10;
private static final int DIRECTLY_MANAGES_LIMIT_LEVEL_TWENTY = 10;
public static void main(String[] args) {
SortedMap<Integer, OrgLevelData> orgDataAtLevel = null;
try {
orgDataAtLevel = compileOrgDataFromResources();
System.out.println("Organisation data compiled");
} catch (IOException e) {
System.err.println(" IO Exception : " + e.getMessage());
throw new RuntimeException(e.getMessage());
}
SqlOrgHierarchy sqlOrgHierarchy = new SqlOrgHierarchy.Builder(orgDataAtLevel).build();
//sqlOrgHierarchy.checkForInConsistentData();
System.out.println("Started creating person objects....");
long tStartPerson = System.currentTimeMillis();
SortedMap<Integer, OrgLevelData> levelWithPeople = sqlOrgHierarchy.toLevelWithPersonObjs(orgDataAtLevel);
long tEndPerson = System.currentTimeMillis();
System.out.println("Created person objects. Time taken : " + (tEndPerson - tStartPerson)/1000 + " sec/s");
System.out.println("Started creating direct managers....");
long tStartDirectManager = System.currentTimeMillis();
List<DirectManager> directManagers = sqlOrgHierarchy.createDirectManagerRelationships(levelWithPeople);
long tEndDirectManager = System.currentTimeMillis();
System.out.println("Created direct managers. Time taken : " + (tEndDirectManager - tStartDirectManager)/1000 + " sec/s");
System.out.println("Started saving data....");
long tStartSave = System.currentTimeMillis();
SqlOrgHierarchyDAO.saveOrgData(levelWithPeople, directManagers);
long tEndSave = System.currentTimeMillis();
System.out.println("Organisation data saved in DB. Time taken : " + (tEndSave - tStartSave)/1000 + " sec/s");
}
private static SortedMap<Integer, OrgLevelData> compileOrgDataFromResources() throws IOException {
// InputStream firstNamesStream = MainClass.class.getResourceAsStream("/firstNames.txt");
// InputStream lastNamesStream = MainClass.class.getResourceAsStream("/lastNames.txt");
// BufferedReader firstNameReader = new BufferedReader(new InputStreamReader(firstNamesStream));
// BufferedReader lastNameReader = new BufferedReader(new InputStreamReader(lastNamesStream));
List<String> firstNames = new ArrayList<>();
List<String> lastNames = new ArrayList<>();
List<String> fullNames = new ArrayList<>();
SortedMap<Integer, OrgLevelData> peopleAtLevel = new TreeMap<>();
// String name = null;
// while ((name = firstNameReader.readLine()) != null) {
// firstNames.add(name);
// while ((name = lastNameReader.readLine()) != null) {
// lastNames.add(name);
// for (String firstName : firstNames) {
// for (String lastName : lastNames) {
// fullNames.add(firstName + " " + lastName);
for(int i = 1; i<=1500; i++){
firstNames.add("first"+i);
}
for(int i = 1; i<=1500; i++){
lastNames.add("last"+i);
}
for (String first : firstNames) {
for (String last : lastNames) {
fullNames.add(first + " " + last);
}
}
firstNames.clear();
lastNames.clear();
System.out.println("Person name list created with size : " + fullNames.size());
/* Case 1 : (Levels = 3, Manages Limit = 5)
*
* At Level 1 => 1
At Level 2 => 1
At Level 3 => 1
At Level 4 => 1
At Level 5 => 1
At Level 6 => 1
At Level 7 => 1
At Level 8 => 1
At Level 9 => 1
At Level 10 => 1
At Level 11 => 1
At Level 12 => 1
At Level 13 => 28
At Level 14 => 160
At Level 15 => 800
Total => 1000
*
*
*
*
*
*
At Level 1 => 1
At Level 2 => 1
At Level 3 => 1
At Level 4 => 1
At Level 5 => 1
At Level 6 => 1
At Level 7 => 1
At Level 8 => 1
At Level 9 => 1
At Level 10 => 1
At Level 11 => 30
At Level 12 => 80
At Level 13 => 280
At Level 14 => 1600
At Level 15 => 8000
Total => 10000
*/
// peopleAtLevel.put(LEVEL_ONE, new OrgLevelData(fullNames.subList(0, 1), DIRECTLY_MANAGES_LIMIT_LEVEL_ONE));
// peopleAtLevel.put(LEVEL_TWO, new OrgLevelData(fullNames.subList(1, 2), DIRECTLY_MANAGES_LIMIT_LEVEL_TWO));
// peopleAtLevel.put(LEVEL_THREE, new OrgLevelData(fullNames.subList(2, 3), DIRECTLY_MANAGES_LIMIT_LEVEL_THREE));
// peopleAtLevel.put(LEVEL_FOUR, new OrgLevelData(fullNames.subList(3, 4), DIRECTLY_MANAGES_LIMIT_LEVEL_FOUR));
// peopleAtLevel.put(LEVEL_FIVE, new OrgLevelData(fullNames.subList(4, 5), DIRECTLY_MANAGES_LIMIT_LEVEL_FIVE));
// peopleAtLevel.put(LEVEL_SIX, new OrgLevelData(fullNames.subList(5, 6),DIRECTLY_MANAGES_LIMIT_LEVEL_SIX));
// peopleAtLevel.put(LEVEL_SEVEN, new OrgLevelData(fullNames.subList(6, 7),DIRECTLY_MANAGES_LIMIT_LEVEL_SEVEN));
// peopleAtLevel.put(LEVEL_EIGHT, new OrgLevelData(fullNames.subList(7, 8),DIRECTLY_MANAGES_LIMIT_LEVEL_EIGHT));
// peopleAtLevel.put(LEVEL_NINE, new OrgLevelData(fullNames.subList(8, 9),DIRECTLY_MANAGES_LIMIT_LEVEL_NINE));
// peopleAtLevel.put(LEVEL_TEN, new OrgLevelData(fullNames.subList(9, 10),DIRECTLY_MANAGES_LIMIT_LEVEL_TEN));
// peopleAtLevel.put(LEVEL_ELEVEN, new OrgLevelData(fullNames.subList(10, 40),DIRECTLY_MANAGES_LIMIT_LEVEL_ELEVEN));
// peopleAtLevel.put(LEVEL_TWELVE, new OrgLevelData(fullNames.subList(40, 120),DIRECTLY_MANAGES_LIMIT_LEVEL_TWELVE));
// peopleAtLevel.put(LEVEL_THIRTEEN, new OrgLevelData(fullNames.subList(120, 400),DIRECTLY_MANAGES_LIMIT_LEVEL_THIRTEEN));
// peopleAtLevel.put(LEVEL_FOURTEEN, new OrgLevelData(fullNames.subList(400, 2000),DIRECTLY_MANAGES_LIMIT_LEVEL_FOURTEEN));
// peopleAtLevel.put(LEVEL_FIFTEEN, new OrgLevelData(fullNames.subList(2000, 10000),DIRECTLY_MANAGES_LIMIT_LEVEL_FIFTEEN));
/* Case 1 : /*
* Case 1 : (Levels = 3, Manages Limit = 100)
* At Level 1 => 100
* At Level 2 => 10000
* At Level 3 => 989900
* Total => 1000000
*
peopleAtLevel.put(LEVEL_ONE, new OrgLevelData(fullNames.subList(0, 100), 100));
peopleAtLevel.put(LEVEL_TWO, new OrgLevelData(fullNames.subList(100, 10100), 100));
peopleAtLevel.put(LEVEL_THREE, new OrgLevelData(fullNames.subList(10100, 1000000), 100));
*/
/* Case 1 : (Levels = 3, Manages Limit = 5)
At Level 1 => 4000
At Level 2 => 16000
At Level 3 => 80000
Total => 100000
peopleAtLevel.put(LEVEL_ONE, new OrgLevelData(fullNames.subList(0, 4000), DIRECTLY_MANAGES_LIMIT_LEVEL_ONE));
peopleAtLevel.put(LEVEL_TWO, new OrgLevelData(fullNames.subList(4000, 20000), DIRECTLY_MANAGES_LIMIT_LEVEL_TWO));
peopleAtLevel.put(LEVEL_THREE, new OrgLevelData(fullNames.subList(20000, 100000), DIRECTLY_MANAGES_LIMIT_LEVEL_THREE));
*/
/* Case 1 : (Levels = 3, Manages Limit = 5)
At Level 1 => 400
At Level 2 => 1600
At Level 3 => 8000
Total => 10000
peopleAtLevel.put(LEVEL_ONE, new OrgLevelData(fullNames.subList(0, 400), DIRECTLY_MANAGES_LIMIT_LEVEL_ONE));
peopleAtLevel.put(LEVEL_TWO, new OrgLevelData(fullNames.subList(400, 2000), DIRECTLY_MANAGES_LIMIT_LEVEL_TWO));
peopleAtLevel.put(LEVEL_THREE, new OrgLevelData(fullNames.subList(2000, 10000), DIRECTLY_MANAGES_LIMIT_LEVEL_THREE));
*/
/* Case 1 : (Levels = 3, Manages Limit = 5)
At Level 1 => 40
At Level 2 => 160
At Level 3 => 800
Total => 1000
peopleAtLevel.put(LEVEL_ONE, new OrgLevelData(fullNames.subList(0, 40), DIRECTLY_MANAGES_LIMIT_LEVEL_ONE));
peopleAtLevel.put(LEVEL_TWO, new OrgLevelData(fullNames.subList(40, 200), DIRECTLY_MANAGES_LIMIT_LEVEL_TWO));
peopleAtLevel.put(LEVEL_THREE, new OrgLevelData(fullNames.subList(200, 1000), DIRECTLY_MANAGES_LIMIT_LEVEL_THREE));
*/
/**
* case 1:
* total people in organisation = 2000000, with Levels = 3, withPersonManagingMaxOf = 1000, directlyReportingToMax = 1
* At Level 1 => 10
* At Level 2 => 10000
* At Level 3 => 1989990
* Total => 2000000
peopleAtLevel.put(LEVEL_ONE, new OrgLevelData(fullNames.subList(0, 10), 1000));
peopleAtLevel.put(LEVEL_TWO, new OrgLevelData(fullNames.subList(10, 10010), 1000));
peopleAtLevel.put(LEVEL_THREE, new OrgLevelData(fullNames.subList(10010, 2000000), 1000));
*/
/**
* Case 1 : (Levels = 3, Manages Limit = 1000)
* At Level 1 => 10
* At Level 2 => 10000
* At Level 3 => 989990
* Total => 1000000
*
peopleAtLevel.put(LEVEL_ONE, new OrgLevelData(fullNames.subList(0, 10), 1000));
peopleAtLevel.put(LEVEL_TWO, new OrgLevelData(fullNames.subList(10, 10010), 1000));
peopleAtLevel.put(LEVEL_THREE, new OrgLevelData(fullNames.subList(10010, 1000000), 1000));
*/
/* Case 2 : (Levels = 4, Manages Limit = 5)
val builder = OrganizationBuilder(names, withPersonManagingMaxOf = 5)
.withPeopleAtLevel(1, 10)
.withPeopleAtLevel(2, 43)
.withPeopleAtLevel(3, 200)
.withPeopleAtLevel(4, 747)
.distribute(Contiguous)
peopleAtLevel.put(LEVEL_ONE, new OrgLevelData(fullNames.subList(0, 10), DIRECTLY_MANAGES_LIMIT_LEVEL_ONE));
peopleAtLevel.put(LEVEL_TWO, new OrgLevelData(fullNames.subList(10, 53), DIRECTLY_MANAGES_LIMIT_LEVEL_TWO));
peopleAtLevel.put(LEVEL_THREE, new OrgLevelData(fullNames.subList(53, 253), DIRECTLY_MANAGES_LIMIT_LEVEL_THREE));
peopleAtLevel.put(LEVEL_FOUR, new OrgLevelData(fullNames.subList(253, 1000),DIRECTLY_MANAGES_LIMIT_LEVEL_FOUR));
*/
/* Case 2 : (Levels = 4, Manages Limit = 5)
At Level 1 => 1000
At Level 2 => 5000
At Level 3 => 20000
At Level 4 => 74000
Total => 100000
peopleAtLevel.put(LEVEL_ONE, new OrgLevelData(fullNames.subList(0, 1000), DIRECTLY_MANAGES_LIMIT_LEVEL_ONE));
peopleAtLevel.put(LEVEL_TWO, new OrgLevelData(fullNames.subList(1000, 6000), DIRECTLY_MANAGES_LIMIT_LEVEL_TWO));
peopleAtLevel.put(LEVEL_THREE, new OrgLevelData(fullNames.subList(6000, 26000), DIRECTLY_MANAGES_LIMIT_LEVEL_THREE));
peopleAtLevel.put(LEVEL_FOUR, new OrgLevelData(fullNames.subList(26000, 100000),DIRECTLY_MANAGES_LIMIT_LEVEL_FOUR));
*/
/*
* case 2:
* total people in organisation = 10000 with levels = 4, withPersonManagingMaxOf = 5, directlyReportingToMax = 1
* At Level 1 => 100
* At Level 2 => 500
* At Level 3 => 2000
* At Level 4 => 7400
* Total => 10000
peopleAtLevel.put(LEVEL_ONE, new OrgLevelData(fullNames.subList(0, 100), DIRECTLY_MANAGES_LIMIT_LEVEL_ONE));
peopleAtLevel.put(LEVEL_TWO, new OrgLevelData(fullNames.subList(100, 600), DIRECTLY_MANAGES_LIMIT_LEVEL_TWO));
peopleAtLevel.put(LEVEL_THREE, new OrgLevelData(fullNames.subList(600, 2600), DIRECTLY_MANAGES_LIMIT_LEVEL_THREE));
peopleAtLevel.put(LEVEL_FOUR, new OrgLevelData(fullNames.subList(2600, 10000),DIRECTLY_MANAGES_LIMIT_LEVEL_FOUR));
*/
/*
* Case 2 : (Levels = 4, Manages Limit = 50)
* At Level 1 => 8
* At Level 2 => 400
* At Level 3 => 20000
* At Level 4 => 979592
* Total => 1000000
*
peopleAtLevel.put(LEVEL_ONE, new OrgLevelData(fullNames.subList(0, 8), 50));
peopleAtLevel.put(LEVEL_TWO, new OrgLevelData(fullNames.subList(8, 408), 50));
peopleAtLevel.put(LEVEL_THREE, new OrgLevelData(fullNames.subList(408, 20408), 50));
peopleAtLevel.put(LEVEL_FOUR, new OrgLevelData(fullNames.subList(20408, 1000000),50));
*/
/**
* Case 2 : (Levels = 4, Manages Limit = 500)
* At Level 1 => 5
* At Level 2 => 25
* At Level 3 => 4000
* At Level 4 => 995970
* Total => 1000000
**
*/
peopleAtLevel.put(LEVEL_ONE, new OrgLevelData(fullNames.subList(0, 5), 500));
peopleAtLevel.put(LEVEL_TWO, new OrgLevelData(fullNames.subList(5, 30), 500));
peopleAtLevel.put(LEVEL_THREE, new OrgLevelData(fullNames.subList(30, 4030), 500));
peopleAtLevel.put(LEVEL_FOUR, new OrgLevelData(fullNames.subList(4030, 1000000),500));
/**
* case 2:
* total people in organisation = 2000000 with levels = 4, withPersonManagingMaxOf = 500, directlyReportingToMax = 1
* At Level 1 => 5
* At Level 2 => 25
* At Level 3 => 4000
* At Level 4 => 1995970
* Total => 2000000
peopleAtLevel.put(LEVEL_ONE, new OrgLevelData(fullNames.subList(0, 5), 500));
peopleAtLevel.put(LEVEL_TWO, new OrgLevelData(fullNames.subList(5, 30), 500));
peopleAtLevel.put(LEVEL_THREE, new OrgLevelData(fullNames.subList(30, 4030), 500));
peopleAtLevel.put(LEVEL_FOUR, new OrgLevelData(fullNames.subList(4030, 2000000),500));
*/
/* Case 3 : (Levels = 5, Manages Limit = 5)
At Level 1 => 3
At Level 2 => 15
At Level 3 => 75
At Level 4 => 300
At Level 5 => 607
Total => 1000
peopleAtLevel.put(LEVEL_ONE, new OrgLevelData(fullNames.subList(0, 3), DIRECTLY_MANAGES_LIMIT_LEVEL_ONE));
peopleAtLevel.put(LEVEL_TWO, new OrgLevelData(fullNames.subList(3, 18), DIRECTLY_MANAGES_LIMIT_LEVEL_TWO));
peopleAtLevel.put(LEVEL_THREE, new OrgLevelData(fullNames.subList(18, 93), DIRECTLY_MANAGES_LIMIT_LEVEL_THREE));
peopleAtLevel.put(LEVEL_FOUR, new OrgLevelData(fullNames.subList(93, 393),DIRECTLY_MANAGES_LIMIT_LEVEL_FOUR));
peopleAtLevel.put(LEVEL_FIVE, new OrgLevelData(fullNames.subList(393, 1000),DIRECTLY_MANAGES_LIMIT_LEVEL_FIVE));
*/
/* Case 3 : (Levels = 5, Manages Limit = 5)
At Level 1 => 300
At Level 2 => 1500
At Level 3 => 7500
At Level 4 => 30000
At Level 5 => 60700
Total => 100000
peopleAtLevel.put(LEVEL_ONE, new OrgLevelData(fullNames.subList(0, 300), DIRECTLY_MANAGES_LIMIT_LEVEL_ONE));
peopleAtLevel.put(LEVEL_TWO, new OrgLevelData(fullNames.subList(300, 1800), DIRECTLY_MANAGES_LIMIT_LEVEL_TWO));
peopleAtLevel.put(LEVEL_THREE, new OrgLevelData(fullNames.subList(1800, 9300), DIRECTLY_MANAGES_LIMIT_LEVEL_THREE));
peopleAtLevel.put(LEVEL_FOUR, new OrgLevelData(fullNames.subList(9300, 39300),DIRECTLY_MANAGES_LIMIT_LEVEL_FOUR));
peopleAtLevel.put(LEVEL_FIVE, new OrgLevelData(fullNames.subList(39300, 100000),DIRECTLY_MANAGES_LIMIT_LEVEL_FIVE));
*/
/*
* case 3:
* total people in organisation = 10000 with levels = 5, withPersonManagingMaxOf = 5, directlyReportingToMax = 1
*
* At Level 1 => 30
* At Level 2 => 150
* At Level 3 => 750
* At Level 4 => 3000
* At Level 5 => 6070
* Total => 10000
peopleAtLevel.put(LEVEL_ONE, new OrgLevelData(fullNames.subList(0, 30), DIRECTLY_MANAGES_LIMIT_LEVEL_ONE));
peopleAtLevel.put(LEVEL_TWO, new OrgLevelData(fullNames.subList(30, 180), DIRECTLY_MANAGES_LIMIT_LEVEL_TWO));
peopleAtLevel.put(LEVEL_THREE, new OrgLevelData(fullNames.subList(180, 930), DIRECTLY_MANAGES_LIMIT_LEVEL_THREE));
peopleAtLevel.put(LEVEL_FOUR, new OrgLevelData(fullNames.subList(930, 3930),DIRECTLY_MANAGES_LIMIT_LEVEL_FOUR));
peopleAtLevel.put(LEVEL_FIVE, new OrgLevelData(fullNames.subList(3930, 10000),DIRECTLY_MANAGES_LIMIT_LEVEL_FIVE));
*/
/*
* Case 3 : (Levels = 5, Manages Limit = 25)
* At Level 1 => 5
* At Level 2 => 125
* At Level 3 => 3125
* At Level 4 => 78125
* At Level 5 => 918620
* Total => 1000000
*
peopleAtLevel.put(LEVEL_ONE, new OrgLevelData(fullNames.subList(0, 5), 25));
peopleAtLevel.put(LEVEL_TWO, new OrgLevelData(fullNames.subList(5, 130), 25));
peopleAtLevel.put(LEVEL_THREE, new OrgLevelData(fullNames.subList(130, 3255), 25));
peopleAtLevel.put(LEVEL_FOUR, new OrgLevelData(fullNames.subList(3255, 81380),25));
peopleAtLevel.put(LEVEL_FIVE, new OrgLevelData(fullNames.subList(81380, 1000000),25));
*/
/**
* case 3:
* total people in organisation = 2000000 with levels = 5, withPersonManagingMaxOf = 500, directlyReportingToMax = 1
*
* At Level 1 => 3
* At Level 2 => 15
* At Level 3 => 400
* At Level 4 => 4000
* At Level 5 => 1995582
* Total => 2000000
peopleAtLevel.put(LEVEL_ONE, new OrgLevelData(fullNames.subList(0, 3), 500));
peopleAtLevel.put(LEVEL_TWO, new OrgLevelData(fullNames.subList(3, 18), 500));
peopleAtLevel.put(LEVEL_THREE, new OrgLevelData(fullNames.subList(18, 418), 500));
peopleAtLevel.put(LEVEL_FOUR, new OrgLevelData(fullNames.subList(418, 4418),500));
peopleAtLevel.put(LEVEL_FIVE, new OrgLevelData(fullNames.subList(4418, 2000000),500));
*/
/*
* case 4:
* total people in organisation = 100000 with levels = 6, withPersonManagingMaxOf = 10, directlyReportingToMax = 1
*
* At Level 1 => 2
* At Level 2 => 20
* At Level 3 => 100
* At Level 4 => 1000
* At Level 5 => 10000
* At Level 6 => 88878
* Total => 100000
peopleAtLevel.put(LEVEL_ONE, new OrgLevelData(fullNames.subList(0, 2), 10));
peopleAtLevel.put(LEVEL_TWO, new OrgLevelData(fullNames.subList(2, 22), 10));
peopleAtLevel.put(LEVEL_THREE, new OrgLevelData(fullNames.subList(22, 122), 10));
peopleAtLevel.put(LEVEL_FOUR, new OrgLevelData(fullNames.subList(122, 1122),10));
peopleAtLevel.put(LEVEL_FIVE, new OrgLevelData(fullNames.subList(1122, 11122),10));
peopleAtLevel.put(LEVEL_SIX, new OrgLevelData(fullNames.subList(11122, 100000),10));
*/
/*
* case 4:
* total people in organisation = 1000 with levels = 6, withPersonManagingMaxOf = 19, directlyReportingToMax = 1
*
* At Level 1 => 1
* At Level 2 => 5
* At Level 3 => 94
* At Level 4 => 200
* At Level 5 => 300
* At Level 6 => 400
* Total => 1000
peopleAtLevel.put(LEVEL_ONE, new OrgLevelData(fullNames.subList(0, 1), 19));
peopleAtLevel.put(LEVEL_TWO, new OrgLevelData(fullNames.subList(1, 6), 19));
peopleAtLevel.put(LEVEL_THREE, new OrgLevelData(fullNames.subList(6, 100), 19));
peopleAtLevel.put(LEVEL_FOUR, new OrgLevelData(fullNames.subList(100, 300),19));
peopleAtLevel.put(LEVEL_FIVE, new OrgLevelData(fullNames.subList(300, 600),19));
peopleAtLevel.put(LEVEL_SIX, new OrgLevelData(fullNames.subList(600, 1000),19));
*/
/* * case 4:
* total people in organisation = 10000 with levels = 6, withPersonManagingMaxOf = 5, directlyReportingToMax = 1
*
* At Level 1 => 30
* At Level 2 => 100
* At Level 3 => 500
* At Level 4 => 1000
* At Level 5 => 3000
* At Level 6 => 5370
* Total => 10000
peopleAtLevel.put(LEVEL_ONE, new OrgLevelData(fullNames.subList(0, 30), DIRECTLY_MANAGES_LIMIT_LEVEL_ONE));
peopleAtLevel.put(LEVEL_TWO, new OrgLevelData(fullNames.subList(30, 130), DIRECTLY_MANAGES_LIMIT_LEVEL_TWO));
peopleAtLevel.put(LEVEL_THREE, new OrgLevelData(fullNames.subList(130, 630), DIRECTLY_MANAGES_LIMIT_LEVEL_THREE));
peopleAtLevel.put(LEVEL_FOUR, new OrgLevelData(fullNames.subList(630, 1630),DIRECTLY_MANAGES_LIMIT_LEVEL_FOUR));
peopleAtLevel.put(LEVEL_FIVE, new OrgLevelData(fullNames.subList(1630, 4630),DIRECTLY_MANAGES_LIMIT_LEVEL_FIVE));
peopleAtLevel.put(LEVEL_SIX, new OrgLevelData(fullNames.subList(4630, 10000),DIRECTLY_MANAGES_LIMIT_LEVEL_SIX));
*/
/* Case 4 : (Levels = 6, Manages Limit = 5)
At Level 1 => 300
At Level 2 => 1000
At Level 3 => 5000
At Level 4 => 10000
At Level 5 => 30000
At Level 6 => 53700
Total => 100000
peopleAtLevel.put(LEVEL_ONE, new OrgLevelData(fullNames.subList(0, 300), DIRECTLY_MANAGES_LIMIT_LEVEL_ONE));
peopleAtLevel.put(LEVEL_TWO, new OrgLevelData(fullNames.subList(300, 1300), DIRECTLY_MANAGES_LIMIT_LEVEL_TWO));
peopleAtLevel.put(LEVEL_THREE, new OrgLevelData(fullNames.subList(1300, 6300), DIRECTLY_MANAGES_LIMIT_LEVEL_THREE));
peopleAtLevel.put(LEVEL_FOUR, new OrgLevelData(fullNames.subList(6300, 16300),DIRECTLY_MANAGES_LIMIT_LEVEL_FOUR));
peopleAtLevel.put(LEVEL_FIVE, new OrgLevelData(fullNames.subList(16300, 46300),DIRECTLY_MANAGES_LIMIT_LEVEL_FIVE));
peopleAtLevel.put(LEVEL_SIX, new OrgLevelData(fullNames.subList(46300, 100000),DIRECTLY_MANAGES_LIMIT_LEVEL_SIX));
*/
/*
* At Level 1 => 1
* At Level 2 => 5
* At Level 3 => 94
* At Level 4 => 200
* At Level 5 => 300
* At Level 6 => 400
* Total => 1000
peopleAtLevel.put(LEVEL_ONE, new OrgLevelData(fullNames.subList(0, 1), DIRECTLY_MANAGES_LIMIT_LEVEL_ONE));
peopleAtLevel.put(LEVEL_TWO, new OrgLevelData(fullNames.subList(1, 6), DIRECTLY_MANAGES_LIMIT_LEVEL_TWO));
peopleAtLevel.put(LEVEL_THREE, new OrgLevelData(fullNames.subList(6, 100), DIRECTLY_MANAGES_LIMIT_LEVEL_THREE));
peopleAtLevel.put(LEVEL_FOUR, new OrgLevelData(fullNames.subList(100, 300),DIRECTLY_MANAGES_LIMIT_LEVEL_FOUR));
peopleAtLevel.put(LEVEL_FIVE, new OrgLevelData(fullNames.subList(300, 600),DIRECTLY_MANAGES_LIMIT_LEVEL_FIVE));
peopleAtLevel.put(LEVEL_SIX, new OrgLevelData(fullNames.subList(600, 1000),DIRECTLY_MANAGES_LIMIT_LEVEL_SIX));
* At Level 1 => 10
* At Level 2 => 100
* At Level 3 => 1000
* At Level 4 => 10000
* At Level 5 => 100000
* At Level 6 => 1000000
* Total => 1111110
peopleAtLevel.put(LEVEL_ONE, new OrgLevelData(fullNames.subList(0, 10), DIRECTLY_MANAGES_LIMIT_LEVEL_ONE));
peopleAtLevel.put(LEVEL_TWO, new OrgLevelData(fullNames.subList(10, 110), DIRECTLY_MANAGES_LIMIT_LEVEL_TWO));
peopleAtLevel.put(LEVEL_THREE, new OrgLevelData(fullNames.subList(110, 1110), DIRECTLY_MANAGES_LIMIT_LEVEL_THREE));
peopleAtLevel.put(LEVEL_FOUR, new OrgLevelData(fullNames.subList(1110, 11110),DIRECTLY_MANAGES_LIMIT_LEVEL_FOUR));
peopleAtLevel.put(LEVEL_FIVE, new OrgLevelData(fullNames.subList(11110, 111110),DIRECTLY_MANAGES_LIMIT_LEVEL_FIVE));
peopleAtLevel.put(LEVEL_SIX, new OrgLevelData(fullNames.subList(111110, 1111110),DIRECTLY_MANAGES_LIMIT_LEVEL_SIX));
*/
/*
* Case 4 : (Levels = 6, Manages Limit = 10)
* At Level 1 => 10
* At Level 2 => 95
* At Level 3 => 950
* At Level 4 => 9500
* At Level 5 => 95000
* At Level 6 => 894445
* Total => 1000000
*
peopleAtLevel.put(LEVEL_ONE, new OrgLevelData(fullNames.subList(0, 10), 10));
peopleAtLevel.put(LEVEL_TWO, new OrgLevelData(fullNames.subList(10, 105), 10));
peopleAtLevel.put(LEVEL_THREE, new OrgLevelData(fullNames.subList(105, 1055), 10));
peopleAtLevel.put(LEVEL_FOUR, new OrgLevelData(fullNames.subList(1055, 10555),10));
peopleAtLevel.put(LEVEL_FIVE, new OrgLevelData(fullNames.subList(10555, 105555),10));
peopleAtLevel.put(LEVEL_SIX, new OrgLevelData(fullNames.subList(105555, 1000000),10));
*/
/**
* case 4:
* total people in organisation = 2000000 with levels = 6, withPersonManagingMaxOf = 500, directlyReportingToMax = 1
*
* At Level 1 => 3
* At Level 2 => 10
* At Level 3 => 50
* At Level 4 => 400
* At Level 5 => 20000
* At Level 6 => 1979537
* Total => 2000000
peopleAtLevel.put(LEVEL_ONE, new OrgLevelData(fullNames.subList(0, 3), 500));
peopleAtLevel.put(LEVEL_TWO, new OrgLevelData(fullNames.subList(3, 13), 500));
peopleAtLevel.put(LEVEL_THREE, new OrgLevelData(fullNames.subList(13, 63), 500));
peopleAtLevel.put(LEVEL_FOUR, new OrgLevelData(fullNames.subList(63, 463),500));
peopleAtLevel.put(LEVEL_FIVE, new OrgLevelData(fullNames.subList(463, 20463),500));
peopleAtLevel.put(LEVEL_SIX, new OrgLevelData(fullNames.subList(20463, 2000000),500));
*/
/*
* case 5:
* total people in organisation = 100000 with levels = 7, withPersonManagingMaxOf = 5, directlyReportingToMax = 1
*
* At Level 1 => 6
* At Level 2 => 29
* At Level 3 => 143
* At Level 4 => 711
* At Level 5 => 3555
* At Level 6 => 17775
* At Level 7 => 77781
* Total => 100000
peopleAtLevel.put(LEVEL_ONE, new OrgLevelData(fullNames.subList(0, 6), DIRECTLY_MANAGES_LIMIT_LEVEL_ONE));
peopleAtLevel.put(LEVEL_TWO, new OrgLevelData(fullNames.subList(6, 35), DIRECTLY_MANAGES_LIMIT_LEVEL_TWO));
peopleAtLevel.put(LEVEL_THREE, new OrgLevelData(fullNames.subList(35, 178), DIRECTLY_MANAGES_LIMIT_LEVEL_THREE));
peopleAtLevel.put(LEVEL_FOUR, new OrgLevelData(fullNames.subList(178, 889),DIRECTLY_MANAGES_LIMIT_LEVEL_FOUR));
peopleAtLevel.put(LEVEL_FIVE, new OrgLevelData(fullNames.subList(889, 4444),DIRECTLY_MANAGES_LIMIT_LEVEL_FIVE));
peopleAtLevel.put(LEVEL_SIX, new OrgLevelData(fullNames.subList(4444, 22219),DIRECTLY_MANAGES_LIMIT_LEVEL_SIX));
peopleAtLevel.put(LEVEL_SEVEN, new OrgLevelData(fullNames.subList(22219, 100000),DIRECTLY_MANAGES_LIMIT_LEVEL_SEVEN));
*/
/*
* case 5:
* total people in organisation = 10000 with levels = 7, withPersonManagingMaxOf = 5, directlyReportingToMax = 1
*
* At Level 1 => 20
* At Level 2 => 50
* At Level 3 => 200
* At Level 4 => 700
* At Level 5 => 1400
* At Level 6 => 2800
* At Level 7 => 4830
* Total => 10000
peopleAtLevel.put(LEVEL_ONE, new OrgLevelData(fullNames.subList(0, 20), DIRECTLY_MANAGES_LIMIT_LEVEL_ONE));
peopleAtLevel.put(LEVEL_TWO, new OrgLevelData(fullNames.subList(20, 70), DIRECTLY_MANAGES_LIMIT_LEVEL_TWO));
peopleAtLevel.put(LEVEL_THREE, new OrgLevelData(fullNames.subList(70, 270), DIRECTLY_MANAGES_LIMIT_LEVEL_THREE));
peopleAtLevel.put(LEVEL_FOUR, new OrgLevelData(fullNames.subList(270, 970),DIRECTLY_MANAGES_LIMIT_LEVEL_FOUR));
peopleAtLevel.put(LEVEL_FIVE, new OrgLevelData(fullNames.subList(970, 2370),DIRECTLY_MANAGES_LIMIT_LEVEL_FIVE));
peopleAtLevel.put(LEVEL_SIX, new OrgLevelData(fullNames.subList(2370, 5170),DIRECTLY_MANAGES_LIMIT_LEVEL_SIX));
peopleAtLevel.put(LEVEL_SEVEN, new OrgLevelData(fullNames.subList(5170, 10000),DIRECTLY_MANAGES_LIMIT_LEVEL_SEVEN));
*/
/*
* Case 5 : (Levels = 7, Manages Limit = 5)
* At Level 1 => 2
* At Level 2 => 5
* At Level 3 => 20
* At Level 4 => 70
* At Level 5 => 140
* At Level 6 => 280
* At Level 7 => 483
*
peopleAtLevel.put(LEVEL_ONE, new OrgLevelData(fullNames.subList(0, 2), DIRECTLY_MANAGES_LIMIT_LEVEL_ONE));
peopleAtLevel.put(LEVEL_TWO, new OrgLevelData(fullNames.subList(2, 7), DIRECTLY_MANAGES_LIMIT_LEVEL_TWO));
peopleAtLevel.put(LEVEL_THREE, new OrgLevelData(fullNames.subList(7, 27), DIRECTLY_MANAGES_LIMIT_LEVEL_THREE));
peopleAtLevel.put(LEVEL_FOUR, new OrgLevelData(fullNames.subList(27, 97),DIRECTLY_MANAGES_LIMIT_LEVEL_FOUR));
peopleAtLevel.put(LEVEL_FIVE, new OrgLevelData(fullNames.subList(97, 237),DIRECTLY_MANAGES_LIMIT_LEVEL_FIVE));
peopleAtLevel.put(LEVEL_SIX, new OrgLevelData(fullNames.subList(237, 517),DIRECTLY_MANAGES_LIMIT_LEVEL_SIX));
peopleAtLevel.put(LEVEL_SEVEN, new OrgLevelData(fullNames.subList(517, 1000),DIRECTLY_MANAGES_LIMIT_LEVEL_SEVEN));
*/
/* Case 5 : (Levels = 7, Manages Limit = 5)
At Level 1 => 200
At Level 2 => 500
At Level 3 => 2000
At Level 4 => 7000
At Level 5 => 14000
At Level 6 => 28000
At Level 7 => 48300
Total => 10000
peopleAtLevel.put(LEVEL_ONE, new OrgLevelData(fullNames.subList(0, 200), DIRECTLY_MANAGES_LIMIT_LEVEL_ONE));
peopleAtLevel.put(LEVEL_TWO, new OrgLevelData(fullNames.subList(200, 700), DIRECTLY_MANAGES_LIMIT_LEVEL_TWO));
peopleAtLevel.put(LEVEL_THREE, new OrgLevelData(fullNames.subList(700, 2700), DIRECTLY_MANAGES_LIMIT_LEVEL_THREE));
peopleAtLevel.put(LEVEL_FOUR, new OrgLevelData(fullNames.subList(2700, 9700),DIRECTLY_MANAGES_LIMIT_LEVEL_FOUR));
peopleAtLevel.put(LEVEL_FIVE, new OrgLevelData(fullNames.subList(9700, 23700),DIRECTLY_MANAGES_LIMIT_LEVEL_FIVE));
peopleAtLevel.put(LEVEL_SIX, new OrgLevelData(fullNames.subList(23700, 51700),DIRECTLY_MANAGES_LIMIT_LEVEL_SIX));
peopleAtLevel.put(LEVEL_SEVEN, new OrgLevelData(fullNames.subList(51700, 100000),DIRECTLY_MANAGES_LIMIT_LEVEL_SEVEN));
*/
/*
* At Level 1 => 1
* At Level 2 => 5
* At Level 3 => 50
* At Level 4 => 94
* At Level 5 => 150
* At Level 6 => 250
* At Level 7 => 450
* Total => 1000
peopleAtLevel.put(LEVEL_ONE, new OrgLevelData(fullNames.subList(0, 1), DIRECTLY_MANAGES_LIMIT_LEVEL_ONE));
peopleAtLevel.put(LEVEL_TWO, new OrgLevelData(fullNames.subList(1, 6), DIRECTLY_MANAGES_LIMIT_LEVEL_TWO));
peopleAtLevel.put(LEVEL_THREE, new OrgLevelData(fullNames.subList(6, 56), DIRECTLY_MANAGES_LIMIT_LEVEL_THREE));
peopleAtLevel.put(LEVEL_FOUR, new OrgLevelData(fullNames.subList(56, 150),DIRECTLY_MANAGES_LIMIT_LEVEL_FOUR));
peopleAtLevel.put(LEVEL_FIVE, new OrgLevelData(fullNames.subList(150, 300),DIRECTLY_MANAGES_LIMIT_LEVEL_FIVE));
peopleAtLevel.put(LEVEL_SIX, new OrgLevelData(fullNames.subList(300, 550),DIRECTLY_MANAGES_LIMIT_LEVEL_SIX));
peopleAtLevel.put(LEVEL_SEVEN, new OrgLevelData(fullNames.subList(550, 1000),DIRECTLY_MANAGES_LIMIT_LEVEL_SEVEN));
* At Level 1 => 1
* At Level 2 => 10
* At Level 3 => 100
* At Level 4 => 1000
* At Level 5 => 10000
* At Level 6 => 100000
* At Level 7 => 1000000
* Total => 1111111
peopleAtLevel.put(LEVEL_ONE, new OrgLevelData(fullNames.subList(0, 1), DIRECTLY_MANAGES_LIMIT_LEVEL_ONE));
peopleAtLevel.put(LEVEL_TWO, new OrgLevelData(fullNames.subList(1, 11), DIRECTLY_MANAGES_LIMIT_LEVEL_TWO));
peopleAtLevel.put(LEVEL_THREE, new OrgLevelData(fullNames.subList(11, 111), DIRECTLY_MANAGES_LIMIT_LEVEL_THREE));
peopleAtLevel.put(LEVEL_FOUR, new OrgLevelData(fullNames.subList(111, 1111),DIRECTLY_MANAGES_LIMIT_LEVEL_FOUR));
peopleAtLevel.put(LEVEL_FIVE, new OrgLevelData(fullNames.subList(1111, 11111),DIRECTLY_MANAGES_LIMIT_LEVEL_FIVE));
peopleAtLevel.put(LEVEL_SIX, new OrgLevelData(fullNames.subList(11111, 111111),DIRECTLY_MANAGES_LIMIT_LEVEL_SIX));
peopleAtLevel.put(LEVEL_SEVEN, new OrgLevelData(fullNames.subList(111111, 1111111),DIRECTLY_MANAGES_LIMIT_LEVEL_SEVEN));
*/
/* val builder = OrganizationBuilder(names, withPersonManagingMaxOf = 8)
.withPeopleAtLevel(1, 5)
.withPeopleAtLevel(2, 40)
.withPeopleAtLevel(3, 320)
.withPeopleAtLevel(4, 2560)
.withPeopleAtLevel(5, 20480)
.withPeopleAtLevel(6, 163840)
.withPeopleAtLevel(7, 812755)
.distribute(Contiguous)
peopleAtLevel.put(LEVEL_ONE, new OrgLevelData(fullNames.subList(0, 5), 8));
peopleAtLevel.put(LEVEL_TWO, new OrgLevelData(fullNames.subList(5, 45), 8));
peopleAtLevel.put(LEVEL_THREE, new OrgLevelData(fullNames.subList(45, 365), 8));
peopleAtLevel.put(LEVEL_FOUR, new OrgLevelData(fullNames.subList(365, 2925),8));
peopleAtLevel.put(LEVEL_FIVE, new OrgLevelData(fullNames.subList(2925, 23405),8));
peopleAtLevel.put(LEVEL_SIX, new OrgLevelData(fullNames.subList(23405, 187245),8));
peopleAtLevel.put(LEVEL_SEVEN, new OrgLevelData(fullNames.subList(187245, 1000000),8));
*/
/**
* case 5:
* total people in organisation = 2000000 with levels = 7, withPersonManagingMaxOf = 100, directlyReportingToMax = 1
*
* At Level 1 => 2
* At Level 2 => 50
* At Level 3 => 200
* At Level 4 => 1000
* At Level 5 => 10000
* At Level 6 => 100000
* At Level 7 => 1888748
* Total => 2000000
peopleAtLevel.put(LEVEL_ONE, new OrgLevelData(fullNames.subList(0, 2), 100));
peopleAtLevel.put(LEVEL_TWO, new OrgLevelData(fullNames.subList(2, 52), 100));
peopleAtLevel.put(LEVEL_THREE, new OrgLevelData(fullNames.subList(52, 252), 100));
peopleAtLevel.put(LEVEL_FOUR, new OrgLevelData(fullNames.subList(252, 1252),100));
peopleAtLevel.put(LEVEL_FIVE, new OrgLevelData(fullNames.subList(1252, 11252),100));
peopleAtLevel.put(LEVEL_SIX, new OrgLevelData(fullNames.subList(11252, 111252),100));
peopleAtLevel.put(LEVEL_SEVEN, new OrgLevelData(fullNames.subList(111252, 2000000),100));
*/
/*val builder = OrganizationBuilder(names, withPersonManagingMaxOf = 4)
.withPeopleAtLevel(1, 5)
.withPeopleAtLevel(2, 19)
.withPeopleAtLevel(3, 76)
.withPeopleAtLevel(4, 303)
.withPeopleAtLevel(5, 1212)
.withPeopleAtLevel(6, 4848)
.withPeopleAtLevel(7, 19392)
.withPeopleAtLevel(8, 74145)
peopleAtLevel.put(LEVEL_ONE, new OrgLevelData(fullNames.subList(0, 5), 4));
peopleAtLevel.put(LEVEL_TWO, new OrgLevelData(fullNames.subList(5, 24), 4));
peopleAtLevel.put(LEVEL_THREE, new OrgLevelData(fullNames.subList(24, 100), 4));
peopleAtLevel.put(LEVEL_FOUR, new OrgLevelData(fullNames.subList(100, 403),4));
peopleAtLevel.put(LEVEL_FIVE, new OrgLevelData(fullNames.subList(403, 1615),4));
peopleAtLevel.put(LEVEL_SIX, new OrgLevelData(fullNames.subList(1615, 6463),4));
peopleAtLevel.put(LEVEL_SEVEN, new OrgLevelData(fullNames.subList(6463, 25855),4));
peopleAtLevel.put(LEVEL_EIGHT, new OrgLevelData(fullNames.subList(25855, 100000),4));
*/
/*
* Case 6 : (Levels = 8, Manages Limit = 4)
* At Level 1 => 1
* At Level 2 => 3
* At Level 3 => 7
* At Level 4 => 12
* At Level 5 => 25
* At Level 6 => 52
* At Level 7 => 200
* At Level 8 => 700
*
peopleAtLevel.put(LEVEL_ONE, new OrgLevelData(fullNames.subList(0, 1), 4));
peopleAtLevel.put(LEVEL_TWO, new OrgLevelData(fullNames.subList(1, 4), 4));
peopleAtLevel.put(LEVEL_THREE, new OrgLevelData(fullNames.subList(4, 11), 4));
peopleAtLevel.put(LEVEL_FOUR, new OrgLevelData(fullNames.subList(11, 23),4));
peopleAtLevel.put(LEVEL_FIVE, new OrgLevelData(fullNames.subList(23, 48),4));
peopleAtLevel.put(LEVEL_SIX, new OrgLevelData(fullNames.subList(48, 100),4));
peopleAtLevel.put(LEVEL_SEVEN, new OrgLevelData(fullNames.subList(100, 300),4));
peopleAtLevel.put(LEVEL_EIGHT, new OrgLevelData(fullNames.subList(300, 1000),4));
*/
/* Case 6 : (Levels = 8, Manages Limit = 5)
At Level 1 => 4
At Level 2 => 20
At Level 3 => 80
At Level 4 => 250
At Level 5 => 700
At Level 6 => 1400
At Level 7 => 2500
At Level 8 => 5046
Total => 10000
peopleAtLevel.put(LEVEL_ONE, new OrgLevelData(fullNames.subList(0, 4), DIRECTLY_MANAGES_LIMIT_LEVEL_ONE));
peopleAtLevel.put(LEVEL_TWO, new OrgLevelData(fullNames.subList(4, 24), DIRECTLY_MANAGES_LIMIT_LEVEL_TWO));
peopleAtLevel.put(LEVEL_THREE, new OrgLevelData(fullNames.subList(24, 104), DIRECTLY_MANAGES_LIMIT_LEVEL_THREE));
peopleAtLevel.put(LEVEL_FOUR, new OrgLevelData(fullNames.subList(104, 354),DIRECTLY_MANAGES_LIMIT_LEVEL_FOUR));
peopleAtLevel.put(LEVEL_FIVE, new OrgLevelData(fullNames.subList(354, 1054),DIRECTLY_MANAGES_LIMIT_LEVEL_FIVE));
peopleAtLevel.put(LEVEL_SIX, new OrgLevelData(fullNames.subList(1054, 2454),DIRECTLY_MANAGES_LIMIT_LEVEL_SIX));
peopleAtLevel.put(LEVEL_SEVEN, new OrgLevelData(fullNames.subList(2454, 4954),DIRECTLY_MANAGES_LIMIT_LEVEL_SEVEN));
peopleAtLevel.put(LEVEL_EIGHT, new OrgLevelData(fullNames.subList(4954, 10000),DIRECTLY_MANAGES_LIMIT_LEVEL_EIGHT));
*/
/*
* At Level 1 => 1
* At Level 2 => 3
* At Level 3 => 10
* At Level 4 => 40
* At Level 5 => 90
* At Level 6 => 150
* At Level 7 => 300
* At Level 8 => 406
* Total => 1000
peopleAtLevel.put(LEVEL_ONE, new OrgLevelData(fullNames.subList(0, 1), DIRECTLY_MANAGES_LIMIT_LEVEL_ONE));
peopleAtLevel.put(LEVEL_TWO, new OrgLevelData(fullNames.subList(1, 4), DIRECTLY_MANAGES_LIMIT_LEVEL_TWO));
peopleAtLevel.put(LEVEL_THREE, new OrgLevelData(fullNames.subList(4, 14), DIRECTLY_MANAGES_LIMIT_LEVEL_THREE));
peopleAtLevel.put(LEVEL_FOUR, new OrgLevelData(fullNames.subList(14, 54),DIRECTLY_MANAGES_LIMIT_LEVEL_FOUR));
peopleAtLevel.put(LEVEL_FIVE, new OrgLevelData(fullNames.subList(54, 144),DIRECTLY_MANAGES_LIMIT_LEVEL_FIVE));
peopleAtLevel.put(LEVEL_SIX, new OrgLevelData(fullNames.subList(144, 294),DIRECTLY_MANAGES_LIMIT_LEVEL_SIX));
peopleAtLevel.put(LEVEL_SEVEN, new OrgLevelData(fullNames.subList(294, 594),DIRECTLY_MANAGES_LIMIT_LEVEL_SEVEN));
peopleAtLevel.put(LEVEL_EIGHT, new OrgLevelData(fullNames.subList(594, 1000),DIRECTLY_MANAGES_LIMIT_LEVEL_EIGHT));
* At Level 1 => 1
* At Level 2 => 5
* At Level 3 => 10
* At Level 4 => 100
* At Level 5 => 1000
* At Level 6 => 10000
* At Level 7 => 100000
* At Level 8 => 1000000
* Total => 1111116
peopleAtLevel.put(LEVEL_ONE, new OrgLevelData(fullNames.subList(0, 1), DIRECTLY_MANAGES_LIMIT_LEVEL_ONE));
peopleAtLevel.put(LEVEL_TWO, new OrgLevelData(fullNames.subList(1, 6), DIRECTLY_MANAGES_LIMIT_LEVEL_TWO));
peopleAtLevel.put(LEVEL_THREE, new OrgLevelData(fullNames.subList(6, 16), DIRECTLY_MANAGES_LIMIT_LEVEL_THREE));
peopleAtLevel.put(LEVEL_FOUR, new OrgLevelData(fullNames.subList(16, 116),DIRECTLY_MANAGES_LIMIT_LEVEL_FOUR));
peopleAtLevel.put(LEVEL_FIVE, new OrgLevelData(fullNames.subList(116, 1116),DIRECTLY_MANAGES_LIMIT_LEVEL_FIVE));
peopleAtLevel.put(LEVEL_SIX, new OrgLevelData(fullNames.subList(1116, 11116),DIRECTLY_MANAGES_LIMIT_LEVEL_SIX));
peopleAtLevel.put(LEVEL_SEVEN, new OrgLevelData(fullNames.subList(11116, 111116),DIRECTLY_MANAGES_LIMIT_LEVEL_SEVEN));
peopleAtLevel.put(LEVEL_EIGHT, new OrgLevelData(fullNames.subList(111116, 1111116),DIRECTLY_MANAGES_LIMIT_LEVEL_EIGHT));
*/
/*
* Case 6 : (Levels = 8, Manages Limit = 5)
* At Level 1 => 11
* At Level 2 => 55
* At Level 3 => 275
* At Level 4 => 1375
* At Level 5 => 6875
* At Level 6 => 34375
* At Level 7 => 171875
* At Level 8 => 785159
* Total => 1000000
peopleAtLevel.put(LEVEL_ONE, new OrgLevelData(fullNames.subList(0, 11), DIRECTLY_MANAGES_LIMIT_LEVEL_ONE));
peopleAtLevel.put(LEVEL_TWO, new OrgLevelData(fullNames.subList(11, 66), DIRECTLY_MANAGES_LIMIT_LEVEL_TWO));
peopleAtLevel.put(LEVEL_THREE, new OrgLevelData(fullNames.subList(66, 341), DIRECTLY_MANAGES_LIMIT_LEVEL_THREE));
peopleAtLevel.put(LEVEL_FOUR, new OrgLevelData(fullNames.subList(341, 1716),DIRECTLY_MANAGES_LIMIT_LEVEL_FOUR));
peopleAtLevel.put(LEVEL_FIVE, new OrgLevelData(fullNames.subList(1716, 8591),DIRECTLY_MANAGES_LIMIT_LEVEL_FIVE));
peopleAtLevel.put(LEVEL_SIX, new OrgLevelData(fullNames.subList(8591, 42966),DIRECTLY_MANAGES_LIMIT_LEVEL_SIX));
peopleAtLevel.put(LEVEL_SEVEN, new OrgLevelData(fullNames.subList(42966, 214841),DIRECTLY_MANAGES_LIMIT_LEVEL_SEVEN));
peopleAtLevel.put(LEVEL_EIGHT, new OrgLevelData(fullNames.subList(214841, 1000000),DIRECTLY_MANAGES_LIMIT_LEVEL_EIGHT));
*/
/**
* case 6:
* total people in organisation = 2000000 with levels = 8, withPersonManagingMaxOf = 50, directlyReportingToMax = 1
*
* At Level 1 => 2
* At Level 2 => 20
* At Level 3 => 100
* At Level 4 => 500
* At Level 5 => 5000
* At Level 6 => 10000
* At Level 7 => 50000
* At Level 8 => 1934378
* Total => 2000000
peopleAtLevel.put(LEVEL_ONE, new OrgLevelData(fullNames.subList(0, 2), 50));
peopleAtLevel.put(LEVEL_TWO, new OrgLevelData(fullNames.subList(2, 22), 50));
peopleAtLevel.put(LEVEL_THREE, new OrgLevelData(fullNames.subList(22, 122), 50));
peopleAtLevel.put(LEVEL_FOUR, new OrgLevelData(fullNames.subList(122, 622),50));
peopleAtLevel.put(LEVEL_FIVE, new OrgLevelData(fullNames.subList(622, 5622),50));
peopleAtLevel.put(LEVEL_SIX, new OrgLevelData(fullNames.subList(5622, 15622),50));
peopleAtLevel.put(LEVEL_SEVEN, new OrgLevelData(fullNames.subList(15622, 65622),50));
peopleAtLevel.put(LEVEL_EIGHT, new OrgLevelData(fullNames.subList(65622, 2000000),50));
*/
/* val builder = OrganizationBuilder(names, withPersonManagingMaxOf = 50)
.withPeopleAtLevel(1, 2)
.withPeopleAtLevel(2, 20)
.withPeopleAtLevel(3, 100)
.withPeopleAtLevel(4, 500)
.withPeopleAtLevel(5, 5000)
.withPeopleAtLevel(6, 10000)
.withPeopleAtLevel(7, 50000)
.withPeopleAtLevel(8, 934378)
.distribute(Contiguous)
peopleAtLevel.put(LEVEL_ONE, new OrgLevelData(fullNames.subList(0, 2), 50));
peopleAtLevel.put(LEVEL_TWO, new OrgLevelData(fullNames.subList(2, 22), 50));
peopleAtLevel.put(LEVEL_THREE, new OrgLevelData(fullNames.subList(22, 122), 50));
peopleAtLevel.put(LEVEL_FOUR, new OrgLevelData(fullNames.subList(122, 622),50));
peopleAtLevel.put(LEVEL_FIVE, new OrgLevelData(fullNames.subList(622, 5622),50));
peopleAtLevel.put(LEVEL_SIX, new OrgLevelData(fullNames.subList(5622, 15622),50));
peopleAtLevel.put(LEVEL_SEVEN, new OrgLevelData(fullNames.subList(15622, 65622),50));
peopleAtLevel.put(LEVEL_EIGHT, new OrgLevelData(fullNames.subList(65622, 1000000),50));
*/
/*
Case 7 : (Levels = 9, Manages Limit = 10)
* At Level 1 => 1
* At Level 2 => 2
* At Level 3 => 5
* At Level 4 => 10
* At Level 5 => 100
* At Level 6 => 1000
* At Level 7 => 10000
* At Level 8 => 100000
* At Level 9 => 1000000
* Total => 1111118
peopleAtLevel.put(LEVEL_ONE, new OrgLevelData(fullNames.subList(0, 1), DIRECTLY_MANAGES_LIMIT_LEVEL_ONE));
peopleAtLevel.put(LEVEL_TWO, new OrgLevelData(fullNames.subList(1, 3), DIRECTLY_MANAGES_LIMIT_LEVEL_TWO));
peopleAtLevel.put(LEVEL_THREE, new OrgLevelData(fullNames.subList(3, 8), DIRECTLY_MANAGES_LIMIT_LEVEL_THREE));
peopleAtLevel.put(LEVEL_FOUR, new OrgLevelData(fullNames.subList(8, 18), DIRECTLY_MANAGES_LIMIT_LEVEL_FOUR));
peopleAtLevel.put(LEVEL_FIVE, new OrgLevelData(fullNames.subList(18, 118),DIRECTLY_MANAGES_LIMIT_LEVEL_FIVE));
peopleAtLevel.put(LEVEL_SIX, new OrgLevelData(fullNames.subList(118, 1118),DIRECTLY_MANAGES_LIMIT_LEVEL_SIX));
peopleAtLevel.put(LEVEL_SEVEN, new OrgLevelData(fullNames.subList(1118, 11118),DIRECTLY_MANAGES_LIMIT_LEVEL_SEVEN));
peopleAtLevel.put(LEVEL_EIGHT, new OrgLevelData(fullNames.subList(11118, 111118),DIRECTLY_MANAGES_LIMIT_LEVEL_EIGHT));
peopleAtLevel.put(LEVEL_NINE, new OrgLevelData(fullNames.subList(111118, 1111118),DIRECTLY_MANAGES_LIMIT_LEVEL_NINE));
*/
/*
Case 8 : (Levels = 10, Manages Limit = 10)
* At Level 1 => 1
* At Level 2 => 2
* At Level 3 => 3
* At Level 4 => 5
* At Level 5 => 10
* At Level 6 => 100
* At Level 7 => 1000
* At Level 8 => 10000
* At Level 9 => 100000
* At Level 10 => 1000000
* Total => 1111121
peopleAtLevel.put(LEVEL_ONE, new OrgLevelData(fullNames.subList(0, 1), DIRECTLY_MANAGES_LIMIT_LEVEL_ONE));
peopleAtLevel.put(LEVEL_TWO, new OrgLevelData(fullNames.subList(1, 3), DIRECTLY_MANAGES_LIMIT_LEVEL_TWO));
peopleAtLevel.put(LEVEL_THREE, new OrgLevelData(fullNames.subList(3, 6), DIRECTLY_MANAGES_LIMIT_LEVEL_THREE));
peopleAtLevel.put(LEVEL_FOUR, new OrgLevelData(fullNames.subList(6, 11), DIRECTLY_MANAGES_LIMIT_LEVEL_FOUR));
peopleAtLevel.put(LEVEL_FIVE, new OrgLevelData(fullNames.subList(11, 21), DIRECTLY_MANAGES_LIMIT_LEVEL_FIVE));
peopleAtLevel.put(LEVEL_SIX, new OrgLevelData(fullNames.subList(21, 121),DIRECTLY_MANAGES_LIMIT_LEVEL_SIX));
peopleAtLevel.put(LEVEL_SEVEN, new OrgLevelData(fullNames.subList(121, 1121),DIRECTLY_MANAGES_LIMIT_LEVEL_SEVEN));
peopleAtLevel.put(LEVEL_EIGHT, new OrgLevelData(fullNames.subList(1121, 11121),DIRECTLY_MANAGES_LIMIT_LEVEL_EIGHT));
peopleAtLevel.put(LEVEL_NINE, new OrgLevelData(fullNames.subList(11121, 111121),DIRECTLY_MANAGES_LIMIT_LEVEL_NINE));
peopleAtLevel.put(LEVEL_TEN, new OrgLevelData(fullNames.subList(111121, 1111121),DIRECTLY_MANAGES_LIMIT_LEVEL_TEN));
*/
/*
(Levels = 12, Manages Limit = 10)
* At Level 1 => 1
* At Level 2 => 1
* At Level 3 => 1
* At Level 4 => 2
* At Level 5 => 3
* At Level 6 => 5
* At Level 7 => 10
* At Level 8 => 100
* At Level 9 => 1000
* At Level 10 => 10000
* At Level 11 => 100000
* At Level 12 => 1000000
* Total => 1111123
peopleAtLevel.put(LEVEL_ONE, new OrgLevelData(fullNames.subList(0, 1), DIRECTLY_MANAGES_LIMIT_LEVEL_ONE));
peopleAtLevel.put(LEVEL_TWO, new OrgLevelData(fullNames.subList(1, 2), DIRECTLY_MANAGES_LIMIT_LEVEL_TWO));
peopleAtLevel.put(LEVEL_THREE, new OrgLevelData(fullNames.subList(2, 3), DIRECTLY_MANAGES_LIMIT_LEVEL_THREE));
peopleAtLevel.put(LEVEL_FOUR, new OrgLevelData(fullNames.subList(3, 5),DIRECTLY_MANAGES_LIMIT_LEVEL_FOUR));
peopleAtLevel.put(LEVEL_FIVE, new OrgLevelData(fullNames.subList(5, 8),DIRECTLY_MANAGES_LIMIT_LEVEL_FIVE));
peopleAtLevel.put(LEVEL_SIX, new OrgLevelData(fullNames.subList(8, 13),DIRECTLY_MANAGES_LIMIT_LEVEL_SIX));
peopleAtLevel.put(LEVEL_SEVEN, new OrgLevelData(fullNames.subList(13, 23),DIRECTLY_MANAGES_LIMIT_LEVEL_SEVEN));
peopleAtLevel.put(LEVEL_EIGHT, new OrgLevelData(fullNames.subList(23, 123),DIRECTLY_MANAGES_LIMIT_LEVEL_EIGHT));
peopleAtLevel.put(LEVEL_NINE, new OrgLevelData(fullNames.subList(123, 1123),DIRECTLY_MANAGES_LIMIT_LEVEL_NINE));
peopleAtLevel.put(LEVEL_TEN, new OrgLevelData(fullNames.subList(1123, 11123),DIRECTLY_MANAGES_LIMIT_LEVEL_TEN));
peopleAtLevel.put(LEVEL_ELEVEN, new OrgLevelData(fullNames.subList(11123, 111123),DIRECTLY_MANAGES_LIMIT_LEVEL_ELEVEN));
peopleAtLevel.put(LEVEL_TWELVE, new OrgLevelData(fullNames.subList(111123, 1111123),DIRECTLY_MANAGES_LIMIT_LEVEL_TWELVE));
*/
/*
(Levels = 15, Manages Limit = 10)
* At Level 1 => 1
* At Level 2 => 1
* At Level 3 => 1
* At Level 4 => 1
* At Level 5 => 1
* At Level 6 => 1
* At Level 7 => 2
* At Level 8 => 3
* At Level 9 => 5
* At Level 10 => 10
* At Level 11 => 100
* At Level 12 => 1000
* At Level 13 => 10000
* At Level 14 => 100000
* At Level 15 => 1000000
* Total => 1111126
peopleAtLevel.put(LEVEL_ONE, new OrgLevelData(fullNames.subList(0, 1), DIRECTLY_MANAGES_LIMIT_LEVEL_ONE));
peopleAtLevel.put(LEVEL_TWO, new OrgLevelData(fullNames.subList(1, 2), DIRECTLY_MANAGES_LIMIT_LEVEL_TWO));
peopleAtLevel.put(LEVEL_THREE, new OrgLevelData(fullNames.subList(2, 3), DIRECTLY_MANAGES_LIMIT_LEVEL_THREE));
peopleAtLevel.put(LEVEL_FOUR, new OrgLevelData(fullNames.subList(3, 4), DIRECTLY_MANAGES_LIMIT_LEVEL_FOUR));
peopleAtLevel.put(LEVEL_FIVE, new OrgLevelData(fullNames.subList(4, 5), DIRECTLY_MANAGES_LIMIT_LEVEL_FIVE));
peopleAtLevel.put(LEVEL_SIX, new OrgLevelData(fullNames.subList(5, 6),DIRECTLY_MANAGES_LIMIT_LEVEL_SIX));
peopleAtLevel.put(LEVEL_SEVEN, new OrgLevelData(fullNames.subList(6, 8),DIRECTLY_MANAGES_LIMIT_LEVEL_SEVEN));
peopleAtLevel.put(LEVEL_EIGHT, new OrgLevelData(fullNames.subList(8, 11),DIRECTLY_MANAGES_LIMIT_LEVEL_EIGHT));
peopleAtLevel.put(LEVEL_NINE, new OrgLevelData(fullNames.subList(11, 16),DIRECTLY_MANAGES_LIMIT_LEVEL_NINE));
peopleAtLevel.put(LEVEL_TEN, new OrgLevelData(fullNames.subList(16, 26),DIRECTLY_MANAGES_LIMIT_LEVEL_TEN));
peopleAtLevel.put(LEVEL_ELEVEN, new OrgLevelData(fullNames.subList(26, 126),DIRECTLY_MANAGES_LIMIT_LEVEL_ELEVEN));
peopleAtLevel.put(LEVEL_TWELVE, new OrgLevelData(fullNames.subList(126, 1126),DIRECTLY_MANAGES_LIMIT_LEVEL_TWELVE));
peopleAtLevel.put(LEVEL_THIRTEEN, new OrgLevelData(fullNames.subList(1126, 11126),DIRECTLY_MANAGES_LIMIT_LEVEL_THIRTEEN));
peopleAtLevel.put(LEVEL_FOURTEEN, new OrgLevelData(fullNames.subList(11126, 111126),DIRECTLY_MANAGES_LIMIT_LEVEL_FOURTEEN));
peopleAtLevel.put(LEVEL_FIFTEEN, new OrgLevelData(fullNames.subList(111126, 1111126),DIRECTLY_MANAGES_LIMIT_LEVEL_FIFTEEN));
*/
/*
(Levels = 20, Manages Limit = 10)
* At Level 1 => 1
* At Level 2 => 1
* At Level 3 => 1
* At Level 4 => 1
* At Level 5 => 1
* At Level 6 => 1
* At Level 7 => 1
* At Level 8 => 1
* At Level 9 => 1
* At Level 10 => 1
* At Level 11 => 1
* At Level 12 => 2
* At Level 13 => 3
* At Level 14 => 5
* At Level 15 => 10
* At Level 16 => 100
* At Level 17 => 1000
* At Level 18 => 10000
* At Level 19 => 100000
* At Level 20 => 1000000
* Total => 1111131
peopleAtLevel.put(LEVEL_ONE, new OrgLevelData(fullNames.subList(0, 1), DIRECTLY_MANAGES_LIMIT_LEVEL_ONE));
peopleAtLevel.put(LEVEL_TWO, new OrgLevelData(fullNames.subList(1, 2), DIRECTLY_MANAGES_LIMIT_LEVEL_TWO));
peopleAtLevel.put(LEVEL_THREE, new OrgLevelData(fullNames.subList(2, 3), DIRECTLY_MANAGES_LIMIT_LEVEL_THREE));
peopleAtLevel.put(LEVEL_FOUR, new OrgLevelData(fullNames.subList(3, 4), DIRECTLY_MANAGES_LIMIT_LEVEL_FOUR));
peopleAtLevel.put(LEVEL_FIVE, new OrgLevelData(fullNames.subList(4, 5), DIRECTLY_MANAGES_LIMIT_LEVEL_FIVE));
peopleAtLevel.put(LEVEL_SIX, new OrgLevelData(fullNames.subList(5, 6), DIRECTLY_MANAGES_LIMIT_LEVEL_SIX));
peopleAtLevel.put(LEVEL_SEVEN, new OrgLevelData(fullNames.subList(6, 7), DIRECTLY_MANAGES_LIMIT_LEVEL_SEVEN));
peopleAtLevel.put(LEVEL_EIGHT, new OrgLevelData(fullNames.subList(7, 8), DIRECTLY_MANAGES_LIMIT_LEVEL_EIGHT));
peopleAtLevel.put(LEVEL_NINE, new OrgLevelData(fullNames.subList(8, 9), DIRECTLY_MANAGES_LIMIT_LEVEL_NINE));
peopleAtLevel.put(LEVEL_TEN, new OrgLevelData(fullNames.subList(9, 10), DIRECTLY_MANAGES_LIMIT_LEVEL_TEN));
peopleAtLevel.put(LEVEL_ELEVEN, new OrgLevelData(fullNames.subList(10, 11),DIRECTLY_MANAGES_LIMIT_LEVEL_ELEVEN));
peopleAtLevel.put(LEVEL_TWELVE, new OrgLevelData(fullNames.subList(11, 13),DIRECTLY_MANAGES_LIMIT_LEVEL_TWELVE));
peopleAtLevel.put(LEVEL_THIRTEEN, new OrgLevelData(fullNames.subList(13, 16),DIRECTLY_MANAGES_LIMIT_LEVEL_THIRTEEN));
peopleAtLevel.put(LEVEL_FOURTEEN, new OrgLevelData(fullNames.subList(16, 21),DIRECTLY_MANAGES_LIMIT_LEVEL_FOURTEEN));
peopleAtLevel.put(LEVEL_FIFTEEN, new OrgLevelData(fullNames.subList(21, 31),DIRECTLY_MANAGES_LIMIT_LEVEL_FIFTEEN));
peopleAtLevel.put(LEVEL_SIXTEEN, new OrgLevelData(fullNames.subList(31, 131),DIRECTLY_MANAGES_LIMIT_LEVEL_SIXTEEN));
peopleAtLevel.put(LEVEL_SEVENTEEN, new OrgLevelData(fullNames.subList(131, 1131),DIRECTLY_MANAGES_LIMIT_LEVEL_SEVENTEEN));
peopleAtLevel.put(LEVEL_EIGHTEEN, new OrgLevelData(fullNames.subList(1131, 11131),DIRECTLY_MANAGES_LIMIT_LEVEL_EIGHTEEN));
peopleAtLevel.put(LEVEL_NINETEEN, new OrgLevelData(fullNames.subList(11131, 111131),DIRECTLY_MANAGES_LIMIT_LEVEL_NINETEEN));
peopleAtLevel.put(LEVEL_TWENTY, new OrgLevelData(fullNames.subList(111131, 1111131),DIRECTLY_MANAGES_LIMIT_LEVEL_TWENTY));
*/
return peopleAtLevel;
}
} |
package nl.mpi.kinnate.ui;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import nl.mpi.arbil.data.ArbilDataNode;
import nl.mpi.arbil.data.ArbilDataNodeLoader;
import nl.mpi.arbil.data.ArbilNode;
import nl.mpi.arbil.ui.ArbilTree;
import nl.mpi.arbil.ui.GuiHelper;
import nl.mpi.kinnate.data.KinTreeNode;
import nl.mpi.kinnate.svg.GraphPanel;
import nl.mpi.kinnate.uniqueidentifiers.UniqueIdentifier;
public class KinTree extends ArbilTree {
GraphPanel graphPanel;
public KinTree(GraphPanel graphPanel) {
this.graphPanel = graphPanel;
}
@Override
protected void putSelectionIntoPreviewTable() {
// todo: in arbil the preview table only shows the lead selection, however in the kinship tree it might best to show the entire selection
ArbilNode[] arbilNodeArray = getAllSelectedNodes(); //LeadSelectionNode();
ArrayList<UniqueIdentifier> identifierList = new ArrayList<UniqueIdentifier>();
// ArrayList<URI> uriList = new ArrayList<URI>();
graphPanel.metadataPanel.removeAllArbilDataNodeRows();
for (ArbilNode arbilNode : arbilNodeArray) {
if (arbilNode instanceof ArbilDataNode) {
// uriList.add(((ArbilDataNode) arbilNode).getURI());
graphPanel.metadataPanel.addSingleArbilDataNode((ArbilDataNode) arbilNode);
} else if (arbilNode instanceof KinTreeNode) {
final KinTreeNode kinTreeNode = (KinTreeNode) arbilNode;
// set the graph selection
if (kinTreeNode.entityData != null) {
identifierList.add(kinTreeNode.entityData.getUniqueIdentifier());
try {
final ArbilDataNode arbilDataNode = ArbilDataNodeLoader.getSingleInstance().getArbilDataNode(null, new URI(((KinTreeNode) arbilNode).entityData.getEntityPath()));
graphPanel.metadataPanel.addSingleArbilDataNode(arbilDataNode);
} catch (URISyntaxException urise) {
GuiHelper.linorgBugCatcher.logError(urise);
}
}
}
}
// set the graph selection
graphPanel.setSelectedIds(identifierList.toArray(new UniqueIdentifier[]{}));
graphPanel.metadataPanel.updateEditorPane();
}
} |
package com.ezardlabs.lostsector;
import com.ezardlabs.dethsquare.Transform;
import com.ezardlabs.dethsquare.Vector2;
import com.ezardlabs.lostsector.NavMesh.NavPoint.NavPointType;
import com.ezardlabs.lostsector.map.MapManager;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Stack;
public class NavMesh {
public static NavPoint[][] navPoints;
private static int maxIndex = 0;
private static NavPoint closest;
private static boolean found = false;
enum LinkType {
WALK,
FALL,
JUMP
}
private static ArrayList<NavPoint> pointsWithAlteredIndices = new ArrayList<>();
public static class NavPoint {
public NavPointType type = NavPointType.NONE;
public final HashSet<Link> links = new HashSet<>();
public final int id;
public final Vector2 position;
private int index = 0;
static class Link {
LinkType linkType;
NavPoint target;
public Link(LinkType linkType, NavPoint target) {
this.linkType = linkType;
this.target = target;
}
}
public NavPoint(int id, Vector2 position) {
this.id = id;
this.position = position;
}
public enum NavPointType {
NONE,
PLATFORM,
LEFT_EDGE,
RIGHT_EDGE,
SOLO
}
void index(int index) {
if (found || (this.index > 0 && index >= this.index)) return;
if (this.index == -1) {
this.index = index;
maxIndex = index;
closest = this;
found = true;
pointsWithAlteredIndices.add(this);
toIndex.clear();
indices.clear();
return;
}
this.index = index;
pointsWithAlteredIndices.add(this);
if (index > maxIndex) {
maxIndex = index;
closest = this;
}
for (Link l : links) {
if (!(l.linkType == LinkType.FALL && l.target.position.y < position.y) && !(l.linkType == LinkType.JUMP && l.target.position.y > position.y)) {
if ((l.target.index <= 0 || index + 1 < l.target.index)) {
toIndex.addLast(l.target);
indices.addLast(index + 1);
// indices.addLast(index + (int) (Math.abs(position.x - l.target.position.x) + Math.abs(position.y - l.target.position.y)));
}
}
}
}
@Override
public String toString() {
String ret = "";
for (Link l : links) {
ret += l.target.id + ", ";
}
return "NavPoint: id = " + id + ", position = " + position + ", index = " + index + ", links = " + ret;
}
}
private static ArrayDeque<NavPoint> toIndex = new ArrayDeque<>();
private static ArrayDeque<Integer> indices = new ArrayDeque<>();
public static NavPoint[] getPath(Transform a, Transform b) {
return getPath(a.position, b.position);
}
public static NavPoint[] getPath(Vector2 a, Vector2 b) {
NavPoint start = getNavPoint(a);
NavPoint end = getNavPoint(b);
if (end != null && end.type == NavPointType.NONE) {
end = navPoints[Math.round((b.x / 100f) + 1)][Math.round(b.y / 100f) + 1];
}
if (start == null || end == null) return new NavPoint[0];
for (int i = 0; i < pointsWithAlteredIndices.size(); i++) {
pointsWithAlteredIndices.get(i).index = 0;
}
pointsWithAlteredIndices.clear();
end.index = -1;
pointsWithAlteredIndices.add(end);
maxIndex = 0;
found = false;
toIndex.clear();
indices.clear();
toIndex.add(start);
indices.add(1);
while (!toIndex.isEmpty()) {
toIndex.pop().index(indices.pop());
}
if (closest.id != end.id) {
return new NavPoint[0];
}
NavPoint[] path = new NavPoint[maxIndex];
if (maxIndex == 0) {
return path;
} else if (maxIndex == 1) {
path[0] = end;
return path;
} else {
path[maxIndex - 1] = end;
for (int i = maxIndex - 2; i >= 0; i
for (NavPoint.Link l : path[i + 1].links) {
if (l.target.index == i + 1 && !(l.target.position.y > path[i + 1].position.y && l.linkType == LinkType.FALL) && !(l.target.position.y < path[i + 1].position.y && l.linkType == LinkType.JUMP)) {
path[i] = l.target;
break;
}
}
}
return path;
}
}
public static NavPoint getNavPoint(Vector2 position) {
return getNavPoint(position.x, position.y);
}
public static NavPoint getNavPoint(float x, float y) {
return navPoints[Math.round(x / 100f)][Math.round(y / 100f) + 1];
}
private static int count = 0;
public static void init(int[][] solidityMap) {
solidityMap = fillInSolidityMap(solidityMap);
navPoints = new NavPoint[solidityMap.length][solidityMap[0].length];
for (int i = 0; i < solidityMap.length; i++) {
for (int j = 0; j < solidityMap[i].length; j++) {
if (solidityMap[i][j] == 0) solidityMap[i][j] = 1;
if (solidityMap[i][j] == 2) solidityMap[i][j] = 0;
navPoints[i][j] = new NavPoint(count++, new Vector2(i * 100, j * 100));
}
}
// Walk links
for (int y = 0; y < solidityMap[0].length; y++) {
boolean platformStarted = false;
for (int x = 0; x < solidityMap.length; x++) {
if (!platformStarted) {
if (!isCollision(solidityMap, x, y) && isCollision(solidityMap, x, y + 1) && !isCollision(solidityMap, x, y - 1)) {
navPoints[x][y].type = NavPointType.LEFT_EDGE;
platformStarted = true;
}
}
if (platformStarted) {
if (isCollision(solidityMap, x + 1, y + 1) &&
!isCollision(solidityMap, x + 1, y) &&
navPoints[x][y].type != NavPointType.LEFT_EDGE) {
navPoints[x][y].type = NavPointType.PLATFORM;
addLink(x, y, x - 1, y, LinkType.WALK);
}
if (!isCollision(solidityMap, x + 1, y + 1) || isCollision(solidityMap, x + 1, y)) {
if (navPoints[x][y].type == NavPointType.LEFT_EDGE) {
navPoints[x][y].type = NavPointType.SOLO;
} else {
navPoints[x][y].type = NavPointType.RIGHT_EDGE;
addLink(x, y, x - 1, y, LinkType.WALK);
}
platformStarted = false;
}
}
}
}
// Fall links
for (int x = 0; x < navPoints.length; x++) {
for (int y = 0; y < navPoints[x].length; y++) {
if (navPoints[x][y].type == NavPointType.RIGHT_EDGE || navPoints[x][y].type == NavPointType.SOLO) {
if (x + 2 < navPoints.length && !isCollision(solidityMap, x + 1, y) && !isCollision(solidityMap, x + 2, y) && !isCollision(solidityMap, x + 1, y - 1) &&
!isCollision(solidityMap, x + 2, y - 1)) {
int yTemp = y + 1;
while (yTemp < navPoints[x].length - 1 && !isCollision(solidityMap, x + 1, yTemp) && !isCollision(solidityMap, x + 2, yTemp)) {
yTemp++;
}
yTemp
if (isCollision(solidityMap, x + 1, yTemp + 1)) {
addLink(x, y, x + 1, yTemp, LinkType.FALL);
if (yTemp - (y + 1) < 3) {
addLink(x, y, x + 1, yTemp, LinkType.JUMP);
}
} else {
addLink(x, y, x + 1, yTemp, LinkType.FALL);
if (yTemp - (y + 1) < 3) {
addLink(x, y, x + 1, yTemp, LinkType.JUMP);
}
}
}
}
if (navPoints[x][y].type == NavPointType.LEFT_EDGE || navPoints[x][y].type == NavPointType.SOLO) {
if (x - 2 > 0 && !isCollision(solidityMap, x - 1, y) && !isCollision(solidityMap, x - 2, y) && !isCollision(solidityMap, x - 1, y - 1) && !isCollision(solidityMap, x - 2, y - 1)) {
int yTemp = y + 1;
while (yTemp < navPoints[x].length - 1 && !isCollision(solidityMap, x - 1, yTemp) && !isCollision(solidityMap, x - 2, yTemp)) {
yTemp++;
}
yTemp
if (isCollision(solidityMap, x - 2, yTemp + 1)) {
addLink(x, y, x - 2, yTemp, LinkType.FALL);
if (yTemp - (y + 1) < 3) {
addLink(x, y, x - 2, yTemp, LinkType.JUMP);
}
} else {
addLink(x, y, x - 1, yTemp, LinkType.FALL);
if (yTemp - (y + 1) < 3) {
addLink(x, y, x - 1, yTemp, LinkType.JUMP);
}
}
}
}
}
}
// Jump links
for (int x = 0; x < navPoints.length; x++) {
for (int y = 0; y < navPoints[x].length; y++) {
if (navPoints[x][y].type == NavPointType.RIGHT_EDGE || navPoints[x][y].type == NavPointType.SOLO) {
if (isCollision(solidityMap, x + 1, y)) {
for (int i = 1; i < 4; i++) {
if (!isCollision(solidityMap, x + 1, y - i) && !isCollision(solidityMap, x + 1, y - i - 1)) {
// addLink(x - 1, y, x + 1, y - i, LinkType.JUMP);
break;
}
}
}
}
if (navPoints[x][y].type == NavPointType.LEFT_EDGE || navPoints[x][y].type == NavPointType.SOLO) {
if (isCollision(solidityMap, x - 1, y)) {
for (int i = 1; i < 4; i++) {
if (!isCollision(solidityMap, x - 1, y - i) && !isCollision(solidityMap, x - 1, y - i - 1)) {
// addLink(x, y, x - 1, y - i, LinkType.JUMP);
break;
}
}
}
}
}
}
}
private static void addLink(int x1, int y1, int x2, int y2, LinkType type) {
navPoints[x1][y1].links.add(new NavPoint.Link(type, navPoints[x2][y2]));
navPoints[x2][y2].links.add(new NavPoint.Link(type, navPoints[x1][y1]));
}
private static int[][] fillInSolidityMap(int[][] solidityMap) {
if (solidityMap == null) return null;
Stack<int[]> stack = new Stack<>();
stack.push(new int[]{(int) MapManager.playerSpawn.x / 100,
(int) MapManager.playerSpawn.y / 100});
while (!stack.empty()) {
int[] pop = stack.pop();
int x = pop[0];
int y = pop[1];
if (solidityMap[x][y] >= 1) continue;
if (solidityMap[x][y] == 0) solidityMap[x][y] = 2;
if (x > 0) stack.push(new int[]{x - 1,
y});
if (x < solidityMap.length - 2) stack.push(new int[]{x + 1,
y});
if (y > 0) stack.push(new int[]{x,
y - 1});
if (y < solidityMap[0].length - 2) stack.push(new int[]{x,
y + 1});
}
return solidityMap;
}
private static boolean isCollision(int[][] solidity, int x, int y) {
return x >= solidity.length || x < 0 || y >= solidity[0].length || y < 0 ||
solidity[x][y] == 1;
}
} |
package burp;
import java.awt.*;
import java.awt.datatransfer.*;
import java.awt.event.*;
import java.nio.charset.StandardCharsets;
import java.util.*;
import javax.swing.*;
import javax.swing.tree.*;
import mjson.Json;
public class JsonJTree extends MouseAdapter implements IMessageEditorTab, ClipboardOwner
{
private final DefaultMutableTreeNode root = new DefaultMutableTreeNode("(JSON root)");
private final JTree tree = new JTree(root);
private final DefaultTreeModel model = (DefaultTreeModel)tree.getModel();
private byte[] content;
private final IExtensionHelpers helpers;
private int bodyOffset;
JsonJTree(IExtensionHelpers helpers) {
tree.getSelectionModel().setSelectionMode
(TreeSelectionModel.SINGLE_TREE_SELECTION);
tree.addMouseListener(this);
this.helpers = helpers;
}
@Override public void mousePressed (MouseEvent e) { if (e.isPopupTrigger()) doPop(e); }
@Override public void mouseReleased(MouseEvent e) { if (e.isPopupTrigger()) doPop(e); }
private void doPop(MouseEvent e) {
final JPopupMenu popup = new JPopupMenu();
final TreePath sp = tree.getSelectionPath();
if (sp == null) return; // nothing was selected
final DefaultMutableTreeNode node = (DefaultMutableTreeNode)sp.getLastPathComponent();
if (node == root) return; // disable for root
final Node item = (Node)node.getUserObject();
addToPopup(popup, "Copy key", new ActionListener() {
public void actionPerformed(ActionEvent e) {
copyString(item.asKeyString());
}
});
if (!item.isArrayOrObject()) {
addToPopup(popup, "Copy value as string", new ActionListener() {
public void actionPerformed(ActionEvent e) {
copyString(item.asValueString());
}
});
}
addToPopup(popup, "Copy value as JSON", new ActionListener() {
public void actionPerformed(ActionEvent e) {
copyString(item.asJsonString());
}
});
popup.show(e.getComponent(), e.getX(), e.getY());
}
private static void addToPopup(JPopupMenu pm, String title, ActionListener al) {
final JMenuItem mi = new JMenuItem(title);
mi.addActionListener(al);
pm.add(mi);
}
private void copyString(final String value) {
Toolkit.getDefaultToolkit().getSystemClipboard()
.setContents(new StringSelection(value), this);
}
public boolean isEnabled(byte[] content, boolean isRequest) {
int len = content.length;
if (len == 0) {
root.removeAllChildren();
model.reload(root);
return false;
}
if (isRequest) {
IRequestInfo i = helpers.analyzeRequest(content);
bodyOffset = i.getBodyOffset();
} else {
IResponseInfo i = helpers.analyzeResponse(content);
bodyOffset = i.getBodyOffset();
}
return (len - bodyOffset >= 2) &&
content[bodyOffset] == (byte)'{' && content[len - 1] == (byte)'}';
// TODO try parsing at this stage
}
public void setMessage(byte[] content, boolean isRequest) {
this.content = content;
root.removeAllChildren();
if (content != null) {
Json node = Json.read(new String(content, bodyOffset,
content.length - bodyOffset, StandardCharsets.UTF_8));
// TODO UTF-8?
dumpObjectNode(root, node);
}
model.reload(root);
expandAllNodes(tree, 0, tree.getRowCount());
}
private static class Node {
private final String key;
private final Json value;
Node(String key, Json value) {
this.key = key;
this.value = value;
}
public boolean isArrayOrObject() {
return value.isArray() || value.isObject();
}
public String asValueString() { return value.asString(); }
public String asJsonString() { return value.toString(); }
public String asKeyString() { return key; }
@Override
public String toString() {
if (value.isNull()) {
return key + ": null";
} else if (value.isString()) {
return key + ": \"" + value.asString() + '"';
} else if (value.isNumber() || value.isBoolean()) {
return key + ": " + value.toString();
}
return key;
}
}
private void dumpObjectNode(DefaultMutableTreeNode dst, Json src) {
Map<String, Json> tm = new TreeMap(String.CASE_INSENSITIVE_ORDER);
tm.putAll(src.asJsonMap());
for (Map.Entry<String, Json> e : tm.entrySet()) {
processNode(dst, e.getKey(), e.getValue());
}
}
private void dumpArrayNode(DefaultMutableTreeNode dst, Json src) {
int i = 0;
for (Json value : src.asJsonList()) {
String key = '[' + String.valueOf(i++) + ']';
processNode(dst, key, value);
}
}
private void processNode(DefaultMutableTreeNode dst, String key, Json value) {
final DefaultMutableTreeNode node =
new DefaultMutableTreeNode(new Node(key, value));
dst.add(node);
if (value.isObject()) {
dumpObjectNode(node, value);
} else if (value.isArray()) {
dumpArrayNode(node, value);
}
}
private void expandAllNodes(JTree tree, int startingIndex, int rowCount){
for(int i=startingIndex;i<rowCount;++i){
tree.expandRow(i);
}
if(tree.getRowCount()!=rowCount){
expandAllNodes(tree, rowCount, tree.getRowCount());
}
}
public String getTabCaption() { return "JSON JTree"; }
public Component getUiComponent() { return new JScrollPane(tree); }
public byte[] getMessage() { return content; }
public boolean isModified() { return false; }
public byte[] getSelectedData() { return null; }
public void lostOwnership(Clipboard aClipboard, Transferable aContents) {}
} |
package com.liferay.lms;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.TimeUnit;
import javax.portlet.PortletRequest;
import org.apache.commons.io.IOUtils;
import com.liferay.counter.service.CounterLocalServiceUtil;
import com.liferay.lms.learningactivity.LearningActivityTypeRegistry;
import com.liferay.lms.learningactivity.ResourceExternalLearningActivityType;
import com.liferay.lms.model.Course;
import com.liferay.lms.model.LearningActivity;
import com.liferay.lms.model.LmsPrefs;
import com.liferay.lms.model.Module;
import com.liferay.lms.model.TestAnswer;
import com.liferay.lms.model.TestQuestion;
import com.liferay.lms.service.CourseLocalServiceUtil;
import com.liferay.lms.service.LearningActivityLocalServiceUtil;
import com.liferay.lms.service.LmsPrefsLocalServiceUtil;
import com.liferay.lms.service.ModuleLocalServiceUtil;
import com.liferay.lms.service.TestAnswerLocalServiceUtil;
import com.liferay.lms.service.TestQuestionLocalServiceUtil;
import com.liferay.portal.DuplicateGroupException;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.language.LanguageUtil;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.messaging.Message;
import com.liferay.portal.kernel.messaging.MessageBusUtil;
import com.liferay.portal.kernel.messaging.MessageListener;
import com.liferay.portal.kernel.messaging.MessageListenerException;
import com.liferay.portal.kernel.repository.model.FileEntry;
import com.liferay.portal.kernel.repository.model.Folder;
import com.liferay.portal.kernel.search.Indexer;
import com.liferay.portal.kernel.search.IndexerRegistryUtil;
import com.liferay.portal.kernel.servlet.SessionErrors;
import com.liferay.portal.kernel.servlet.SessionMessages;
import com.liferay.portal.kernel.util.ParamUtil;
import com.liferay.portal.kernel.util.StringPool;
import com.liferay.portal.kernel.xml.Document;
import com.liferay.portal.kernel.xml.DocumentException;
import com.liferay.portal.kernel.xml.Element;
import com.liferay.portal.kernel.xml.SAXReaderUtil;
import com.liferay.portal.model.Group;
import com.liferay.portal.model.LayoutSetPrototype;
import com.liferay.portal.model.ResourceConstants;
import com.liferay.portal.model.Role;
import com.liferay.portal.model.RoleConstants;
import com.liferay.portal.model.User;
import com.liferay.portal.security.auth.PrincipalThreadLocal;
import com.liferay.portal.security.permission.ActionKeys;
import com.liferay.portal.security.permission.PermissionChecker;
import com.liferay.portal.security.permission.PermissionCheckerFactoryUtil;
import com.liferay.portal.security.permission.PermissionThreadLocal;
import com.liferay.portal.service.GroupLocalServiceUtil;
import com.liferay.portal.service.LayoutSetLocalServiceUtil;
import com.liferay.portal.service.LayoutSetPrototypeLocalServiceUtil;
import com.liferay.portal.service.ResourcePermissionLocalServiceUtil;
import com.liferay.portal.service.RoleLocalServiceUtil;
import com.liferay.portal.service.ServiceContext;
import com.liferay.portal.service.ServiceContextFactory;
import com.liferay.portal.service.UserGroupRoleLocalServiceUtil;
import com.liferay.portal.service.UserLocalServiceUtil;
import com.liferay.portal.theme.ThemeDisplay;
import com.liferay.portal.util.PortalUtil;
import com.liferay.portlet.announcements.model.AnnouncementsEntry;
import com.liferay.portlet.announcements.model.AnnouncementsFlagConstants;
import com.liferay.portlet.announcements.service.AnnouncementsEntryServiceUtil;
import com.liferay.portlet.announcements.service.AnnouncementsFlagLocalServiceUtil;
import com.liferay.portlet.asset.NoSuchEntryException;
import com.liferay.portlet.asset.model.AssetEntry;
import com.liferay.portlet.asset.service.AssetEntryLocalServiceUtil;
import com.liferay.portlet.documentlibrary.DuplicateFileException;
import com.liferay.portlet.documentlibrary.model.DLFileEntry;
import com.liferay.portlet.documentlibrary.model.DLFolder;
import com.liferay.portlet.documentlibrary.model.DLFolderConstants;
import com.liferay.portlet.documentlibrary.service.DLAppLocalServiceUtil;
import com.liferay.portlet.documentlibrary.service.DLFileEntryLocalServiceUtil;
import com.liferay.portlet.documentlibrary.service.DLFolderLocalServiceUtil;
public class CloneCourse implements MessageListener {
private static Log log = LogFactoryUtil.getLog(CloneCourse.class);
public static String DOCUMENTLIBRARY_MAINFOLDER = "ResourceUploads";
long groupId;
String newCourseName;
ThemeDisplay themeDisplay;
ServiceContext serviceContext;
Date startDate;
Date endDate;
boolean visible;
boolean includeTeacher;
private String cloneTraceStr = "
public CloneCourse(long groupId, String newCourseName, ThemeDisplay themeDisplay, Date startDate, Date endDate, ServiceContext serviceContext) {
super();
this.groupId = groupId;
this.newCourseName = newCourseName;
this.themeDisplay = themeDisplay;
this.startDate = startDate;
this.endDate = endDate;
this.serviceContext = serviceContext;
}
public CloneCourse() {
}
@Override
public void receive(Message message) throws MessageListenerException {
try {
this.groupId = message.getLong("groupId");
this.newCourseName = message.getString("newCourseName");
this.startDate = (Date)message.get("startDate");
this.endDate = (Date)message.get("endDate");
this.serviceContext = (ServiceContext)message.get("serviceContext");
this.themeDisplay = (ThemeDisplay)message.get("themeDisplay");
this.visible = message.getBoolean("visible");
this.includeTeacher = message.getBoolean("includeTeacher");
Role adminRole = RoleLocalServiceUtil.getRole(themeDisplay.getCompanyId(),"Administrator");
List<User> adminUsers = UserLocalServiceUtil.getRoleUsers(adminRole.getRoleId());
PrincipalThreadLocal.setName(adminUsers.get(0).getUserId());
PermissionChecker permissionChecker =PermissionCheckerFactoryUtil.create(adminUsers.get(0), true);
PermissionThreadLocal.setPermissionChecker(permissionChecker);
doCloneCourse();
} catch (Exception e) {
e.printStackTrace();
}
}
@SuppressWarnings("unchecked")
public void doCloneCourse() throws Exception {
cloneTraceStr += " Course to clone\n........................." + groupId;
System.out.println(" + groupId: "+groupId);
Group group = GroupLocalServiceUtil.getGroup(groupId);
Course course = CourseLocalServiceUtil.getCourseByGroupCreatedId(groupId);
System.out.println(" + course: "+course.getTitle(themeDisplay.getLocale()));
cloneTraceStr += " course:" + course.getTitle(themeDisplay.getLocale());
cloneTraceStr += " groupId:" + groupId;
Date today=new Date(System.currentTimeMillis());
String courseTemplate = this.serviceContext.getRequest().getParameter("courseTemplate");
long layoutSetPrototypeId = 0;
if(courseTemplate.indexOf("&")>-1){
layoutSetPrototypeId = Long.parseLong(courseTemplate.split("&")[1]);
}else{
layoutSetPrototypeId = Long.parseLong(courseTemplate);
}
/*LmsPrefs lmsPrefs=LmsPrefsLocalServiceUtil.getLmsPrefsIni(serviceContext.getCompanyId());
System.out.println(" + getLmsTemplates: "+lmsPrefs.getLmsTemplates());
if(lmsPrefs.getLmsTemplates().contains(",")){
String []ids = lmsPrefs.getLmsTemplates().split(",");
for(String id:ids){
LayoutSetPrototype layout = LayoutSetPrototypeLocalServiceUtil.getLayoutSetPrototype(Long.valueOf(id));
layoutSetPrototypeId=Long.valueOf(id);
System.out.println(" + layout: "+layout.getDescription());
if(layout.getDescription().equals("course")){
break;
}
}
}else if(!"".equals(lmsPrefs.getLmsTemplates())){
LayoutSetPrototype layout = LayoutSetPrototypeLocalServiceUtil.getLayoutSetPrototype(Long.valueOf(lmsPrefs.getLmsTemplates()));
layoutSetPrototypeId=Long.valueOf(lmsPrefs.getLmsTemplates());
}else{
layoutSetPrototypeId = LayoutSetLocalServiceUtil.getLayoutSet(groupId, true).getLayoutSetPrototypeId();
}*/
System.out.println(" + layoutSetPrototypeId: "+layoutSetPrototypeId);
cloneTraceStr += " layoutSetPrototypeId:" + layoutSetPrototypeId;
try{
AssetEntryLocalServiceUtil.validate(course.getGroupCreatedId(), Course.class.getName(), serviceContext.getAssetCategoryIds(), serviceContext.getAssetTagNames());
serviceContext.setAssetCategoryIds(AssetEntryLocalServiceUtil.getEntry(Course.class.getName(), course.getCourseId()).getCategoryIds());
System.out.println(" + AssetCategoryIds: "+AssetEntryLocalServiceUtil.getEntry(Course.class.getName(), course.getCourseId()).getCategoryIds().toString());
}catch(Exception e){
serviceContext.setAssetCategoryIds(new long[]{});
//serviceContext.setAssetTagNames(AssetEntryLocalServiceUtil.getEntry(Course.class.getName(), course.getCourseId()).getTags());
}
//Course newCourse = CourseLocalServiceUtil.addCourse(newCourseName, course.getDescription(), "", themeDisplay.getLocale() , today, startDate, endDate, serviceContext, course.getCalificationType());
//when lmsprefs has more than one lmstemplate selected the addcourse above throws an error.
int typeSite = GroupLocalServiceUtil.getGroup(course.getGroupCreatedId()).getType();
Course newCourse = null;
String summary = new String();
try{
summary = AssetEntryLocalServiceUtil.getEntry(Course.class.getName(),course.getCourseId()).getSummary(themeDisplay.getLocale());
newCourse = CourseLocalServiceUtil.addCourse(newCourseName, course.getDescription(themeDisplay.getLocale()),summary
, "", themeDisplay.getLocale(), today, startDate, endDate, layoutSetPrototypeId, typeSite, serviceContext, course.getCalificationType(), (int)course.getMaxusers(),true);
newCourse.setWelcome(course.getWelcome());
newCourse.setWelcomeMsg(course.getWelcomeMsg());
newCourse.setWelcomeSubject(course.getWelcomeSubject());
newCourse.setGoodbye(course.getGoodbye());
newCourse.setGoodbyeMsg(course.getGoodbyeMsg());
newCourse.setGoodbyeSubject(course.getGoodbyeSubject());
newCourse.setCourseEvalId(course.getCourseEvalId());
} catch(DuplicateGroupException e){
if(log.isDebugEnabled())e.printStackTrace();
throw new DuplicateGroupException();
}
newCourse.setExpandoBridgeAttributes(serviceContext);
newCourse.getExpandoBridge().setAttributes(course.getExpandoBridge().getAttributes());
//Course newCourse = CourseLocalServiceUtil.addCourse(newCourseName, course.getDescription(), "", "", themeDisplay.getLocale(), today, today, today, layoutSetPrototypeId, serviceContext);
Group newGroup = GroupLocalServiceUtil.getGroup(newCourse.getGroupCreatedId());
serviceContext.setScopeGroupId(newCourse.getGroupCreatedId());
Role siteMemberRole = RoleLocalServiceUtil.getRole(themeDisplay.getCompanyId(), RoleConstants.SITE_MEMBER);
newCourse.setIcon(course.getIcon());
try{
newCourse = CourseLocalServiceUtil.modCourse(newCourse, serviceContext);
AssetEntry entry = AssetEntryLocalServiceUtil.getEntry(Course.class.getName(),newCourse.getCourseId());
entry.setVisible(visible);
entry.setSummary(summary);
AssetEntryLocalServiceUtil.updateAssetEntry(entry);
newGroup.setName(newCourse.getTitle(themeDisplay.getLocale(), true));
newGroup.setDescription(summary);
GroupLocalServiceUtil.updateGroup(newGroup);
}catch(Exception e){
if(log.isDebugEnabled())e.printStackTrace();
}
newCourse.setUserId(themeDisplay.getUserId());
System.out.println("
System.out.println(" + to course: "+ newCourse.getTitle(Locale.getDefault()) +", GroupCreatedId: "+newCourse.getGroupCreatedId()+", GroupId: "+newCourse.getGroupId());
cloneTraceStr += "\n New course\n........................." + groupId;
cloneTraceStr += " Course: "+ newCourse.getTitle(Locale.getDefault()) +"\n GroupCreatedId: "+newCourse.getGroupCreatedId()+"\n GroupId: "+newCourse.getGroupId();
cloneTraceStr += "\n.........................";
/**
* METO AL USUARIO CREADOR DEL CURSO COMO PROFESOR
*/
if(includeTeacher){
System.out.println(includeTeacher);
if (!GroupLocalServiceUtil.hasUserGroup(themeDisplay.getUserId(), newCourse.getGroupCreatedId())) {
GroupLocalServiceUtil.addUserGroups(themeDisplay.getUserId(), new long[] { newCourse.getGroupCreatedId() });
//The application only send one mail at listener
//User user = UserLocalServiceUtil.getUser(userId);
//sendEmail(user, course);
}
LmsPrefs lmsPrefs=LmsPrefsLocalServiceUtil.getLmsPrefs(themeDisplay.getCompanyId());
long teacherRoleId=RoleLocalServiceUtil.getRole(lmsPrefs.getEditorRole()).getRoleId();
UserGroupRoleLocalServiceUtil.addUserGroupRoles(new long[] { themeDisplay.getUserId() }, newCourse.getGroupCreatedId(), teacherRoleId);
}
long days = 0;
boolean isFirstModule = true;
LearningActivityTypeRegistry learningActivityTypeRegistry = new LearningActivityTypeRegistry();
List<Module> modules = ModuleLocalServiceUtil.findAllInGroup(groupId);
HashMap<Long,Long> correlationActivities = new HashMap<Long, Long>();
HashMap<Long,Long> correlationModules = new HashMap<Long, Long>();
HashMap<Long,Long> modulesDependencesList = new HashMap<Long, Long>();
for(Module module:modules){
/*
if(isFirstModule){
Calendar c = Calendar.getInstance();
c.setTimeInMillis(startDate.getTime() - module.getStartDate().getTime());
days = c.get(Calendar.DAY_OF_YEAR);
if(c.get(Calendar.YEAR) - 1970 > 0){
days += 365 * (c.get(Calendar.YEAR) - 1970);
}
isFirstModule = false;
System.out.println(" Days to add: "+ days +" "+startDate+" "+module.getStartDate()+" "+c.getTime());
cloneTraceStr += "\n Days to add: "+ days +" "+startDate+" "+module.getStartDate()+" "+c.getTime();
cloneTraceStr += "\n\n";
}
*/
Module newModule;
try {
newModule = ModuleLocalServiceUtil.createModule(CounterLocalServiceUtil.increment(Module.class.getName()));
correlationModules.put(module.getModuleId(), newModule.getModuleId());
if(module.getPrecedence()!=0){
modulesDependencesList.put(module.getModuleId(),module.getPrecedence());
}
newModule.setTitle(module.getTitle());
newModule.setDescription(module.getDescription());
newModule.setGroupId(newCourse.getGroupId());
newModule.setCompanyId(newCourse.getCompanyId());
newModule.setGroupId(newCourse.getGroupCreatedId());
newModule.setUserId(newCourse.getUserId());
newModule.setOrdern(newModule.getModuleId());
//Icono
newModule.setIcon(module.getIcon());
/*
Calendar start = Calendar.getInstance();
start.setTimeInMillis(module.getStartDate().getTime() + TimeUnit.MILLISECONDS.convert(days, TimeUnit.DAYS));
Calendar stop = Calendar.getInstance();
stop.setTimeInMillis(module.getEndDate().getTime() + TimeUnit.MILLISECONDS.convert(days, TimeUnit.DAYS));
*/
//System.out.println(" stopDate : "+ stop.getTime() +" -> "+module.getEndDate());
newModule.setStartDate(startDate);
newModule.setEndDate(endDate);
newModule.setDescription(descriptionFilesClone(module.getDescription(),newCourse.getGroupCreatedId(), newModule.getModuleId(),themeDisplay.getUserId()));
ModuleLocalServiceUtil.addModule(newModule);
System.out.println("\n Module : " + module.getTitle(Locale.getDefault()) +"("+module.getModuleId()+")");
System.out.println(" + Module : " + newModule.getTitle(Locale.getDefault()) +"("+newModule.getModuleId()+")" );
cloneTraceStr += " Module: " + newModule.getTitle(Locale.getDefault()) +"("+newModule.getModuleId()+")";
} catch (Exception e) {
e.printStackTrace();
continue;
}
List<LearningActivity> activities = LearningActivityLocalServiceUtil.getLearningActivitiesOfModule(module.getModuleId());
HashMap<Long, Long> pending = new HashMap<Long, Long>();
for(LearningActivity activity:activities){
LearningActivity newLearnActivity;
LearningActivity nuevaLarn = null;
try {
newLearnActivity = LearningActivityLocalServiceUtil.createLearningActivity(CounterLocalServiceUtil.increment(LearningActivity.class.getName()));
newLearnActivity.setTitle(activity.getTitle());
newLearnActivity.setDescription(activity.getDescription());
newLearnActivity.setExtracontent(activity.getExtracontent());
newLearnActivity.setTypeId(activity.getTypeId());
newLearnActivity.setTries(activity.getTries());
newLearnActivity.setPasspuntuation(activity.getPasspuntuation());
newLearnActivity.setPriority(newLearnActivity.getActId());
boolean actPending = false;
if(activity.getPrecedence()>0){
if(correlationActivities.get(activity.getPrecedence())==null){
actPending = true;
}else{
newLearnActivity.setPrecedence(correlationActivities.get(activity.getPrecedence()));
}
}
newLearnActivity.setWeightinmodule(activity.getWeightinmodule());
newLearnActivity.setGroupId(newModule.getGroupId());
newLearnActivity.setModuleId(newModule.getModuleId());
newLearnActivity.setStartdate(startDate);
newLearnActivity.setEnddate(endDate);
newLearnActivity.setDescription(descriptionFilesClone(activity.getDescription(),newModule.getGroupId(), newLearnActivity.getActId(),themeDisplay.getUserId()));
nuevaLarn=LearningActivityLocalServiceUtil.addLearningActivity(newLearnActivity,serviceContext);
System.out.println(" Learning Activity : " + activity.getTitle(Locale.getDefault())+ " ("+activity.getActId()+", " + LanguageUtil.get(Locale.getDefault(),learningActivityTypeRegistry.getLearningActivityType(activity.getTypeId()).getName())+")");
System.out.println(" + Learning Activity : " + nuevaLarn.getTitle(Locale.getDefault())+ " ("+nuevaLarn.getActId()+", " + LanguageUtil.get(Locale.getDefault(),learningActivityTypeRegistry.getLearningActivityType(nuevaLarn.getTypeId()).getName())+")");
cloneTraceStr += " Learning Activity: " + nuevaLarn.getTitle(Locale.getDefault())+ " ("+nuevaLarn.getActId()+", " + LanguageUtil.get(Locale.getDefault(),learningActivityTypeRegistry.getLearningActivityType(nuevaLarn.getTypeId()).getName())+")";
cloneActivityFile(activity, nuevaLarn, themeDisplay.getUserId(), serviceContext);
long actId = nuevaLarn.getActId();
correlationActivities.put(activity.getActId(), actId);
boolean visible = ResourcePermissionLocalServiceUtil.hasResourcePermission(siteMemberRole.getCompanyId(), LearningActivity.class.getName(),
ResourceConstants.SCOPE_INDIVIDUAL, Long.toString(actId),siteMemberRole.getRoleId(), ActionKeys.VIEW);
if(!visible) {
ResourcePermissionLocalServiceUtil.setResourcePermissions(siteMemberRole.getCompanyId(), LearningActivity.class.getName(),
ResourceConstants.SCOPE_INDIVIDUAL, Long.toString(actId),siteMemberRole.getRoleId(), new String[] {ActionKeys.VIEW});
}
if(actPending){
pending.put(actId, activity.getPrecedence());
}
} catch (Exception e) {
e.printStackTrace();
continue;
}
List<TestQuestion> questions = TestQuestionLocalServiceUtil.getQuestions(activity.getActId());
for(TestQuestion question:questions)
{
TestQuestion newTestQuestion;
try {
newTestQuestion = TestQuestionLocalServiceUtil.addQuestion(nuevaLarn.getActId(), question.getText(), question.getQuestionType());
newTestQuestion.setText(descriptionFilesClone(question.getText(),newModule.getGroupId(), newTestQuestion.getActId(),themeDisplay.getUserId()));
TestQuestionLocalServiceUtil.updateTestQuestion(newTestQuestion, true);
System.out.println(" Test question : " + question.getQuestionId() );
System.out.println(" + Test question : " + newTestQuestion.getQuestionId() );
cloneTraceStr += "\n Test question: " + newTestQuestion.getQuestionId();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
continue;
}
List<TestAnswer> answers = TestAnswerLocalServiceUtil.getTestAnswersByQuestionId(question.getQuestionId());
for(TestAnswer answer:answers){
try {
TestAnswer newTestAnswer = TestAnswerLocalServiceUtil.addTestAnswer(question.getQuestionId(), answer.getAnswer(), answer.getFeedbackCorrect(), answer.getFeedbacknocorrect(), answer.isIsCorrect());
newTestAnswer.setQuestionId(newTestQuestion.getQuestionId());
newTestAnswer.setAnswer(descriptionFilesClone(answer.getAnswer(),newModule.getGroupId(), newTestAnswer.getActId(),themeDisplay.getUserId()));
TestAnswerLocalServiceUtil.updateTestAnswer(newTestAnswer, true);
System.out.println(" Test answer : " + answer.getAnswerId());
System.out.println(" + Test answer : " + newTestAnswer.getAnswerId());
cloneTraceStr += "\n Test answer: " + newTestAnswer.getAnswerId();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
if(pending.size()>0){
for(Long id : pending.keySet()){
LearningActivity la = LearningActivityLocalServiceUtil.getLearningActivity(id);
if(log.isDebugEnabled())log.debug(la);
if(la!=null){
Long idAsig = pending.get(id);
if(log.isDebugEnabled())log.debug(idAsig);
if(idAsig!=null){
Long other = correlationActivities.get(idAsig);
if(log.isDebugEnabled())log.debug(other);
la.setPrecedence(other);
LearningActivityLocalServiceUtil.updateLearningActivity(la);
}
}
}
}
}
//Dependencias de modulos
System.out.println("modulesDependencesList "+modulesDependencesList.keySet());
for(Long id : modulesDependencesList.keySet()){
//id del modulo actual
Long moduleToBePrecededNew = correlationModules.get(id);
Long modulePredecesorIdOld = modulesDependencesList.get(id);
Long modulePredecesorIdNew = correlationModules.get(modulePredecesorIdOld);
Module moduleNew = ModuleLocalServiceUtil.getModule(moduleToBePrecededNew);
moduleNew.setPrecedence(modulePredecesorIdNew);
ModuleLocalServiceUtil.updateModule(moduleNew);
}
System.out.println(" ENDS!");
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd kk:mm:ss");
dateFormat.setTimeZone(themeDisplay.getTimeZone());
String[] args = {newCourse.getTitle(themeDisplay.getLocale()), dateFormat.format(startDate), dateFormat.format(endDate)};
sendNotification(LanguageUtil.get(themeDisplay.getLocale(),"courseadmin.clone.confirmation.title"), LanguageUtil.format(themeDisplay.getLocale(),"courseadmin.clone.confirmation.message", args), themeDisplay.getPortalURL()+"/web/"+newGroup.getFriendlyURL(), "Avisos", 1);
}
public String descriptionFilesClone(String description, long groupId, long actId, long userId){
String newDescription = description;
try {
Document document = SAXReaderUtil.read(description.replace("<","<").replace(" ",""));
Element rootElement = document.getRootElement();
for (Element entryElement : rootElement.elements("Description")) {
for (Element entryElementP : entryElement.elements("p")) {
//Para las imagenes
for (Element entryElementImg : entryElementP.elements("img")) {
String src = entryElementImg.attributeValue("src");
String []srcInfo = src.split("/");
String fileUuid = "", fileGroupId ="";
if(srcInfo.length >= 6 && srcInfo[1].compareTo("documents") == 0){
fileUuid = srcInfo[srcInfo.length-1];
fileGroupId = srcInfo[2];
String []uuidInfo = fileUuid.split("\\?");
String uuid="";
if(srcInfo.length > 0){
uuid=uuidInfo[0];
}
FileEntry file;
try {
file = DLAppLocalServiceUtil.getFileEntryByUuidAndGroupId(uuid, Long.parseLong(fileGroupId));
ServiceContext serviceContext = new ServiceContext();
serviceContext.setScopeGroupId(groupId);
serviceContext.setUserId(userId);
serviceContext.setCompanyId(file.getCompanyId());
serviceContext.setAddGroupPermissions(true);
FileEntry newFile = cloneFileDescription(file, actId, file.getUserId(), serviceContext);
newDescription = descriptionCloneFile(newDescription, file, newFile);
System.out.println(" + Description file image : " + file.getTitle() +" ("+file.getMimeType()+")");
} catch (Exception e) {
// TODO Auto-generated catch block
//e.printStackTrace();
System.out.println("* ERROR! Description file image : " + e.getMessage());
}
}
}
//Para los enlaces
for (Element entryElementLink : entryElementP.elements("a")) {
String href = entryElementLink.attributeValue("href");
String []hrefInfo = href.split("/");
String fileUuid = "", fileGroupId ="";
if(hrefInfo.length >= 6 && hrefInfo[1].compareTo("documents") == 0){
fileUuid = hrefInfo[hrefInfo.length-1];
fileGroupId = hrefInfo[2];
String []uuidInfo = fileUuid.split("\\?");
String uuid="";
if(hrefInfo.length > 0){
uuid=uuidInfo[0];
}
FileEntry file;
try {
file = DLAppLocalServiceUtil.getFileEntryByUuidAndGroupId(uuid, Long.parseLong(fileGroupId));
ServiceContext serviceContext = new ServiceContext();
serviceContext.setScopeGroupId(groupId);
serviceContext.setUserId(userId);
serviceContext.setCompanyId(file.getCompanyId());
serviceContext.setAddGroupPermissions(true);
FileEntry newFile = cloneFileDescription(file, actId, file.getUserId(), serviceContext);
newDescription = descriptionCloneFile(newDescription, file, newFile);
System.out.println(" + Description file pdf : " + file.getTitle() +" "+file.getFileEntryId() );
} catch (Exception e) {
// TODO Auto-generated catch block
//e.printStackTrace();
System.out.println("* ERROR! Description file pdf : " + e.getMessage());
}
}
//Si en los enlaces tienen una imagen para hacer click.
for (Element entryElementLinkImage : entryElementLink.elements("img")) {
;//parseImage(entryElementLinkImage, element, context, moduleId);
}
}
}
}
} catch (DocumentException de) {
} catch (Exception e) {
// TODO Auto-generated catch block
//e.printStackTrace();
System.out.println("* ERROR! Document Exception : " + e.getMessage());
}
return newDescription;
}
private String descriptionCloneFile(String description, FileEntry oldFile, FileEntry newFile){
String res = description;
//Precondicion
if(oldFile == null || newFile == null){
return res;
}
//<img src="/documents/10808/0/GibbonIndexer.jpg/b24c4a8f-e65c-434a-ba36-3b3e10b21a8d?t=1376472516221"
//<a href="/documents/10808/10884/documento.pdf/32c193ed-16b3-4a83-93da-630501b72ee4">Documento</a></p>
String target = "/documents/"+oldFile.getRepositoryId()+"/"+oldFile.getFolderId()+"/"+URLEncoder.encode(oldFile.getTitle())+"/"+oldFile.getUuid();
String replacement = "/documents/"+newFile.getRepositoryId()+"/"+newFile.getFolderId()+"/"+URLEncoder.encode(newFile.getTitle())+"/"+newFile.getUuid();
res = description.replace(target, replacement);
//System.out.println(" res : " + res );
if(res.equals(description)){
System.out.println(" :: description : " + description );
System.out.println(" :: target : " + target );
System.out.println(" :: replacement : " + replacement );
}
String changed = (!res.equals(description))?" changed":" not changed";
System.out.println(" + Description file : " + newFile.getTitle() +" (" + newFile.getMimeType() + ")" + changed);
return res;
}
private void cloneActivityFile(LearningActivity actOld, LearningActivity actNew, long userId, ServiceContext serviceContext){
try {
System.out.println("cloneActivityFile");
String entryIdStr = "";
if(actOld.getTypeId() == 2){
entryIdStr = LearningActivityLocalServiceUtil.getExtraContentValue(actOld.getActId(), "document");
}else if(actOld.getTypeId() == 7){
entryIdStr = LearningActivityLocalServiceUtil.getExtraContentValue(actOld.getActId(), "assetEntry");
}
if(!entryIdStr.equals("")){
AssetEntry docAsset = AssetEntryLocalServiceUtil.getAssetEntry(Long.valueOf(entryIdStr));
long entryId = 0;
if(docAsset.getUrl()!=null && docAsset.getUrl().trim().length()>0){
entryId = Long.valueOf(entryIdStr);
}else{
if(actNew.getTypeId() == 2){
try{
HashMap<String, String> map = LearningActivityLocalServiceUtil.convertXMLExtraContentToHashMap(actNew.getActId());
Iterator <String> keysString = map.keySet().iterator();
int index = 0;
while (keysString.hasNext()){
String key = keysString.next();
if(!key.equals("video") && key.indexOf("document")!=-1){
index++;
long assetEntryIdOld = Long.parseLong(map.get(key));
AssetEntry docAssetOLD= AssetEntryLocalServiceUtil.getAssetEntry(assetEntryIdOld);
DLFileEntry oldFile=DLFileEntryLocalServiceUtil.getDLFileEntry(docAssetOLD.getClassPK());
InputStream inputStream = DLFileEntryLocalServiceUtil.getFileAsStream(userId, oldFile.getFileVersion().getFileEntryId(), oldFile.getFileVersion().getVersion());
byte[] byteArray = null;
try {
byteArray = IOUtils.toByteArray(inputStream);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
long repositoryId = DLFolderConstants.getDataRepositoryId(actNew.getGroupId(), DLFolderConstants.DEFAULT_PARENT_FOLDER_ID);
long dlMainFolderId = 0;
boolean dlMainFolderFound = false;
//Get main folder
try {
//Get main folder
Folder dlFolderMain = DLAppLocalServiceUtil.getFolder(repositoryId,DLFolderConstants.DEFAULT_PARENT_FOLDER_ID,DOCUMENTLIBRARY_MAINFOLDER+actNew.getActId());
dlMainFolderId = dlFolderMain.getFolderId();
dlMainFolderFound = true;
//Get portlet folder
} catch (Exception ex){
}
//Damos permisos al archivo para usuarios de comunidad.
serviceContext.setAddGroupPermissions(true);
//Create main folder if not exist
if(!dlMainFolderFound){
Folder newDocumentMainFolder = DLAppLocalServiceUtil.addFolder(userId, repositoryId,DLFolderConstants.DEFAULT_PARENT_FOLDER_ID, DOCUMENTLIBRARY_MAINFOLDER+actNew.getActId(), DOCUMENTLIBRARY_MAINFOLDER+actNew.getActId(), serviceContext);
dlMainFolderFound = true;
dlMainFolderId = newDocumentMainFolder.getFolderId();
}
String ficheroExtStr = "";
String extension[] = oldFile.getTitle().split("\\.");
if(extension.length > 0){
ficheroExtStr = "."+extension[extension.length-1];
}
FileEntry newFile = DLAppLocalServiceUtil.addFileEntry(
userId, repositoryId , dlMainFolderId , oldFile.getTitle()+ficheroExtStr, oldFile.getMimeType(),
oldFile.getTitle(), StringPool.BLANK, StringPool.BLANK, byteArray , serviceContext ) ;
//AssetEntry asset = AssetEntryLocalServiceUtil.getEntry(DLFileEntry.class.getName(), newFile.getPrimaryKey());
//System.out.println(" DLFileEntry newFile: "+newFile.getTitle()+", newFile PrimaryKey: "+newFile.getPrimaryKey()+", EntryId: "+asset.getEntryId());
map.put(key, String.valueOf(AssetEntryLocalServiceUtil.getEntry(DLFileEntry.class.getName(), newFile.getPrimaryKey()).getEntryId()));
Role siteMemberRole = RoleLocalServiceUtil.getRole(serviceContext.getCompanyId(), RoleConstants.SITE_MEMBER);
ResourcePermissionLocalServiceUtil.setResourcePermissions(serviceContext.getCompanyId(), LearningActivity.class.getName(),
ResourceConstants.SCOPE_INDIVIDUAL, Long.toString(actNew.getActId()),siteMemberRole.getRoleId(), new String[] {ActionKeys.VIEW});
}
LearningActivityLocalServiceUtil.saveHashMapToXMLExtraContent(actNew.getActId(), map);
}
} catch (NoSuchEntryException nsee) {
System.out.println(" asset not exits ");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
serviceContext.setAddGroupPermissions(serviceContext.isAddGroupPermissions());
}
}else{
entryId = cloneFile(Long.valueOf(entryIdStr), actNew, userId, serviceContext);
}
}
if(actNew.getTypeId() == 2){
//LearningActivityLocalServiceUtil.setExtraContentValue(actNew.getActId(), "document", String.valueOf(entryId));
}else if(actNew.getTypeId() == 7){
LearningActivityLocalServiceUtil.setExtraContentValue(actNew.getActId(), "assetEntry", String.valueOf(entryId));
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private long cloneFile(long entryId, LearningActivity actNew, long userId, ServiceContext serviceContext){
long assetEntryId = 0;
boolean addGroupPermissions = serviceContext.isAddGroupPermissions();
try {
System.out.println("EntryId: "+entryId);
AssetEntry docAsset = AssetEntryLocalServiceUtil.getAssetEntry(entryId);
//docAsset.getUrl()!=""
//DLFileEntryLocalServiceUtil.getDLFileEntry(fileEntryId)
System.out.println(docAsset.getClassPK());
DLFileEntry docfile = DLFileEntryLocalServiceUtil.getDLFileEntry(docAsset.getClassPK());
InputStream is = DLFileEntryLocalServiceUtil.getFileAsStream(userId, docfile.getFileEntryId(), docfile.getVersion());
//Crear el folder
DLFolder dlFolder = createDLFoldersForLearningActivity(userId, serviceContext.getScopeGroupId(), actNew.getActId(), actNew.getTitle(Locale.getDefault()), serviceContext);
long repositoryId = DLFolderConstants.getDataRepositoryId(actNew.getGroupId(), DLFolderConstants.DEFAULT_PARENT_FOLDER_ID);
String ficheroStr = docfile.getTitle();
if(!docfile.getTitle().endsWith(docfile.getExtension())){
ficheroStr = ficheroStr +"."+ docfile.getExtension();
}
serviceContext.setAddGroupPermissions(true);
FileEntry newFile = DLAppLocalServiceUtil.addFileEntry(
serviceContext.getUserId(), repositoryId , dlFolder.getFolderId() , ficheroStr, docfile.getMimeType(),
docfile.getTitle(), StringPool.BLANK, StringPool.BLANK, is, docfile.getSize() , serviceContext ) ;
AssetEntry asset = AssetEntryLocalServiceUtil.getEntry(DLFileEntry.class.getName(), newFile.getPrimaryKey());
System.out.println(" asset : " + asset.getEntryId());
assetEntryId = asset.getEntryId();
} catch (NoSuchEntryException nsee) {
System.out.println(" asset not exits ");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
serviceContext.setAddGroupPermissions(addGroupPermissions);
}
return assetEntryId;
}
private FileEntry cloneFileDescription(FileEntry file, long actId, long userId, ServiceContext serviceContext){
long folderId = 0;
try {
InputStream is = DLFileEntryLocalServiceUtil.getFileAsStream(userId, file.getFileEntryId(), file.getVersion());
//Crear el folder
DLFolder dlFolder = createDLFoldersForLearningActivity(userId, serviceContext.getScopeGroupId(), actId, String.valueOf(actId), serviceContext);
folderId = dlFolder.getFolderId();
//long repId = DLFolderConstants.getDataRepositoryId(file.getGroupId(), DLFolderConstants.DEFAULT_PARENT_FOLDER_ID);
long repositoryId = DLFolderConstants.getDataRepositoryId(serviceContext.getScopeGroupId(), DLFolderConstants.DEFAULT_PARENT_FOLDER_ID);
String ficheroStr = file.getTitle();
if(!file.getTitle().endsWith(file.getExtension())){
ficheroStr = ficheroStr +"."+ file.getExtension();
}
return DLAppLocalServiceUtil.addFileEntry(
serviceContext.getUserId(), repositoryId , folderId , ficheroStr, file.getMimeType(),
file.getTitle(), StringPool.BLANK, StringPool.BLANK, is, file.getSize() , serviceContext ) ;
}catch(DuplicateFileException dfl){
try{
return DLAppLocalServiceUtil.getFileEntry(serviceContext.getScopeGroupId(), folderId, file.getTitle());
}catch(Exception e){
e.printStackTrace();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
private long createDLFolders(Long userId,Long repositoryId,PortletRequest portletRequest) throws PortalException, SystemException{
//Variables for folder ids
Long dlMainFolderId = 0L;
//Search for folder in Document Library
boolean dlMainFolderFound = false;
//Get main folder
try {
//Get main folder
Folder dlFolderMain = DLAppLocalServiceUtil.getFolder(repositoryId,DLFolderConstants.DEFAULT_PARENT_FOLDER_ID,DOCUMENTLIBRARY_MAINFOLDER);
dlMainFolderId = dlFolderMain.getFolderId();
dlMainFolderFound = true;
//Get portlet folder
} catch (Exception ex){
}
ServiceContext serviceContext= ServiceContextFactory.getInstance( DLFolder.class.getName(), portletRequest);
//Damos permisos al archivo para usuarios de comunidad.
serviceContext.setAddGroupPermissions(true);
//Create main folder if not exist
if(!dlMainFolderFound){
Folder newDocumentMainFolder = DLAppLocalServiceUtil.addFolder(userId, repositoryId,DLFolderConstants.DEFAULT_PARENT_FOLDER_ID, DOCUMENTLIBRARY_MAINFOLDER, DOCUMENTLIBRARY_MAINFOLDER, serviceContext);
dlMainFolderId = newDocumentMainFolder.getFolderId();
}//Create portlet folder if not exist
return dlMainFolderId;
}
private DLFolder getMainDLFolder(Long userId, Long groupId, ServiceContext serviceContext) throws PortalException, SystemException{
DLFolder mainFolder = null;
boolean addGroupPermissions = serviceContext.isAddGroupPermissions();
try {
mainFolder = DLFolderLocalServiceUtil.getFolder(groupId,0,"ResourceUploads");
} catch (Exception ex){
long repositoryId = DLFolderConstants.getDataRepositoryId(groupId, DLFolderConstants.DEFAULT_PARENT_FOLDER_ID);
//mountPoint -> Si es carpeta raiz.
serviceContext.setAddGroupPermissions(true);
mainFolder = DLFolderLocalServiceUtil.addFolder(userId, groupId, repositoryId, false, 0, "ResourceUploads", "ResourceUploads", serviceContext);
} finally {
serviceContext.setAddGroupPermissions(addGroupPermissions);
}
return mainFolder;
}
private DLFolder createDLFoldersForLearningActivity(Long userId, Long groupId, Long actId, String title, ServiceContext serviceContext) throws PortalException, SystemException{
DLFolder newDLFolder = null;
try {
DLFolder dlMainFolder = getMainDLFolder(userId, groupId, serviceContext);
//A partir de ahora, guardamos los ficheros en el "Resource Uploads".
return dlMainFolder;
} catch (Exception e) {
// TODO Auto-generated catch block
//e.printStackTrace();
System.out.println("* ERROR! createDLFoldersForLearningActivity: " + e.getMessage());
}
return newDLFolder;
}
private void sendNotification(String title, String content, String url, String type, int priority){
//ThemeDisplay themeDisplay = (ThemeDisplay) actionRequest.getAttribute(WebKeys.THEME_DISPLAY);
SimpleDateFormat formatDay = new SimpleDateFormat("dd");
formatDay.setTimeZone(themeDisplay.getTimeZone());
SimpleDateFormat formatMonth = new SimpleDateFormat("MM");
formatMonth.setTimeZone(themeDisplay.getTimeZone());
SimpleDateFormat formatYear = new SimpleDateFormat("yyyy");
formatYear.setTimeZone(themeDisplay.getTimeZone());
SimpleDateFormat formatHour = new SimpleDateFormat("HH");
formatHour.setTimeZone(themeDisplay.getTimeZone());
SimpleDateFormat formatMin = new SimpleDateFormat("mm");
formatMin.setTimeZone(themeDisplay.getTimeZone());
Date today=new Date(System.currentTimeMillis());
int displayDateDay=Integer.parseInt(formatDay.format(today));
int displayDateMonth=Integer.parseInt(formatMonth.format(today))-1;
int displayDateYear=Integer.parseInt(formatYear.format(today));
int displayDateHour=Integer.parseInt(formatHour.format(today));
int displayDateMinute=Integer.parseInt(formatMin.format(today));
int expirationDateDay=Integer.parseInt(formatDay.format(today));
int expirationDateMonth=Integer.parseInt(formatMonth.format(today))-1;
int expirationDateYear=Integer.parseInt(formatYear.format(today))+1;
int expirationDateHour=Integer.parseInt(formatHour.format(today));
int expirationDateMinute=Integer.parseInt(formatMin.format(today));
long classNameId=PortalUtil.getClassNameId(User.class.getName());
long classPK=themeDisplay.getUserId();
AnnouncementsEntry ae;
try {
ae = AnnouncementsEntryServiceUtil.addEntry(
themeDisplay.getPlid(), classNameId, classPK, title, content, url, type,
displayDateMonth, displayDateDay, displayDateYear, displayDateHour, displayDateMinute,
expirationDateMonth, expirationDateDay, expirationDateYear, expirationDateHour, expirationDateMinute,
priority, false);
AnnouncementsFlagLocalServiceUtil.addFlag(classPK,ae.getEntryId(),AnnouncementsFlagConstants.UNREAD);
} catch (PortalException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SystemException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} |
package com.github.autoftp;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import jline.console.ConsoleReader;
import org.joda.time.DateTime;
import com.github.autoftp.client.ClientFactory.ClientType;
import com.github.autoftp.config.HostConfig;
import com.github.autoftp.config.SettingsProvider;
import com.github.autoftp.connection.FtpFile;
import com.github.autoftp.schedule.ConnectionScheduleExecutor;
public class AutoFtpScreen implements ConnectionListener {
private static final int MB = 1000 * 1000;
private ConsoleReader reader = null;
private PrintWriter writer = null;
private SettingsProvider settingsProvider;
private ConnectionScheduleExecutor executor;
public AutoFtpScreen() {
settingsProvider = new SettingsProvider();
executor = new ConnectionScheduleExecutor();
try {
reader = new ConsoleReader();
writer = new PrintWriter(reader.getOutput());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Auto FTP\r\n");
try {
while (true) {
writer.println("1. Run");
writer.println("2. Set up server info");
writer.println("3. Add file filters");
writer.println("4. Quit");
writer.flush();
String option = reader.readLine("\r\nEnter option: ");
if (option.equals("1")) {
run();
return;
} else if (option.equals("2")) {
setUpServer();
} else if (option.equals("3")) {
setUpFilters();
} else {
return;
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void setUpFilters() throws IOException {
List<String> currentFilters = settingsProvider.getFilterExpressions();
if (currentFilters.isEmpty())
writer.println("No filters currently set up.");
else {
writer.println("Current filters: \r\n");
for (String filter : currentFilters)
writer.println(filter);
writer.flush();
String choice = reader.readLine("\r\nDo you want to remove these? (y/N): ");
if (choice.toUpperCase().equals("Y"))
currentFilters.clear();
}
List<String> newFilters = new ArrayList<String>(currentFilters);
writer.println("\r\nEnter your filters. When done, leave the last line blank and hit <Enter>.");
writer.println("? = Single character. * = Any number of any character.");
writer.flush();
boolean stillEntering = true;
while (stillEntering) {
try {
String filter = reader.readLine("> ");
if (filter.trim().length() > 0)
newFilters.add(filter);
else
stillEntering = false;
} catch (IOException e) {
writer.println("Error writing to screen: " + e.getMessage());
writer.flush();
stillEntering = false;
}
}
settingsProvider.setFilterExpressions(newFilters);
writer.println("Done.\r\n");
writer.flush();
}
private void setUpServer() {
writer.println("Please enter the details of the server you want to connect to:\r\n");
writer.flush();
try {
HostConfig hostConfig = new HostConfig();
hostConfig.setHostname(reader.readLine("Server address: "));
hostConfig.setPort(Integer.parseInt(reader.readLine("Server port: ")));
hostConfig.setClientType(ClientType.valueOf(reader.readLine("Server type (FTP/SFTP): ").toUpperCase()));
hostConfig.setUsername(reader.readLine("Username: "));
hostConfig.setPassword(reader.readLine("Password: ", new Character('*')));
hostConfig.setFileDirectory(reader.readLine("Directory to scan: "));
settingsProvider.setHost(hostConfig);
settingsProvider.setConnectionInterval(Integer.parseInt(reader.readLine("Scan interval (in minutes): ")));
settingsProvider.setDownloadDirectory(reader.readLine("Download destination directory: "));
writer.println("Done.\r\n");
writer.flush();
} catch (IOException e) {
writer.println("Error printing to screen: " + e.getMessage());
writer.flush();
}
}
private void run() {
writer.println("\r\n");
executor.scheduleAndListen(this);
}
@Override
public void onConnection() {
printInfo("Connected to server.");
}
@Override
public void onDisconnection() {
printInfo("Disconnected from server. Going idle.");
}
@Override
public void onFilterListObtained(List<FtpFile> files) {
int fileCount = files.size();
printInfo(String.format("%d %s found:", fileCount, (fileCount == 1 ? "file" : "files")));
writer.println("\r\n");
for (FtpFile file : files)
printFile(file);
writer.println("\r\n");
writer.flush();
}
@Override
public void onError(String errorMessage) {
printError(errorMessage);
}
@Override
public void onDownloadStarted(String filename) {
printDownload(filename);
}
@Override
public void onDownloadFinished() {
printInfo("Download finished.");
}
public void printDownload(String filename) {
String formattedMessage = String.format("%s [Download] %s", DateTime.now().toString("dd/MM/yyy HH:mm:ss"), filename);
writer.println(formattedMessage);
writer.flush();
}
public void printError(String message) {
String formattedMessage = String.format("%s [Error] %s", DateTime.now().toString("dd/MM/yyy HH:mm:ss"), message);
writer.println(formattedMessage);
writer.flush();
}
public void printInfo(String info) {
String formattedMessage = String.format("%s [Info] %s", DateTime.now().toString("dd/MM/yyy HH:mm:ss"), info);
writer.println(formattedMessage);
writer.flush();
}
public void printFile(FtpFile file) {
DecimalFormat format = new DecimalFormat("
String extension = "MB";
long fileSize = file.getSize();
long sizeInMb = fileSize / MB;
long printableSize = sizeInMb;
if (sizeInMb > 1000l) {
printableSize = (sizeInMb / 1000);
extension = "GB";
}
String formattedMessage = String.format("\t%s %s\t|\t%s", format.format(printableSize), extension, file.getName());
writer.println(formattedMessage);
writer.flush();
}
} |
package com.jaamsim.input;
import java.lang.reflect.Array;
import java.util.List;
import java.util.Map;
import com.jaamsim.datatypes.DoubleVector;
import com.jaamsim.datatypes.IntegerVector;
import com.jaamsim.input.ExpResult.Iterator;
import com.jaamsim.units.DimensionlessUnit;
import com.jaamsim.units.Unit;
public class ExpCollections {
public static boolean isCollectionClass(Class<?> klass) {
if (Map.class.isAssignableFrom(klass)) {
return true;
}
if (List.class.isAssignableFrom(klass)) {
return true;
}
if (DoubleVector.class.isAssignableFrom(klass)) {
return true;
}
if (IntegerVector.class.isAssignableFrom(klass)) {
return true;
}
if (klass.isArray()) {
return true;
}
return false;
}
public static ExpResult getCollection(Object obj, Class<? extends Unit> ut) {
if (obj instanceof Map) {
MapCollection col = new MapCollection((Map<?,?>)obj, ut);
return ExpResult.makeCollectionResult(col);
}
if (obj instanceof List) {
ListCollection col = new ListCollection((List<?>)obj, ut);
return ExpResult.makeCollectionResult(col);
}
if (obj.getClass().isArray()) {
ArrayCollection col = new ArrayCollection(obj, ut);
return ExpResult.makeCollectionResult(col);
}
if (obj instanceof DoubleVector) {
DoubleVectorCollection col = new DoubleVectorCollection((DoubleVector)obj, ut);
return ExpResult.makeCollectionResult(col);
}
if (obj instanceof IntegerVector) {
IntegerVectorCollection col = new IntegerVectorCollection((IntegerVector)obj, ut);
return ExpResult.makeCollectionResult(col);
}
assert false;
return null;
}
private static class ListCollection implements ExpResult.Collection {
private static class Iter implements ExpResult.Iterator {
private int next = 0;
private final List<?> list;
public Iter(List l) {
this.list = l;
}
@Override
public boolean hasNext() {
return next < list.size();
}
@Override
public ExpResult nextKey() throws ExpError {
ExpResult ret = ExpResult.makeNumResult(next + 1, DimensionlessUnit.class);
next++;
return ret;
}
}
@Override
public Iterator getIter() {
return new Iter(list);
}
private final List<?> list;
private final Class<? extends Unit> unitType;
public ListCollection(List<?> l, Class<? extends Unit> ut) {
this.list = l;
this.unitType = ut;
}
@Override
public ExpResult index(ExpResult index) throws ExpError {
if (index.type != ExpResType.NUMBER) {
throw new ExpError(null, 0, "ArrayList is not being indexed by a number");
}
int indexVal = (int)index.value - 1; // Expressions use 1-base arrays
if (indexVal >= list.size() || indexVal < 0) {
return ExpResult.makeNumResult(0, unitType); // TODO: Is this how we want to handle this case?
}
Object val = list.get(indexVal);
return ExpEvaluator.getResultFromObject(val, unitType);
}
@Override
public int getSize() {
return list.size();
}
}
private static class ArrayCollection implements ExpResult.Collection {
private final Object array;
private final Class<? extends Unit> unitType;
public ArrayCollection(Object a, Class<? extends Unit> ut) {
this.array = a;
this.unitType = ut;
}
private static class Iter implements ExpResult.Iterator {
private int next = 0;
private final Object array;
public Iter(Object a) {
array = a;
}
@Override
public boolean hasNext() {
return next < Array.getLength(array);
}
@Override
public ExpResult nextKey() throws ExpError {
ExpResult ret = ExpResult.makeNumResult(next + 1, DimensionlessUnit.class);
next++;
return ret;
}
}
@Override
public Iterator getIter() {
return new Iter(array);
}
@Override
public ExpResult index(ExpResult index) throws ExpError {
if (index.type != ExpResType.NUMBER) {
throw new ExpError(null, 0, "ArrayList is not being indexed by a number");
}
int indexVal = (int)index.value - 1;
int length = Array.getLength(array);
if (indexVal >= length || indexVal < 0) {
return ExpResult.makeNumResult(0, unitType); // TODO: Is this how we want to handle this case?
}
Class<?> componentClass = array.getClass().getComponentType();
if (!componentClass.isPrimitive()) {
// This is an object type so we can use the rest of the reflection system as usual
Object val = Array.get(array, indexVal);
return ExpEvaluator.getResultFromObject(val, unitType);
}
if ( componentClass == Double.TYPE ||
componentClass == Float.TYPE ||
componentClass == Long.TYPE ||
componentClass == Integer.TYPE ||
componentClass == Short.TYPE ||
componentClass == Byte.TYPE ||
componentClass == Character.TYPE) {
// This is a numeric type and should be convertible to double
return ExpResult.makeNumResult(Array.getDouble(array, indexVal), unitType);
}
if (componentClass == Boolean.TYPE) {
// Convert boolean to 1 or 0
double val = (Array.getBoolean(array, indexVal)) ? 1.0 : 0.0;
return ExpResult.makeNumResult(val, unitType);
}
throw new ExpError(null, 0, "Unknown type in array");
}
@Override
public int getSize() {
return Array.getLength(array);
}
}
private static class DoubleVectorCollection implements ExpResult.Collection {
private final DoubleVector vector;
private final Class<? extends Unit> unitType;
public DoubleVectorCollection(DoubleVector v, Class<? extends Unit> ut) {
this.vector = v;
this.unitType = ut;
}
private static class Iter implements ExpResult.Iterator {
private int next = 0;
private final DoubleVector vector;
public Iter(DoubleVector v) {
this.vector = v;
}
@Override
public boolean hasNext() {
return next < vector.size();
}
@Override
public ExpResult nextKey() throws ExpError {
ExpResult ret = ExpResult.makeNumResult(next + 1, DimensionlessUnit.class);
next++;
return ret;
}
}
@Override
public Iterator getIter() {
return new Iter(vector);
}
@Override
public ExpResult index(ExpResult index) throws ExpError {
if (index.type != ExpResType.NUMBER) {
throw new ExpError(null, 0, "DoubleVector is not being indexed by a number");
}
int indexVal = (int)index.value - 1; // Expressions use 1-base arrays
if (indexVal >= vector.size() || indexVal < 0) {
return ExpResult.makeNumResult(0, unitType); // TODO: Is this how we want to handle this case?
}
Double value = vector.get(indexVal);
return ExpResult.makeNumResult(value, unitType);
}
@Override
public int getSize() {
return vector.size();
}
}
private static class IntegerVectorCollection implements ExpResult.Collection {
private final IntegerVector vector;
private final Class<? extends Unit> unitType;
public IntegerVectorCollection(IntegerVector v, Class<? extends Unit> ut) {
this.vector = v;
this.unitType = ut;
}
private class Iter implements ExpResult.Iterator {
private int next = 0;
private final IntegerVector vector;
public Iter(IntegerVector v) {
this.vector = v;
}
@Override
public boolean hasNext() {
return next < vector.size();
}
@Override
public ExpResult nextKey() throws ExpError {
ExpResult ret = ExpResult.makeNumResult(next + 1, DimensionlessUnit.class);
next++;
return ret;
}
}
@Override
public Iterator getIter() {
return new Iter(vector);
}
@Override
public ExpResult index(ExpResult index) throws ExpError {
if (index.type != ExpResType.NUMBER) {
throw new ExpError(null, 0, "IntegerVector is not being indexed by a number");
}
int indexVal = (int)index.value - 1; // Expressions use 1-base arrays
if (indexVal >= vector.size() || indexVal < 0) {
return ExpResult.makeNumResult(0, unitType); // TODO: Is this how we want to handle this case?
}
Integer value = vector.get(indexVal);
return ExpResult.makeNumResult(value, unitType);
}
@Override
public int getSize() {
return vector.size();
}
}
private static class MapCollection implements ExpResult.Collection {
private final Map<?,?> map;
private final Class<? extends Unit> unitType;
public MapCollection(Map<?,?> m, Class<? extends Unit> ut) {
this.map = m;
this.unitType = ut;
}
private static class Iter implements ExpResult.Iterator {
java.util.Iterator<?> keySetIt;
public Iter(Map<?,?> map) {
keySetIt = map.keySet().iterator();
}
@Override
public boolean hasNext() {
return keySetIt.hasNext();
}
@Override
public ExpResult nextKey() throws ExpError {
Object mapKey = keySetIt.next();
return ExpEvaluator.getResultFromObject(mapKey, DimensionlessUnit.class);
}
}
@Override
public Iterator getIter() {
return new Iter(map);
}
@Override
public ExpResult index(ExpResult index) throws ExpError {
Object key;
switch (index.type) {
case ENTITY:
key = index.entVal;
break;
case NUMBER:
key = Double.valueOf(index.value);
break;
case STRING:
key = index.stringVal;
break;
case COLLECTION:
throw new ExpError(null, 0, "Can not index with a collection");
default:
assert(false);
key = null;
break;
}
Object val = map.get(key);
if (val == null) {
return ExpResult.makeNumResult(0, unitType); // TODO: Is this how we want to handle this case?
}
return ExpEvaluator.getResultFromObject(val, unitType);
}
@Override
public int getSize() {
return map.size();
}
}
} |
// 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:17-01-13");
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");
}
} |
// 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.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.KalturaDocumentService;
import com.kaltura.client.services.KalturaEmailIngestionProfileService;
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.KalturaXInternalService;
import com.kaltura.client.services.KalturaMetadataService;
import com.kaltura.client.services.KalturaMetadataProfileService;
import com.kaltura.client.services.KalturaDocumentsService;
import com.kaltura.client.services.KalturaSystemPartnerService;
import com.kaltura.client.services.KalturaEntryAdminService;
import com.kaltura.client.services.KalturaUiConfAdminService;
import com.kaltura.client.services.KalturaReportAdminService;
import com.kaltura.client.services.KalturaKalturaInternalToolsSystemHelperService;
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.KalturaScheduledTaskProfileService;
import com.kaltura.client.services.KalturaIntegrationService;
import com.kaltura.client.types.KalturaBaseResponseProfile;
/**
* This class was generated using generate.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:15-12-12");
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 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 KalturaDocumentService documentService;
public KalturaDocumentService getDocumentService() {
if(this.documentService == null)
this.documentService = new KalturaDocumentService(this);
return this.documentService;
}
protected KalturaEmailIngestionProfileService EmailIngestionProfileService;
public KalturaEmailIngestionProfileService getEmailIngestionProfileService() {
if(this.EmailIngestionProfileService == null)
this.EmailIngestionProfileService = new KalturaEmailIngestionProfileService(this);
return this.EmailIngestionProfileService;
}
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 KalturaXInternalService xInternalService;
public KalturaXInternalService getXInternalService() {
if(this.xInternalService == null)
this.xInternalService = new KalturaXInternalService(this);
return this.xInternalService;
}
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 KalturaSystemPartnerService systemPartnerService;
public KalturaSystemPartnerService getSystemPartnerService() {
if(this.systemPartnerService == null)
this.systemPartnerService = new KalturaSystemPartnerService(this);
return this.systemPartnerService;
}
protected KalturaEntryAdminService entryAdminService;
public KalturaEntryAdminService getEntryAdminService() {
if(this.entryAdminService == null)
this.entryAdminService = new KalturaEntryAdminService(this);
return this.entryAdminService;
}
protected KalturaUiConfAdminService uiConfAdminService;
public KalturaUiConfAdminService getUiConfAdminService() {
if(this.uiConfAdminService == null)
this.uiConfAdminService = new KalturaUiConfAdminService(this);
return this.uiConfAdminService;
}
protected KalturaReportAdminService reportAdminService;
public KalturaReportAdminService getReportAdminService() {
if(this.reportAdminService == null)
this.reportAdminService = new KalturaReportAdminService(this);
return this.reportAdminService;
}
protected KalturaKalturaInternalToolsSystemHelperService kalturaInternalToolsSystemHelperService;
public KalturaKalturaInternalToolsSystemHelperService getKalturaInternalToolsSystemHelperService() {
if(this.kalturaInternalToolsSystemHelperService == null)
this.kalturaInternalToolsSystemHelperService = new KalturaKalturaInternalToolsSystemHelperService(this);
return this.kalturaInternalToolsSystemHelperService;
}
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 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.paperbackswap.Oauth;
import com.paperbackswap.Url.PbsUrlBuilder;
import gumi.builders.UrlBuilder;
import oauth.signpost.OAuthConsumer;
import oauth.signpost.OAuthProvider;
import oauth.signpost.OAuthProviderListener;
import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;
import oauth.signpost.commonshttp.CommonsHttpOAuthProvider;
import oauth.signpost.exception.*;
import oauth.signpost.http.HttpRequest;
import oauth.signpost.http.HttpResponse;
import oauth.signpost.signature.AuthorizationHeaderSigningStrategy;
import oauth.signpost.signature.HmacSha1MessageSigner;
import org.apache.commons.lang3.StringUtils;
import static com.paperbackswap.Url.PbsOAuthUrl.*;
@SuppressWarnings("UnusedDeclaration")
public class PbsOauth {
private boolean isAuthorizing;
private static OAuthConsumer consumer;
private static OAuthProvider provider;
private static final String USER_AGENT_HEADER = "User-Agent";
private static final String USER_AGENT = "pbs-api-client/1.3";
public PbsOauth(String apiKey, String apiSecret) {
consumer = new CommonsHttpOAuthConsumer(apiKey, apiSecret);
provider = new CommonsHttpOAuthProvider(
REQUEST_TOKEN,
ACCESS_TOKEN,
AUTHORIZE);
consumer.setSigningStrategy(new AuthorizationHeaderSigningStrategy());
consumer.setMessageSigner(new HmacSha1MessageSigner());
}
public PbsOauth(String apiKey, String apiSecret, String token, String secret) {
this(apiKey, apiSecret);
setTokenWithSecret(token, secret);
}
public synchronized void setTokenWithSecret(String token, String secret) {
consumer.setTokenWithSecret(token, secret);
}
public String getToken() {
return consumer.getToken();
}
public String getTokenSecret() {
return consumer.getTokenSecret();
}
public String getRequestTokenUrl() {
return provider.getRequestTokenEndpointUrl();
}
public String getAccessTokenUrl() {
return provider.getAccessTokenEndpointUrl();
}
/**
* Called to begin OAuth dance. Open the returned URL in a browser,
* @param callback URI to redirect to when authorization is complete, be sure to have listener configured.
* Listener will need to capture 'verifier' query parameter.
* isAuthorizing is set to true when this method is called.
* @return Token secret string
* @throws OAuthCommunicationException
* @throws OAuthExpectationFailedException
* @throws OAuthNotAuthorizedException
* @throws OAuthMessageSignerException
*/
public String getRequestTokenUrl(String callback) throws OAuthException {
isAuthorizing = true;
provider.setListener(new OAuthProviderListener() {
@Override
public void prepareRequest(HttpRequest request) throws Exception {
// Custom user agent
request.setHeader(USER_AGENT_HEADER, USER_AGENT);
}
@Override
public void prepareSubmission(HttpRequest request) throws Exception {
// System.out.println(request.getAllHeaders());
}
@Override
public boolean onResponseReceived(HttpRequest request, HttpResponse response) throws Exception {
// BasicHttpResponse responseObject = ((BasicHttpResponse) response.unwrap());
// System.out.println("Status: " + responseObject.getStatusLine().getStatusCode());
// String body = IOUtils.toString(responseObject.getEntity().getContent());
// System.out.println("Body: "+body);
// Header engineHeader = (Header) responseObject.getHeaders("Engine")[0];
// System.out.println("Engine: " + engineHeader.getValue());
return false;
}
});
//return provider.retrieveRequestToken(consumer, callback);
return OAuthBackoff.retrieveRequestTokenWithRetry(provider, consumer, callback);
}
/**
* Called to retrieve access token from OAuth provider once verifier has been retrieved from request token URI
* This implies user has authorized the initial request in a web browser.
* isAuthorizing is set to false if this succeeds.
*
* @param verifier Verifier as retrieved from request token URL, as called from getRequestTokenUri method.
*/
public void retrieveAccessToken(String verifier) throws OAuthException {
provider.setListener(new OAuthProviderListener() {
@Override
public void prepareRequest(HttpRequest request) throws Exception {
request.setHeader(USER_AGENT_HEADER, USER_AGENT);
}
@Override
public void prepareSubmission(HttpRequest request) throws Exception {
}
@Override
public boolean onResponseReceived(HttpRequest request, HttpResponse response) throws Exception {
return false;
}
});
provider.setOAuth10a(true); //This is SUPER important...won't work without it
//provider.retrieveAccessToken(consumer, verifier);
provider = OAuthBackoff.retrieveAccessTokenWithRetry(provider, consumer, verifier);
isAuthorizing = false; // authorization dance is complete
}
// Keep track of whether the app is in the oauth dance
public boolean isAuthorizing() {
return isAuthorizing;
}
/**
* Checks to see if the user has been authorized to make API calls with the app
*
* @return Determines if all OAuth 1.0 keys are present and isn't currently in OAuth dance
*/
public boolean isAuthorized() {
return (!StringUtils.isEmpty(consumer.getToken()) &&
!StringUtils.isEmpty(consumer.getTokenSecret())&&
!isAuthorizing());
}
/**
* Adds OAuth signature query params to URL
*
* @param url URL to have OAuth parameters added
* @return Uses provided OAuth 1.0a key/token to create fresh OAuth query params
*/
public static String signRequest(String url) throws OAuthCommunicationException, OAuthExpectationFailedException, OAuthMessageSignerException {
return consumer.sign(PbsUrlBuilder.fromUrl(url).withoutOAuthQuery().toString());
}
/**
* Checks to see if the provided URL has OAuth 1.0a query parameters
* @param url Any URL with OAuth 1.0a query params
* @return True if OAuth 1.0a query params are in provided URL
*/
public static boolean isSigned(String url) {
UrlBuilder builder = UrlBuilder.fromString(url);
for (String key : PARAMETERS) {
if (!builder.queryParameters.containsKey(key)) {
return false;
}
}
return true;
}
} |
package com.pesegato.MonkeySheet;
import com.jme3.texture.Texture;
/**
* @author Pesegato
*/
public class MSFrame {
int position;
int sheet;
Texture sheetX;
public MSFrame(int position, int sheet) {
this.position = position;
this.sheet = sheet;
}
public int getPosition() {
return position;
}
public void setTexture(Texture sheetX) {
this.sheetX = sheetX;
}
} |
package com.redhat.victims;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.jar.Attributes;
import org.apache.commons.io.FilenameUtils;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.internal.LinkedHashTreeMap;
import com.redhat.victims.fingerprint.Algorithms;
import com.redhat.victims.fingerprint.Artifact;
import com.redhat.victims.fingerprint.Fingerprint;
import com.redhat.victims.fingerprint.Metadata;
/**
* This is the java class relating to victims records.
*
* @author gcmurphy
* @author abn
*
*/
public class VictimsRecord {
public static final String DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss";
public static final String SCHEMA_VERSION = "2.0";
// structure info
public String db_version = SCHEMA_VERSION;
// record information
public RecordStatus status;
public Integer id;
public Date date;
public Date submittedon;
public String submitter;
// entry information
public ArrayList<String> cves;
public String name;
public String format;
public String vendor;
public String version;
public ArrayList<MetaRecord> meta;
public String hash;
public HashRecords hashes;
public static VictimsRecord fromJSON(String jsonStr) {
Gson gson = new GsonBuilder().setDateFormat(DATE_FORMAT).create();
return gson.fromJson(jsonStr, VictimsRecord.class);
}
public String toString() {
Gson gson = new GsonBuilder().setDateFormat(DATE_FORMAT).create();
return gson.toJson(this);
}
private void setFromMetadata(Metadata md) {
// TODO: add pom.properties support?
String vendorkey = Attributes.Name.IMPLEMENTATION_VENDOR.toString();
String versionkey = Attributes.Name.IMPLEMENTATION_VERSION.toString();
String namekey = Attributes.Name.IMPLEMENTATION_TITLE.toString();
if (this.vendor == null) {
this.vendor = md.get(vendorkey);
}
if (this.version == null) {
this.version = md.get(versionkey);
}
if (this.name == null) {
this.name = md.get(namekey);
}
}
public VictimsRecord(Artifact artifact) {
this.status = RecordStatus.NEW;
this.meta = new ArrayList<MetaRecord>();
this.hashes = new HashRecords();
this.cves = new ArrayList<String>();
// Process the metadatas if available
HashMap<String, Metadata> metadatas = artifact.metadata();
if (metadatas != null) {
for (Object key : metadatas.keySet()) {
Metadata md = metadatas.get(key);
setFromMetadata(md);
MetaRecord mr = new MetaRecord();
mr.put(FieldName.META_FILENAME, key);
mr.put(FieldName.META_PROPERTIES, md);
meta.add(mr);
}
}
this.format = FormatMap.mapType(artifact.filetype());
if (this.name == null) {
// If metadata did not provide a name then use filename
this.name = FilenameUtils.getBaseName(artifact.filename());
}
// Reorganize hashes if available
ArrayList<Artifact> artifacts = artifact.contents();
if (artifacts != null) {
for (Artifact file : artifacts) {
if (file.filetype().equals(".class")) {
Fingerprint fingerprint = file.fingerprint();
if (fingerprint != null) {
for (Algorithms alg : fingerprint.keySet()) {
String key = normalizeKey(alg);
if (!this.hashes.containsKey(key)) {
Record hashRecord = new Record();
hashRecord.put(FieldName.FILE_HASHES,
new StringMap());
hashRecord.put(FieldName.COMBINED_HASH,
artifact.fingerprint().get(alg));
this.hashes.put(key, hashRecord);
}
((StringMap) this.hashes.get(key).get(
FieldName.FILE_HASHES)).put(
fingerprint.get(alg), file.filename());
}
}
}
}
}
// Get the hash for the file
this.hash = artifact.fingerprint().get(Algorithms.SHA512);
}
/**
* Handles difference in the keys used for algorithms
*
* @param alg
* @return
*/
public static String normalizeKey(Algorithms alg) {
if (alg.equals(Algorithms.SHA512)) {
return FieldName.SHA512;
}
return alg.toString().toLowerCase();
}
public static enum RecordStatus {
SUBMITTED, RELEASED, NEW
};
public static class FieldName {
public static final String FILE_HASHES = "files";
public static final String COMBINED_HASH = "combined";
public static final String SHA512 = "sha512";
public static final String META_PROPERTIES = "properties";
public static final String META_FILENAME = "filename";
}
public static class FormatMap {
protected static HashMap<String, String> MAP = new HashMap<String, String>();
static {
MAP.put(".jar", "Jar");
MAP.put(".class", "Class");
MAP.put(".pom", "Pom");
}
public static String mapType(String filetype) {
if (MAP.containsKey(filetype.toLowerCase())) {
return MAP.get(filetype.toLowerCase());
}
return "Unknown";
}
}
@SuppressWarnings("serial")
public static class StringMap extends HashMap<String, String> {
}
@SuppressWarnings("serial")
public static class Record extends HashMap<String, Object> {
}
@SuppressWarnings("serial")
public static class HashRecords extends HashMap<String, Record> {
}
@SuppressWarnings("serial")
public static class MetaRecord extends Record {
public static final ArrayList<Class<?>> PERMITTED_VALUE_TYPES = new ArrayList<Class<?>>();
static {
PERMITTED_VALUE_TYPES.add(Metadata.class);
PERMITTED_VALUE_TYPES.add(String.class);
PERMITTED_VALUE_TYPES.add(LinkedHashTreeMap.class);
}
@Override
public Object put(String key, Object value) {
if (!PERMITTED_VALUE_TYPES.contains(value.getClass())) {
System.out.println(key.toString());
throw new IllegalArgumentException(String.format(
"Values of class type <%s> are not permitted in <%s>",
value.getClass().getName(), this.getClass().getName()));
}
return super.put(key, value);
}
}
} |
package com.sandwell.JavaSimulation;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
public class Util {
private static String cargoUnits = "";
private static String cargoUnitsPerHour = "";
public static final Comparator<Entity> nameSort = new Comparator<Entity>() {
@Override
public int compare(Entity a, Entity b) {
return a.getName().compareTo(b.getName());
}
};
public static String getCargoUnits() {
return cargoUnits;
}
public static String getCargoUnitsPerHour() {
return cargoUnitsPerHour;
}
public static void setCargoUnits(String units) {
cargoUnits = units;
cargoUnitsPerHour = cargoUnits + "/h";
}
/**
*
*
* { aaa, bbb, ccc, ddd }
* { ", bbb, ccc, ddd }
* { aaa, bbb, ", ddd }
* { "aaa, bbb, ccc, ddd }
* { aaa, bbb, "ccc, ddd }
* { a"aa, bbb, ccc, ddd } <-- disregard this possibility
* { aaa, bbb, cc"c, ddd } <-- disregard this possibility
*
*
* Returns true if record is not empty; false, otherwise.
*
*/
public static boolean discardComment( Vector record ) {
boolean containsCmd;
int recSize;
int indexFirst; // Index of first cell containing a string that starts with "
if ( record == null ) {
return false;
}
recSize = record.size();
if ( recSize == 0 ) {
return false;
}
// Find in record the index of the first cell that contains string of the form "aaa.
// Disregard strings of the forms aaa"bbb and aaa"
indexFirst = recSize;
for ( int i = 0; i < recSize; i++ ) {
if ( ((String)record.get(i)).startsWith( "\"" )) {
indexFirst = i;
break;
}
}
// Strip away comment string from record. Return true if record contains a command; false, otherwise
// Note that indexFirst cannot be greater than recSize
if ( indexFirst == recSize ) { // no comments found
containsCmd = true;
}
else if ( indexFirst > 0 ) { // command and comment found
containsCmd = true;
// Discard elements from index to (recSize - 1)
for ( int x = indexFirst; x < recSize; x++ ) {
record.removeElementAt( indexFirst );
}
}
else { // if (indexFirst == 0), it means that record contains only comment
containsCmd = false;
record.clear();
}
return containsCmd;
} // discardComment
/**
* if ( fileFullName = "C:\Projects\A01.cfg" ), returns "A01.cfg"
* if ( fileFullName = "A01.cfg" ), returns "A01.cfg"
*/
public static String fileShortName( String fileFullName ) {
int indexLast = fileFullName.lastIndexOf( '\\' );
indexLast = Math.max( indexLast, fileFullName.lastIndexOf( '/') );
String fileName = fileFullName.substring( indexLast + 1 );
return fileName;
}
public static String getAbsoluteFilePath( String filePath ) {
String absoluteFilePath;
try {
java.io.File absFile = new java.io.File( filePath );
if( absFile.isAbsolute() ) {
absoluteFilePath = absFile.getCanonicalPath();
if(absFile.isFile()) {
absoluteFilePath = "file:/" + absoluteFilePath;
}
else {
absoluteFilePath += System.getProperty( "file.separator" );
}
}
else {
// For absolute files inside the resource folder of the jar file
if (Simulation.class.getResource(filePath) != null) {
absoluteFilePath = Simulation.class.getResource(filePath).toString();
}
else {
// Does the relative filepath exist inside the jar file?
String relativeURL = FileEntity.getRelativeURL( filePath );
if (Simulation.class.getResource(relativeURL) != null) {
absoluteFilePath = Simulation.class.getResource(relativeURL).getFile();
}
else {
absoluteFilePath = FileEntity.getRootDirectory() + System.getProperty( "file.separator" ) + filePath;
absoluteFilePath = FileEntity.getRelativeURL(absoluteFilePath);
if(FileEntity.fileExists(absoluteFilePath)) {
absoluteFilePath = "file:/" + absoluteFilePath;
}
}
}
}
}
catch( Exception e ) {
throw new ErrorException( e );
}
return absoluteFilePath;
}
public static String getFileExtention(String name){
if(name.indexOf(".") < 0)
return "";
String ext = name.substring( name.lastIndexOf(".")).trim();
return ext.replace(".", "").toUpperCase();
}
/**
* Expects a StringVector of one of two forms:
* 1. { entry entry entry } { entry entry entry }
* 2. entry entry entry
* If format 1, returns a vector of stringvectors without braces.
* if format 2, returns a vector of a stringvector, size1.
* @param data
* @return
*/
public static ArrayList<StringVector> splitStringVectorByBraces(StringVector data) {
ArrayList<StringVector> newData = new ArrayList<StringVector>();
for (int i=0; i < data.size(); i++) {
//skip over opening brace if present
if (data.get(i).equals("{") )
continue;
StringVector cmd = new StringVector();
//iterate until closing brace, or end of entry
for (int j = i; j < data.size(); j++, i++){
if (data.get(j).equals("}"))
break;
cmd.add(data.get(j));
}
//add to vector
newData.add(cmd);
}
return newData;
}
private static class CriteriaHolder implements Comparable<CriteriaHolder> {
private final Object obj;
private final double crit1;
private final double crit2;
private final double crit3;
private final double crit4;
private final double crit5;
CriteriaHolder(Object obj, double c1, double c2, double c3, double c4, double c5) {
this.obj = obj;
crit1 = c1;
crit2 = c2;
crit3 = c3;
crit4 = c4;
crit5 = c5;
}
@Override
/**
* We sort from largest to smallest, so reverse the order in Double.compare.
*/
public int compareTo(CriteriaHolder u) {
int comp;
comp = Double.compare(u.crit1, this.crit1);
if (comp != 0)
return comp;
comp = Double.compare(u.crit2, this.crit2);
if (comp != 0)
return comp;
comp = Double.compare(u.crit3, this.crit3);
if (comp != 0)
return comp;
comp = Double.compare(u.crit4, this.crit4);
if (comp != 0)
return comp;
return Double.compare(u.crit5, this.crit5);
}
}
public static void mergeSort(Vector objectsToSort, DoubleVector crit1) {
mergeSort(objectsToSort, crit1, crit1, crit1, crit1, crit1);
}
public static void mergeSort(Vector objectsToSort, DoubleVector crit1,
DoubleVector crit2) {
mergeSort(objectsToSort, crit1, crit2, crit2, crit2, crit2);
}
public static void mergeSort(Vector objectsToSort, DoubleVector crit1,
DoubleVector crit2, DoubleVector crit3,
DoubleVector crit4, DoubleVector crit5) {
ArrayList<CriteriaHolder> temp = new ArrayList<Util.CriteriaHolder>(objectsToSort.size());
for (int i = 0; i < objectsToSort.size(); i++) {
temp.add(new CriteriaHolder(objectsToSort.get(i), crit1.get(i), crit2.get(i), crit3.get(i), crit4.get(i), crit5.get(i)));
}
Collections.sort(temp);
objectsToSort.clear();
for (int i = 0; i < temp.size(); i++) {
objectsToSort.add(temp.get(i).obj);
}
}
/**
* Returns the pixel length of the string with specified font
* @param str
* @param font
* @return
*/
public static int getPixelWidthOfString_ForFont( String str, Font font ) {
FontMetrics metrics = new FontMetrics(font) { };
Rectangle2D bounds = metrics.getStringBounds( str, null);
return (int) bounds.getWidth();
}
public static String HTMLString(String font, String size, String backgroundColor, String color, String accent, String text) {
StringBuilder ret = new StringBuilder("<html><pre style=\"font-family:");
if (font == null)
ret.append("verdana");
else
ret.append(font);
if (size != null) {
ret.append(";font-size:");
ret.append(size);
}
if (backgroundColor != null) {
ret.append(";background-color:");
ret.append(backgroundColor);
}
if (color != null) {
ret.append(";color:");
ret.append(color);
}
ret.append("\">");
if (accent != null) {
ret.append(accent);
}
ret.append(text);
return ret.toString();
}
} |
package com.stripe.sdk.util;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import com.google.gson.Gson;
import com.stripe.sdk.model.Charge;
import com.stripe.sdk.model.Customer;
import com.stripe.sdk.model.DeleteResponse;
import com.stripe.sdk.model.Invoice;
import com.stripe.sdk.model.InvoiceItem;
import com.stripe.sdk.model.StripeErrorResponse;
import com.stripe.sdk.model.Subscription;
import com.stripe.sdk.exception.StripeBadRequestException;
import com.stripe.sdk.exception.StripeException;
import com.stripe.sdk.exception.StripeNotFoundException;
import com.stripe.sdk.exception.StripeRequestFailedException;
import com.stripe.sdk.exception.StripeServerErrorException;
import com.stripe.sdk.exception.StripeUnauthorizedException;
public class StripeClient {
protected static final String ENDPOINT = "api.stripe.com";
protected static final String PROTOCOL = "https";
protected static final String BASEPATH = "/v1/";
protected static String key = "";
protected static Gson gson = new Gson();
public static Charge newCharge(long amount, String currency,
String customer, String card) throws Exception {
String[] params = { "amount", "currency", "customer", "card" };
String[] values = { amount + "", currency, customer, card };
String response = makeRequest("charges", "POST", params, values);
return gson.fromJson(response, Charge.class);
}
public static Charge newCharge(long amount, String currency,
String cardNumber, String cardExpMonth, String cardExpYear,
String cardCVC, String cardName, String cardAddressLine1,
String cardAddressLine2, String cardAddressZip,
String cardAddressState, String cardAddressCountry)
throws Exception {
String[] params = { "amount", "currency", "card[number]",
"card[exp_month]", "card[exp_year]", "card[cvc]", "card[name]",
"card[address_line1]", "card[address_line2]",
"card[address_state]", "card[address_zip]",
"card[address_country]" };
String[] values = { amount + "", currency, cardNumber, cardExpMonth,
cardExpYear, cardCVC, cardName, cardAddressLine1,
cardAddressLine2, cardAddressState, cardAddressZip,
cardAddressCountry };
String response = makeRequest("charges", "POST", params, values);
return gson.fromJson(response, Charge.class);
}
public static Charge getCharge(String id) throws Exception {
String response = makeRequest("charges/" + id, "GET", null, null);
return gson.fromJson(response, Charge.class);
}
public static Charge refundCharge(String id) throws Exception {
String response = makeRequest("charges/" + id + "/refund", "POST",
null, null);
return gson.fromJson(response, Charge.class);
}
public static Charge[] getCharges() throws Exception {
return getCharges(10, 0);
}
public static Charge[] getCharges(int count, int offset) throws Exception {
return getCharges(count, offset, null);
}
public static Charge[] getCharges(int count, int offset, String customer)
throws Exception {
String[] params = { "count", "offset", "customer" };
String[] values = { count + "", offset + "", customer };
String response = makeRequest("charges", "GET", params, values);
return gson.fromJson(response, Charge[].class);
}
public static Customer newCustomer(String email, String description)
throws Exception {
return newCustomer(null, email, description, null, null);
}
public static Customer newCustomer(String coupon, String email,
String description) throws Exception {
return newCustomer(coupon, email, description, null, null);
}
public static Customer newCustomer(String coupon, String email,
String description, String plan, Long trialEnd) throws Exception {
return newCustomer(coupon, email, description, plan, trialEnd, null,
null, null, null, null, null, null, null, null, null);
}
public static Customer newCustomer(String coupon, String email,
String description, String plan, Long trialEnd, String cardNumber,
String cardExpMonth, String cardExpYear, String cardCVC,
String cardName, String cardAddressLine1, String cardAddressLine2,
String cardAddressZip, String cardAddressState,
String cardAddressCountry) throws Exception {
String[] params = { "coupon", "email", "description", "plan",
"trial_end", "card[number]", "card[exp_month]",
"card[exp_year]", "card[cvc]", "card[name]",
"card[address_line1]", "card[address_line2]",
"card[address_state]", "card[address_zip]",
"card[address_country]" };
String[] values = { coupon, email, description, plan,
trialEnd == null ? null : trialEnd + "", cardNumber,
cardExpMonth, cardExpYear, cardCVC, cardName, cardAddressLine1,
cardAddressLine2, cardAddressState, cardAddressZip,
cardAddressCountry };
String response = makeRequest("customers", "POST", params, values);
return gson.fromJson(response, Customer.class);
}
public static Customer getCustomer(String id) throws Exception {
String response = makeRequest("customers/" + id, "GET", null, null);
return gson.fromJson(response, Customer.class);
}
public static Customer updateCustomer(String id, String[] fields,
String[] values) throws Exception {
String response = makeRequest("customers/" + id, "POST", fields, values);
return gson.fromJson(response, Customer.class);
}
public static DeleteResponse deleteCustomer(String id) throws Exception {
String response = makeRequest("customers/" + id, "DELETE", null, null);
return gson.fromJson(response, DeleteResponse.class);
}
public static Customer[] getCustomers() throws Exception {
return getCustomers(10, 0);
}
public static Customer[] getCustomers(int count, int offset)
throws Exception {
String[] params = { "count", "offset" };
String[] values = { count + "", offset + "" };
String response = makeRequest("customers", "GET", params, values);
return gson.fromJson(response, Customer[].class);
}
public static Subscription updateSubscription(String customer, String plan,
String coupon, Boolean prorate, Long trialEnd, String cardNumber,
String cardExpMonth, String cardExpYear, String cardCVC,
String cardName, String cardAddressLine1, String cardAddressLine2,
String cardAddressZip, String cardAddressState,
String cardAddressCountry) throws Exception {
String[] params = { "plan", "coupon", "prorate", "trial_end",
"card[exp_month]", "card[exp_year]", "card[cvc]", "card[name]",
"card[address_line1]", "card[address_line2]",
"card[address_state]", "card[address_zip]",
"card[address_country]" };
String[] values = { plan, coupon, prorate.toString(), trialEnd + "",
cardNumber, cardExpMonth, cardExpYear, cardCVC, cardName,
cardAddressLine1, cardAddressLine2, cardAddressState,
cardAddressZip, cardAddressCountry };
String response = makeRequest(
"customers/" + customer + "/subscription", "POST", params,
values);
return gson.fromJson(response, Subscription.class);
}
public static Subscription cancelSubscription(String customer,
Boolean atPeriodEnd) throws Exception {
String[] params = { "at_period_end" };
String[] values = { atPeriodEnd.toString() };
String response = makeRequest(
"customers/" + customer + "/subscription", "DELETE", params,
values);
return gson.fromJson(response, Subscription.class);
}
public static InvoiceItem createInvoiceItem(String customer, long amount,
String currency, String description) throws Exception {
String[] params = { "customer", "amount", "currency", "description" };
String[] values = { customer, amount + "", currency, description };
String response = makeRequest("invoiceitems", "POST", params, values);
return gson.fromJson(response, InvoiceItem.class);
}
public static InvoiceItem getInvoiceItem(String id) throws Exception {
String response = makeRequest("invoiceitems/" + id, "GET", null, null);
return gson.fromJson(response, InvoiceItem.class);
}
public static InvoiceItem updateInvoiceItem(String id, long amount,
String currency, String description) throws Exception {
String[] params = { "amount", "currency", "description" };
String[] values = { amount + "", currency, description };
String response = makeRequest("invoiceitems/" + id, "POST", params,
values);
return gson.fromJson(response, InvoiceItem.class);
}
public static InvoiceItem deleteInvoiceItem(String id) throws Exception {
String response = makeRequest("invoiceitems/" + id, "DELETE", null,
null);
return gson.fromJson(response, InvoiceItem.class);
}
public static InvoiceItem[] getInvoiceItems(String customer)
throws Exception {
return getInvoiceItems(customer, 10, 0);
}
public static InvoiceItem[] getInvoiceItems(int count, int offset)
throws Exception {
return getInvoiceItems(null, count, offset);
}
public static InvoiceItem[] getInvoiceItems(String customer, int count,
int offset) throws Exception {
String[] params = { "customer", "count", "offset" };
String[] values = { customer, count + "", offset + "" };
String response = makeRequest("invoiceitems", "GET", params, values);
return gson.fromJson(response, InvoiceItem[].class);
}
public static Invoice getInvoice(String id) throws Exception {
String response = makeRequest("invoices/" + id, "GET", null, null);
return gson.fromJson(response, Invoice.class);
}
public static Invoice[] getInvoices(String customer) throws Exception {
return getInvoices(customer, 10, 0);
}
public static Invoice[] getInvoices(int count, int offset) throws Exception {
return getInvoices(null, count, offset);
}
public static Invoice[] getInvoices(String customer, int count, int offset)
throws Exception {
String[] params = { "customer", "count", "offset" };
String[] values = { customer, count + "", offset + "" };
String response = makeRequest("invoiceitems", "GET", params, values);
return gson.fromJson(response, Invoice[].class);
}
public static Invoice getUpcomingInvoice(String customer) throws Exception {
String[] params = { "customer" };
String[] values = { customer };
String response = makeRequest("invoices/upcoming", "GET", params,
values);
return gson.fromJson(response, Invoice.class);
}
public static void setKey(String aKey) {
key = aKey;
}
public static String makeRequest(String path, String method,
String[] params, String[] values) throws Exception {
String query = "";
String data = "";
if (params != null && values != null) {
for (int i = 0; i < params.length; i++) {
if (values[i] != null) {
if (method == "POST") {
data += "&" + params[i] + "=" + values[i];
} else {
query += "&" + params[i] + "=" + values[i];
}
}
}
}
URI uri = new URI(PROTOCOL, ENDPOINT, BASEPATH + path, query, null);
URL url = uri.toURL();
return makeTheRequest(url, method, data);
}
protected static String makeTheRequest(URL url, String method, String data)
throws Exception {
String ret = null;
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Authorization", "Basic " + key);
conn.setRequestMethod(method);
conn.setUseCaches(false);
if (method == "POST") {
conn.setDoOutput(true);
OutputStreamWriter osw = new OutputStreamWriter(
conn.getOutputStream());
osw.write(data);
osw.close();
} else {
conn.connect();
}
BufferedReader br = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
String line;
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null) {
sb.append(line);
}
ret = sb.toString();
if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
Gson gson = new Gson();
StripeErrorResponse err = gson.fromJson(ret,
StripeErrorResponse.class);
StripeException ex = new StripeException();
switch (conn.getResponseCode()) {
case HttpURLConnection.HTTP_BAD_REQUEST:
ex = new StripeBadRequestException();
break;
case HttpURLConnection.HTTP_UNAUTHORIZED:
ex = new StripeUnauthorizedException();
break;
case HttpURLConnection.HTTP_PAYMENT_REQUIRED:
StripeRequestFailedException rex = new StripeRequestFailedException();
rex.setType(err.error.type);
rex.setCode(err.error.code);
rex.setParam(err.error.param);
ex = rex;
break;
case HttpURLConnection.HTTP_NOT_FOUND:
ex = new StripeNotFoundException();
break;
case 500:
case 502:
case 503:
case 504:
ex = new StripeServerErrorException();
break;
}
ex.setStatusCode(conn.getResponseCode());
ex.setMessage(err.error.message);
throw ex;
}
return ret;
}
} |
// java-signals
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
// included in all copies or substantial portions of the Software.
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
package com.threerings.signals;
import java.lang.ref.WeakReference;
import java.util.Collections;
import java.util.concurrent.CopyOnWriteArrayList;
import com.google.common.primitives.Ints;
/**
* The workhorse that does all the connection management and dispatching for the arity types. Not
* part of the public API.
*/
class Signaller
{
@SuppressWarnings("rawtypes")
public Connection connect (Object listener, int priority)
{
if (listener instanceof Listener3) {
return new Connection3Impl((Listener3)listener, priority);
} else if (listener instanceof Listener2) {
return new Connection2Impl((Listener2)listener, priority);
} else if (listener instanceof Listener1) {
return new Connection1Impl((Listener1)listener, priority);
} else {
return new Connection0Impl((Listener0)listener, priority);
}
}
public void disconnect (Object listener)
{
for (ConnectionImpl<?> conn : _observers) {
if (conn.get() == listener) {
conn.disconnect();
return;
}
}
}
public void dispatch (Object...args)
{
for (ConnectionImpl<?> conn : _observers) {
if (!conn.apply(args)) {
conn.disconnect();
}
}
}
protected abstract class ConnectionImpl<L>
implements Connection, Comparable<ConnectionImpl<?>> {
public ConnectionImpl (L listener, int priority) {
Signaller.this.disconnect(listener);
_priority = priority;
_listener = listener;
_ref = new WeakReference<L>(_listener);
synchronized (_observers) {
int idx = Collections.binarySearch(_observers, this);
if (idx < 0) {
// Nothing with this priority in the list, so use binarySearch's idx
idx = -idx - 1;
} else {
// Found something with the priority, so sort past items at the same priority
while (idx < _observers.size() && _priority == _observers.get(idx)._priority) {
idx++;
}
}
_observers.add(idx, this);
}
}
public L get () {
return _listener == null ? _ref.get() : _listener;
}
public void disconnect () {
_connected = false;
synchronized (_observers) {
_observers.remove(this);
}
}
public Connection once () {
_stayInList = false;
return this;
}
public Connection makeWeak () {
_listener = null;
return this;
}
public boolean apply (Object...args) {
if (!_connected) { return true; }
// Get a reference to listener before calling apply in case we're made weak
L listener = _listener;
if (listener != null) {
applyToArity(listener, args);
} else {
listener = _ref.get();
if (listener != null) {
applyToArity(listener, args);
} else {
return true;// We've been collected; remove us from the dispatch list
}
}
return _stayInList;
}
public int compareTo (ConnectionImpl<?> other) {
return Ints.compare(other._priority, _priority);
}
protected abstract void applyToArity(L listener, Object...args);
protected L _listener;
protected boolean _stayInList = true;
protected volatile boolean _connected = true;
protected final WeakReference<L> _ref;
protected final int _priority;
}
protected class Connection0Impl extends ConnectionImpl<Listener0> {
public Connection0Impl (Listener0 listener, int priority) {
super(listener, priority);
}
@Override protected void applyToArity (Listener0 listener, Object...args) {
listener.apply();
}
}
protected class Connection1Impl extends ConnectionImpl<Listener1<?>> {
public Connection1Impl (Listener1<?> listener, int priority) {
super(listener, priority);
}
@Override @SuppressWarnings({"unchecked", "rawtypes"})
protected void applyToArity (Listener1 listener, Object...args) {
listener.apply(args[0]);
}
}
protected class Connection2Impl extends ConnectionImpl<Listener2<?, ?>> {
public Connection2Impl (Listener2<?, ?> listener, int priority) {
super(listener, priority);
}
@Override @SuppressWarnings({"unchecked", "rawtypes"})
protected void applyToArity (Listener2 listener, Object...args) {
listener.apply(args[0], args[1]);
}
}
protected class Connection3Impl extends ConnectionImpl<Listener3<?, ?, ?>> {
public Connection3Impl (Listener3<?, ?, ?> listener, int priority) {
super(listener, priority);
}
@Override @SuppressWarnings({"unchecked", "rawtypes"})
protected void applyToArity (Listener3 listener, Object...args) {
listener.apply(args[0], args[1], args[2]);
}
}
/** Connections to the signal sorted by priority and then insertion order. */
protected final CopyOnWriteArrayList<ConnectionImpl<?>> _observers =
new CopyOnWriteArrayList<Signaller.ConnectionImpl<?>>();
} |
package com.tmitim.twittercli;
import java.util.stream.Stream;
import com.github.rvesse.airline.annotations.Cli;
import com.tmitim.twittercli.commands.DirectMessage;
import com.tmitim.twittercli.commands.Favorite;
import com.tmitim.twittercli.commands.Help;
import com.tmitim.twittercli.commands.Location;
import com.tmitim.twittercli.commands.TimeLineCommand;
import com.tmitim.twittercli.commands.Trend;
import com.tmitim.twittercli.commands.Tweet;
import com.tmitim.twittercli.commands.Search;
@Cli(
name = "twitter",
description = "Twitter CLI", defaultCommand = TimeLineCommand.class,
commands = { Tweet.class, TimeLineCommand.class, Location.class, Trend.class, Search.class, DirectMessage.class,
Favorite.class, Help.class }
)
public class TwitterCli {
public static void main(String[] args) {
com.github.rvesse.airline.Cli<Runnable> cli = new com.github.rvesse.airline.Cli<>(TwitterCli.class);
if (Stream.of(args).anyMatch(x -> x.equals("--version") || x.equals(("-v")))) {
String version = TwitterCli.class.getPackage().getImplementationVersion();
System.out.println(String.format("TwitterCLI4j: %s", version));
return;
}
try {
Runnable cmd = cli.parse(args);
cmd.run();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
} |
package com.uwetrottmann.thetvdb;
import com.uwetrottmann.thetvdb.services.Authentication;
import com.uwetrottmann.thetvdb.services.Search;
import com.uwetrottmann.thetvdb.services.Series;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import java.io.IOException;
@SuppressWarnings("WeakerAccess")
public class TheTvdb {
public static final String API_URL = "https://api.thetvdb.com";
public static final String API_VERSION = "2.0.0";
private static final String HEADER_ACCEPT = "Accept";
public static final String HEADER_ACCEPT_LANGUAGE = "Accept-Language";
private static final String HEADER_AUTHORIZATION = "Authorization";
private Retrofit retrofit;
private HttpLoggingInterceptor logging;
private boolean isDebug;
private String jsonWebToken;
/**
* Create a new manager instance.
*/
public TheTvdb() {
}
public TheTvdb setJsonWebToken(String value) {
this.jsonWebToken = value;
retrofit = null;
return this;
}
/**
* Set the default logging interceptors log level.
*
* @param isDebug If true, the log level is set to {@link HttpLoggingInterceptor.Level#BODY}. Otherwise {@link
* HttpLoggingInterceptor.Level#NONE}.
* @see #okHttpClientBuilder()
*/
public TheTvdb setIsDebug(boolean isDebug) {
this.isDebug = isDebug;
if (logging != null) {
logging.setLevel(isDebug ? HttpLoggingInterceptor.Level.BODY : HttpLoggingInterceptor.Level.NONE);
}
return this;
}
/**
* Creates a {@link Retrofit.Builder} that sets the base URL, adds a Gson converter and sets {@link
* #okHttpClientBuilder()} as its client.
* <p>
* Override this to for example set your own call executor.
*
* @see #okHttpClientBuilder()
*/
protected Retrofit.Builder retrofitBuilder() {
return new Retrofit.Builder()
.baseUrl(API_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(okHttpClientBuilder().build());
}
/**
* Creates a {@link OkHttpClient.Builder} for usage with {@link #retrofitBuilder()}. Adds interceptors to add auth
* headers and to log requests.
* <p>
* Override this to for example add your own interceptors.
*
* @see #retrofitBuilder()
*/
protected OkHttpClient.Builder okHttpClientBuilder() {
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request.Builder builder = chain.request().newBuilder();
builder.header(HEADER_ACCEPT, "application/vnd.thetvdb.v" + API_VERSION);
if (jsonWebToken != null && jsonWebToken.length() != 0) {
builder.header(HEADER_AUTHORIZATION, "Bearer" + " " + jsonWebToken);
}
return chain.proceed(builder.build());
}
});
if (isDebug) {
logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
builder.addInterceptor(logging);
}
return builder;
}
/**
* Return the current {@link Retrofit} instance. If none exists (first call, auth changed), builds a new one. <p/>
* <p>When building, sets the base url and a custom client with an {@link Interceptor} which supplies
* authentication
* data.
*/
protected Retrofit getRetrofit() {
if (retrofit == null) {
retrofit = retrofitBuilder().build();
}
return retrofit;
}
/**
* Obtaining and refreshing your JWT token.
*/
public Authentication authentication() {
return getRetrofit().create(Authentication.class);
}
/**
* Information about a specific series.
*/
public Series series() {
return getRetrofit().create(Series.class);
}
/**
* Search for a particular series.
*/
public Search search() {
return getRetrofit().create(Search.class);
}
} |
package crazypants.enderio.config;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import net.minecraft.item.ItemStack;
import net.minecraftforge.common.config.Configuration;
import tterrag.core.common.event.ConfigFileChangedEvent;
import cpw.mods.fml.client.event.ConfigChangedEvent.OnConfigChangedEvent;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.Optional.Method;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.common.registry.GameRegistry;
import crazypants.enderio.EnderIO;
import crazypants.enderio.Log;
import crazypants.enderio.machine.obelisk.weather.TileWeatherObelisk.WeatherTask;
import crazypants.vecmath.VecmathUtil;
public final class Config {
public static class Section {
public final String name;
public final String lang;
public Section(String name, String lang) {
this.name = name;
this.lang = lang;
register();
}
private void register() {
sections.add(this);
}
public String lc() {
return name.toLowerCase();
}
}
public static final List<Section> sections;
static {
sections = new ArrayList<Section>();
}
public static Configuration config;
public static final Section sectionPower = new Section("Power Settings", "power");
public static final Section sectionRecipe = new Section("Recipe Settings", "recipe");
public static final Section sectionItems = new Section("Item Enabling", "item");
public static final Section sectionEfficiency = new Section("Efficiency Settings", "efficiency");
public static final Section sectionPersonal = new Section("Personal Settings", "personal");
public static final Section sectionAnchor = new Section("Anchor Settings", "anchor");
public static final Section sectionStaff = new Section("Staff Settings", "staff");
public static final Section sectionDarkSteel = new Section("Dark Steel", "darksteel");
public static final Section sectionFarm = new Section("Farm Settings", "farm");
public static final Section sectionAesthetic = new Section("Aesthetic Settings", "aesthetic");
public static final Section sectionAdvanced = new Section("Advanced Settings", "advanced");
public static final Section sectionMagnet = new Section("Magnet Settings", "magnet");
public static final Section sectionFluid = new Section("Fluid Settings", "fluid");
public static final Section sectionSpawner = new Section("PoweredSpawner Settings", "spawner");
public static final Section sectionKiller = new Section("Killer Joe Settings", "killerjoe");
public static final Section sectionSoulBinder = new Section("Soul Binder Settings", "soulBinder");
public static final Section sectionAttractor = new Section("Mob Attractor Settings", "attractor");
public static final Section sectionLootConfig = new Section("Loot Config", "lootconfig");
public static final Section sectionMobConfig = new Section("Mob Config", "mobconfig");
public static final Section sectionRailConfig = new Section("Rail", "railconfig");
public static final Section sectionEnchantments = new Section("Enchantments", "enchantments");
public static final Section sectionWeather = new Section("Weather", "weather");
public static final Section sectionTelepad = new Section("Telepad", "telepad");
public static final Section sectionInventoryPanel = new Section("InventoryPanel", "inventorypanel");
public static final Section sectionMisc = new Section("Misc", "misc");
public static final double DEFAULT_CONDUIT_SCALE = 0.6;
public static boolean reinforcedObsidianEnabled = true;
public static boolean reinforcedObsidianUseDarkSteelBlocks = false;
public static boolean useAlternateBinderRecipe = false;
public static boolean useAlternateTesseractModel = false;
public static boolean photovoltaicCellEnabled = true;
public static boolean reservoirEnabled = true;
public static double conduitScale = DEFAULT_CONDUIT_SCALE;
public static int numConduitsPerRecipe = 8;
public static boolean transceiverEnabled = true;
public static double transceiverEnergyLoss = 0.1;
public static int transceiverUpkeepCostRF = 10;
public static int transceiverBucketTransmissionCostRF = 100;
public static int transceiverMaxIoRF = 20480;
public static boolean transceiverUseEasyRecipe = false;
public static File configDirectory;
public static boolean useHardRecipes = false;
public static boolean useSteelInChassi = false;
public static boolean detailedPowerTrackingEnabled = false;
public static boolean useSneakMouseWheelYetaWrench = true;
public static boolean useSneakRightClickYetaWrench = false;
public static boolean itemConduitUsePhyscialDistance = false;
public static int enderFluidConduitExtractRate = 200;
public static int enderFluidConduitMaxIoRate = 800;
public static int advancedFluidConduitExtractRate = 100;
public static int advancedFluidConduitMaxIoRate = 400;
public static int fluidConduitExtractRate = 50;
public static int fluidConduitMaxIoRate = 200;
public static int gasConduitExtractRate = 200;
public static int gasConduitMaxIoRate = 800;
public static boolean updateLightingWhenHidingFacades = false;
public static boolean travelAnchorEnabled = true;
public static int travelAnchorMaxDistance = 48;
public static int travelStaffMaxDistance = 128;
public static float travelStaffPowerPerBlockRF = 250;
public static int travelStaffMaxBlinkDistance = 16;
public static int travelStaffBlinkPauseTicks = 10;
public static boolean travelStaffEnabled = true;
public static boolean travelStaffBlinkEnabled = true;
public static boolean travelStaffBlinkThroughSolidBlocksEnabled = true;
public static boolean travelStaffBlinkThroughClearBlocksEnabled = true;
public static boolean travelStaffBlinkThroughUnbreakableBlocksEnabled = false;
public static String[] travelStaffBlinkBlackList = new String[] {
"minecraft:bedrock",
"Thaumcraft:blockWarded"
};
public static float travelAnchorZoomScale = 0.2f;
public static int enderIoRange = 8;
public static boolean enderIoMeAccessEnabled = true;
public static double[] darkSteelPowerDamgeAbsorptionRatios = {0.5, 0.6, 0.75, 0.95};
public static int darkSteelPowerStorageBase = 100000;
public static int darkSteelPowerStorageLevelOne = 150000;
public static int darkSteelPowerStorageLevelTwo = 250000;
public static int darkSteelPowerStorageLevelThree = 1000000;
public static float darkSteelSpeedOneWalkModifier = 0.1f;
public static float darkSteelSpeedTwoWalkMultiplier = 0.2f;
public static float darkSteelSpeedThreeWalkMultiplier = 0.3f;
public static float darkSteelSpeedOneSprintModifier = 0.1f;
public static float darkSteelSpeedTwoSprintMultiplier = 0.3f;
public static float darkSteelSpeedThreeSprintMultiplier = 0.5f;
public static int darkSteelSpeedOneCost = 10;
public static int darkSteelSpeedTwoCost = 15;
public static int darkSteelSpeedThreeCost = 20;
public static double darkSteelBootsJumpModifier = 1.5;
public static int darkSteelJumpOneCost = 10;
public static int darkSteelJumpTwoCost = 15;
public static int darkSteelJumpThreeCost = 20;
public static boolean slotZeroPlacesEight = true;
public static int darkSteelWalkPowerCost = darkSteelPowerStorageLevelTwo / 3000;
public static int darkSteelSprintPowerCost = darkSteelWalkPowerCost * 4;
public static boolean darkSteelDrainPowerFromInventory = false;
public static int darkSteelBootsJumpPowerCost = 150;
public static int darkSteelFallDistanceCost = 75;
public static float darkSteelSwordWitherSkullChance = 0.05f;
public static float darkSteelSwordWitherSkullLootingModifier = 0.05f;
public static float darkSteelSwordSkullChance = 0.1f;
public static float darkSteelSwordSkullLootingModifier = 0.075f;
public static float vanillaSwordSkullLootingModifier = 0.05f;
public static float vanillaSwordSkullChance = 0.05f;
public static float ticCleaverSkullDropChance = 0.1f;
public static float ticBeheadingSkullModifier = 0.075f;
public static float fakePlayerSkullChance = 0.5f;
public static int darkSteelSwordPowerUsePerHit = 750;
public static double darkSteelSwordEnderPearlDropChance = 1;
public static double darkSteelSwordEnderPearlDropChancePerLooting = 0.5;
public static int darkSteelPickEffeciencyObsidian = 50;
public static int darkSteelPickPowerUseObsidian = 10000;
public static float darkSteelPickApplyObsidianEffeciencyAtHardess = 40;
public static int darkSteelPickPowerUsePerDamagePoint = 750;
public static float darkSteelPickEffeciencyBoostWhenPowered = 2;
public static boolean darkSteelPickMinesTiCArdite = true;
public static int darkSteelAxePowerUsePerDamagePoint = 750;
public static int darkSteelAxePowerUsePerDamagePointMultiHarvest = 1500;
public static float darkSteelAxeEffeciencyBoostWhenPowered = 2;
public static float darkSteelAxeSpeedPenaltyMultiHarvest = 4;
public static int darkSteelShearsDurabilityFactor = 5;
public static int darkSteelShearsPowerUsePerDamagePoint = 250;
public static float darkSteelShearsEffeciencyBoostWhenPowered = 2.0f;
public static int darkSteelShearsBlockAreaBoostWhenPowered = 2;
public static float darkSteelShearsEntityAreaBoostWhenPowered = 3.0f;
public static int darkSteelUpgradeVibrantCost = 10;
public static int darkSteelUpgradePowerOneCost = 10;
public static int darkSteelUpgradePowerTwoCost = 15;
public static int darkSteelUpgradePowerThreeCost = 20;
public static int darkSteelGliderCost = 10;
public static double darkSteelGliderHorizontalSpeed = 0.03;
public static double darkSteelGliderVerticalSpeed = -0.05;
public static double darkSteelGliderVerticalSpeedSprinting = -0.15;
public static int darkSteelGogglesOfRevealingCost = 10;
public static int darkSteelApiaristArmorCost = 10;
public static int darkSteelSwimCost = 10;
public static int darkSteelNightVisionCost = 10;
public static int darkSteelSoundLocatorCost = 10;
public static int darkSteelSoundLocatorRange = 40;
public static int darkSteelSoundLocatorLifespan = 40;
public static int darkSteelTravelCost = 30;
public static int darkSteelSpoonCost = 10;
public static int darkSteelSolarOneGen = 10;
public static int darkSteelSolarOneCost = 15;
public static int darkSteelSolarTwoGen = 40;
public static int darkSteelSolarTwoCost = 30;
public static boolean darkSteelSolarChargeOthers = true;
public static float darkSteelAnvilDamageChance = 0.024f;
public static float darkSteelLadderSpeedBoost = 0.06f;
public static int hootchPowerPerCycleRF = 60;
public static int hootchPowerTotalBurnTime = 6000;
public static int rocketFuelPowerPerCycleRF = 160;
public static int rocketFuelPowerTotalBurnTime = 7000;
public static int fireWaterPowerPerCycleRF = 80;
public static int fireWaterPowerTotalBurnTime = 15000;
public static int vatPowerUserPerTickRF = 20;
public static int maxPhotovoltaicOutputRF = 10;
public static int maxPhotovoltaicAdvancedOutputRF = 40;
public static int zombieGeneratorRfPerTick = 80;
public static int zombieGeneratorTicksPerBucketFuel = 10000;
public static int stirlingGeneratorBaseRfPerTick = 20;
public static boolean combustionGeneratorUseOpaqueModel = true;
public static boolean addFuelTooltipsToAllFluidContainers = true;
public static boolean addFurnaceFuelTootip = true;
public static boolean addDurabilityTootip = true;
public static boolean addOreDictionaryTooltips = false;
public static boolean addRegisterdNameTooltip = false;
public static int farmContinuousEnergyUseRF = 40;
public static int farmActionEnergyUseRF = 500;
public static int farmAxeActionEnergyUseRF = 1000;
public static int farmBonemealActionEnergyUseRF = 160;
public static int farmBonemealTryEnergyUseRF = 80;
public static int farmDefaultSize = 3;
public static boolean farmAxeDamageOnLeafBreak = false;
public static float farmToolTakeDamageChance = 1;
public static boolean disableFarmNotification = false;
public static boolean farmEssenceBerriesEnabled = true;
public static boolean farmManaBeansEnabled = false;
public static boolean farmHarvestJungleWhenCocoa = false;
public static String[] hoeStrings = new String[] {
"minecraft:wooden_hoe", "minecraft:stone_hoe", "minecraft:iron_hoe", "minecraft:diamond_hoe", "minecraft:golden_hoe",
"MekanismTools:ObsidianHoe", "MekanismTools:LapisLazuliHoe", "MekanismTools:OsmiumHoe", "MekanismTools:BronzeHoe", "MekanismTools:GlowstoneHoe",
"MekanismTools:SteelHoe",
"Steamcraft:hoeBrass", "Steamcraft:hoeGildedGold",
"Railcraft:tool.steel.hoe",
"TConstruct:mattock",
"appliedenergistics2:item.ToolCertusQuartzHoe", "appliedenergistics2:item.ToolNetherQuartzHoe",
"ProjRed|Exploration:projectred.exploration.hoeruby", "ProjRed|Exploration:projectred.exploration.hoesapphire",
"ProjRed|Exploration:projectred.exploration.hoeperidot",
"magicalcrops:magicalcrops_AccioHoe", "magicalcrops:magicalcrops_CrucioHoe", "magicalcrops:magicalcrops_ImperioHoe",
// disabled as it is currently not unbreaking as advertised "magicalcrops:magicalcrops_ZivicioHoe",
"BiomesOPlenty:hoeAmethyst", "BiomesOPlenty:hoeMud",
"Eln:Eln.Copper Hoe",
"Thaumcraft:ItemHoeThaumium", "Thaumcraft:ItemHoeElemental", "Thaumcraft:ItemHoeVoid",
"ThermalExpansion:tool.hoeInvar"
};
public static List<ItemStack> farmHoes = new ArrayList<ItemStack>();
public static int farmSaplingReserveAmount = 8;
public static int magnetPowerUsePerSecondRF = 1;
public static int magnetPowerCapacityRF = 100000;
public static int magnetRange = 5;
public static String[] magnetBlacklist = new String[] { "appliedenergistics2:item.ItemCrystalSeed", "Botania:livingrock",
"Botania:manaTablet" };
public static boolean useCombustionGenModel = false;
public static int crafterRfPerCraft = 2500;
public static int capacitorBankMaxIoRF = 5000;
public static int capacitorBankMaxStorageRF = 5000000;
public static int capacitorBankTierOneMaxIoRF = 1000;
public static int capacitorBankTierOneMaxStorageRF = 1000000;
public static int capacitorBankTierTwoMaxIoRF = 5000;
public static int capacitorBankTierTwoMaxStorageRF = 5000000;
public static int capacitorBankTierThreeMaxIoRF = 25000;
public static int capacitorBankTierThreeMaxStorageRF = 25000000;
public static int poweredSpawnerMinDelayTicks = 200;
public static int poweredSpawnerMaxDelayTicks = 800;
public static int poweredSpawnerLevelOnePowerPerTickRF = 160;
public static int poweredSpawnerLevelTwoPowerPerTickRF = 500;
public static int poweredSpawnerLevelThreePowerPerTickRF = 1500;
public static int poweredSpawnerMaxPlayerDistance = 0;
public static int poweredSpawnerDespawnTimeSeconds = 120;
public static boolean poweredSpawnerUseVanillaSpawChecks = false;
public static double brokenSpawnerDropChance = 1;
public static String[] brokenSpawnerToolBlacklist = new String[] {
"RotaryCraft:rotarycraft_item_bedpick"
};
public static int powerSpawnerAddSpawnerCost = 30;
public static int painterEnergyPerTaskRF = 2000;
public static int vacuumChestRange = 6;
public static boolean useModMetals = true;
public static int wirelessChargerRange = 24;
public static long nutrientFoodBoostDelay = 400;
public static int enchanterBaseLevelCost = 4;
public static boolean machineSoundsEnabled = true;
public static float machineSoundVolume = 1.0f;
public static int killerJoeNutrientUsePerAttackMb = 5;
public static double killerJoeAttackHeight = 2;
public static double killerJoeAttackWidth = 2;
public static double killerJoeAttackLength = 4;
public static double killerJoeHooverXpWidth = 5;
public static double killerJoeHooverXpLength = 10;
public static int killerJoeMaxXpLevel = Integer.MAX_VALUE;
public static boolean killerJoeMustSee = false;
public static boolean allowTileEntitiesAsPaintSource = true;
public static boolean isGasConduitEnabled = true;
public static boolean enableMEConduits = true;
public static String[] soulVesselBlackList = new String[0];
public static boolean soulVesselCapturesBosses = false;
public static int soulBinderLevelOnePowerPerTickRF = 500;
public static int soulBinderLevelTwoPowerPerTickRF = 1000;
public static int soulBinderLevelThreePowerPerTickRF = 2000;
public static int soulBinderBrokenSpawnerRF = 2500000;
public static int soulBinderBrokenSpawnerLevels = 15;
public static int soulBinderReanimationRF = 100000;
public static int soulBinderReanimationLevels = 10;
public static int soulBinderEnderCystalRF = 100000;
public static int soulBinderEnderCystalLevels = 10;
public static int soulBinderAttractorCystalRF = 100000;
public static int soulBinderAttractorCystalLevels = 10;
public static int soulBinderEnderRailRF = 100000;
public static int soulBinderEnderRailLevels = 10;
public static int soulBinderMaxXpLevel = 40;
public static boolean powerConduitCanDifferentTiersConnect = false;
public static int powerConduitTierOneRF = 640;
public static int powerConduitTierTwoRF = 5120;
public static int powerConduitTierThreeRF = 20480;
public static boolean powerConduitOutputMJ = true;
public static int sliceAndSpliceLevelOnePowerPerTickRF = 80;
public static int sliceAndSpliceLevelTwoPowerPerTickRF = 160;
public static int sliceAndSpliceLevelThreePowerPerTickRF = 320;
public static boolean soulBinderRequiresEndermanSkull = true;
public static int attractorRangeLevelOne = 16;
public static int attractorPowerPerTickLevelOne = 20;
public static int attractorRangeLevelTwo = 32;
public static int attractorPowerPerTickLevelTwo = 40;
public static int attractorRangeLevelThree = 64;
public static int attractorPowerPerTickLevelThree = 80;
public static int spawnGuardRangeLevelOne = 64;
public static int spawnGuardPowerPerTickLevelOne = 80;
public static int spawnGuardRangeLevelTwo = 96;
public static int spawnGuardPowerPerTickLevelTwo = 300;
public static int spawnGuardRangeLevelThree = 160;
public static int spawnGuardPowerPerTickLevelThree = 800;
public static boolean spawnGuardStopAllSlimesDebug = false;
public static boolean spawnGuardStopAllSquidSpawning = false;
public static String weatherObeliskClearItem = "minecraft:cake";
public static String weatherObeliskRainItem = "minecraft:water_bucket";
public static String weatherObeliskThunderItem = "minecraft:lava_bucket";
public static int weatherObeliskClearPower = 1000000;
public static int weatherObeliskRainPower = 250000;
public static int weatherObeliskThunderPower = 500000;
//Loot Defaults
public static boolean lootDarkSteel = true;
public static boolean lootItemConduitProbe = true;
public static boolean lootQuartz = true;
public static boolean lootNetherWart = true;
public static boolean lootEnderPearl = true;
public static boolean lootElectricSteel = true;
public static boolean lootRedstoneAlloy = true;
public static boolean lootPhasedIron = true;
public static boolean lootPhasedGold = true;
public static boolean lootTravelStaff = true;
public static boolean lootTheEnder = true;
public static boolean lootDarkSteelBoots = true;
public static boolean dumpMobNames = false;
public static boolean enderRailEnabled = true;
public static int enderRailPowerRequireCrossDimensions = 10000;
public static int enderRailPowerRequiredPerBlock = 10;
public static boolean enderRailCapSameDimensionPowerAtCrossDimensionCost = true;
public static int enderRailTicksBeforeForceSpawningLinkedCarts = 60;
public static boolean enderRailTeleportPlayers = false;
public static int xpObeliskMaxXpLevel = Integer.MAX_VALUE;
public static String xpJuiceName = "xpjuice";
public static boolean clearGlassSameTexture = false;
public static boolean clearGlassConnectToFusedQuartz = false;
public static int enchantmentSoulBoundId = -1;
public static int enchantmentSoulBoundWeight = 1;
public static boolean enchantmentSoulBoundEnabled = true;
public static boolean replaceWitherSkeletons = true;
public static boolean enableWaterFromBottles = true;
public static boolean telepadLockDimension = true;
public static boolean telepadLockCoords = true;
public static float inventoryPanelPowerPerMB = 800.0f;
public static float inventoryPanelScanCostPerSlot = 0.1f;
public static float inventoryPanelExtractCostPerItem = 12.0f;
public static float inventoryPanelExtractCostPerOperation = 32.0f;
public static void load(FMLPreInitializationEvent event) {
FMLCommonHandler.instance().bus().register(new Config());
configDirectory = new File(event.getModConfigurationDirectory(), EnderIO.MODID.toLowerCase());
if(!configDirectory.exists()) {
configDirectory.mkdir();
}
File configFile = new File(configDirectory, "EnderIO.cfg");
config = new Configuration(configFile);
syncConfig(false);
}
public static void syncConfig(boolean load) {
try {
if (load) {
config.load();
}
Config.processConfig(config);
} catch (Exception e) {
Log.error("EnderIO has a problem loading it's configuration");
e.printStackTrace();
} finally {
if(config.hasChanged()) {
config.save();
}
}
}
@SubscribeEvent
public void onConfigChanged(OnConfigChangedEvent event) {
if(event.modID.equals(EnderIO.MODID)) {
Log.info("Updating config...");
syncConfig(false);
postInit();
}
}
@SubscribeEvent
@Method(modid = "ttCore")
public void onConfigFileChanged(ConfigFileChangedEvent event) {
if (event.modID.equals(EnderIO.MODID)) {
Log.info("Updating config...");
syncConfig(true);
event.setSuccessful();
postInit();
}
}
public static void processConfig(Configuration config) {
capacitorBankMaxIoRF = config.get(sectionPower.name, "capacitorBankMaxIoRF", capacitorBankMaxIoRF, "The maximum IO for a single capacitor in RF/t")
.getInt(capacitorBankMaxIoRF);
capacitorBankMaxStorageRF = config.get(sectionPower.name, "capacitorBankMaxStorageRF", capacitorBankMaxStorageRF,
"The maximum storage for a single capacitor in RF")
.getInt(capacitorBankMaxStorageRF);
capacitorBankTierOneMaxIoRF = config.get(sectionPower.name, "capacitorBankTierOneMaxIoRF", capacitorBankTierOneMaxIoRF,
"The maximum IO for a single tier one capacitor in RF/t")
.getInt(capacitorBankTierOneMaxIoRF);
capacitorBankTierOneMaxStorageRF = config.get(sectionPower.name, "capacitorBankTierOneMaxStorageRF", capacitorBankTierOneMaxStorageRF,
"The maximum storage for a single tier one capacitor in RF")
.getInt(capacitorBankTierOneMaxStorageRF);
capacitorBankTierTwoMaxIoRF = config.get(sectionPower.name, "capacitorBankTierTwoMaxIoRF", capacitorBankTierTwoMaxIoRF,
"The maximum IO for a single tier two capacitor in RF/t")
.getInt(capacitorBankTierTwoMaxIoRF);
capacitorBankTierTwoMaxStorageRF = config.get(sectionPower.name, "capacitorBankTierTwoMaxStorageRF", capacitorBankTierTwoMaxStorageRF,
"The maximum storage for a single tier two capacitor in RF")
.getInt(capacitorBankTierTwoMaxStorageRF);
capacitorBankTierThreeMaxIoRF = config.get(sectionPower.name, "capacitorBankTierThreeMaxIoRF", capacitorBankTierThreeMaxIoRF,
"The maximum IO for a single tier three capacitor in RF/t")
.getInt(capacitorBankTierThreeMaxIoRF);
capacitorBankTierThreeMaxStorageRF = config.get(sectionPower.name, "capacitorBankTierThreeMaxStorageRF", capacitorBankTierThreeMaxStorageRF,
"The maximum storage for a single tier three capacitor in RF")
.getInt(capacitorBankTierThreeMaxStorageRF);
powerConduitTierOneRF = config.get(sectionPower.name, "powerConduitTierOneRF", powerConduitTierOneRF, "The maximum IO for the tier 1 power conduit")
.getInt(powerConduitTierOneRF);
powerConduitTierTwoRF = config.get(sectionPower.name, "powerConduitTierTwoRF", powerConduitTierTwoRF, "The maximum IO for the tier 2 power conduit")
.getInt(powerConduitTierTwoRF);
powerConduitTierThreeRF = config.get(sectionPower.name, "powerConduitTierThreeRF", powerConduitTierThreeRF, "The maximum IO for the tier 3 power conduit")
.getInt(powerConduitTierThreeRF);
powerConduitCanDifferentTiersConnect = config
.getBoolean("powerConduitCanDifferentTiersConnect", sectionPower.name, powerConduitCanDifferentTiersConnect,
"If set to false power conduits of different tiers cannot be connected. in this case a block such as a cap. bank is needed to bridge different tiered networks");
powerConduitOutputMJ = config.getBoolean("powerConduitOutputMJ", sectionPower.name, powerConduitOutputMJ, "When set to true power conduits will output MJ if RF is not supported");
painterEnergyPerTaskRF = config.get(sectionPower.name, "painterEnergyPerTaskRF", painterEnergyPerTaskRF,
"The total amount of RF required to paint one block")
.getInt(painterEnergyPerTaskRF);
useHardRecipes = config.get(sectionRecipe.name, "useHardRecipes", useHardRecipes, "When enabled machines cost significantly more.")
.getBoolean(useHardRecipes);
soulBinderRequiresEndermanSkull = config.getBoolean("soulBinderRequiresEndermanSkull", sectionRecipe.name, soulBinderRequiresEndermanSkull,
"When true the Soul Binder requires an Enderman Skull to craft");
allowTileEntitiesAsPaintSource = config.get(sectionRecipe.name, "allowTileEntitiesAsPaintSource", allowTileEntitiesAsPaintSource,
"When enabled blocks with tile entities (e.g. machines) can be used as paint targets.")
.getBoolean(allowTileEntitiesAsPaintSource);
useSteelInChassi = config.get(sectionRecipe.name, "useSteelInChassi", useSteelInChassi, "When enabled machine chassis will require steel instead of iron.")
.getBoolean(useSteelInChassi);
numConduitsPerRecipe = config.get(sectionRecipe.name, "numConduitsPerRecipe", numConduitsPerRecipe,
"The number of conduits crafted per recipe.").getInt(numConduitsPerRecipe);
transceiverUseEasyRecipe= config.get(sectionRecipe.name, "transceiverUseEasyRecipe", transceiverUseEasyRecipe, "When enabled the dim trans. will use a cheaper recipe")
.getBoolean(useHardRecipes);
enchanterBaseLevelCost = config.get(sectionRecipe.name, "enchanterBaseLevelCost", enchanterBaseLevelCost,
"Base level cost added to all recipes in the enchanter.").getInt(enchanterBaseLevelCost);
photovoltaicCellEnabled = config.get(sectionItems.name, "photovoltaicCellEnabled", photovoltaicCellEnabled,
"If set to false: Photovoltaic Cells will not be craftable.")
.getBoolean(photovoltaicCellEnabled);
reservoirEnabled= config.get(sectionItems.name, "reservoirEnabled", reservoirEnabled,
"If set to false reservoirs will not be craftable.")
.getBoolean(reservoirEnabled);
transceiverEnabled = config.get(sectionItems.name, "transceiverEnabled", transceiverEnabled,
"If set to false: Dimensional Transceivers will not be craftable.")
.getBoolean(transceiverEnabled);
maxPhotovoltaicOutputRF = config.get(sectionPower.name, "maxPhotovoltaicOutputRF", maxPhotovoltaicOutputRF,
"Maximum output in RF/t of the Photovoltaic Panels.").getInt(maxPhotovoltaicOutputRF);
maxPhotovoltaicAdvancedOutputRF = config.get(sectionPower.name, "maxPhotovoltaicAdvancedOutputRF", maxPhotovoltaicAdvancedOutputRF,
"Maximum output in RF/t of the Advanced Photovoltaic Panels.").getInt(maxPhotovoltaicAdvancedOutputRF);
useAlternateBinderRecipe = config.get(sectionRecipe.name, "useAlternateBinderRecipe", false, "Create conduit binder in crafting table instead of furnace")
.getBoolean(useAlternateBinderRecipe);
conduitScale = config.get(sectionAesthetic.name, "conduitScale", DEFAULT_CONDUIT_SCALE,
"Valid values are between 0-1, smallest conduits at 0, largest at 1.\n" +
"In SMP, all clients must be using the same value as the server.").getDouble(DEFAULT_CONDUIT_SCALE);
conduitScale = VecmathUtil.clamp(conduitScale, 0, 1);
wirelessChargerRange = config.get(sectionEfficiency.name, "wirelessChargerRange", wirelessChargerRange,
"The range of the wireless charger").getInt(wirelessChargerRange);
fluidConduitExtractRate = config.get(sectionEfficiency.name, "fluidConduitExtractRate", fluidConduitExtractRate,
"Number of millibuckets per tick extracted by a fluid conduits auto extracting").getInt(fluidConduitExtractRate);
fluidConduitMaxIoRate = config.get(sectionEfficiency.name, "fluidConduitMaxIoRate", fluidConduitMaxIoRate,
"Number of millibuckets per tick that can pass through a single connection to a fluid conduit.").getInt(fluidConduitMaxIoRate);
advancedFluidConduitExtractRate = config.get(sectionEfficiency.name, "advancedFluidConduitExtractRate", advancedFluidConduitExtractRate,
"Number of millibuckets per tick extracted by pressurised fluid conduits auto extracting").getInt(advancedFluidConduitExtractRate);
advancedFluidConduitMaxIoRate = config.get(sectionEfficiency.name, "advancedFluidConduitMaxIoRate", advancedFluidConduitMaxIoRate,
"Number of millibuckets per tick that can pass through a single connection to an pressurised fluid conduit.").getInt(advancedFluidConduitMaxIoRate);
enderFluidConduitExtractRate = config.get(sectionEfficiency.name, "enderFluidConduitExtractRate", enderFluidConduitExtractRate,
"Number of millibuckets per tick extracted by ender fluid conduits auto extracting").getInt(enderFluidConduitExtractRate);
enderFluidConduitMaxIoRate = config.get(sectionEfficiency.name, "enderFluidConduitMaxIoRate", enderFluidConduitMaxIoRate,
"Number of millibuckets per tick that can pass through a single connection to an ender fluid conduit.").getInt(enderFluidConduitMaxIoRate);
gasConduitExtractRate = config.get(sectionEfficiency.name, "gasConduitExtractRate", gasConduitExtractRate,
"Amount of gas per tick extracted by gas conduits auto extracting").getInt(gasConduitExtractRate);
gasConduitMaxIoRate = config.get(sectionEfficiency.name, "gasConduitMaxIoRate", gasConduitMaxIoRate,
"Amount of gas per tick that can pass through a single connection to a gas conduit.").getInt(gasConduitMaxIoRate);
useAlternateTesseractModel = config.get(sectionAesthetic.name, "useAlternateTransceiverModel", useAlternateTesseractModel,
"Use TheKazador's alternative model for the Dimensional Transceiver")
.getBoolean(false);
transceiverEnergyLoss = config.get(sectionPower.name, "transceiverEnergyLoss", transceiverEnergyLoss,
"Amount of energy lost when transfered by Dimensional Transceiver; 0 is no loss, 1 is 100% loss").getDouble(transceiverEnergyLoss);
transceiverUpkeepCostRF = config.get(sectionPower.name, "transceiverUpkeepCostRF", transceiverUpkeepCostRF,
"Number of RF/t required to keep a Dimensional Transceiver connection open").getInt(transceiverUpkeepCostRF);
transceiverMaxIoRF = config.get(sectionPower.name, "transceiverMaxIoRF", transceiverMaxIoRF,
"Maximum RF/t sent and received by a Dimensional Transceiver per tick. Input and output limits are not cumulative").getInt(transceiverMaxIoRF);
transceiverBucketTransmissionCostRF = config.get(sectionEfficiency.name, "transceiverBucketTransmissionCostRF", transceiverBucketTransmissionCostRF,
"The cost in RF of transporting a bucket of fluid via a Dimensional Transceiver.").getInt(transceiverBucketTransmissionCostRF);
vatPowerUserPerTickRF = config.get(sectionPower.name, "vatPowerUserPerTickRF", vatPowerUserPerTickRF,
"Power use (RF/t) used by the vat.").getInt(vatPowerUserPerTickRF);
detailedPowerTrackingEnabled = config
.get(
sectionAdvanced.name,
"perInterfacePowerTrackingEnabled",
detailedPowerTrackingEnabled,
"Enable per tick sampling on individual power inputs and outputs. This allows slightly more detailed messages from the RF Reader but has a negative impact on server performance.")
.getBoolean(detailedPowerTrackingEnabled);
useSneakMouseWheelYetaWrench = config.get(sectionPersonal.name, "useSneakMouseWheelYetaWrench", useSneakMouseWheelYetaWrench,
"If true, shift-mouse wheel will change the conduit display mode when the YetaWrench is equipped.")
.getBoolean(useSneakMouseWheelYetaWrench);
useSneakRightClickYetaWrench = config.get(sectionPersonal.name, "useSneakRightClickYetaWrench", useSneakRightClickYetaWrench,
"If true, shift-clicking the YetaWrench on a null or non wrenchable object will change the conduit display mode.")
.getBoolean(useSneakRightClickYetaWrench);
machineSoundsEnabled = config.get(sectionPersonal.name, "useMachineSounds", machineSoundsEnabled,
"If true, machines will make sounds.")
.getBoolean(machineSoundsEnabled);
machineSoundVolume = (float) config.get(sectionPersonal.name, "machineSoundVolume", machineSoundVolume, "Volume of machine sounds.").getDouble(
machineSoundVolume);
itemConduitUsePhyscialDistance = config.get(sectionEfficiency.name, "itemConduitUsePhyscialDistance", itemConduitUsePhyscialDistance, "If true, " +
"'line of sight' distance rather than conduit path distance is used to calculate priorities.")
.getBoolean(itemConduitUsePhyscialDistance);
vacuumChestRange = config.get(sectionEfficiency.name, "vacumChestRange", vacuumChestRange, "The range of the vacuum chest").getInt(vacuumChestRange);
if(!useSneakMouseWheelYetaWrench && !useSneakRightClickYetaWrench) {
Log.warn("Both useSneakMouseWheelYetaWrench and useSneakRightClickYetaWrench are set to false. Enabling mouse wheel.");
useSneakMouseWheelYetaWrench = true;
}
reinforcedObsidianEnabled = config.get(sectionItems.name, "reinforcedObsidianEnabled", reinforcedObsidianEnabled,
"When set to false reinforced obsidian is not craftable.").getBoolean(reinforcedObsidianEnabled);
reinforcedObsidianUseDarkSteelBlocks = config.get(sectionRecipe.name, "reinforcedObsidianUseDarkSteelBlocks", reinforcedObsidianUseDarkSteelBlocks,
"When set to true four dark steel blocks are required instead of ingots when making reinforced obsidian.").getBoolean(reinforcedObsidianUseDarkSteelBlocks);
travelAnchorEnabled = config.get(sectionItems.name, "travelAnchorEnabled", travelAnchorEnabled,
"When set to false: the travel anchor will not be craftable.").getBoolean(travelAnchorEnabled);
travelAnchorMaxDistance = config.get(sectionAnchor.name, "travelAnchorMaxDistance", travelAnchorMaxDistance,
"Maximum number of blocks that can be traveled from one travel anchor to another.").getInt(travelAnchorMaxDistance);
travelStaffMaxDistance = config.get(sectionStaff.name, "travelStaffMaxDistance", travelStaffMaxDistance,
"Maximum number of blocks that can be traveled using the Staff of the Traveling.").getInt(travelStaffMaxDistance);
travelStaffPowerPerBlockRF = (float) config.get(sectionStaff.name, "travelStaffPowerPerBlockRF", travelStaffPowerPerBlockRF,
"Number of RF required per block travelled using the Staff of the Traveling.").getDouble(travelStaffPowerPerBlockRF);
travelStaffMaxBlinkDistance = config.get(sectionStaff.name, "travelStaffMaxBlinkDistance", travelStaffMaxBlinkDistance,
"Max number of blocks teleported when shift clicking the staff.").getInt(travelStaffMaxBlinkDistance);
travelStaffBlinkPauseTicks = config.get(sectionStaff.name, "travelStaffBlinkPauseTicks", travelStaffBlinkPauseTicks,
"Minimum number of ticks between 'blinks'. Values of 10 or less allow a limited sort of flight.").getInt(travelStaffBlinkPauseTicks);
travelStaffEnabled = config.get(sectionStaff.name, "travelStaffEnabled", travelAnchorEnabled,
"If set to false: the travel staff will not be craftable.").getBoolean(travelStaffEnabled);
travelStaffBlinkEnabled = config.get(sectionStaff.name, "travelStaffBlinkEnabled", travelStaffBlinkEnabled,
"If set to false: the travel staff can not be used to shift-right click teleport, or blink.").getBoolean(travelStaffBlinkEnabled);
travelStaffBlinkThroughSolidBlocksEnabled = config.get(sectionStaff.name, "travelStaffBlinkThroughSolidBlocksEnabled",
travelStaffBlinkThroughSolidBlocksEnabled,
"If set to false: the travel staff can be used to blink through any block.").getBoolean(travelStaffBlinkThroughSolidBlocksEnabled);
travelStaffBlinkThroughClearBlocksEnabled = config
.get(sectionItems.name, "travelStaffBlinkThroughClearBlocksEnabled", travelStaffBlinkThroughClearBlocksEnabled,
"If travelStaffBlinkThroughSolidBlocksEnabled is set to false and this is true: the travel " +
"staff can only be used to blink through transparent or partial blocks (e.g. torches). " +
"If both are false: only air blocks may be teleported through.")
.getBoolean(travelStaffBlinkThroughClearBlocksEnabled);
travelStaffBlinkThroughUnbreakableBlocksEnabled = config.get(sectionItems.name, "travelStaffBlinkThroughUnbreakableBlocksEnabled",
travelStaffBlinkThroughUnbreakableBlocksEnabled, "Allows the travel staff to blink through unbreakable blocks such as warded blocks and bedrock.")
.getBoolean();
travelStaffBlinkBlackList = config.getStringList("travelStaffBlinkBlackList", sectionStaff.name, travelStaffBlinkBlackList,
"Lists the blocks that cannot be teleported through in the form 'modID:blockName'");
travelAnchorZoomScale = config.getFloat("travelAnchorZoomScale", sectionStaff.name, travelAnchorZoomScale, 0, 1,
"Set the max zoomed size of a travel anchor as an aprox. percentage of screen height");
enderIoRange = config.get(sectionEfficiency.name, "enderIoRange", enderIoRange,
"Range accessible (in blocks) when using the Ender IO.").getInt(enderIoRange);
enderIoMeAccessEnabled = config.get(sectionPersonal.name, "enderIoMeAccessEnabled", enderIoMeAccessEnabled,
"If false: you will not be able to access a ME access or crafting terminal using the Ender IO.").getBoolean(enderIoMeAccessEnabled);
updateLightingWhenHidingFacades = config.get(sectionEfficiency.name, "updateLightingWhenHidingFacades", updateLightingWhenHidingFacades,
"When true: correct lighting is recalculated (client side) for conduit bundles when transitioning to"
+ " from being hidden behind a facade. This produces "
+ "better quality rendering but can result in frame stutters when switching to/from a wrench.")
.getBoolean(updateLightingWhenHidingFacades);
darkSteelPowerDamgeAbsorptionRatios = config
.get(sectionDarkSteel.name, "darkSteelPowerDamgeAbsorptionRatios", darkSteelPowerDamgeAbsorptionRatios,
"A list of the amount of durability damage absorbed when items are powered. In order of upgrade level. 1=100% so items take no durability damage when powered.")
.getDoubleList();
darkSteelPowerStorageBase = config.get(sectionDarkSteel.name, "darkSteelPowerStorageBase", darkSteelPowerStorageBase,
"Base amount of power stored by dark steel items.").getInt(darkSteelPowerStorageBase);
darkSteelPowerStorageLevelOne = config.get(sectionDarkSteel.name, "darkSteelPowerStorageLevelOne", darkSteelPowerStorageLevelOne,
"Amount of power stored by dark steel items with a level 1 upgrade.").getInt(darkSteelPowerStorageLevelOne);
darkSteelPowerStorageLevelTwo = config.get(sectionDarkSteel.name, "darkSteelPowerStorageLevelTwo", darkSteelPowerStorageLevelTwo,
"Amount of power stored by dark steel items with a level 2 upgrade.").getInt(darkSteelPowerStorageLevelTwo);
darkSteelPowerStorageLevelThree = config.get(sectionDarkSteel.name, "darkSteelPowerStorageLevelThree", darkSteelPowerStorageLevelThree,
"Amount of power stored by dark steel items with a level 3 upgrade.").getInt(darkSteelPowerStorageLevelThree);
darkSteelUpgradeVibrantCost = config.get(sectionDarkSteel.name, "darkSteelUpgradeVibrantCost", darkSteelUpgradeVibrantCost,
"Number of levels required for the 'Empowered.").getInt(darkSteelUpgradeVibrantCost);
darkSteelUpgradePowerOneCost = config.get(sectionDarkSteel.name, "darkSteelUpgradePowerOneCost", darkSteelUpgradePowerOneCost,
"Number of levels required for the 'Power 1.").getInt(darkSteelUpgradePowerOneCost);
darkSteelUpgradePowerTwoCost = config.get(sectionDarkSteel.name, "darkSteelUpgradePowerTwoCost", darkSteelUpgradePowerTwoCost,
"Number of levels required for the 'Power 2.").getInt(darkSteelUpgradePowerTwoCost);
darkSteelUpgradePowerThreeCost = config.get(sectionDarkSteel.name, "darkSteelUpgradePowerThreeCost", darkSteelUpgradePowerThreeCost,
"Number of levels required for the 'Power 3' upgrade.").getInt(darkSteelUpgradePowerThreeCost);
darkSteelJumpOneCost = config.get(sectionDarkSteel.name, "darkSteelJumpOneCost", darkSteelJumpOneCost,
"Number of levels required for the 'Jump 1' upgrade.").getInt(darkSteelJumpOneCost);
darkSteelJumpTwoCost = config.get(sectionDarkSteel.name, "darkSteelJumpTwoCost", darkSteelJumpTwoCost,
"Number of levels required for the 'Jump 2' upgrade.").getInt(darkSteelJumpTwoCost);
darkSteelJumpThreeCost = config.get(sectionDarkSteel.name, "darkSteelJumpThreeCost", darkSteelJumpThreeCost,
"Number of levels required for the 'Jump 3' upgrade.").getInt(darkSteelJumpThreeCost);
darkSteelSpeedOneCost = config.get(sectionDarkSteel.name, "darkSteelSpeedOneCost", darkSteelSpeedOneCost,
"Number of levels required for the 'Speed 1' upgrade.").getInt(darkSteelSpeedOneCost);
darkSteelSpeedTwoCost = config.get(sectionDarkSteel.name, "darkSteelSpeedTwoCost", darkSteelSpeedTwoCost,
"Number of levels required for the 'Speed 2' upgrade.").getInt(darkSteelSpeedTwoCost);
darkSteelSpeedThreeCost = config.get(sectionDarkSteel.name, "darkSteelSpeedThreeCost", darkSteelSpeedThreeCost,
"Number of levels required for the 'Speed 3' upgrade.").getInt(darkSteelSpeedThreeCost);
slotZeroPlacesEight = config.get(sectionDarkSteel.name, "shouldSlotZeroWrap", slotZeroPlacesEight, "Should the dark steel placement, when in the first (0th) slot, place the item in the last slot. If false, will place what's in the second slot.").getBoolean();
darkSteelSpeedOneWalkModifier = (float) config.get(sectionDarkSteel.name, "darkSteelSpeedOneWalkModifier", darkSteelSpeedOneWalkModifier,
"Speed modifier applied when walking in the Dark Steel Boots with Speed I.").getDouble(darkSteelSpeedOneWalkModifier);
darkSteelSpeedTwoWalkMultiplier = (float) config.get(sectionDarkSteel.name, "darkSteelSpeedTwoWalkMultiplier", darkSteelSpeedTwoWalkMultiplier,
"Speed modifier applied when walking in the Dark Steel Boots with Speed I.").getDouble(darkSteelSpeedTwoWalkMultiplier);
darkSteelSpeedThreeWalkMultiplier = (float) config.get(sectionDarkSteel.name, "darkSteelSpeedThreeWalkMultiplier", darkSteelSpeedThreeWalkMultiplier,
"Speed modifier applied when walking in the Dark Steel Boots with Speed I.").getDouble(darkSteelSpeedThreeWalkMultiplier);
darkSteelSpeedOneSprintModifier = (float) config.get(sectionDarkSteel.name, "darkSteelSpeedOneSprintModifier", darkSteelSpeedOneSprintModifier,
"Speed modifier applied when walking in the Dark Steel Boots with Speed I.").getDouble(darkSteelSpeedOneSprintModifier);
darkSteelSpeedTwoSprintMultiplier = (float) config.get(sectionDarkSteel.name, "darkSteelSpeedTwoSprintMultiplier", darkSteelSpeedTwoSprintMultiplier,
"Speed modifier applied when walking in the Dark Steel Boots with Speed I.").getDouble(darkSteelSpeedTwoSprintMultiplier);
darkSteelSpeedThreeSprintMultiplier = (float) config.get(sectionDarkSteel.name, "darkSteelSpeedThreeSprintMultiplier", darkSteelSpeedThreeSprintMultiplier,
"Speed modifier applied when walking in the Dark Steel Boots with Speed I.").getDouble(darkSteelSpeedThreeSprintMultiplier);
darkSteelBootsJumpModifier = config.get(sectionDarkSteel.name, "darkSteelBootsJumpModifier", darkSteelBootsJumpModifier,
"Jump height modifier applied when jumping with Dark Steel Boots equipped").getDouble(darkSteelBootsJumpModifier);
darkSteelPowerStorageBase = config.get(sectionDarkSteel.name, "darkSteelPowerStorage", darkSteelPowerStorageBase,
"Amount of power stored (RF) per crystal in the armor items recipe.").getInt(darkSteelPowerStorageBase);
darkSteelWalkPowerCost = config.get(sectionDarkSteel.name, "darkSteelWalkPowerCost", darkSteelWalkPowerCost,
"Amount of power stored (RF) per block walked when wearing the dark steel boots.").getInt(darkSteelWalkPowerCost);
darkSteelSprintPowerCost = config.get(sectionDarkSteel.name, "darkSteelSprintPowerCost", darkSteelWalkPowerCost,
"Amount of power stored (RF) per block walked when wearing the dark steel boots.").getInt(darkSteelSprintPowerCost);
darkSteelDrainPowerFromInventory = config.get(sectionDarkSteel.name, "darkSteelDrainPowerFromInventory", darkSteelDrainPowerFromInventory,
"If true, dark steel armor will drain power stored (RF) in power containers in the players inventory.").getBoolean(darkSteelDrainPowerFromInventory);
darkSteelBootsJumpPowerCost = config.get(sectionDarkSteel.name, "darkSteelBootsJumpPowerCost", darkSteelBootsJumpPowerCost,
"Base amount of power used per jump (RF) dark steel boots. The second jump in a 'double jump' uses 2x this etc").getInt(darkSteelBootsJumpPowerCost);
darkSteelFallDistanceCost = config.get(sectionDarkSteel.name, "darkSteelFallDistanceCost", darkSteelFallDistanceCost,
"Amount of power used (RF) per block height of fall distance damage negated.").getInt(darkSteelFallDistanceCost);
darkSteelSwimCost = config.get(sectionDarkSteel.name, "darkSteelSwimCost", darkSteelSwimCost,
"Number of levels required for the 'Swim' upgrade.").getInt(darkSteelSwimCost);
darkSteelNightVisionCost = config.get(sectionDarkSteel.name, "darkSteelNightVisionCost", darkSteelNightVisionCost,
"Number of levels required for the 'Night Vision' upgrade.").getInt(darkSteelNightVisionCost);
darkSteelGliderCost = config.get(sectionDarkSteel.name, "darkSteelGliderCost", darkSteelGliderCost,
"Number of levels required for the 'Glider' upgrade.").getInt(darkSteelGliderCost);
darkSteelGliderHorizontalSpeed = config.get(sectionDarkSteel.name, "darkSteelGliderHorizontalSpeed", darkSteelGliderHorizontalSpeed,
"Horizontal movement speed modifier when gliding.").getDouble(darkSteelGliderHorizontalSpeed);
darkSteelGliderVerticalSpeed = config.get(sectionDarkSteel.name, "darkSteelGliderVerticalSpeed", darkSteelGliderVerticalSpeed,
"Rate of altitude loss when gliding.").getDouble(darkSteelGliderVerticalSpeed);
darkSteelGliderVerticalSpeedSprinting = config.get(sectionDarkSteel.name, "darkSteelGliderVerticalSpeedSprinting", darkSteelGliderVerticalSpeedSprinting,
"Rate of altitude loss when sprinting and gliding.").getDouble(darkSteelGliderVerticalSpeedSprinting);
darkSteelSoundLocatorCost = config.get(sectionDarkSteel.name, "darkSteelSoundLocatorCost", darkSteelSoundLocatorCost,
"Number of levels required for the 'Sound Locator' upgrade.").getInt(darkSteelSoundLocatorCost);
darkSteelSoundLocatorRange = config.get(sectionDarkSteel.name, "darkSteelSoundLocatorRange", darkSteelSoundLocatorRange,
"Range of the 'Sound Locator' upgrade.").getInt(darkSteelSoundLocatorRange);
darkSteelSoundLocatorLifespan = config.get(sectionDarkSteel.name, "darkSteelSoundLocatorLifespan", darkSteelSoundLocatorLifespan,
"Number of ticks the 'Sound Locator' icons are displayed for.").getInt(darkSteelSoundLocatorLifespan);
darkSteelGogglesOfRevealingCost= config.get(sectionDarkSteel.name, "darkSteelGogglesOfRevealingCost", darkSteelGogglesOfRevealingCost,
"Number of levels required for the Goggles of Revealing upgrade.").getInt(darkSteelGogglesOfRevealingCost);
darkSteelApiaristArmorCost= config.get(sectionDarkSteel.name, "darkSteelApiaristArmorCost", darkSteelApiaristArmorCost,
"Number of levels required for the Apiarist Armor upgrade.").getInt(darkSteelApiaristArmorCost);
darkSteelTravelCost = config.get(sectionDarkSteel.name, "darkSteelTravelCost", darkSteelTravelCost,
"Number of levels required for the 'Travel' upgrade.").getInt(darkSteelTravelCost);
darkSteelSpoonCost = config.get(sectionDarkSteel.name, "darkSteelSpoonCost", darkSteelSpoonCost,
"Number of levels required for the 'Spoon' upgrade.").getInt(darkSteelSpoonCost);
darkSteelSolarOneCost = config.get(sectionDarkSteel.name, "darkSteelSolarOneCost", darkSteelSolarOneCost,
"Cost in XP levels of the Solar I upgrade.").getInt();
darkSteelSolarOneGen = config.get(sectionDarkSteel.name, "darkSteelSolarOneGen", darkSteelSolarOneGen,
"RF per SECOND generated by the Solar I upgrade. Split between all equipped DS armors.").getInt();
darkSteelSolarTwoCost = config.get(sectionDarkSteel.name, "darkSteelSolarTwoCost", darkSteelSolarTwoCost,
"Cost in XP levels of the Solar II upgrade.").getInt();
darkSteelSolarTwoGen = config.get(sectionDarkSteel.name, "darkSteelSolarTwoGen", darkSteelSolarTwoGen,
"RF per SECOND generated by the Solar II upgrade. Split between all equipped DS armors.").getInt();
darkSteelSolarChargeOthers = config.get(sectionDarkSteel.name, "darkSteelSolarChargeOthers", darkSteelSolarChargeOthers,
"If enabled allows the solar upgrade to charge non-darksteel armors that the player is wearing.").getBoolean();
darkSteelSwordSkullChance = (float) config.get(sectionDarkSteel.name, "darkSteelSwordSkullChance", darkSteelSwordSkullChance,
"The base chance that a skull will be dropped when using a powered dark steel sword (0 = no chance, 1 = 100% chance)").getDouble(
darkSteelSwordSkullChance);
darkSteelSwordSkullLootingModifier = (float) config.get(sectionDarkSteel.name, "darkSteelSwordSkullLootingModifier", darkSteelSwordSkullLootingModifier,
"The chance per looting level that a skull will be dropped when using a powered dark steel sword (0 = no chance, 1 = 100% chance)").getDouble(
darkSteelSwordSkullLootingModifier);
darkSteelSwordWitherSkullChance = (float) config.get(sectionDarkSteel.name, "darkSteelSwordWitherSkullChance", darkSteelSwordWitherSkullChance,
"The base chance that a wither skull will be dropped when using a powered dark steel sword (0 = no chance, 1 = 100% chance)").getDouble(
darkSteelSwordWitherSkullChance);
darkSteelSwordWitherSkullLootingModifier = (float) config.get(sectionDarkSteel.name, "darkSteelSwordWitherSkullLootingModifie",
darkSteelSwordWitherSkullLootingModifier,
"The chance per looting level that a wither skull will be dropped when using a powered dark steel sword (0 = no chance, 1 = 100% chance)").getDouble(
darkSteelSwordWitherSkullLootingModifier);
vanillaSwordSkullChance = (float) config.get(sectionDarkSteel.name, "vanillaSwordSkullChance", vanillaSwordSkullChance,
"The base chance that a skull will be dropped when using a non dark steel sword (0 = no chance, 1 = 100% chance)").getDouble(
vanillaSwordSkullChance);
vanillaSwordSkullLootingModifier = (float) config.get(sectionPersonal.name, "vanillaSwordSkullLootingModifier", vanillaSwordSkullLootingModifier,
"The chance per looting level that a skull will be dropped when using a non-dark steel sword (0 = no chance, 1 = 100% chance)").getDouble(
vanillaSwordSkullLootingModifier);
ticCleaverSkullDropChance = (float) config.get(sectionDarkSteel.name, "ticCleaverSkullDropChance", ticCleaverSkullDropChance,
"The base chance that an Enderman Skull will be dropped when using TiC Cleaver").getDouble(
ticCleaverSkullDropChance);
ticBeheadingSkullModifier = (float) config.get(sectionPersonal.name, "ticBeheadingSkullModifier", ticBeheadingSkullModifier,
"The chance per level of Beheading that a skull will be dropped when using a TiC weapon").getDouble(
ticBeheadingSkullModifier);
fakePlayerSkullChance = (float) config
.get(
sectionDarkSteel.name,
"fakePlayerSkullChance",
fakePlayerSkullChance,
"The ratio of skull drops when a mob is killed by a 'FakePlayer', such as Killer Joe. When set to 0 no skulls will drop, at 1 the rate of skull drops is not modified")
.getDouble(
fakePlayerSkullChance);
darkSteelSwordPowerUsePerHit = config.get(sectionDarkSteel.name, "darkSteelSwordPowerUsePerHit", darkSteelSwordPowerUsePerHit,
"The amount of power (RF) used per hit.").getInt(darkSteelSwordPowerUsePerHit);
darkSteelSwordEnderPearlDropChance = config.get(sectionDarkSteel.name, "darkSteelSwordEnderPearlDropChance", darkSteelSwordEnderPearlDropChance,
"The chance that an ender pearl will be dropped when using a dark steel sword (0 = no chance, 1 = 100% chance)").getDouble(
darkSteelSwordEnderPearlDropChance);
darkSteelSwordEnderPearlDropChancePerLooting = config.get(sectionDarkSteel.name, "darkSteelSwordEnderPearlDropChancePerLooting",
darkSteelSwordEnderPearlDropChancePerLooting,
"The chance for each looting level that an additional ender pearl will be dropped when using a dark steel sword (0 = no chance, 1 = 100% chance)")
.getDouble(
darkSteelSwordEnderPearlDropChancePerLooting);
darkSteelPickPowerUseObsidian = config.get(sectionDarkSteel.name, "darkSteelPickPowerUseObsidian", darkSteelPickPowerUseObsidian,
"The amount of power (RF) used to break an obsidian block.").getInt(darkSteelPickPowerUseObsidian);
darkSteelPickEffeciencyObsidian = config.get(sectionDarkSteel.name, "darkSteelPickEffeciencyObsidian", darkSteelPickEffeciencyObsidian,
"The efficiency when breaking obsidian with a powered Dark Pickaxe.").getInt(darkSteelPickEffeciencyObsidian);
darkSteelPickApplyObsidianEffeciencyAtHardess = (float) config.get(sectionDarkSteel.name, "darkSteelPickApplyObsidianEffeciencyAtHardess",
darkSteelPickApplyObsidianEffeciencyAtHardess,
"If set to a value > 0, the obsidian speed and power use will be used for all blocks with hardness >= to this value.").getDouble(
darkSteelPickApplyObsidianEffeciencyAtHardess);
darkSteelPickPowerUsePerDamagePoint = config.get(sectionDarkSteel.name, "darkSteelPickPowerUsePerDamagePoint", darkSteelPickPowerUsePerDamagePoint,
"Power use (RF) per damage/durability point avoided.").getInt(darkSteelPickPowerUsePerDamagePoint);
darkSteelPickEffeciencyBoostWhenPowered = (float) config.get(sectionDarkSteel.name, "darkSteelPickEffeciencyBoostWhenPowered",
darkSteelPickEffeciencyBoostWhenPowered, "The increase in efficiency when powered.").getDouble(darkSteelPickEffeciencyBoostWhenPowered);
darkSteelPickMinesTiCArdite = config.getBoolean("darkSteelPickMinesTiCArdite", sectionDarkSteel.name, darkSteelPickMinesTiCArdite,
"When true the dark steel pick will be able to mine TiC Ardite and Cobalt");
darkSteelAxePowerUsePerDamagePoint = config.get(sectionDarkSteel.name, "darkSteelAxePowerUsePerDamagePoint", darkSteelAxePowerUsePerDamagePoint,
"Power use (RF) per damage/durability point avoided.").getInt(darkSteelAxePowerUsePerDamagePoint);
darkSteelAxePowerUsePerDamagePointMultiHarvest = config.get(sectionDarkSteel.name, "darkSteelPickAxeUsePerDamagePointMultiHarvest",
darkSteelAxePowerUsePerDamagePointMultiHarvest,
"Power use (RF) per damage/durability point avoided when shift-harvesting multiple logs").getInt(darkSteelAxePowerUsePerDamagePointMultiHarvest);
darkSteelAxeSpeedPenaltyMultiHarvest = (float) config.get(sectionDarkSteel.name, "darkSteelAxeSpeedPenaltyMultiHarvest",
darkSteelAxeSpeedPenaltyMultiHarvest,
"How much slower shift-harvesting logs is.").getDouble(darkSteelAxeSpeedPenaltyMultiHarvest);
darkSteelAxeEffeciencyBoostWhenPowered = (float) config.get(sectionDarkSteel.name, "darkSteelAxeEffeciencyBoostWhenPowered",
darkSteelAxeEffeciencyBoostWhenPowered, "The increase in efficiency when powered.").getDouble(darkSteelAxeEffeciencyBoostWhenPowered);
darkSteelShearsDurabilityFactor = config.get(sectionDarkSteel.name, "darkSteelShearsDurabilityFactor", darkSteelShearsDurabilityFactor,
"How much more durable as vanilla shears they are.").getInt(darkSteelShearsDurabilityFactor);
darkSteelShearsPowerUsePerDamagePoint = config.get(sectionDarkSteel.name, "darkSteelShearsPowerUsePerDamagePoint", darkSteelShearsPowerUsePerDamagePoint,
"Power use (RF) per damage/durability point avoided.").getInt(darkSteelShearsPowerUsePerDamagePoint);
darkSteelShearsEffeciencyBoostWhenPowered = (float) config.get(sectionDarkSteel.name, "darkSteelShearsEffeciencyBoostWhenPowered",
darkSteelShearsEffeciencyBoostWhenPowered, "The increase in efficiency when powered.").getDouble(darkSteelShearsEffeciencyBoostWhenPowered);
darkSteelShearsBlockAreaBoostWhenPowered = config.get(sectionDarkSteel.name, "darkSteelShearsBlockAreaBoostWhenPowered", darkSteelShearsBlockAreaBoostWhenPowered,
"The increase in effected area (radius) when powered and used on blocks.").getInt(darkSteelShearsBlockAreaBoostWhenPowered);
darkSteelShearsEntityAreaBoostWhenPowered = (float) config.get(sectionDarkSteel.name, "darkSteelShearsEntityAreaBoostWhenPowered",
darkSteelShearsEntityAreaBoostWhenPowered, "The increase in effected area (radius) when powered and used on sheep.").getDouble(darkSteelShearsEntityAreaBoostWhenPowered);
darkSteelAnvilDamageChance = (float) config.get(sectionDarkSteel.name, "darkSteelAnvilDamageChance", darkSteelAnvilDamageChance, "Chance that the dark steel anvil will take damage after repairing something.").getDouble();
darkSteelLadderSpeedBoost = (float) config.get(sectionDarkSteel.name, "darkSteelLadderSpeedBoost", darkSteelLadderSpeedBoost, "Speed boost, in blocks per tick, that the DS ladder gives over the vanilla ladder.").getDouble();
hootchPowerPerCycleRF = config.get(sectionPower.name, "hootchPowerPerCycleRF", hootchPowerPerCycleRF,
"The amount of power generated per BC engine cycle. Examples: BC Oil = 30, BC Fuel = 60").getInt(hootchPowerPerCycleRF);
hootchPowerTotalBurnTime = config.get(sectionPower.name, "hootchPowerTotalBurnTime", hootchPowerTotalBurnTime,
"The total burn time. Examples: BC Oil = 5000, BC Fuel = 25000").getInt(hootchPowerTotalBurnTime);
rocketFuelPowerPerCycleRF = config.get(sectionPower.name, "rocketFuelPowerPerCycleRF", rocketFuelPowerPerCycleRF,
"The amount of power generated per BC engine cycle. Examples: BC Oil = 3, BC Fuel = 6").getInt(rocketFuelPowerPerCycleRF);
rocketFuelPowerTotalBurnTime = config.get(sectionPower.name, "rocketFuelPowerTotalBurnTime", rocketFuelPowerTotalBurnTime,
"The total burn time. Examples: BC Oil = 5000, BC Fuel = 25000").getInt(rocketFuelPowerTotalBurnTime);
fireWaterPowerPerCycleRF = config.get(sectionPower.name, "fireWaterPowerPerCycleRF", fireWaterPowerPerCycleRF,
"The amount of power generated per BC engine cycle. Examples: BC Oil = 30, BC Fuel = 60").getInt(fireWaterPowerPerCycleRF);
fireWaterPowerTotalBurnTime = config.get(sectionPower.name, "fireWaterPowerTotalBurnTime", fireWaterPowerTotalBurnTime,
"The total burn time. Examples: BC Oil = 5000, BC Fuel = 25000").getInt(fireWaterPowerTotalBurnTime);
zombieGeneratorRfPerTick = config.get(sectionPower.name, "zombieGeneratorRfPerTick", zombieGeneratorRfPerTick,
"The amount of power generated per tick.").getInt(zombieGeneratorRfPerTick);
zombieGeneratorTicksPerBucketFuel = config.get(sectionPower.name, "zombieGeneratorTicksPerMbFuel", zombieGeneratorTicksPerBucketFuel,
"The number of ticks one bucket of fuel lasts.").getInt(zombieGeneratorTicksPerBucketFuel);
stirlingGeneratorBaseRfPerTick = config.get(sectionPower.name, "stirlingGeneratorBaseRfPerTick", stirlingGeneratorBaseRfPerTick,
"The amount of power generated per tick.").getInt(stirlingGeneratorBaseRfPerTick);
addFuelTooltipsToAllFluidContainers = config.get(sectionPersonal.name, "addFuelTooltipsToAllFluidContainers", addFuelTooltipsToAllFluidContainers,
"If true, the RF/t and burn time of the fuel will be displayed in all tooltips for fluid containers with fuel.").getBoolean(
addFuelTooltipsToAllFluidContainers);
addDurabilityTootip = config.get(sectionPersonal.name, "addDurabilityTootip", addFuelTooltipsToAllFluidContainers,
"If true, adds durability tooltips to tools and armor").getBoolean(
addDurabilityTootip);
addFurnaceFuelTootip = config.get(sectionPersonal.name, "addFurnaceFuelTootip", addFuelTooltipsToAllFluidContainers,
"If true, adds burn duration tooltips to furnace fuels").getBoolean(addFurnaceFuelTootip);
addOreDictionaryTooltips = config.get(sectionPersonal.name, "addOreDictionaryTooltips", addOreDictionaryTooltips,
"If true, adds ore dictionary registrations to tooltips").getBoolean(addOreDictionaryTooltips);
addRegisterdNameTooltip = config.get(sectionPersonal.name, "addRegisterdNameTooltip", addRegisterdNameTooltip,
"If true, adds the registered name for the item").getBoolean(addRegisterdNameTooltip);
farmContinuousEnergyUseRF = config.get(sectionFarm.name, "farmContinuousEnergyUseRF", farmContinuousEnergyUseRF,
"The amount of power used by a farm per tick ").getInt(farmContinuousEnergyUseRF);
farmActionEnergyUseRF = config.get(sectionFarm.name, "farmActionEnergyUseRF", farmActionEnergyUseRF,
"The amount of power used by a farm per action (eg plant, till, harvest) ").getInt(farmActionEnergyUseRF);
farmAxeActionEnergyUseRF = config.get(sectionFarm.name, "farmAxeActionEnergyUseRF", farmAxeActionEnergyUseRF,
"The amount of power used by a farm per wood block 'chopped'").getInt(farmAxeActionEnergyUseRF);
farmBonemealActionEnergyUseRF = config.get(sectionFarm.name, "farmBonemealActionEnergyUseRF", farmBonemealActionEnergyUseRF,
"The amount of power used by a farm per bone meal used").getInt(farmBonemealActionEnergyUseRF);
farmBonemealTryEnergyUseRF = config.get(sectionFarm.name, "farmBonemealTryEnergyUseRF", farmBonemealTryEnergyUseRF,
"The amount of power used by a farm per bone meal try").getInt(farmBonemealTryEnergyUseRF);
farmDefaultSize = config.get(sectionFarm.name, "farmDefaultSize", farmDefaultSize,
"The number of blocks a farm will extend from its center").getInt(farmDefaultSize);
farmAxeDamageOnLeafBreak = config.get(sectionFarm.name, "farmAxeDamageOnLeafBreak", farmAxeDamageOnLeafBreak,
"Should axes in a farm take damage when breaking leaves?").getBoolean(farmAxeDamageOnLeafBreak);
farmToolTakeDamageChance = (float) config.get(sectionFarm.name, "farmToolTakeDamageChance", farmToolTakeDamageChance,
"The chance that a tool in the farm will take damage.").getDouble(farmToolTakeDamageChance);
disableFarmNotification = config.get(sectionFarm.name, "disableFarmNotifications", disableFarmNotification,
"Disable the notification text above the farm block.").getBoolean();
farmEssenceBerriesEnabled = config.get(sectionFarm.name, "farmEssenceBerriesEnabled", farmEssenceBerriesEnabled,
"This setting controls whether essence berry bushes from TiC can be harvested by the farm.").getBoolean();
farmManaBeansEnabled = config.get(sectionFarm.name, "farmManaBeansEnabled", farmManaBeansEnabled,
"This setting controls whether mana beans from Thaumcraft can be harvested by the farm.").getBoolean();
farmHarvestJungleWhenCocoa = config.get(sectionFarm.name, "farmHarvestJungleWhenCocoa", farmHarvestJungleWhenCocoa,
"If this is enabled the farm will harvest jungle wood even if it has cocoa beans in its inventory.").getBoolean();
hoeStrings = config.get(sectionFarm.name, "farmHoes", hoeStrings,
"Use this to specify items that can be hoes in the farming station. Use the registry name (eg. modid:name).").getStringList();
farmSaplingReserveAmount = config.get(sectionFarm.name, "farmSaplingReserveAmount", farmSaplingReserveAmount,
"The amount of saplings the farm has to have in reserve to switch to shearing all leaves. If there are less " +
"saplings in store, it will only shear part the leaves and break the others for spalings. Set this to 0 to " +
"always shear all leaves.").getInt(farmSaplingReserveAmount);
combustionGeneratorUseOpaqueModel = config.get(sectionAesthetic.name, "combustionGeneratorUseOpaqueModel", combustionGeneratorUseOpaqueModel,
"If set to true: fluid will not be shown in combustion generator tanks. Improves FPS. ").getBoolean(combustionGeneratorUseOpaqueModel);
magnetPowerUsePerSecondRF = config.get(sectionMagnet.name, "magnetPowerUsePerTickRF", magnetPowerUsePerSecondRF,
"The amount of RF power used per tick when the magnet is active").getInt(magnetPowerUsePerSecondRF);
magnetPowerCapacityRF = config.get(sectionMagnet.name, "magnetPowerCapacityRF", magnetPowerCapacityRF,
"Amount of RF power stored in a fully charged magnet").getInt(magnetPowerCapacityRF);
magnetRange = config.get(sectionMagnet.name, "magnetRange", magnetRange,
"Range of the magnet in blocks.").getInt(magnetRange);
magnetBlacklist = config.getStringList("magnetBlacklist", sectionMagnet.name, magnetBlacklist,
"These items will not be picked up by the magnet.");
useCombustionGenModel = config.get(sectionAesthetic.name, "useCombustionGenModel", useCombustionGenModel,
"If set to true: WIP Combustion Generator model will be used").getBoolean(useCombustionGenModel);
crafterRfPerCraft = config.get("AutoCrafter Settings", "crafterRfPerCraft", crafterRfPerCraft,
"RF used per autocrafted recipe").getInt(crafterRfPerCraft);
poweredSpawnerMinDelayTicks = config.get(sectionSpawner.name, "poweredSpawnerMinDelayTicks", poweredSpawnerMinDelayTicks,
"Min tick delay between spawns for a non-upgraded spawner").getInt(poweredSpawnerMinDelayTicks);
poweredSpawnerMaxDelayTicks = config.get(sectionSpawner.name, "poweredSpawnerMaxDelayTicks", poweredSpawnerMaxDelayTicks,
"Min tick delay between spawns for a non-upgraded spawner").getInt(poweredSpawnerMaxDelayTicks);
poweredSpawnerLevelOnePowerPerTickRF = config.get(sectionSpawner.name, "poweredSpawnerLevelOnePowerPerTickRF", poweredSpawnerLevelOnePowerPerTickRF,
"RF per tick for a level 1 (non-upgraded) spawner. See PoweredSpanerConfig_Core.json for mob type multipliers").getInt(poweredSpawnerLevelOnePowerPerTickRF);
poweredSpawnerLevelTwoPowerPerTickRF = config.get(sectionSpawner.name, "poweredSpawnerLevelTwoPowerPerTickRF", poweredSpawnerLevelTwoPowerPerTickRF,
"RF per tick for a level 2 spawner").getInt(poweredSpawnerLevelTwoPowerPerTickRF);
poweredSpawnerLevelThreePowerPerTickRF = config.get(sectionSpawner.name, "poweredSpawnerLevelThreePowerPerTickRF",
poweredSpawnerLevelThreePowerPerTickRF,
"RF per tick for a level 3 spawner").getInt(poweredSpawnerLevelThreePowerPerTickRF);
poweredSpawnerMaxPlayerDistance = config.get(sectionSpawner.name, "poweredSpawnerMaxPlayerDistance", poweredSpawnerMaxPlayerDistance,
"Max distance of the closest player for the spawner to be active. A zero value will remove the player check").getInt(poweredSpawnerMaxPlayerDistance);
poweredSpawnerDespawnTimeSeconds = config.get(sectionSpawner.name, "poweredSpawnerDespawnTimeSeconds" , poweredSpawnerDespawnTimeSeconds,
"Number of seconds in which spawned entities are protected from despawning").getInt(poweredSpawnerDespawnTimeSeconds);
poweredSpawnerUseVanillaSpawChecks = config.get(sectionSpawner.name, "poweredSpawnerUseVanillaSpawChecks", poweredSpawnerUseVanillaSpawChecks,
"If true, regular spawn checks such as lighting level and dimension will be made before spawning mobs").getBoolean(poweredSpawnerUseVanillaSpawChecks);
brokenSpawnerDropChance = (float) config.get(sectionSpawner.name, "brokenSpawnerDropChance", brokenSpawnerDropChance,
"The chance a broken spawner will be dropped when a spawner is broken. 1 = 100% chance, 0 = 0% chance").getDouble(brokenSpawnerDropChance);
brokenSpawnerToolBlacklist = config.getStringList("brokenSpawnerToolBlacklist", sectionSpawner.name, brokenSpawnerToolBlacklist,
"When a spawner is broken with these tools they will not drop a broken spawner");
powerSpawnerAddSpawnerCost = config.get(sectionSpawner.name, "powerSpawnerAddSpawnerCost", powerSpawnerAddSpawnerCost,
"The number of levels it costs to add a broken spawner").getInt(powerSpawnerAddSpawnerCost);
useModMetals = config.get(sectionRecipe.name, "useModMetals", useModMetals,
"If true copper and tin will be used in recipes when registered in the ore dictionary").getBoolean(useModMetals);
nutrientFoodBoostDelay = config.get(sectionFluid.name, "nutrientFluidFoodBoostDelay", nutrientFoodBoostDelay,
"The delay in ticks between when nutrient distillation boosts your food value.").getInt((int) nutrientFoodBoostDelay);
killerJoeNutrientUsePerAttackMb = config.get(sectionKiller.name, "killerJoeNutrientUsePerAttackMb", killerJoeNutrientUsePerAttackMb,
"The number of millibuckets of nutrient fluid used per attack.").getInt(killerJoeNutrientUsePerAttackMb);
killerJoeAttackHeight = config.get(sectionKiller.name, "killerJoeAttackHeight", killerJoeAttackHeight,
"The reach of attacks above and bellow Joe.").getDouble(killerJoeAttackHeight);
killerJoeAttackWidth = config.get(sectionKiller.name, "killerJoeAttackWidth", killerJoeAttackWidth,
"The reach of attacks to each side of Joe.").getDouble(killerJoeAttackWidth);
killerJoeAttackLength = config.get(sectionKiller.name, "killerJoeAttackLength", killerJoeAttackLength,
"The reach of attacks in front of Joe.").getDouble(killerJoeAttackLength);
killerJoeHooverXpLength = config.get(sectionKiller.name, "killerJoeHooverXpLength", killerJoeHooverXpLength,
"The distance from which XP will be gathered to each side of Joe.").getDouble(killerJoeHooverXpLength);
killerJoeHooverXpWidth = config.get(sectionKiller.name, "killerJoeHooverXpWidth", killerJoeHooverXpWidth,
"The distance from which XP will be gathered in front of Joe.").getDouble(killerJoeHooverXpWidth);
killerJoeMaxXpLevel = config.get(sectionMisc.name, "killerJoeMaxXpLevel", killerJoeMaxXpLevel, "Maximum level of XP the killer joe can contain.").getInt();
killerJoeMustSee = config.get(sectionKiller.name, "killerJoeMustSee", killerJoeMustSee, "Set whether the Killer Joe can attack through blocks.").getBoolean();
// Add deprecated comment
config.getString("isGasConduitEnabled", sectionItems.name, "auto", "Deprecated option. Use boolean \"gasConduitsEnabled\" below.");
isGasConduitEnabled = config.getBoolean("gasConduitEnabled", sectionItems.name, isGasConduitEnabled,
"If true, gas conduits will be enabled if the Mekanism Gas API is found. False to forcibly disable.");
enableMEConduits = config.getBoolean("enableMEConduits", sectionItems.name, enableMEConduits, "Allows ME conduits. Only has an effect with AE2 installed.");
soulVesselBlackList = config.getStringList("soulVesselBlackList", sectionSoulBinder.name, soulVesselBlackList,
"Entities listed here will can not be captured in a Soul Vial");
soulVesselCapturesBosses = config.getBoolean("soulVesselCapturesBosses", sectionSoulBinder.name, soulVesselCapturesBosses,
"When set to false, any mob with a 'boss bar' won't be able to be captured in the Soul Vial");
soulBinderLevelOnePowerPerTickRF = config.get(sectionSoulBinder.name, "soulBinderLevelOnePowerPerTickRF", soulBinderLevelOnePowerPerTickRF,
"The number of RF/t consumed by an unupgraded soul binder.").getInt(soulBinderLevelOnePowerPerTickRF);
soulBinderLevelTwoPowerPerTickRF = config.get(sectionSoulBinder.name, "soulBinderLevelTwoPowerPerTickRF", soulBinderLevelTwoPowerPerTickRF,
"The number of RF/t consumed by a soul binder with a double layer capacitor upgrade.").getInt(soulBinderLevelTwoPowerPerTickRF);
soulBinderLevelThreePowerPerTickRF = config.get(sectionSoulBinder.name, "soulBinderLevelThreePowerPerTickRF", soulBinderLevelThreePowerPerTickRF,
"The number of RF/t consumed by a soul binder with an octadic capacitor upgrade.").getInt(soulBinderLevelThreePowerPerTickRF);
soulBinderBrokenSpawnerRF = config.get(sectionSoulBinder.name, "soulBinderBrokenSpawnerRF", soulBinderBrokenSpawnerRF,
"The number of RF required to change the type of a broken spawner.").getInt(soulBinderBrokenSpawnerRF);
soulBinderReanimationRF = config.get(sectionSoulBinder.name, "soulBinderReanimationRF", soulBinderReanimationRF,
"The number of RF required to to re-animated a mob head.").getInt(soulBinderReanimationRF);
soulBinderEnderCystalRF = config.get(sectionSoulBinder.name, "soulBinderEnderCystalRF", soulBinderEnderCystalRF,
"The number of RF required to create an ender crystal.").getInt(soulBinderEnderCystalRF);
soulBinderAttractorCystalRF = config.get(sectionSoulBinder.name, "soulBinderAttractorCystalRF", soulBinderAttractorCystalRF,
"The number of RF required to create an attractor crystal.").getInt(soulBinderAttractorCystalRF);
soulBinderEnderRailRF = config.get(sectionSoulBinder.name, "soulBinderEnderRailRF", soulBinderEnderRailRF,
"The number of RF required to create an ender rail.").getInt(soulBinderEnderRailRF);
soulBinderAttractorCystalLevels = config.get(sectionSoulBinder.name, "soulBinderAttractorCystalLevels", soulBinderAttractorCystalLevels,
"The number of levels required to create an attractor crystal.").getInt(soulBinderAttractorCystalLevels);
soulBinderEnderCystalLevels = config.get(sectionSoulBinder.name, "soulBinderEnderCystalLevels", soulBinderEnderCystalLevels,
"The number of levels required to create an ender crystal.").getInt(soulBinderEnderCystalLevels);
soulBinderReanimationLevels = config.get(sectionSoulBinder.name, "soulBinderReanimationLevels", soulBinderReanimationLevels,
"The number of levels required to re-animate a mob head.").getInt(soulBinderReanimationLevels);
soulBinderBrokenSpawnerLevels = config.get(sectionSoulBinder.name, "soulBinderBrokenSpawnerLevels", soulBinderBrokenSpawnerLevels,
"The number of levels required to change the type of a broken spawner.").getInt(soulBinderBrokenSpawnerLevels);
soulBinderEnderRailLevels = config.get(sectionSoulBinder.name, "soulBinderEnderRailLevels", soulBinderEnderRailLevels,
"The number of levels required to create an ender rail.").getInt(soulBinderEnderRailLevels);
soulBinderMaxXpLevel = config.get(sectionSoulBinder.name, "soulBinderMaxXPLevel", soulBinderMaxXpLevel, "Maximum level of XP the soul binder can contain.").getInt();
sliceAndSpliceLevelOnePowerPerTickRF = config.get(sectionPower.name, "sliceAndSpliceLevelOnePowerPerTickRF", sliceAndSpliceLevelOnePowerPerTickRF,
"The number of RF/t consumed by an unupgraded Slice'N'Splice").getInt(sliceAndSpliceLevelOnePowerPerTickRF);
sliceAndSpliceLevelTwoPowerPerTickRF = config.get(sectionPower.name, "sliceAndSpliceLevelTwoPowerPerTickRF", sliceAndSpliceLevelTwoPowerPerTickRF,
"The number of RF/t consumed by a Slice'N'Splice with a double layer capacitor upgrade.").getInt(sliceAndSpliceLevelTwoPowerPerTickRF);
sliceAndSpliceLevelThreePowerPerTickRF = config.get(sectionPower.name, "sliceAndSpliceLevelThreePowerPerTickRF", sliceAndSpliceLevelThreePowerPerTickRF,
"The number of RF/t consumed by a Slice'N'Splice with an octadic capacitor upgrade.").getInt(sliceAndSpliceLevelThreePowerPerTickRF);
attractorRangeLevelOne = config.get(sectionAttractor.name, "attractorRangeLevelOne", attractorRangeLevelOne,
"The range of the mob attractor with no upgrades").getInt(attractorRangeLevelOne);
attractorRangeLevelTwo = config.get(sectionAttractor.name, "attractorRangeLevelTwo", attractorRangeLevelTwo,
"The range of the mob attractor with a double layer capacitor upgrade").getInt(attractorRangeLevelTwo);
attractorRangeLevelThree = config.get(sectionAttractor.name, "attractorRangeLevelThree", attractorRangeLevelThree,
"The range of the mob attractor with an octadic capacitor upgrade").getInt(attractorRangeLevelThree);
attractorPowerPerTickLevelOne = config.get(sectionAttractor.name, "attractorPowerPerTickLevelOne", attractorPowerPerTickLevelOne,
"The RF/t power use of a levele 1 mob attractor").getInt(attractorPowerPerTickLevelOne);
attractorPowerPerTickLevelTwo = config.get(sectionAttractor.name, "attractorPowerPerTickLevelTwo", attractorPowerPerTickLevelTwo,
"The RF/t power use of a levele 2 mob attractor").getInt(attractorPowerPerTickLevelTwo);
attractorPowerPerTickLevelThree = config.get(sectionAttractor.name, "attractorPowerPerTickLevelThree", attractorPowerPerTickLevelThree,
"The RF/t power use of a levele 3 mob attractor").getInt(attractorPowerPerTickLevelThree);
spawnGuardRangeLevelOne = config.get(sectionAttractor.name, "spawnGuardRangeLevelOne", spawnGuardRangeLevelOne,
"The range of the spawn guard with no upgrades").getInt(spawnGuardRangeLevelOne);
spawnGuardRangeLevelTwo = config.get(sectionAttractor.name, "spawnGuardRangeLevelTwo", spawnGuardRangeLevelTwo,
"The range of the spawn guard with a double layer capacitor upgrade").getInt(spawnGuardRangeLevelTwo);
spawnGuardRangeLevelThree = config.get(sectionAttractor.name, "spawnGuardRangeLevelThree", spawnGuardRangeLevelThree,
"The range of the spawn guard with an octadic capacitor upgrade").getInt(spawnGuardRangeLevelThree);
spawnGuardPowerPerTickLevelOne = config.get(sectionAttractor.name, "spawnGuardPowerPerTickLevelOne", spawnGuardPowerPerTickLevelOne,
"The RF/t power use of a levele 1 spawn guard").getInt(spawnGuardPowerPerTickLevelOne);
spawnGuardPowerPerTickLevelTwo = config.get(sectionAttractor.name, "spawnGuardPowerPerTickLevelTwo", spawnGuardPowerPerTickLevelTwo,
"The RF/t power use of a levele 2 spawn guard").getInt(spawnGuardPowerPerTickLevelTwo);
spawnGuardPowerPerTickLevelThree = config.get(sectionAttractor.name, "spawnGuardPowerPerTickLevelThree", spawnGuardPowerPerTickLevelThree,
"The RF/t power use of a levele 3 spawn guard").getInt(spawnGuardPowerPerTickLevelThree);
spawnGuardStopAllSlimesDebug = config.getBoolean("spawnGuardStopAllSlimesDebug", sectionAttractor.name, spawnGuardStopAllSlimesDebug,
"When true slimes wont be allowed to spawn at all. Only added to aid testing in super flat worlds.");
spawnGuardStopAllSquidSpawning = config.getBoolean("spawnGuardStopAllSquidSpawning", sectionAttractor.name, spawnGuardStopAllSquidSpawning,
"When true no squid will be spawned.");
weatherObeliskClearItem = config.get(sectionWeather.name, "weatherObeliskClearItem", weatherObeliskClearItem,
"The item required to set the world to clear weather.").getString();
weatherObeliskRainItem = config.get(sectionWeather.name, "weatherObeliskRainItem", weatherObeliskRainItem,
"The item required to set the world to rainy weather.").getString();
weatherObeliskThunderItem = config.get(sectionWeather.name, "weatherObeliskThunderItem", weatherObeliskThunderItem,
"The item required to set the world to thundering weather.").getString();
weatherObeliskClearPower = config.get(sectionWeather.name, "weatherObeliskClearPower", weatherObeliskClearPower,
"The power required to set the world to clear weather").getInt();
weatherObeliskRainPower = config.get(sectionWeather.name, "weatherObeliskRainPower", weatherObeliskRainPower,
"The power required to set the world to rainy weather").getInt();
weatherObeliskThunderPower = config.get(sectionWeather.name, "weatherObeliskThunderPower", weatherObeliskThunderPower,
"The power required to set the world to thundering weather").getInt();
// Loot Config
lootDarkSteel = config.getBoolean("lootDarkSteel", sectionLootConfig.name, lootDarkSteel, "Adds Darksteel Ingots to loot tables");
lootItemConduitProbe = config.getBoolean("lootItemConduitProbe", sectionLootConfig.name, lootItemConduitProbe, "Adds ItemConduitProbe to loot tables");
lootQuartz = config.getBoolean("lootQuartz", sectionLootConfig.name, lootQuartz, "Adds quartz to loot tables");
lootNetherWart = config.getBoolean("lootNetherWart", sectionLootConfig.name, lootNetherWart, "Adds nether wart to loot tables");
lootEnderPearl = config.getBoolean("lootEnderPearl", sectionLootConfig.name, lootEnderPearl, "Adds ender pearls to loot tables");
lootElectricSteel = config.getBoolean("lootElectricSteel", sectionLootConfig.name, lootElectricSteel, "Adds Electric Steel Ingots to loot tables");
lootRedstoneAlloy = config.getBoolean("lootRedstoneAlloy", sectionLootConfig.name, lootRedstoneAlloy, "Adds Redstone Alloy Ingots to loot tables");
lootPhasedIron = config.getBoolean("lootPhasedIron", sectionLootConfig.name, lootPhasedIron, "Adds Phased Iron Ingots to loot tables");
lootPhasedGold = config.getBoolean("lootPhasedGold", sectionLootConfig.name, lootPhasedGold, "Adds Phased Gold Ingots to loot tables");
lootTravelStaff = config.getBoolean("lootTravelStaff", sectionLootConfig.name, lootTravelStaff, "Adds Travel Staff to loot tables");
lootTheEnder = config.getBoolean("lootTheEnder", sectionLootConfig.name, lootTheEnder, "Adds The Ender to loot tables");
lootDarkSteelBoots = config.getBoolean("lootDarkSteelBoots", sectionLootConfig.name, lootDarkSteelBoots, "Adds Darksteel Boots to loot tables");
enderRailEnabled = config.getBoolean("enderRailEnabled", sectionRailConfig.name, enderRailEnabled, "Wether Ender Rails are enabled");
enderRailPowerRequireCrossDimensions = config.get(sectionRailConfig.name, "enderRailPowerRequireCrossDimensions", enderRailPowerRequireCrossDimensions,
"The amount of power required to transport a cart across dimensions").getInt(enderRailPowerRequireCrossDimensions);
enderRailPowerRequiredPerBlock = config.get(sectionRailConfig.name, "enderRailPowerRequiredPerBlock", enderRailPowerRequiredPerBlock,
"The amount of power required to teleport a cart per block in the same dimension").getInt(enderRailPowerRequiredPerBlock);
enderRailCapSameDimensionPowerAtCrossDimensionCost = config.getBoolean("enderRailCapSameDimensionPowerAtCrossDimensionCost", sectionRailConfig.name, enderRailCapSameDimensionPowerAtCrossDimensionCost,
"When set to true the RF cost of sending a cart within the same dimension will be capped to the cross dimension cost");
enderRailTicksBeforeForceSpawningLinkedCarts = config.get(sectionRailConfig.name, "enderRailTicksBeforeForceSpawningLinkedCarts", enderRailTicksBeforeForceSpawningLinkedCarts,
"The number of ticks to wait for the track to clear before force spawning the next cart in a (RailCraft) linked set").getInt(enderRailTicksBeforeForceSpawningLinkedCarts);
enderRailTeleportPlayers = config.getBoolean("enderRailTeleportPlayers", sectionRailConfig.name, enderRailTeleportPlayers, "If true player in minecarts will be teleported. WARN: WIP, seems to cause a memory leak.");
dumpMobNames = config.getBoolean("dumpMobNames", sectionMobConfig.name, dumpMobNames,
"When set to true a list of all registered mobs will be dumped to config/enderio/mobTypes.txt The names are in the format required by EIOs mob blacklists.");
xpObeliskMaxXpLevel = config.get(sectionMisc.name, "xpObeliskMaxXpLevel", xpObeliskMaxXpLevel, "Maximum level of XP the xp obelisk can contain.").getInt();
xpJuiceName = config.getString("xpJuiceName", sectionMisc.name, xpJuiceName, "Id of liquid XP fluid (WARNING: only for users who know what they are doing - changing this id can break worlds) - this should match the with OpenBlocks when installed");
clearGlassSameTexture = config.getBoolean("clearGlassSameTexture", sectionMisc.name, clearGlassSameTexture, "If true, quite clear glass will use the fused quartz border texture for the block instead of the white border.");
clearGlassConnectToFusedQuartz = config.getBoolean("clearGlassConnectToFusedQuartz", sectionMisc.name, clearGlassConnectToFusedQuartz, "If true, quite clear glass will connect textures with fused quartz.");
enchantmentSoulBoundEnabled = config.getBoolean("enchantmentSoulBoundEnabled", sectionEnchantments.name, enchantmentSoulBoundEnabled,
"If false the soul bound enchantment will not be available");
enchantmentSoulBoundId = config.get(sectionEnchantments.name, "enchantmentSoulBoundId", enchantmentSoulBoundId,
"The id of the enchantment. If set to -1 the lowest unassigned id will be used.").getInt(enchantmentSoulBoundId);
enchantmentSoulBoundWeight = config.get(sectionEnchantments.name, "enchantmentSoulBoundWeight", enchantmentSoulBoundWeight,
"The chance of getting this enchantment in the enchantment table").getInt(enchantmentSoulBoundWeight);
replaceWitherSkeletons = config.get(sectionMisc.name, "replaceWitherSkeletons", replaceWitherSkeletons,
"Separates wither and normal skeletons into different entities, enables the powered spawner to treat them differently [EXPERIMENTAL - MAY CAUSE ISSUES WITH OTHER MODS]").getBoolean();
enableWaterFromBottles = config
.get(
sectionMisc.name,
"enableWaterFromBottles",
enableWaterFromBottles,
"Enables emptying vanilla water bottles without breaking the bottle. In combination with a water source block this allows duping of water without cost.")
.getBoolean();
telepadLockDimension = config.get(sectionTelepad.name, "lockDimension", telepadLockDimension,
"If true, the dimension cannot be set via the GUI, the coord selector must be used.").getBoolean();
telepadLockCoords = config.get(sectionTelepad.name, "lockCoords", telepadLockCoords,
"If true, the coordinates cannot be set via the GUI, the coord selector must be used.").getBoolean();
inventoryPanelPowerPerMB = config.getFloat("powerPerMB", sectionInventoryPanel.name, inventoryPanelPowerPerMB, 1.0f, 10000.0f,
"Internal power generated per mB. The default of 800/mB matches the RF generation of the Zombie generator. A panel tries to refill only once every second - setting this value too low slows down the scanning speed.");
inventoryPanelScanCostPerSlot = config.getFloat("scanCostPerSlot", sectionInventoryPanel.name, inventoryPanelScanCostPerSlot, 0.0f, 10.0f,
"Internal power used for scanning a slot");
inventoryPanelExtractCostPerItem = config.getFloat("extractCostPerItem", sectionInventoryPanel.name, inventoryPanelExtractCostPerItem, 0.0f, 10.0f,
"Internal power used per item extracted (not a stack of items)");
inventoryPanelExtractCostPerOperation = config.getFloat("extractCostPerOperation", sectionInventoryPanel.name, inventoryPanelExtractCostPerOperation, 0.0f, 10000.0f,
"Internal power used per extract operation (independent of stack size)");
}
public static void init() {
WeatherTask.CLEAR.setRequiredItem(getStackForString(weatherObeliskClearItem));
WeatherTask.RAIN.setRequiredItem(getStackForString(weatherObeliskRainItem));
WeatherTask.STORM.setRequiredItem(getStackForString(weatherObeliskThunderItem));
}
public static void postInit() {
for (String s : hoeStrings) {
ItemStack hoe = getStackForString(s);
if(hoe != null) {
farmHoes.add(hoe);
}
}
}
public static ItemStack getStackForString(String s) {
String[] nameAndMeta = s.split(";");
int meta = nameAndMeta.length == 1 ? 0 : Integer.parseInt(nameAndMeta[1]);
String[] data = nameAndMeta[0].split(":");
ItemStack stack = GameRegistry.findItemStack(data[0], data[1], 1);
if(stack == null) {
return null;
}
stack.setItemDamage(meta);
return stack;
}
private Config() {
}
} |
package de.fraunhofer.iosb.ilt.sta;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import org.apache.http.Consts;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import org.apache.http.client.methods.HttpRequestBase;
/**
*
* @author scf
*/
public class Utils {
/**
* The logger for this class.
*/
private static final Logger LOGGER = LoggerFactory.getLogger(Utils.class);
/**
* Returns true if the given string is null, or empty.
*
* @param string the string to check.
* @return true if string == null || string.isEmpty()
*/
public static boolean isNullOrEmpty(String string) {
return string == null || string.isEmpty();
}
/**
* Replaces all ' in the string with ''.
*
* @param in The string to escape.
* @return The escaped string.
*/
public static String escapeForStringConstant(String in) {
return in.replaceAll("'", "''");
}
public static String quoteForUrl(Object in) {
if (in instanceof Number) {
return in.toString();
}
return "'" + escapeForStringConstant(in.toString()) + "'";
}
/**
* Urlencodes the given string, optionally not encoding forward slashes.
*
* In urls, forward slashes before the "?" must never be urlEncoded.
* Urlencoding of slashes could otherwise be used to obfuscate phising URLs.
*
* @param string The string to urlEncode.
* @param notSlashes If true, forward slashes are not encoded.
* @return The urlEncoded string.
*/
public static String urlEncode(String string, boolean notSlashes) {
if (notSlashes) {
return urlEncodeNotSlashes(string);
}
try {
return URLEncoder.encode(string, StandardCharsets.UTF_8.name());
} catch (UnsupportedEncodingException ex) {
LOGGER.error("Should not happen, UTF-8 should always be supported.", ex);
}
return string;
}
/**
* Urlencodes the given string
*
* @param string The string to urlEncode.
* @return The urlEncoded string.
*/
public static String urlEncode(String string) {
try {
return URLEncoder.encode(string, StandardCharsets.UTF_8.name());
} catch (UnsupportedEncodingException ex) {
LOGGER.error("Should not happen, UTF-8 should always be supported.", ex);
}
return string;
}
/**
* Urlencodes the given string, except for the forward slashes.
*
* @param string The string to urlEncode.
* @return The urlEncoded string.
*/
public static String urlEncodeNotSlashes(String string) {
try {
String[] split = string.split("/");
for (int i = 0; i < split.length; i++) {
split[i] = URLEncoder.encode(split[i], StandardCharsets.UTF_8.name());
}
return String.join("/", split);
} catch (UnsupportedEncodingException ex) {
LOGGER.error("Should not happen, UTF-8 should always be supported.", ex);
}
return string;
}
/**
* Throws a StatusCodeException if the given response did not have status
* code 2xx
*
* @param request The request that generated the response.
* @param response The response to check the status code of.
* @throws StatusCodeException If the response was not 2xx.
*/
public static void throwIfNotOk(HttpRequestBase request, CloseableHttpResponse response) throws StatusCodeException {
final int statusCode = response.getStatusLine().getStatusCode();
if (statusCode < 200 || statusCode >= 300) {
String returnContent = null;
try {
returnContent = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
} catch (IOException exc) {
LOGGER.warn("Failed to get content from error response.", exc);
}
if (statusCode == 401 || statusCode == 403) {
request.getURI();
throw new NotAuthorizedException(request.getURI().toString(), response.getStatusLine().getReasonPhrase(), returnContent);
}
if (statusCode == 404) {
throw new NotFoundException(request.getURI().toString(), response.getStatusLine().getReasonPhrase(), returnContent);
}
throw new StatusCodeException(request.getURI().toString(), statusCode, response.getStatusLine().getReasonPhrase(), returnContent);
}
}
public static CloseableHttpClient createInsecureHttpClient() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
SSLContext sslContext = SSLContextBuilder
.create()
.loadTrustMaterial(new TrustSelfSignedStrategy())
.build();
HostnameVerifier allowAllHosts = new NoopHostnameVerifier();
SSLConnectionSocketFactory connectionFactory = new SSLConnectionSocketFactory(sslContext, allowAllHosts);
return HttpClients
.custom()
.useSystemProperties()
.setSSLSocketFactory(connectionFactory)
.build();
}
} |
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.Optional;
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 Optional<String> findTestCaseMethodNameInStack() {
final StackTraceElement ste = findTestCaseMethodInStack();
if ( ste == null ) {
return Optional.empty();
}
final String methodName = ste.getMethodName();
return Optional.of( methodName );
}
public static Optional<String> findTestCaseMethodNameInStack( final StackTraceElement[] trace ) {
final StackTraceElement ste = findTestCaseMethodInStack( trace );
if ( ste == null ) {
return Optional.empty();
}
final String methodName = ste.getMethodName();
return Optional.of( methodName );
}
public static Optional<String> findTestCaseClassNameInStack() {
final StackTraceElement ste = findTestCaseMethodInStack();
if ( ste == null ) {
return Optional.empty();
}
final String className = ste.getClassName();
return Optional.of( className );
}
public static Optional<String> findTestCaseClassNameInStack( final StackTraceElement[] trace ) {
final StackTraceElement ste = findTestCaseMethodInStack( trace );
if ( ste == null ) {
return Optional.empty();
}
final String className = ste.getClassName();
return Optional.of( className );
}
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 edu.brandeis.cs.steele.util;
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* Derive a new <code>Iterable</code> by removing adjacent duplicates
* of the provided <i>sortable</i> <code>Iterable</code>s.
* <p>Much like the STL version below:<br>
* <code>std::unique_copy(c.begin(), c.end(),
* std::ostream_iterator<c::type>(std::cout, " "));</code>
*/
class Uniq<T extends Object & Comparable<? super T>> implements Iterable<T> {
private static final long serialVersionUID = 1L;
private final Iterable<T> base;
Uniq(final Iterable<T> base) {
this(false, base);
}
Uniq(final boolean validateSort, final Iterable<T> base) {
validateSort(validateSort, base);
this.base = base;
}
/** {@inheritDoc} */
public Iterator<T> iterator() {
return new UniqIterator<T>(base);
}
private void validateSort(final boolean validateSort, final Iterable<T> base) {
if (false == validateSort) {
return;
}
if (Utils.isSorted(base, true) == false) {
final StringBuilder msg = new StringBuilder("Iterable ").
append(base).append(" violates sort criteria.");
throw new IllegalArgumentException(msg.toString());
}
}
/**
* <h4>TODO</h4>
* - support remove()
*/
private static class UniqIterator<T extends Object & Comparable<? super T>> implements Iterator<T> {
private static final long serialVersionUID = 1L;
private static final Object SENTINEL = new Object();
private final Iterator<T> base;
private Object top;
UniqIterator(final Iterable<T> iterable) {
this.base = iterable.iterator();
if (this.base.hasNext()) {
this.top = base.next();
} else {
this.top = SENTINEL;
}
}
/** {@inheritDoc} */
public T next() {
if (top == SENTINEL) {
throw new NoSuchElementException();
} else {
// store curr value of top
// find next value of top discarding any that are equal to currTop
// or setting top to SENTINEL to mark eos
T currTop = (T)top;
Object nextTop = SENTINEL;
while (base.hasNext()) {
final T next = base.next();
if (currTop.compareTo(next) == 0) {
continue;
} else {
nextTop = next;
break;
}
}
top = nextTop;
return currTop;
}
}
/** {@inheritDoc} */
// user's don't have to explicitly call this although that's a bit crazy
public boolean hasNext() {
return top != SENTINEL;
}
/** {@inheritDoc} */
public void remove() {
throw new UnsupportedOperationException();
// this is call refers to the last iterator which returned an item via next()
}
} // end class UniqIterator
} |
package fi.helsinki.cs.titokone;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import fi.helsinki.cs.ttk91.TTK91Cpu;
/**
* This class takes care of the animation window. It digs the
* needed information from a RunInfo instance.
*/
public class Animator extends JPanel implements Runnable {
private static final long serialVersionUID = -2401442068137343247L;
private final static Font textFont = new Font("Arial", Font.BOLD, 16);
private final static int R0 = 0;
private final static int R1 = 1;
private final static int R2 = 2;
private final static int R3 = 3;
private final static int R4 = 4;
private final static int R5 = 5;
private final static int R6 = 6;
private final static int R7 = 7;
private final static int TR = 8;
private final static int PC = 9;
private final static int IR = 10;
private final static int SR = 11;
private final static int BASE = 12;
private final static int LIMIT = 13;
private final static int MAR = 14;
private final static int MBR = 15;
private final static int ALU_IN1 = 16;
private final static int ALU_IN2 = 17;
private final static int ALU_OUT = 18;
private final static int EXTERNAL_DEVICE = 19;
private final static int MEMORY = 20;
private final static int[][] routeToBus = {
{182, 97, 220, 97},
{182, 119, 220, 119},
{182, 141, 220, 141},
{182, 163, 220, 163},
{182, 185, 220, 185},
{182, 207, 220, 207},
{182, 229, 220, 229},
{182, 251, 220, 251},
{257, 110, 220, 110},
{257, 132, 220, 132},
{257, 154, 220, 154},
{257, 176, 220, 176},
{257, 295, 220, 295}, // BASE
{257, 317, 220, 317}, // LIMIT
{257, 339, 220, 339}, // MAR
{257, 361, 220, 361}, // MBR
{182, 327, 220, 327}, // ALU_IN1
{182, 349, 220, 349}, // ALU_IN2
{182, 393, 220, 393}, // ALU_OUT
{520, 423, 520, 491, 220, 491}, // EXTERNAL_DEVICE
{661, 423, 661, 491, 220, 491}, // MEMORY
};
private final static int[][] whereWriteValueTo = {
{73, 105},
{73, 127},
{73, 149},
{73, 171},
{73, 193},
{73, 215},
{73, 237},
{73, 259},
{264, 117},
{264, 139},
{264, 161},
{264, 183},
{264, 303}, // BASE
{264, 325}, // LIMIT
{264, 347}, // MAR
{264, 369}, // MBR
{74, 334}, // ALU_IN1
{74, 356}, // ALU_IN2
{74, 401}, // ALU_OUT
};
private final static int[][] whereWriteLabelTo = {
{35, 103},
{35, 125},
{35, 147},
{35, 169},
{35, 191},
{35, 213},
{35, 235},
{35, 257},
{376, 116},
{376, 138},
{376, 160},
{376, 182},
{376, 302}, // BASE
{376, 324}, // LIMIT
{376, 346}, // MAR
{376, 368}, // MBR
{35, 333}, // ALU_IN1
{35, 355}, // ALU_IN2
{35, 400}, // ALU_OUT
{35, 80}, // Registers
{261, 80}, // Control unit
{261, 270}, // MMU
{35, 305}, // ALU
{525, 385}, // External device
{525, 70}, // Memory
};
private final static String[] labels = {
"R0",
"R1",
"R2",
"R3",
"R4",
"R5",
"R6",
"R7",
"TR",
"PC",
"IR",
"SR",
"BASE",
"LIMIT",
"MAR",
"MBR",
"IN1",
"IN2",
"OUT",
"Registers",
"Control unit",
"MMU",
"ALU",
"External device",
"Memory"
};
/**
* Contains values of registers, alu, memory and external device.
*/
private int[] value = new int[routeToBus.length];
/**
* Current command label
*/
private String currentCommand = "";
/**
* Comment label
*/
private String comment1 = "";
private String comment2 = "";
/**
* String presentation of status register.
*/
private String SR_String = "";
/**
* If this is true, animation will be executed without repaitings and delays.
*/
private boolean executeAnimationImmediately = false;
/**
* Is animation currently running.
*/
private boolean isAnimating = false;
/**
* Thread, that runs animation.
*/
private Thread animationThread;
/**
* RunInfo object of currently running animation.
*/
private RunInfo info;
private BufferedImage backgroundImage, doubleBuffer;
private int pointX = -1, pointY = -1;
private int delay = 40;
/**
* Base used for values shown by this GUI.
*/
private ValueBase valueBase = ValueBase.DEC;
/**
* Creats new animator.
*
* @throws IOException If there are problems reading background image throw IOException.
*/
public Animator() throws IOException {
// read the background image
ClassLoader foo = getClass().getClassLoader();
BufferedImage bi = ImageIO.read(foo.getResourceAsStream("fi/helsinki/cs/titokone/img/animator.gif"));
backgroundImage = new BufferedImage(bi.getWidth(), bi.getHeight(), BufferedImage.TYPE_INT_RGB);
doubleBuffer = new BufferedImage(bi.getWidth(), bi.getHeight(), BufferedImage.TYPE_INT_RGB);
backgroundImage.createGraphics().drawImage(bi, 0, 0, null);
}
/**
* Set base used when drawing values on UI
* @param base used to convert register values etc.
*/
public void setValueBase(ValueBase base) {
valueBase = base;
}
@Override
public void paint(Graphics g) {
// copy background image to double buffer
backgroundImage.copyData(doubleBuffer.getRaster());
Graphics g2 = doubleBuffer.createGraphics();
g2.setColor(Color.BLACK);
g2.setFont(textFont);
// write labels
for (int i = 0; i < labels.length; i++) {
g2.drawString(new Message(labels[i]).toString(), whereWriteLabelTo[i][0], whereWriteLabelTo[i][1]);
}
// write values (registers, alu, control unit, mmu)
for (int i = 0; i < whereWriteValueTo.length; i++) {
if (i != SR) {
g2.drawString(valueBase.toString(value[i]), whereWriteValueTo[i][0], whereWriteValueTo[i][1]);
} else {
g2.drawString(SR_String, whereWriteValueTo[i][0], whereWriteValueTo[i][1]);
}
}
// write current command and comments
g2.drawString(new Message("Current command: ").toString() + currentCommand, 217, 23);
g2.drawString(comment1, 29, 548);
g2.drawString(comment2, 29, 581);
// draw red animation spot
if (pointX != -1) {
g2.setColor(Color.RED);
g2.fillOval(pointX - 5, pointY - 5, 10, 10);
}
// draw double buffer to frame
g.drawImage(doubleBuffer, 0, 0, getWidth(), getHeight(), null);
}
/**
* Animation is done in this run method. animate method awakes new thread
* with this run method.
*/
@Override
public void run() {
// Information about command cycle:
currentCommand = "";
// animate instruction fetch
comment1 = new Message("Fetch the next instruction from memory slot {0} to IR and increase PC by one.", valueBase.toString(value[PC])).toString();
animateAnEvent(PC, MAR);
animateAnEvent(PC, PC, value[PC] + 1);
animateAnEvent(MAR, MEMORY);
animateAnEvent(MEMORY, MBR, info.getBinary());
animateAnEvent(MBR, IR);
currentCommand = info.getLineContents(); //+ " (" + info.getColonString() + ")";
int opcode = info.getBinary() >>> 24;
int Rj = info.getFirstOperand();
int Ri = info.getIndexRegister();
int ADDR = info.getADDR();
int memoryFetches = info.getMemoryfetches();
int[] regs = info.getRegisters();
int Rj_value = value[Rj];
int Ri_value = value[Ri];
// if NOP interrupt immediately
if (opcode == 0) {
comment1 = new Message("No-operation command completed.").toString();
isAnimating = executeAnimationImmediately = false;
return;
}
if (Ri != 0) {
ADDR += Ri_value;
}
int param = ADDR;
int whereIsSecondOperand = IR;
if (memoryFetches == 1) {
param = info.getValueAtADDR();
whereIsSecondOperand = MBR;
comment1 = new Message("Fetch second operand from memory slot {0}.", valueBase.toString(ADDR)).toString();
animateAnEvent(IR, MAR, ADDR);
animateAnEvent(MAR, MEMORY);
animateAnEvent(MEMORY, MBR, param);
} else if (memoryFetches == 2) {
param = info.getSecondFetchValue();
whereIsSecondOperand = MBR;
comment1 = new Message("Indirect memory accessing mode.").toString();
comment2 = new Message("1: Fetch indexing value from memory slot {0}.", valueBase.toString(ADDR)).toString();
animateAnEvent(IR, MAR, ADDR);
animateAnEvent(MAR, MEMORY);
animateAnEvent(MEMORY, MBR, info.getValueAtADDR());
comment1 = new Message("Indirect memory accessing mode.").toString();
comment2 = new Message("2: Fetch second operand from memory slot {0}.", valueBase.toString(value[MBR])).toString();
animateAnEvent(MBR, MAR);
animateAnEvent(MAR, MEMORY);
animateAnEvent(MEMORY, MBR, param);
comment2 = "";
}
switch (info.getOperationtype()) {
case RunDebugger.DATA_TRANSFER_OPERATION:
switch (opcode) {
case 1: // STORE
comment1 = new Message("Write value {0} from register R{1} to memory slot {2}.", new String[]{valueBase.toString(Rj_value), String.valueOf(Rj), valueBase.toString(param)}).toString();
animateAnEvent(whereIsSecondOperand, MAR, param);
animateAnEvent(Rj, MBR);
animateAnEvent(MBR, MEMORY);
break;
case 2: // LOAD
comment1 = new Message("Load value {0} to register R{1}.", new String[]{valueBase.toString(param), String.valueOf(Rj)}).toString();
animateAnEvent(whereIsSecondOperand, Rj, param);
break;
case 3:
int inValue = info.whatIN()[1];
comment1 = new Message("Read value {0} from {1} to register R{2}.", new String[]{valueBase.toString(inValue), info.whatDevice(), String.valueOf(Rj)}).toString();
animateAnEvent(whereIsSecondOperand, MAR);
animateAnEvent(MAR, EXTERNAL_DEVICE);
animateAnEvent(EXTERNAL_DEVICE, MBR, inValue);
animateAnEvent(MBR, Rj);
break;
case 4: // OUT
@SuppressWarnings("unused")
int outValue = info.whatOUT()[1];
comment1 = new Message("Write value {0} from register R{1} to {2}.", new String[]{valueBase.toString(value[Rj]), String.valueOf(Rj), info.whatDevice()}).toString();
animateAnEvent(Rj, MBR);
animateAnEvent(MBR, EXTERNAL_DEVICE);
break;
}
break;
case RunDebugger.ALU_OPERATION:
comment1 = new Message("Copy register R{0} to ALU IN1.", String.valueOf(Rj)).toString();
animateAnEvent(Rj, ALU_IN1);
comment1 = new Message("Copy second operand to ALU IN2.").toString();
animateAnEvent(whereIsSecondOperand, ALU_IN2, param);
comment1 = new Message("ALU computes the result.").toString();
comment1 = new Message("Copy ALU result to register R{0}", String.valueOf(Rj)).toString();
value[ALU_OUT] = info.getALUResult();
animateAnEvent(ALU_OUT, Rj);
break;
case RunDebugger.COMP_OPERATION:
comment1 = new Message("Copy register R{0} to ALU IN1.", String.valueOf(Rj)).toString();
animateAnEvent(Rj, ALU_IN1);
comment1 = new Message("Copy second operand to ALU IN2.").toString();
animateAnEvent(whereIsSecondOperand, ALU_IN2, param);
comment1 = new Message("ALU computes the comparison result.").toString();
comment2 = new Message("0=greater, 1=equals, 2=less").toString();
value[ALU_OUT] = info.getCompareStatus();
comment1 = new Message("Set comparison result to SR").toString();
animateAnEvent(ALU_OUT, SR);
switch (info.getCompareStatus()) {
case 0:
SR_String = "1 0 0...";
break;
case 1:
SR_String = "0 1 0...";
break;
case 2:
SR_String = "0 0 1...";
break;
default:
SR_String = "0 0 0...";
break;
}
comment2 = "";
break;
case RunDebugger.BRANCH_OPERATION:
if (value[PC] == info.getNewPC()) {
comment1 = new Message("Branching command - branching condition is false, so do nothing.").toString();
} else {
comment1 = new Message("Branching command - branching condition is true, so update PC.").toString();
animateAnEvent(whereIsSecondOperand, PC, param);
}
break;
case RunDebugger.SUB_OPERATION:
if (opcode == 49) { // CALL
comment1 = new Message("Save new PC to TR").toString();
animateAnEvent(whereIsSecondOperand, TR, param);
comment1 = new Message("Increase stack pointer R{0} by one and push PC to stack.", String.valueOf(Rj)).toString();
animateAnEvent(Rj, Rj, value[Rj] + 1);
animateAnEvent(Rj, MAR);
animateAnEvent(PC, MBR);
animateAnEvent(MBR, MEMORY);
comment1 = new Message("Increase stack pointer R{0} by one and push FP to stack.", String.valueOf(Rj)).toString();
animateAnEvent(Rj, Rj, value[Rj] + 1);
animateAnEvent(Rj, MAR);
animateAnEvent(R7, MBR);
animateAnEvent(MBR, MEMORY);
comment1 = new Message("Copy stack pointer to FP.").toString();
animateAnEvent(Rj, R7);
comment1 = new Message("Update PC.").toString();
animateAnEvent(TR, PC);
} else if (opcode == 50) {
comment1 = new Message("Pop PC from stack and decrease stack pointer R{0} by one.", String.valueOf(Rj)).toString();
animateAnEvent(Rj, MAR);
animateAnEvent(Rj, Rj, value[Rj] - 1);
animateAnEvent(MAR, MEMORY);
animateAnEvent(MEMORY, MBR, info.getNewPC());
animateAnEvent(MBR, PC);
comment1 = new Message("Pop FP from stack and decrease stack pointer R{0} by one.", String.valueOf(Rj)).toString();
animateAnEvent(Rj, MAR);
animateAnEvent(Rj, Rj, value[Rj] - 1);
animateAnEvent(MAR, MEMORY);
animateAnEvent(MEMORY, MBR, regs[7]);
animateAnEvent(MBR, R7);
comment1 = new Message("Decrease {0} parameters from stack pointer R{1}.", new String[]{String.valueOf(param), String.valueOf(Rj)}).toString();
animateAnEvent(Rj, Rj, regs[Rj]);
}
break;
case RunDebugger.STACK_OPERATION:
int popValue;
switch (opcode) {
case 51: // PUSH
comment1 = new Message("Increase stack pointer R{0} by one then write second operand to stack", String.valueOf(Rj)).toString();
animateAnEvent(Rj, Rj, value[Rj] + 1);
animateAnEvent(Rj, MAR);
animateAnEvent(whereIsSecondOperand, MBR);
animateAnEvent(MBR, MEMORY);
break;
case 52: // POP
comment1 = new Message("Read value from stack to R{0} then decrease stack pointer R{1} by one.", new String[]{String.valueOf(Ri), String.valueOf(Rj)}).toString();
popValue = regs[Ri]; // popped value founds at destination register
if (Ri == Rj) {
popValue++;
}
animateAnEvent(Rj, MAR);
animateAnEvent(MAR, MEMORY);
animateAnEvent(MEMORY, MBR, popValue);
animateAnEvent(MBR, Ri);
animateAnEvent(Rj, Rj, value[Rj] - 1);
break;
case 53: // PUSHR
for (int i = 0; i <= 6; i++) {
comment1 = new Message("Increase stack pointer R{0} by one then write R{1} to stack.", new String[]{String.valueOf(Rj), String.valueOf(i)}).toString();
animateAnEvent(Rj, Rj, value[Rj] + 1);
animateAnEvent(Rj, MAR);
animateAnEvent(i, MBR);
animateAnEvent(MBR, MEMORY);
}
break;
case 54: // POPR
for (int i = 6; i >= 0; i
comment1 = new Message("Read value from stack then decrease stack pointer R{0} by one.", String.valueOf(Rj)).toString();
popValue = regs[i]; // popped value founds at destination register
if (i == Rj) {
popValue += Rj + 1;
}
animateAnEvent(Rj, MAR);
animateAnEvent(MAR, MEMORY);
animateAnEvent(MEMORY, MBR, popValue);
animateAnEvent(MBR, i);
animateAnEvent(Rj, Rj, value[Rj] - 1);
}
break;
}
break;
case RunDebugger.SVC_OPERATION:
comment1 = new Message("Supervisor call to operating system's services.").toString();
// update possibly changed registers
for (int i = 0; i < 8; i++) {
value[i] = regs[i];
}
break;
}
isAnimating = executeAnimationImmediately = false;
}
/**
* Stops currently running animation if there is one. The rest of the animation is done
* without delays and this method returns after current animation is done and new values
* are updated.
*/
public void stopAnimation() {
if (!isAnimating) {
return;
}
executeAnimationImmediately = true;
animationThread.interrupt();
while (isAnimating) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
}
}
}
public boolean isAnimationRunning() {
return isAnimating;
}
/**
* This method produces an animation of a command based on
* the information in the RunInfo parameter. Animation is set to run only if
* there is no animation currently running.
*
* @param info A RunInfo to base the animation on.
* @return Returns false, if there is already an animation running.
*/
public boolean animate(RunInfo info) {
if (isAnimating) {
return false; // cannot do two animations at the same time
}
isAnimating = true;
this.info = info;
animationThread = new Thread(this);
animationThread.start();
return true;
}
/**
* Initalizes animation.
*
* @param cpu A TTK91Cpu, giving the start values of the registers.
* @param baseValue Value of the BASE register in MMU.
* @param limitValue Value of the LIMIT register in MMU.
*/
public void init(TTK91Cpu cpu, int baseValue, int limitValue) {
value[R0] = cpu.getValueOf(TTK91Cpu.REG_R0);
value[R1] = cpu.getValueOf(TTK91Cpu.REG_R1);
value[R2] = cpu.getValueOf(TTK91Cpu.REG_R2);
value[R3] = cpu.getValueOf(TTK91Cpu.REG_R3);
value[R4] = cpu.getValueOf(TTK91Cpu.REG_R4);
value[R5] = cpu.getValueOf(TTK91Cpu.REG_R5);
value[R6] = cpu.getValueOf(TTK91Cpu.REG_R6);
value[R7] = cpu.getValueOf(TTK91Cpu.REG_R7);
value[PC] = cpu.getValueOf(TTK91Cpu.CU_PC);
value[IR] = cpu.getValueOf(TTK91Cpu.CU_IR);
value[TR] = cpu.getValueOf(TTK91Cpu.CU_TR);
value[SR] = -1;
SR_String = "0 0 0...";
value[BASE] = baseValue;
value[LIMIT] = 1 << limitValue;
}
/**
* Sets animation delay.
*
* @param delay Delay between frames in milliseconds.
*/
public void setAnimationDelay(int delay) {
this.delay = delay;
}
/**
* This method animates one event like "move 7 from R1 to In2 in ALU using
* the bus in between" The building block of a more complex operations like
* "STORE R1, 100" where one needs to fetch an instruction, decipher it etc.
*
* @param from From where does the value come from.
* @param to Where is the value going to be transported.
* @param newValue New value replaces the old value in destination.
*/
private void animateAnEvent(int from, int to, int newValue) {
if (executeAnimationImmediately) {
value[to] = newValue;
return;
}
// form the route
int routeLength = routeToBus[from].length + routeToBus[to].length;
int[] route = new int[routeLength];
for (int i = 0; i < routeToBus[from].length; i++) {
route[i] = routeToBus[from][i];
}
for (int i = 0; i < routeToBus[to].length; i += 2) {
route[i + routeToBus[from].length] = routeToBus[to][routeToBus[to].length - i - 2];
route[i + 1 + routeToBus[from].length] = routeToBus[to][routeToBus[to].length - i - 1];
}
// fixes...
if (from == MAR && to == MEMORY) {
route = new int[]{378, 340, 470, 340, 470, 90, 516, 90};
}
if (from == MBR && to == MEMORY) {
route = new int[]{378, 362, 470, 362, 470, 90, 516, 90};
}
if (from == MEMORY && to == MBR) {
route = new int[]{516, 90, 470, 90, 470, 362, 378, 362};
}
if (from == MAR && to == EXTERNAL_DEVICE) {
route = new int[]{378, 340, 470, 340, 470, 405, 516, 405};
}
if (from == MBR && to == EXTERNAL_DEVICE) {
route = new int[]{378, 362, 470, 362, 470, 405, 516, 405};
}
if (from == EXTERNAL_DEVICE && to == MBR) {
route = new int[]{516, 405, 470, 405, 470, 362, 378, 362};
}
int x1 = route[0];
int y1 = route[1];
int x2, y2;
for (int i = 2; i < route.length; i += 2) {
x2 = route[i];
y2 = route[i + 1];
while (x1 != x2 || y1 != y2) {
if (x1 < x2) {
x1 = Math.min(x2, x1 + 8);
}
if (x1 > x2) {
x1 = Math.max(x2, x1 - 8);
}
if (y1 < y2) {
y1 = Math.min(y2, y1 + 8);
}
if (y1 > y2) {
y1 = Math.max(y2, y1 - 8);
}
pointX = x1;
pointY = y1;
repaint();
try {
Thread.sleep(delay);
} catch (InterruptedException e) {
value[to] = newValue;
return;
}
}
}
pointX = pointY = -1;
value[to] = newValue;
repaint();
}
private void animateAnEvent(int from, int to) {
animateAnEvent(from, to, value[from]);
}
public static void main(String[] args) throws IOException {
Animator a = new Animator();
a.setAnimationDelay(80);
a.init(new Processor(512), 0, 512);
JFrame f = new JFrame();
f.setSize(810, 636);
f.setTitle("Animator");
f.getContentPane().add(a);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
RunDebugger runDebugger = new RunDebugger();
runDebugger.cycleStart(0, "IN R7, 10(R1)");
runDebugger.setOperationType(RunDebugger.DATA_TRANSFER_OPERATION);
runDebugger.setIN(1, 75);
runDebugger.runCommand(65601546);
a.animate(runDebugger.cycleEnd());
while (a.isAnimationRunning()) {
;
}
try {
Thread.sleep(3000);
} catch (Exception e) {
}
runDebugger.cycleStart(0, "OUT R3, =0");
runDebugger.setOperationType(RunDebugger.DATA_TRANSFER_OPERATION);
runDebugger.setOUT(0, -1);
runDebugger.runCommand(73400320);
a.animate(runDebugger.cycleEnd());
while (a.isAnimationRunning()) {
;
}
try {
Thread.sleep(3000);
} catch (Exception e) {
}
runDebugger.cycleStart(1, "STORE R1, @100");
runDebugger.setOperationType(RunDebugger.DATA_TRANSFER_OPERATION);
runDebugger.setValueAtADDR(666);
runDebugger.runCommand(27787365);
a.animate(runDebugger.cycleEnd());
while (a.isAnimationRunning()) {
;
}
try {
Thread.sleep(3000);
} catch (Exception e) {
}
runDebugger.cycleStart(0, "NOP");
runDebugger.setOperationType(RunDebugger.NO_OPERATION);
runDebugger.runCommand(0);
a.animate(runDebugger.cycleEnd());
while (a.isAnimationRunning()) {
;
}
try {
Thread.sleep(3000);
} catch (Exception e) {
}
runDebugger.cycleStart(0, "LOAD R2, @10(R1)");
runDebugger.setOperationType(RunDebugger.DATA_TRANSFER_OPERATION);
runDebugger.setValueAtADDR(100);
runDebugger.setSecondFetchValue(1000);
runDebugger.runCommand(38862858);
a.animate(runDebugger.cycleEnd());
while (a.isAnimationRunning()) {
;
}
try {
Thread.sleep(3000);
} catch (Exception e) {
}
runDebugger.cycleStart(0, "COMP R0, @30");
runDebugger.setOperationType(RunDebugger.COMP_OPERATION);
runDebugger.runCommand(521142302);
runDebugger.setCompareResult(0);
a.animate(runDebugger.cycleEnd());
while (a.isAnimationRunning()) {
;
}
try {
Thread.sleep(3000);
} catch (Exception e) {
}
runDebugger.cycleStart(0, "JZER R2, 100");
runDebugger.setOperationType(RunDebugger.BRANCH_OPERATION);
runDebugger.setNewPC(32);
runDebugger.runCommand(574619748);
a.animate(runDebugger.cycleEnd());
while (a.isAnimationRunning()) {
;
}
try {
Thread.sleep(3000);
} catch (Exception e) {
}
runDebugger.cycleStart(0, "ADD R6, =20");
runDebugger.setOperationType(RunDebugger.ALU_OPERATION);
runDebugger.setALUResult(20);
runDebugger.runCommand(297795604);
a.animate(runDebugger.cycleEnd());
while (a.isAnimationRunning()) {
;
}
try {
Thread.sleep(3000);
} catch (Exception e) {
}
runDebugger.cycleStart(0, "LOAD R1, =100");
runDebugger.setOperationType(RunDebugger.DATA_TRANSFER_OPERATION);
runDebugger.runCommand(35651684);
a.animate(runDebugger.cycleEnd());
while (a.isAnimationRunning()) {
;
}
try {
Thread.sleep(3000);
} catch (Exception e) {
}
runDebugger.cycleStart(0, "CALL R3, 40(R1)");
runDebugger.setOperationType(RunDebugger.SUB_OPERATION);
runDebugger.runCommand(828440616);
runDebugger.setNewPC(140);
a.animate(runDebugger.cycleEnd());
while (a.isAnimationRunning()) {
;
}
try {
Thread.sleep(3000);
} catch (Exception e) {
}
runDebugger.cycleStart(0, "EXIT SP, =4");
runDebugger.setOperationType(RunDebugger.SUB_OPERATION);
runDebugger.runCommand(851443716);
runDebugger.setNewPC(5);
runDebugger.setRegisters(new int[]{0, 0, 0, 0, 0, 0, -6, 100});
a.animate(runDebugger.cycleEnd());
while (a.isAnimationRunning()) {
;
}
try {
Thread.sleep(3000);
} catch (Exception e) {
}
runDebugger.cycleStart(0, "COMP R0, @30");
runDebugger.setOperationType(RunDebugger.COMP_OPERATION);
runDebugger.runCommand(521142302);
runDebugger.setCompareResult(2);
a.animate(runDebugger.cycleEnd());
while (a.isAnimationRunning()) {
;
}
try {
Thread.sleep(3000);
} catch (Exception e) {
}
runDebugger.cycleStart(0, "PUSH R6, 100(R4)");
runDebugger.setOperationType(RunDebugger.STACK_OPERATION);
runDebugger.runCommand(869007460);
a.animate(runDebugger.cycleEnd());
while (a.isAnimationRunning()) {
;
}
try {
Thread.sleep(3000);
} catch (Exception e) {
}
runDebugger.cycleStart(0, "POP R6, R6");
runDebugger.setOperationType(RunDebugger.STACK_OPERATION);
runDebugger.runCommand(885391360);
runDebugger.setRegisters(new int[]{1, 2, 3, 4, 5, 6, 99, 8});
a.animate(runDebugger.cycleEnd());
while (a.isAnimationRunning()) {
;
}
try {
Thread.sleep(3000);
} catch (Exception e) {
}
runDebugger.cycleStart(0, "POPR R0");
runDebugger.setOperationType(RunDebugger.STACK_OPERATION);
runDebugger.setRegisters(new int[]{107, 106, 105, 104, 103, 102, 101, 100});
runDebugger.runCommand(905969664);
a.animate(runDebugger.cycleEnd());
while (a.isAnimationRunning()) {
;
}
try {
Thread.sleep(3000);
} catch (Exception e) {
}
}
} |
package hudson.plugins.ec2;
import com.amazonaws.AmazonServiceException;
import hudson.Extension;
import hudson.Util;
import hudson.model.Describable;
import hudson.model.TaskListener;
import hudson.model.Descriptor;
import hudson.model.Descriptor.FormException;
import hudson.model.Hudson;
import hudson.model.Label;
import hudson.model.Node;
import hudson.model.labels.LabelAtom;
import hudson.plugins.ec2.util.DeviceMappingParser;
import hudson.util.FormValidation;
import hudson.util.ListBoxModel;
import java.io.IOException;
import java.io.PrintStream;
import java.net.URL;
import java.util.*;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import jenkins.slaves.iterators.api.NodeIterator;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringUtils;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.QueryParameter;
import com.amazonaws.AmazonClientException;
import com.amazonaws.auth.AWSCredentialsProvider;
import com.amazonaws.services.ec2.AmazonEC2;
import com.amazonaws.services.ec2.model.*;
/**
* Template of {@link EC2AbstractSlave} to launch.
*
* @author Kohsuke Kawaguchi
*/
public class SlaveTemplate implements Describable<SlaveTemplate> {
public final String ami;
public final String description;
public final String zone;
public final SpotConfiguration spotConfig;
public final String securityGroups;
public final String remoteFS;
public final InstanceType type;
public final String labels;
public final Node.Mode mode;
public final String initScript;
public final String tmpDir;
public final String userData;
public final String numExecutors;
public final String remoteAdmin;
public final String jvmopts;
public final String subnetId;
public final String idleTerminationMinutes;
public final String iamInstanceProfile;
public final boolean useEphemeralDevices;
public final String customDeviceMapping;
public int instanceCap;
public final boolean stopOnTerminate;
private final List<EC2Tag> tags;
public final boolean usePrivateDnsName;
public final boolean associatePublicIp;
protected transient EC2Cloud parent;
public final boolean useDedicatedTenancy;
public AMITypeData amiType;
public int launchTimeout;
private transient /*almost final*/ Set<LabelAtom> labelSet;
private transient /*almost final*/ Set<String> securityGroupSet;
/*
* Necessary to handle reading from old configurations. The UnixData object is
* created in readResolve()
*/
@Deprecated
public transient String sshPort;
@Deprecated
public transient String rootCommandPrefix;
@DataBoundConstructor
public SlaveTemplate(String ami, String zone, SpotConfiguration spotConfig, String securityGroups, String remoteFS, InstanceType type, String labelString, Node.Mode mode, String description, String initScript, String tmpDir, String userData, String numExecutors, String remoteAdmin, AMITypeData amiType, String jvmopts, boolean stopOnTerminate, String subnetId, List<EC2Tag> tags, String idleTerminationMinutes, boolean usePrivateDnsName, String instanceCapStr, String iamInstanceProfile, boolean useEphemeralDevices, boolean useDedicatedTenancy, String launchTimeoutStr, boolean associatePublicIp, String customDeviceMapping) {
this.ami = ami;
this.zone = zone;
this.spotConfig = spotConfig;
this.securityGroups = securityGroups;
this.remoteFS = remoteFS;
this.amiType = amiType;
this.type = type;
this.labels = Util.fixNull(labelString);
this.mode = mode;
this.description = description;
this.initScript = initScript;
this.tmpDir = tmpDir;
this.userData = userData;
this.numExecutors = Util.fixNull(numExecutors).trim();
this.remoteAdmin = remoteAdmin;
this.jvmopts = jvmopts;
this.stopOnTerminate = stopOnTerminate;
this.subnetId = subnetId;
this.tags = tags;
this.idleTerminationMinutes = idleTerminationMinutes;
this.usePrivateDnsName = usePrivateDnsName;
this.associatePublicIp = associatePublicIp;
this.useDedicatedTenancy = useDedicatedTenancy;
if (null == instanceCapStr || instanceCapStr.equals("")) {
this.instanceCap = Integer.MAX_VALUE;
} else {
this.instanceCap = Integer.parseInt(instanceCapStr);
}
try {
this.launchTimeout = Integer.parseInt(launchTimeoutStr);
} catch (NumberFormatException nfe ) {
this.launchTimeout = Integer.MAX_VALUE;
}
this.iamInstanceProfile = iamInstanceProfile;
this.useEphemeralDevices = useEphemeralDevices;
this.customDeviceMapping = customDeviceMapping;
readResolve(); // initialize
}
/**
* Backward compatible constructor for reloading previous version data
*/
public SlaveTemplate(String ami, String zone, SpotConfiguration spotConfig, String securityGroups, String remoteFS, String sshPort, InstanceType type, String labelString, Node.Mode mode, String description, String initScript, String tmpDir, String userData, String numExecutors, String remoteAdmin, String rootCommandPrefix, String jvmopts, boolean stopOnTerminate, String subnetId, List<EC2Tag> tags, String idleTerminationMinutes, boolean usePrivateDnsName, String instanceCapStr, String iamInstanceProfile, boolean useEphemeralDevices, String launchTimeoutStr)
{
this(ami, zone, spotConfig, securityGroups, remoteFS, type, labelString, mode, description, initScript, tmpDir, userData, numExecutors, remoteAdmin, new UnixData(rootCommandPrefix, sshPort), jvmopts, stopOnTerminate, subnetId, tags, idleTerminationMinutes, usePrivateDnsName, instanceCapStr, iamInstanceProfile, useEphemeralDevices, false, launchTimeoutStr, false, null);
}
public EC2Cloud getParent() {
return parent;
}
public String getBidType(){
if(spotConfig == null)
return null;
return spotConfig.spotInstanceBidType;
}
public String getLabelString() {
return labels;
}
public Node.Mode getMode() {
return mode;
}
public String getDisplayName() {
return description+" ("+ami+")";
}
String getZone() {
return zone;
}
public String getSecurityGroupString() {
return securityGroups;
}
public Set<String> getSecurityGroupSet() {
return securityGroupSet;
}
public Set<String> parseSecurityGroups() {
if (securityGroups == null || "".equals(securityGroups.trim())) {
return Collections.emptySet();
} else {
return new HashSet<String>(Arrays.asList(securityGroups.split("\\s*,\\s*")));
}
}
public int getNumExecutors() {
try {
return Integer.parseInt(numExecutors);
} catch (NumberFormatException e) {
return EC2AbstractSlave.toNumExecutors(type);
}
}
public int getSshPort() {
try {
String sshPort = "";
if (amiType.isUnix()) {
sshPort = ((UnixData)amiType).getSshPort();
}
return Integer.parseInt(sshPort);
} catch (NumberFormatException e) {
return 22;
}
}
public String getRemoteAdmin() {
return remoteAdmin;
}
public String getRootCommandPrefix() {
return amiType.isUnix() ? ((UnixData)amiType).getRootCommandPrefix() : "";
}
public String getSubnetId() {
return subnetId;
}
public boolean getAssociatePublicIp() {
return associatePublicIp;
}
public List<EC2Tag> getTags() {
if (null == tags) return null;
return Collections.unmodifiableList(tags);
}
public String getidleTerminationMinutes() {
return idleTerminationMinutes;
}
public boolean getUseDedicatedTenancy() {
return useDedicatedTenancy;
}
public Set<LabelAtom> getLabelSet(){
return labelSet;
}
public int getInstanceCap() {
return instanceCap;
}
public String getInstanceCapStr() {
if (instanceCap==Integer.MAX_VALUE) {
return "";
} else {
return String.valueOf(instanceCap);
}
}
public String getSpotMaxBidPrice(){
if (spotConfig == null)
return null;
return SpotConfiguration.normalizeBid(spotConfig.spotMaxBidPrice);
}
public String getIamInstanceProfile() {
return iamInstanceProfile;
}
/**
* Provisions a new EC2 slave or starts a previously stopped on-demand instance.
*
* @return always non-null. This needs to be then added to {@link Hudson#addNode(Node)}.
*/
public EC2AbstractSlave provision(TaskListener listener) throws AmazonClientException, IOException {
if (this.spotConfig != null){
return provisionSpot(listener);
}
return provisionOndemand(listener);
}
/**
* Provisions an On-demand EC2 slave by launching a new instance or
* starting a previously-stopped instance.
*/
private EC2AbstractSlave provisionOndemand(TaskListener listener) throws AmazonClientException, IOException {
PrintStream logger = listener.getLogger();
AmazonEC2 ec2 = getParent().connect();
try {
logger.println("Launching " + ami + " for template " + description);
LOGGER.info("Launching " + ami + " for template " + description);
KeyPair keyPair = getKeyPair(ec2);
RunInstancesRequest riRequest = new RunInstancesRequest(ami, 1, 1);
InstanceNetworkInterfaceSpecification net = new InstanceNetworkInterfaceSpecification();
if (useEphemeralDevices) {
setupEphemeralDeviceMapping(riRequest);
}
else {
setupCustomDeviceMapping(riRequest);
}
List<Filter> diFilters = new ArrayList<Filter>();
diFilters.add(new Filter("image-id").withValues(ami));
if (StringUtils.isNotBlank(getZone())) {
Placement placement = new Placement(getZone());
if (getUseDedicatedTenancy()) {
placement.setTenancy("dedicated");
}
riRequest.setPlacement(placement);
diFilters.add(new Filter("availability-zone").withValues(getZone()));
}
if (StringUtils.isNotBlank(getSubnetId())) {
if (getAssociatePublicIp()) {
net.setSubnetId(getSubnetId());
}else{
riRequest.setSubnetId(getSubnetId());
}
diFilters.add(new Filter("subnet-id").withValues(getSubnetId()));
/* If we have a subnet ID then we can only use VPC security groups */
if (!securityGroupSet.isEmpty()) {
List<String> group_ids = getEc2SecurityGroups(ec2);
if (!group_ids.isEmpty()) {
if (getAssociatePublicIp()) {
net.setGroups(group_ids);
}else{
riRequest.setSecurityGroupIds(group_ids);
}
diFilters.add(new Filter("instance.group-id").withValues(group_ids));
}
}
} else {
/* No subnet: we can use standard security groups by name */
riRequest.setSecurityGroups(securityGroupSet);
if (securityGroupSet.size() > 0)
diFilters.add(new Filter("instance.group-name").withValues(securityGroupSet));
}
String userDataString = Base64.encodeBase64String(userData.getBytes());
riRequest.setUserData(userDataString);
riRequest.setKeyName(keyPair.getKeyName());
diFilters.add(new Filter("key-name").withValues(keyPair.getKeyName()));
riRequest.setInstanceType(type.toString());
diFilters.add(new Filter("instance-type").withValues(type.toString()));
if (getAssociatePublicIp()) {
net.setAssociatePublicIpAddress(true);
net.setDeviceIndex(0);
riRequest.withNetworkInterfaces(net);
}
boolean hasCustomTypeTag = false;
HashSet<Tag> inst_tags = null;
if (tags != null && !tags.isEmpty()) {
inst_tags = new HashSet<Tag>();
for(EC2Tag t : tags) {
inst_tags.add(new Tag(t.getName(), t.getValue()));
diFilters.add(new Filter("tag:"+t.getName()).withValues(t.getValue()));
if (StringUtils.equals(t.getName(), EC2Tag.TAG_NAME_JENKINS_SLAVE_TYPE)) {
hasCustomTypeTag = true;
}
}
}
if (!hasCustomTypeTag) {
if (inst_tags == null){
inst_tags = new HashSet<Tag>();
}
inst_tags.add(new Tag(EC2Tag.TAG_NAME_JENKINS_SLAVE_TYPE, "demand"));
}
DescribeInstancesRequest diRequest = new DescribeInstancesRequest();
diFilters.add(new Filter("instance-state-name").withValues(InstanceStateName.Stopped.toString(),
InstanceStateName.Stopping.toString()));
diRequest.setFilters(diFilters);
logger.println("Looking for existing instances with describe-instance: "+diRequest);
LOGGER.fine("Looking for existing instances with describe-instance: "+diRequest);
DescribeInstancesResult diResult = ec2.describeInstances(diRequest);
Instance existingInstance = null;
if (StringUtils.isNotBlank(getIamInstanceProfile())) {
riRequest.setIamInstanceProfile(new IamInstanceProfileSpecification().withArn(getIamInstanceProfile()));
// cannot filter on IAM Instance Profile, so search in result
reservationLoop:
for (Reservation reservation : diResult.getReservations()) {
for (Instance instance : reservation.getInstances()) {
if (instance.getIamInstanceProfile() != null && instance.getIamInstanceProfile().getArn().equals(getIamInstanceProfile())) {
existingInstance = instance;
break reservationLoop;
}
}
}
} else if (diResult.getReservations().size() > 0) {
existingInstance = diResult.getReservations().get(0).getInstances().get(0);
}
if (existingInstance == null) {
// Have to create a new instance
Instance inst = ec2.runInstances(riRequest).getReservation().getInstances().get(0);
/* Now that we have our instance, we can set tags on it */
if (inst_tags != null) {
for (int i = 0; i < 5; i++) {
try {
updateRemoteTags(ec2, inst_tags, inst.getInstanceId());
break;
} catch (AmazonServiceException e) {
if (e.getErrorCode().equals("InvalidInstanceRequestID.NotFound")) {
Thread.sleep(5000);
continue;
}
throw e;
}
}
// That was a remote request - we should also update our local instance data.
inst.setTags(inst_tags);
}
logger.println("No existing instance found - created: "+inst);
LOGGER.info("No existing instance found - created: "+inst);
return newOndemandSlave(inst);
}
logger.println("Found existing stopped instance: "+existingInstance);
LOGGER.info("Found existing stopped instance: "+existingInstance);
List<String> instances = new ArrayList<String>();
instances.add(existingInstance.getInstanceId());
StartInstancesRequest siRequest = new StartInstancesRequest(instances);
StartInstancesResult siResult = ec2.startInstances(siRequest);
logger.println("Starting existing instance: "+existingInstance+ " result:"+siResult);
LOGGER.fine("Starting existing instance: "+existingInstance+ " result:"+siResult);
for (EC2AbstractSlave ec2Node: NodeIterator.nodes(EC2AbstractSlave.class)){
if (ec2Node.getInstanceId().equals(existingInstance.getInstanceId())) {
logger.println("Found existing corresponding Jenkins slave: "+ec2Node);
LOGGER.finer("Found existing corresponding Jenkins slave: "+ec2Node);
return ec2Node;
}
}
// Existing slave not found
logger.println("Creating new Jenkins slave for existing instance: "+existingInstance);
LOGGER.info("Creating new Jenkins slave for existing instance: "+existingInstance);
return newOndemandSlave(existingInstance);
} catch (FormException e) {
throw new AssertionError(); // we should have discovered all configuration issues upfront
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
private void setupEphemeralDeviceMapping(RunInstancesRequest riRequest) {
final List<BlockDeviceMapping> oldDeviceMapping = getAmiBlockDeviceMappings();
final Set<String> occupiedDevices = new HashSet<String>();
for (final BlockDeviceMapping mapping: oldDeviceMapping ) {
occupiedDevices.add(mapping.getDeviceName());
}
final List<String> available = new ArrayList<String>(Arrays.asList(
"ephemeral0", "ephemeral1", "ephemeral2", "ephemeral3"
));
final List<BlockDeviceMapping> newDeviceMapping = new ArrayList<BlockDeviceMapping>(4);
for (char suffix = 'b'; suffix <= 'z' && !available.isEmpty(); suffix++) {
final String deviceName = String.format("/dev/xvd%s", suffix);
if (occupiedDevices.contains(deviceName)) continue;
final BlockDeviceMapping newMapping = new BlockDeviceMapping()
.withDeviceName(deviceName)
.withVirtualName(available.get(0))
;
newDeviceMapping.add(newMapping);
available.remove(0);
}
riRequest.withBlockDeviceMappings(newDeviceMapping);
}
private List<BlockDeviceMapping> getAmiBlockDeviceMappings() {
for (final Image image: getParent().connect().describeImages().getImages()) {
if (ami.equals(image.getImageId())) {
return image.getBlockDeviceMappings();
}
}
throw new AmazonClientException("Unable to get AMI device mapping for " + ami);
}
private void setupCustomDeviceMapping(RunInstancesRequest riRequest) {
if (StringUtils.isNotBlank(customDeviceMapping)) {
riRequest.setBlockDeviceMappings(DeviceMappingParser.parse(customDeviceMapping));
}
}
/**
* Provision a new slave for an EC2 spot instance to call back to Jenkins
*/
private EC2AbstractSlave provisionSpot(TaskListener listener) throws AmazonClientException, IOException {
PrintStream logger = listener.getLogger();
AmazonEC2 ec2 = getParent().connect();
try{
logger.println("Launching " + ami + " for template " + description);
LOGGER.info("Launching " + ami + " for template " + description);
KeyPair keyPair = getKeyPair(ec2);
RequestSpotInstancesRequest spotRequest = new RequestSpotInstancesRequest();
// Validate spot bid before making the request
if (getSpotMaxBidPrice() == null){
// throw new FormException("Invalid Spot price specified: " + getSpotMaxBidPrice(), "spotMaxBidPrice");
throw new AmazonClientException("Invalid Spot price specified: " + getSpotMaxBidPrice());
}
spotRequest.setSpotPrice(getSpotMaxBidPrice());
spotRequest.setInstanceCount(Integer.valueOf(1));
spotRequest.setType(getBidType());
LaunchSpecification launchSpecification = new LaunchSpecification();
InstanceNetworkInterfaceSpecification net = new InstanceNetworkInterfaceSpecification();
launchSpecification.setImageId(ami);
launchSpecification.setInstanceType(type);
if (StringUtils.isNotBlank(getZone())) {
SpotPlacement placement = new SpotPlacement(getZone());
launchSpecification.setPlacement(placement);
}
if (StringUtils.isNotBlank(getSubnetId())) {
if (getAssociatePublicIp()) {
net.setSubnetId(getSubnetId());
}else{
launchSpecification.setSubnetId(getSubnetId());
}
/* If we have a subnet ID then we can only use VPC security groups */
if (!securityGroupSet.isEmpty()) {
List<String> group_ids = getEc2SecurityGroups(ec2);
if (!group_ids.isEmpty()){
if (getAssociatePublicIp()) {
net.setGroups(group_ids);
}else{
ArrayList<GroupIdentifier> groups = new ArrayList<GroupIdentifier>();
for (String group_id : group_ids) {
GroupIdentifier group = new GroupIdentifier();
group.setGroupId(group_id);
groups.add(group);
}
if (!groups.isEmpty())
launchSpecification.setAllSecurityGroups(groups);
}
}
}
} else {
/* No subnet: we can use standard security groups by name */
if (securityGroupSet.size() > 0)
launchSpecification.setSecurityGroups(securityGroupSet);
}
// The slave must know the Jenkins server to register with as well
// as the name of the node in Jenkins it should register as. The only
// way to give information to the Spot slaves is through the ec2 user data
String jenkinsUrl = Hudson.getInstance().getRootUrl();
// We must provide a unique node name for the slave to connect to Jenkins.
// We don't have the EC2 generated instance ID, or the Spot request ID
// until after the instance is requested, which is then too late to set the
// user-data for the request. Instead we generate a unique name from UUID
// so that the slave has a unique name within Jenkins to register to.
String slaveName = UUID.randomUUID().toString();
String newUserData = "";
// We want to allow node configuration with cloud-init and user-data,
// while maintaining backward compatibility with old ami's
// The 'new' way is triggered by the presence of '${SLAVE_NAME}'' in the user data
// (which is not too much to ask)
if (userData.contains("${SLAVE_NAME}")) {
// The cloud-init compatible way
newUserData = new String(userData);
newUserData = newUserData.replace("${SLAVE_NAME}", slaveName);
newUserData = newUserData.replace("${JENKINS_URL}", jenkinsUrl);
} else {
// The 'old' way - maitain full backward compatibility
newUserData = "JENKINS_URL=" + jenkinsUrl +
"&SLAVE_NAME=" + slaveName +
"&USER_DATA=" + Base64.encodeBase64String(userData.getBytes());
}
String userDataString = Base64.encodeBase64String(newUserData.getBytes());
launchSpecification.setUserData(userDataString);
launchSpecification.setKeyName(keyPair.getKeyName());
launchSpecification.setInstanceType(type.toString());
if (getAssociatePublicIp()) {
net.setAssociatePublicIpAddress(true);
net.setDeviceIndex(0);
launchSpecification.withNetworkInterfaces(net);
}
boolean hasCustomTypeTag = false;
HashSet<Tag> inst_tags = null;
if (tags != null && !tags.isEmpty()) {
inst_tags = new HashSet<Tag>();
for(EC2Tag t : tags) {
inst_tags.add(new Tag(t.getName(), t.getValue()));
if (StringUtils.equals(t.getName(), EC2Tag.TAG_NAME_JENKINS_SLAVE_TYPE)) {
hasCustomTypeTag = true;
}
}
}
if (!hasCustomTypeTag) {
inst_tags.add(new Tag(EC2Tag.TAG_NAME_JENKINS_SLAVE_TYPE, "spot"));
}
if (StringUtils.isNotBlank(getIamInstanceProfile())) {
launchSpecification.setIamInstanceProfile(new IamInstanceProfileSpecification().withArn(getIamInstanceProfile()));
}
spotRequest.setLaunchSpecification(launchSpecification);
// Make the request for a new Spot instance
RequestSpotInstancesResult reqResult = ec2.requestSpotInstances(spotRequest);
List<SpotInstanceRequest> reqInstances = reqResult.getSpotInstanceRequests();
if (reqInstances.size() <= 0){
throw new AmazonClientException("No spot instances found");
}
SpotInstanceRequest spotInstReq = reqInstances.get(0);
if (spotInstReq == null){
throw new AmazonClientException("Spot instance request is null");
}
/* Now that we have our Spot request, we can set tags on it */
if (inst_tags != null) {
for (int i = 0; i < 5; i++) {
try {
updateRemoteTags(ec2, inst_tags, spotInstReq.getSpotInstanceRequestId());
break;
} catch (AmazonServiceException e) {
if (e.getErrorCode().equals("InvalidSpotInstanceRequestID.NotFound")) {
Thread.sleep(5000);
continue;
}
throw e;
}
}
// That was a remote request - we should also update our local instance data.
spotInstReq.setTags(inst_tags);
}
logger.println("Spot instance id in provision: " + spotInstReq.getSpotInstanceRequestId());
LOGGER.info("Spot instance id in provision: " + spotInstReq.getSpotInstanceRequestId());
return newSpotSlave(spotInstReq, slaveName);
} catch (FormException e) {
throw new AssertionError(); // we should have discovered all configuration issues upfront
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
protected EC2OndemandSlave newOndemandSlave(Instance inst) throws FormException, IOException {
return new EC2OndemandSlave(inst.getInstanceId(), description, remoteFS, getNumExecutors(), labels, mode, initScript, tmpDir, remoteAdmin, jvmopts, stopOnTerminate, idleTerminationMinutes, inst.getPublicDnsName(), inst.getPrivateDnsName(), EC2Tag.fromAmazonTags(inst.getTags()), parent.name, usePrivateDnsName, useDedicatedTenancy, getLaunchTimeout(), amiType);
}
protected EC2SpotSlave newSpotSlave(SpotInstanceRequest sir, String name) throws FormException, IOException {
return new EC2SpotSlave(name, sir.getSpotInstanceRequestId(), description, remoteFS, getNumExecutors(), mode, initScript, tmpDir, labels, remoteAdmin, jvmopts, idleTerminationMinutes, EC2Tag.fromAmazonTags(sir.getTags()), parent.name, usePrivateDnsName, getLaunchTimeout(), amiType);
}
/**
* Get a KeyPair from the configured information for the slave template
*/
private KeyPair getKeyPair(AmazonEC2 ec2) throws IOException, AmazonClientException{
KeyPair keyPair = parent.getPrivateKey().find(ec2);
if(keyPair==null) {
throw new AmazonClientException("No matching keypair found on EC2. Is the EC2 private key a valid one?");
}
return keyPair;
}
/**
* Update the tags stored in EC2 with the specified information
*/
private void updateRemoteTags(AmazonEC2 ec2, Collection<Tag> inst_tags, String... params) {
CreateTagsRequest tag_request = new CreateTagsRequest();
tag_request.withResources(params).setTags(inst_tags);
ec2.createTags(tag_request);
}
/**
* Get a list of security group ids for the slave
*/
private List<String> getEc2SecurityGroups(AmazonEC2 ec2) throws AmazonClientException{
List<String> group_ids = new ArrayList<String>();
DescribeSecurityGroupsResult group_result = getSecurityGroupsBy("group-name", securityGroupSet, ec2);
if (group_result.getSecurityGroups().size() == 0) {
group_result = getSecurityGroupsBy("group-id", securityGroupSet, ec2);
}
for (SecurityGroup group : group_result.getSecurityGroups()) {
if (group.getVpcId() != null && !group.getVpcId().isEmpty()) {
List<Filter> filters = new ArrayList<Filter>();
filters.add(new Filter("vpc-id").withValues(group.getVpcId()));
filters.add(new Filter("state").withValues("available"));
filters.add(new Filter("subnet-id").withValues(getSubnetId()));
DescribeSubnetsRequest subnet_req = new DescribeSubnetsRequest();
subnet_req.withFilters(filters);
DescribeSubnetsResult subnet_result = ec2.describeSubnets(subnet_req);
List<Subnet> subnets = subnet_result.getSubnets();
if(subnets != null && !subnets.isEmpty()) {
group_ids.add(group.getGroupId());
}
}
}
if (securityGroupSet.size() != group_ids.size()) {
throw new AmazonClientException( "Security groups must all be VPC security groups to work in a VPC context" );
}
return group_ids;
}
private DescribeSecurityGroupsResult getSecurityGroupsBy(String filterName, Set<String> filterValues, AmazonEC2 ec2) {
DescribeSecurityGroupsRequest group_req = new DescribeSecurityGroupsRequest();
group_req.withFilters(new Filter(filterName).withValues(filterValues));
return ec2.describeSecurityGroups(group_req);
}
/**
* Provisions a new EC2 slave based on the currently running instance on EC2,
* instead of starting a new one.
*/
public EC2AbstractSlave attach(String instanceId, TaskListener listener) throws AmazonClientException, IOException {
PrintStream logger = listener.getLogger();
AmazonEC2 ec2 = getParent().connect();
try {
logger.println("Attaching to "+instanceId);
LOGGER.info("Attaching to "+instanceId);
DescribeInstancesRequest request = new DescribeInstancesRequest();
request.setInstanceIds(Collections.singletonList(instanceId));
Instance inst = ec2.describeInstances(request).getReservations().get(0).getInstances().get(0);
return newOndemandSlave(inst);
} catch (FormException e) {
throw new AssertionError(); // we should have discovered all configuration issues upfront
}
}
/**
* Initializes data structure that we don't persist.
*/
protected Object readResolve() {
labelSet = Label.parse(labels);
securityGroupSet = parseSecurityGroups();
/**
* In releases of this plugin prior to 1.18, template-specific instance caps could be configured
* but were not enforced. As a result, it was possible to have the instance cap for a template
* be configured to 0 (zero) with no ill effects. Starting with version 1.18, template-specific
* instance caps are enforced, so if a configuration has a cap of zero for a template, no instances
* will be launched from that template. Since there is no practical value of intentionally setting
* the cap to zero, this block will override such a setting to a value that means 'no cap'.
*/
if (instanceCap == 0) {
instanceCap = Integer.MAX_VALUE;
}
if (amiType == null) {
amiType = new UnixData(rootCommandPrefix, sshPort);
}
return this;
}
public Descriptor<SlaveTemplate> getDescriptor() {
return Hudson.getInstance().getDescriptor(getClass());
}
public int getLaunchTimeout() {
return launchTimeout <= 0 ? Integer.MAX_VALUE : launchTimeout;
}
public String getLaunchTimeoutStr() {
if (launchTimeout==Integer.MAX_VALUE) {
return "";
} else {
return String.valueOf(launchTimeout);
}
}
public boolean isWindowsSlave()
{
return amiType.isWindows();
}
public boolean isUnixSlave()
{
return amiType.isUnix();
}
public String getAdminPassword()
{
return amiType.isWindows() ? ((WindowsData)amiType).getPassword() : "";
}
private boolean isUseHTTPS() {
return amiType.isWindows() ? ((WindowsData)amiType).isUseHTTPS() : false;
}
@Extension
public static final class DescriptorImpl extends Descriptor<SlaveTemplate> {
@Override
public String getDisplayName() {
return null;
}
public List<Descriptor<AMITypeData>> getAMITypeDescriptors()
{
return Hudson.getInstance().<AMITypeData,Descriptor<AMITypeData>>getDescriptorList(AMITypeData.class);
}
/**
* Since this shares much of the configuration with {@link EC2Computer}, check its help page, too.
*/
@Override
public String getHelpFile(String fieldName) {
String p = super.getHelpFile(fieldName);
if (p==null)
p = Hudson.getInstance().getDescriptor(EC2OndemandSlave.class).getHelpFile(fieldName);
if (p==null)
p = Hudson.getInstance().getDescriptor(EC2SpotSlave.class).getHelpFile(fieldName);
return p;
}
/***
* Check that the AMI requested is available in the cloud and can be used.
*/
public FormValidation doValidateAmi(
@QueryParameter boolean useInstanceProfileForCredentials,
@QueryParameter String accessId, @QueryParameter String secretKey,
@QueryParameter String ec2endpoint, @QueryParameter String region,
final @QueryParameter String ami) throws IOException {
AWSCredentialsProvider credentialsProvider = EC2Cloud.createCredentialsProvider(useInstanceProfileForCredentials, accessId, secretKey);
AmazonEC2 ec2;
if (region != null) {
ec2 = EC2Cloud.connect(credentialsProvider, AmazonEC2Cloud.getEc2EndpointUrl(region));
} else {
ec2 = EC2Cloud.connect(credentialsProvider, new URL(ec2endpoint));
}
if(ec2!=null) {
try {
List<String> images = new LinkedList<String>();
images.add(ami);
List<String> owners = new LinkedList<String>();
List<String> users = new LinkedList<String>();
DescribeImagesRequest request = new DescribeImagesRequest();
request.setImageIds(images);
request.setOwners(owners);
request.setExecutableUsers(users);
List<Image> img = ec2.describeImages(request).getImages();
if(img==null || img.isEmpty()) {
// de-registered AMI causes an empty list to be returned. so be defensive
// against other possibilities
return FormValidation.error("No such AMI, or not usable with this accessId: "+ami);
}
String ownerAlias = img.get(0).getImageOwnerAlias();
return FormValidation.ok(img.get(0).getImageLocation() +
(ownerAlias != null ? " by " + ownerAlias : ""));
} catch (AmazonClientException e) {
return FormValidation.error(e.getMessage());
}
} else
return FormValidation.ok(); // can't test
}
public FormValidation doCheckLabelString(@QueryParameter String value, @QueryParameter Node.Mode mode) {
if (mode == Node.Mode.EXCLUSIVE && (value == null || value.trim() == "")) {
return FormValidation.warning("You may want to assign labels to this node;" +
" it's marked to only run jobs that are exclusively tied to itself or a label.");
}
return FormValidation.ok();
}
public FormValidation doCheckIdleTerminationMinutes(@QueryParameter String value) {
if (value == null || value.trim() == "") return FormValidation.ok();
try {
int val = Integer.parseInt(value);
if (val >= -59) return FormValidation.ok();
}
catch ( NumberFormatException nfe ) {}
return FormValidation.error("Idle Termination time must be a greater than -59 (or null)");
}
public FormValidation doCheckInstanceCapStr(@QueryParameter String value) {
if (value == null || value.trim() == "") return FormValidation.ok();
try {
int val = Integer.parseInt(value);
if (val > 0) return FormValidation.ok();
} catch ( NumberFormatException nfe ) {}
return FormValidation.error("InstanceCap must be a non-negative integer (or null)");
}
public FormValidation doCheckLaunchTimeoutStr(@QueryParameter String value) {
if (value == null || value.trim() == "") return FormValidation.ok();
try {
int val = Integer.parseInt(value);
if (val >= 0) return FormValidation.ok();
} catch ( NumberFormatException nfe ) {}
return FormValidation.error("Launch Timeout must be a non-negative integer (or null)");
}
public ListBoxModel doFillZoneItems( @QueryParameter boolean useInstanceProfileForCredentials,
@QueryParameter String accessId,
@QueryParameter String secretKey,
@QueryParameter String region)
throws IOException, ServletException
{
AWSCredentialsProvider credentialsProvider = EC2Cloud.createCredentialsProvider(useInstanceProfileForCredentials, accessId, secretKey);
return EC2AbstractSlave.fillZoneItems(credentialsProvider, region);
}
/* Validate the Spot Max Bid Price to ensure that it is a floating point number >= .001 */
public FormValidation doCheckSpotMaxBidPrice( @QueryParameter String spotMaxBidPrice ) {
if(SpotConfiguration.normalizeBid(spotMaxBidPrice) != null){
return FormValidation.ok();
}
return FormValidation.error("Not a correct bid price");
}
// Retrieve the availability zones for the region
private ArrayList<String> getAvailabilityZones(AmazonEC2 ec2) {
ArrayList<String> availabilityZones = new ArrayList<String>();
DescribeAvailabilityZonesResult zones = ec2.describeAvailabilityZones();
List<AvailabilityZone> zoneList = zones.getAvailabilityZones();
for (AvailabilityZone z : zoneList) {
availabilityZones.add(z.getZoneName());
}
return availabilityZones;
}
/**
* Populates the Bid Type Drop down on the slave template config.
* @return
*/
public ListBoxModel doFillBidTypeItems() {
ListBoxModel items = new ListBoxModel();
items.add(SpotInstanceType.OneTime.toString());
items.add(SpotInstanceType.Persistent.toString());
return items;
}
/* Check the current Spot price of the selected instance type for the selected region */
public FormValidation doCurrentSpotPrice( @QueryParameter boolean useInstanceProfileForCredentials,
@QueryParameter String accessId, @QueryParameter String secretKey,
@QueryParameter String region, @QueryParameter String type,
@QueryParameter String zone ) throws IOException, ServletException {
String cp = "";
String zoneStr = "";
// Connect to the EC2 cloud with the access id, secret key, and region queried from the created cloud
AWSCredentialsProvider credentialsProvider = EC2Cloud.createCredentialsProvider(useInstanceProfileForCredentials, accessId, secretKey);
AmazonEC2 ec2 = EC2Cloud.connect(credentialsProvider, AmazonEC2Cloud.getEc2EndpointUrl(region));
if(ec2!=null) {
try {
// Build a new price history request with the currently selected type
DescribeSpotPriceHistoryRequest request = new DescribeSpotPriceHistoryRequest();
// If a zone is specified, set the availability zone in the request
// Else, proceed with no availability zone which will result with the cheapest Spot price
if(getAvailabilityZones(ec2).contains(zone)){
request.setAvailabilityZone(zone);
zoneStr = zone + " availability zone";
} else {
zoneStr = region + " region";
}
/*
* Iterate through the AWS instance types to see if can find a match for the databound
* String type. This is necessary because the AWS API needs the instance type
* string formatted a particular way to retrieve prices and the form gives us the strings
* in a different format. For example "T1Micro" vs "t1.micro".
*/
InstanceType ec2Type = null;
for(InstanceType it : InstanceType.values()){
if (it.name().toString().equals(type)){
ec2Type = it;
break;
}
}
/*
* If the type string cannot be matched with an instance type,
* throw a Form error
*/
if(ec2Type == null){
return FormValidation.error("Could not resolve instance type: " + type);
}
Collection<String> instanceType = new ArrayList<String>();
instanceType.add(ec2Type.toString());
request.setInstanceTypes(instanceType);
request.setStartTime(new Date());
// Retrieve the price history request result and store the current price
DescribeSpotPriceHistoryResult result = ec2.describeSpotPriceHistory(request);
if(!result.getSpotPriceHistory().isEmpty()){
SpotPrice currentPrice = result.getSpotPriceHistory().get(0);
cp = currentPrice.getSpotPrice();
}
} catch (AmazonClientException e) {
return FormValidation.error(e.getMessage());
}
}
/*
* If we could not return the current price of the instance display an error
* Else, remove the additional zeros from the current price and return it to the interface
* in the form of a message
*/
if(cp.isEmpty()){
return FormValidation.error("Could not retrieve current Spot price");
} else {
cp = cp.substring(0, cp.length() - 3);
return FormValidation.ok("The current Spot price for a " + type +
" in the " + zoneStr + " is $" + cp );
}
}
}
private static final Logger LOGGER = Logger.getLogger(SlaveTemplate.class.getName());
} |
package innovimax.mixthem.arguments;
import java.util.EnumSet;
/**
* <p>This is a detailed enumeration of rules used to mix files.</p>
* <p>Some rules may not be implemented yet.<.p>
* <p>(Also used to print usage.)</p>
* @author Innovimax
* @version 1.0
*/
public enum Rule {
FILE_1("1", "1", "will output file1", true, EnumSet.noneOf(RuleParam.class)),
FILE_2("2", "2", "will output file2", true, EnumSet.noneOf(RuleParam.class)),
ADD("+", "add", "will output file1+file2", true, EnumSet.noneOf(RuleParam.class)),
ALT_LINE("alt-line", "altline", "will output one line of each starting with first line of file1", true, EnumSet.noneOf(RuleParam.class)),
ALT_CHAR("alt-char", "altchar", "will output one char of each starting with first char of file1", true, EnumSet.noneOf(RuleParam.class)),
RANDOM_ALT_LINE("random-alt-line", "random-altline", "will output one line of each code randomly based on a seed for reproducability", true, EnumSet.of(RuleParam._RANDOM_SEED)),
JOIN("join", "join", "will output merging of lines that have common occurrence", true, EnumSet.of(RuleParam._JOIN_COL1, RuleParam._JOIN_COL2)),
ZIP_LINE("zip-line", "zipline", "will output zip of line from file1 and file2", true, EnumSet.of(RuleParam._ZIP_SEP)),
ZIP_CHAR("zip-char", "zipchar", "will output zip of char from file1 and file2", true, EnumSet.of(RuleParam._ZIP_SEP)),
ZIP_CELL("zip-cell", "zipcell", "will output zip of cell from file1 and file2", true, EnumSet.of(RuleParam._ZIP_SEP));
private final String name, extension, description;
private final boolean implemented;
private final EnumSet<RuleParam> params;
private Rule(String name, String extension, String description, boolean implemented, EnumSet<RuleParam> params) {
this.name = name;
this.extension = extension;
this.description = description;
this.implemented = implemented;
this.params = params;
}
/**
* Returns true if the rule is currently implemented.
* @return True if the rule is currently implemented
*/
public boolean isImplemented() {
return this.implemented;
}
/**
* Returns the name of this rule on command line.
* @return The name of the rule on command line
*/
public String getName() {
return this.name;
}
/**
* Returns the file extension used for outputting.
* @return The file extension for the rule
*/
public String getExtension() {
return this.extension;
}
/**
* Returns the description of this rule.
* @return The description of the rule
*/
public String getDescription() {
return this.description;
}
/**
* Returns an iterator over the additional parameters in this rule.
* @return An iterator over the additional parameters in this rule
*/
public Iterable<RuleParam> getParams() {
return this.params;
}
/**
* Finds the Rule object correponding to a name
* @param name The name of the rule in command line
* @return The {@link Rule} object
*/
public static Rule findByName(String name) {
for(Rule rule : values()){
if (rule.getName().equals(name)) {
return rule;
}
}
return null;
}
} |
package io.clickhandler.web.dom;
import jsinterop.annotations.JsIgnore;
import jsinterop.annotations.JsProperty;
import jsinterop.annotations.JsType;
@JsType
public class CSSProps {
@JsProperty
public Object backgroundColor;
@JsProperty
public Number boxFlex;
@JsProperty
public Number boxFlexGroup;
@JsProperty
public Number columnCount;
@JsProperty
public Object flex;
@JsProperty
public Number flexGrow;
@JsProperty
public Number flexShrink;
@JsProperty
public Object fontWeight;
@JsProperty
public Number lineClamp;
@JsProperty
public Object lineHeight;
@JsProperty
public Number opacity;
@JsProperty
public Number order;
@JsProperty
public Number orphans;
@JsProperty
public Number widows;
@JsProperty
public Number zIndex;
@JsProperty
public Number zoom;
@JsProperty
public Object fontSize;
@JsProperty
public Number fillOpacity;
@JsProperty
public Number strokeOpacity;
@JsProperty
public Number strokeWidth;
@JsProperty
public Object alignContent;
@JsProperty
public Object alignItems;
@JsProperty
public Object alignSelf;
@JsProperty
public Object alignmentAdjust;
@JsProperty
public Object alignmentBaseline;
@JsProperty
public Object animationDelay;
@JsProperty
public Object animationDirection;
@JsProperty
public Object animationIterationCount;
@JsProperty
public Object animationName;
@JsProperty
public Object animationPlayState;
@JsProperty
public Object appearance;
@JsProperty
public Object backfaceVisibility;
@JsProperty
public Object backgroundBlendMode;
@JsProperty
public Object backgroundComposite;
@JsProperty
public Object backgroundImage;
@JsProperty
public Object backgroundOrigin;
@JsProperty
public Object backgroundPositionX;
@JsProperty
public Object backgroundRepeat;
@JsProperty
public Object baselineShift;
@JsProperty
public Object behavior;
@JsProperty
public Object border;
@JsProperty
public Object borderBottomLeftRadius;
@JsProperty
public Object borderBottomRightRadius;
@JsProperty
public Object borderBottomWidth;
@JsProperty
public Object borderCollapse;
@JsProperty
public Object borderColor;
@JsProperty
public Object borderCornerShape;
@JsProperty
public Object borderImageSource;
@JsProperty
public Object borderImageWidth;
@JsProperty
public Object borderLeft;
@JsProperty
public Object borderLeftColor;
@JsProperty
public Object borderLeftStyle;
@JsProperty
public Object borderLeftWidth;
@JsProperty
public Object borderRight;
@JsProperty
public Object borderRightColor;
@JsProperty
public Object borderRightStyle;
@JsProperty
public Object borderRightWidth;
@JsProperty
public Object borderSpacing;
@JsProperty
public Object borderStyle;
@JsProperty
public Object borderTop;
@JsProperty
public Object borderTopColor;
@JsProperty
public Object borderTopLeftRadius;
@JsProperty
public Object borderTopRightRadius;
@JsProperty
public Object borderTopStyle;
@JsProperty
public Object borderTopWidth;
@JsProperty
public Object borderWidth;
@JsProperty
public Object boxAlign;
@JsProperty
public Object boxDecorationBreak;
@JsProperty
public Object boxDirection;
@JsProperty
public Object boxLineProgression;
@JsProperty
public Object boxLines;
@JsProperty
public Object boxOrdinalGroup;
@JsProperty
public Object breakAfter;
@JsProperty
public Object breakBefore;
@JsProperty
public Object breakInside;
@JsProperty
public Object clear;
@JsProperty
public Object clip;
@JsProperty
public Object clipRule;
@JsProperty
public Object color;
@JsProperty
public Object columnFill;
@JsProperty
public Object columnGap;
@JsProperty
public Object columnRule;
@JsProperty
public Object columnRuleColor;
@JsProperty
public Object columnRuleWidth;
@JsProperty
public Object columnSpan;
@JsProperty
public Object columnWidth;
@JsProperty
public Object columns;
@JsProperty
public Object counterIncrement;
@JsProperty
public Object counterReset;
@JsProperty
public Object cue;
@JsProperty
public Object cueAfter;
@JsProperty
public Object direction;
@JsProperty
public Object display;
@JsProperty
public Object fill;
@JsProperty
public Object fillRule;
@JsProperty
public Object filter;
@JsProperty
public Object flexAlign;
@JsProperty
public Object flexBasis;
@JsProperty
public Object flexDirection;
@JsProperty
public Object flexFlow;
@JsProperty
public Object flexItemAlign;
@JsProperty
public Object flexLinePack;
@JsProperty
public Object flexOrder;
@JsProperty(name = "float")
public Object _float;
@JsProperty
public Object flowFrom;
@JsProperty
public Object font;
@JsProperty
public Object fontFamily;
@JsProperty
public Object fontKerning;
@JsProperty
public Object fontSizeAdjust;
@JsProperty
public Object fontStretch;
@JsProperty
public Object fontStyle;
@JsProperty
public Object fontSynthesis;
@JsProperty
public Object fontVariant;
@JsProperty
public Object fontVariantAlternates;
@JsProperty
public Object gridArea;
@JsProperty
public Object gridColumn;
@JsProperty
public Object gridColumnEnd;
@JsProperty
public Object gridColumnStart;
@JsProperty
public Object gridRow;
@JsProperty
public Object gridRowEnd;
@JsProperty
public Object gridRowPosition;
@JsProperty
public Object gridRowSpan;
@JsProperty
public Object gridTemplateAreas;
@JsProperty
public Object gridTemplateColumns;
@JsProperty
public Object gridTemplateRows;
@JsProperty
public Object height;
@JsProperty
public Object hyphenateLimitChars;
@JsProperty
public Object hyphenateLimitLines;
@JsProperty
public Object hyphenateLimitZone;
@JsProperty
public Object hyphens;
@JsProperty
public Object imeMode;
@JsProperty
public Object layoutGrid;
@JsProperty
public Object layoutGridChar;
@JsProperty
public Object layoutGridLine;
@JsProperty
public Object layoutGridMode;
@JsProperty
public Object layoutGridType;
@JsProperty
public Object left;
@JsProperty
public Object letterSpacing;
@JsProperty
public Object lineBreak;
@JsProperty
public Object listStyle;
@JsProperty
public Object listStyleImage;
@JsProperty
public Object listStylePosition;
@JsProperty
public Object listStyleType;
@JsProperty
public Object margin;
@JsProperty
public Object marginBottom;
@JsProperty
public Object marginLeft;
@JsProperty
public Object marginRight;
@JsProperty
public Object marginTop;
@JsProperty
public Object marqueeDirection;
@JsProperty
public Object marqueeStyle;
@JsProperty
public Object mask;
@JsProperty
public Object maskBorder;
@JsProperty
public Object maskBorderRepeat;
@JsProperty
public Object maskBorderSlice;
@JsProperty
public Object maskBorderSource;
@JsProperty
public Object maskBorderWidth;
@JsProperty
public Object maskClip;
@JsProperty
public Object maskOrigin;
@JsProperty
public Object maxFontSize;
@JsProperty
public Object maxHeight;
@JsProperty
public Object maxWidth;
@JsProperty
public Object minWidth;
@JsProperty
public Object outline;
@JsProperty
public Object outlineColor;
@JsProperty
public Object outlineOffset;
@JsProperty
public Object overflow;
@JsProperty
public Object overflowStyle;
@JsProperty
public Object overflowX;
@JsProperty
public Object padding;
@JsProperty
public Object paddingBottom;
@JsProperty
public Object paddingLeft;
@JsProperty
public Object paddingRight;
@JsProperty
public Object paddingTop;
@JsProperty
public Object pageBreakAfter;
@JsProperty
public Object pageBreakBefore;
@JsProperty
public Object pageBreakInside;
@JsProperty
public Object pause;
@JsProperty
public Object pauseAfter;
@JsProperty
public Object pauseBefore;
@JsProperty
public Object perspective;
@JsProperty
public Object perspectiveOrigin;
@JsProperty
public Object pointerEvents;
@JsProperty
public Object position;
@JsProperty
public Object punctuationTrim;
@JsProperty
public Object quotes;
@JsProperty
public Object regionFragment;
@JsProperty
public Object restAfter;
@JsProperty
public Object restBefore;
@JsProperty
public Object right;
@JsProperty
public Object rubyAlign;
@JsProperty
public Object rubyPosition;
@JsProperty
public Object shapeImageThreshold;
@JsProperty
public Object shapeInside;
@JsProperty
public Object shapeMargin;
@JsProperty
public Object shapeOutside;
@JsProperty
public Object speak;
@JsProperty
public Object speakAs;
@JsProperty
public Object tabSize;
@JsProperty
public Object tableLayout;
@JsProperty
public Object textAlign;
@JsProperty
public Object textAlignLast;
@JsProperty
public Object textDecoration;
@JsProperty
public Object textDecorationColor;
@JsProperty
public Object textDecorationLine;
@JsProperty
public Object textDecorationLineThrough;
@JsProperty
public Object textDecorationNone;
@JsProperty
public Object textDecorationOverline;
@JsProperty
public Object textDecorationSkip;
@JsProperty
public Object textDecorationStyle;
@JsProperty
public Object textDecorationUnderline;
@JsProperty
public Object textEmphasis;
@JsProperty
public Object textEmphasisColor;
@JsProperty
public Object textEmphasisStyle;
@JsProperty
public Object textHeight;
@JsProperty
public Object textIndent;
@JsProperty
public Object textJustifyTrim;
@JsProperty
public Object textKashidaSpace;
@JsProperty
public Object textLineThrough;
@JsProperty
public Object textLineThroughColor;
@JsProperty
public Object textLineThroughMode;
@JsProperty
public Object textLineThroughStyle;
@JsProperty
public Object textLineThroughWidth;
@JsProperty
public Object textOverflow;
@JsProperty
public Object textOverline;
@JsProperty
public Object textOverlineColor;
@JsProperty
public Object textOverlineMode;
@JsProperty
public Object textOverlineStyle;
@JsProperty
public Object textOverlineWidth;
@JsProperty
public Object textRendering;
@JsProperty
public Object textScript;
@JsProperty
public Object textShadow;
@JsProperty
public Object textTransform;
@JsProperty
public Object textUnderlinePosition;
@JsProperty
public Object textUnderlineStyle;
@JsProperty
public Object top;
@JsProperty
public Object touchAction;
@JsProperty
public Object transform;
@JsProperty
public Object transformOrigin;
@JsProperty
public Object transformOriginZ;
@JsProperty
public Object transformStyle;
@JsProperty
public Object transition;
@JsProperty
public Object transitionDelay;
@JsProperty
public Object transitionDuration;
@JsProperty
public Object transitionProperty;
@JsProperty
public Object transitionTimingFunction;
@JsProperty
public Object unicodeBidi;
@JsProperty
public Object unicodeRange;
@JsProperty
public Object userFocus;
@JsProperty
public Object userInput;
@JsProperty
public Object verticalAlign;
@JsProperty
public Object visibility;
@JsProperty
public Object voiceBalance;
@JsProperty
public Object voiceDuration;
@JsProperty
public Object voiceFamily;
@JsProperty
public Object voicePitch;
@JsProperty
public Object voiceRange;
@JsProperty
public Object voiceRate;
@JsProperty
public Object voiceStress;
@JsProperty
public Object voiceVolume;
@JsProperty
public Object whiteSpace;
@JsProperty
public Object whiteSpaceTreatment;
@JsProperty
public Object width;
@JsProperty
public Object wordBreak;
@JsProperty
public Object wordSpacing;
@JsProperty
public Object wordWrap;
@JsProperty
public Object wrapFlow;
@JsProperty
public Object wrapMargin;
@JsProperty
public Object wrapOption;
@JsProperty
public Object writingMode;
@JsIgnore
public CSSProps backgroundColor(Object value) {
this.backgroundColor = value;
return this;
}
@JsIgnore
public CSSProps boxFlex(Number value) {
this.boxFlex = value;
return this;
}
@JsIgnore
public CSSProps boxFlexGroup(Number value) {
this.boxFlexGroup = value;
return this;
}
@JsIgnore
public CSSProps columnCount(Number value) {
this.columnCount = value;
return this;
}
@JsIgnore
public CSSProps flex(Object value) {
this.flex = value;
return this;
}
@JsIgnore
public CSSProps flexGrow(Number value) {
this.flexGrow = value;
return this;
}
@JsIgnore
public CSSProps flexShrink(Number value) {
this.flexShrink = value;
return this;
}
@JsIgnore
public CSSProps fontWeight(Object value) {
this.fontWeight = value;
return this;
}
@JsIgnore
public CSSProps lineClamp(Number value) {
this.lineClamp = value;
return this;
}
@JsIgnore
public CSSProps lineHeight(Object value) {
this.lineHeight = value;
return this;
}
@JsIgnore
public CSSProps opacity(Number value) {
this.opacity = value;
return this;
}
@JsIgnore
public CSSProps order(Number value) {
this.order = value;
return this;
}
@JsIgnore
public CSSProps orphans(Number value) {
this.orphans = value;
return this;
}
@JsIgnore
public CSSProps widows(Number value) {
this.widows = value;
return this;
}
@JsIgnore
public CSSProps zIndex(Number value) {
this.zIndex = value;
return this;
}
@JsIgnore
public CSSProps zoom(Number value) {
this.zoom = value;
return this;
}
@JsIgnore
public CSSProps fontSize(Object value) {
this.fontSize = value;
return this;
}
@JsIgnore
public CSSProps fillOpacity(Number value) {
this.fillOpacity = value;
return this;
}
@JsIgnore
public CSSProps strokeOpacity(Number value) {
this.strokeOpacity = value;
return this;
}
@JsIgnore
public CSSProps strokeWidth(Number value) {
this.strokeWidth = value;
return this;
}
@JsIgnore
public CSSProps alignContent(Object value) {
this.alignContent = value;
return this;
}
@JsIgnore
public CSSProps alignItems(Object value) {
this.alignItems = value;
return this;
}
@JsIgnore
public CSSProps alignSelf(Object value) {
this.alignSelf = value;
return this;
}
@JsIgnore
public CSSProps alignmentAdjust(Object value) {
this.alignmentAdjust = value;
return this;
}
@JsIgnore
public CSSProps alignmentBaseline(Object value) {
this.alignmentBaseline = value;
return this;
}
@JsIgnore
public CSSProps animationDelay(Object value) {
this.animationDelay = value;
return this;
}
@JsIgnore
public CSSProps animationDirection(Object value) {
this.animationDirection = value;
return this;
}
@JsIgnore
public CSSProps animationIterationCount(Object value) {
this.animationIterationCount = value;
return this;
}
@JsIgnore
public CSSProps animationName(Object value) {
this.animationName = value;
return this;
}
@JsIgnore
public CSSProps animationPlayState(Object value) {
this.animationPlayState = value;
return this;
}
@JsIgnore
public CSSProps appearance(Object value) {
this.appearance = value;
return this;
}
@JsIgnore
public CSSProps backfaceVisibility(Object value) {
this.backfaceVisibility = value;
return this;
}
@JsIgnore
public CSSProps backgroundBlendMode(Object value) {
this.backgroundBlendMode = value;
return this;
}
@JsIgnore
public CSSProps backgroundComposite(Object value) {
this.backgroundComposite = value;
return this;
}
@JsIgnore
public CSSProps backgroundImage(Object value) {
this.backgroundImage = value;
return this;
}
@JsIgnore
public CSSProps backgroundOrigin(Object value) {
this.backgroundOrigin = value;
return this;
}
@JsIgnore
public CSSProps backgroundPositionX(Object value) {
this.backgroundPositionX = value;
return this;
}
@JsIgnore
public CSSProps backgroundRepeat(Object value) {
this.backgroundRepeat = value;
return this;
}
@JsIgnore
public CSSProps baselineShift(Object value) {
this.baselineShift = value;
return this;
}
@JsIgnore
public CSSProps behavior(Object value) {
this.behavior = value;
return this;
}
@JsIgnore
public CSSProps border(Object value) {
this.border = value;
return this;
}
@JsIgnore
public CSSProps borderBottomLeftRadius(Object value) {
this.borderBottomLeftRadius = value;
return this;
}
@JsIgnore
public CSSProps borderBottomRightRadius(Object value) {
this.borderBottomRightRadius = value;
return this;
}
@JsIgnore
public CSSProps borderBottomWidth(Object value) {
this.borderBottomWidth = value;
return this;
}
@JsIgnore
public CSSProps borderCollapse(Object value) {
this.borderCollapse = value;
return this;
}
@JsIgnore
public CSSProps borderColor(Object value) {
this.borderColor = value;
return this;
}
@JsIgnore
public CSSProps borderCornerShape(Object value) {
this.borderCornerShape = value;
return this;
}
@JsIgnore
public CSSProps borderImageSource(Object value) {
this.borderImageSource = value;
return this;
}
@JsIgnore
public CSSProps borderImageWidth(Object value) {
this.borderImageWidth = value;
return this;
}
@JsIgnore
public CSSProps borderLeft(Object value) {
this.borderLeft = value;
return this;
}
@JsIgnore
public CSSProps borderLeftColor(Object value) {
this.borderLeftColor = value;
return this;
}
@JsIgnore
public CSSProps borderLeftStyle(Object value) {
this.borderLeftStyle = value;
return this;
}
@JsIgnore
public CSSProps borderLeftWidth(Object value) {
this.borderLeftWidth = value;
return this;
}
@JsIgnore
public CSSProps borderRight(Object value) {
this.borderRight = value;
return this;
}
@JsIgnore
public CSSProps borderRightColor(Object value) {
this.borderRightColor = value;
return this;
}
@JsIgnore
public CSSProps borderRightStyle(Object value) {
this.borderRightStyle = value;
return this;
}
@JsIgnore
public CSSProps borderRightWidth(Object value) {
this.borderRightWidth = value;
return this;
}
@JsIgnore
public CSSProps borderSpacing(Object value) {
this.borderSpacing = value;
return this;
}
@JsIgnore
public CSSProps borderStyle(Object value) {
this.borderStyle = value;
return this;
}
@JsIgnore
public CSSProps borderTop(Object value) {
this.borderTop = value;
return this;
}
@JsIgnore
public CSSProps borderTopColor(Object value) {
this.borderTopColor = value;
return this;
}
@JsIgnore
public CSSProps borderTopLeftRadius(Object value) {
this.borderTopLeftRadius = value;
return this;
}
@JsIgnore
public CSSProps borderTopRightRadius(Object value) {
this.borderTopRightRadius = value;
return this;
}
@JsIgnore
public CSSProps borderTopStyle(Object value) {
this.borderTopStyle = value;
return this;
}
@JsIgnore
public CSSProps borderTopWidth(Object value) {
this.borderTopWidth = value;
return this;
}
@JsIgnore
public CSSProps borderWidth(Object value) {
this.borderWidth = value;
return this;
}
@JsIgnore
public CSSProps boxAlign(Object value) {
this.boxAlign = value;
return this;
}
@JsIgnore
public CSSProps boxDecorationBreak(Object value) {
this.boxDecorationBreak = value;
return this;
}
@JsIgnore
public CSSProps boxDirection(Object value) {
this.boxDirection = value;
return this;
}
@JsIgnore
public CSSProps boxLineProgression(Object value) {
this.boxLineProgression = value;
return this;
}
@JsIgnore
public CSSProps boxLines(Object value) {
this.boxLines = value;
return this;
}
@JsIgnore
public CSSProps boxOrdinalGroup(Object value) {
this.boxOrdinalGroup = value;
return this;
}
@JsIgnore
public CSSProps breakAfter(Object value) {
this.breakAfter = value;
return this;
}
@JsIgnore
public CSSProps breakBefore(Object value) {
this.breakBefore = value;
return this;
}
@JsIgnore
public CSSProps breakInside(Object value) {
this.breakInside = value;
return this;
}
@JsIgnore
public CSSProps clear(Object value) {
this.clear = value;
return this;
}
@JsIgnore
public CSSProps clip(Object value) {
this.clip = value;
return this;
}
@JsIgnore
public CSSProps clipRule(Object value) {
this.clipRule = value;
return this;
}
@JsIgnore
public CSSProps color(Object value) {
this.color = value;
return this;
}
@JsIgnore
public CSSProps columnFill(Object value) {
this.columnFill = value;
return this;
}
@JsIgnore
public CSSProps columnGap(Object value) {
this.columnGap = value;
return this;
}
@JsIgnore
public CSSProps columnRule(Object value) {
this.columnRule = value;
return this;
}
@JsIgnore
public CSSProps columnRuleColor(Object value) {
this.columnRuleColor = value;
return this;
}
@JsIgnore
public CSSProps columnRuleWidth(Object value) {
this.columnRuleWidth = value;
return this;
}
@JsIgnore
public CSSProps columnSpan(Object value) {
this.columnSpan = value;
return this;
}
@JsIgnore
public CSSProps columnWidth(Object value) {
this.columnWidth = value;
return this;
}
@JsIgnore
public CSSProps columns(Object value) {
this.columns = value;
return this;
}
@JsIgnore
public CSSProps counterIncrement(Object value) {
this.counterIncrement = value;
return this;
}
@JsIgnore
public CSSProps counterReset(Object value) {
this.counterReset = value;
return this;
}
@JsIgnore
public CSSProps cue(Object value) {
this.cue = value;
return this;
}
@JsIgnore
public CSSProps cueAfter(Object value) {
this.cueAfter = value;
return this;
}
@JsIgnore
public CSSProps direction(Object value) {
this.direction = value;
return this;
}
@JsIgnore
public CSSProps display(Object value) {
this.display = value;
return this;
}
@JsIgnore
public CSSProps fill(Object value) {
this.fill = value;
return this;
}
@JsIgnore
public CSSProps fillRule(Object value) {
this.fillRule = value;
return this;
}
@JsIgnore
public CSSProps filter(Object value) {
this.filter = value;
return this;
}
@JsIgnore
public CSSProps flexAlign(Object value) {
this.flexAlign = value;
return this;
}
@JsIgnore
public CSSProps flexBasis(Object value) {
this.flexBasis = value;
return this;
}
@JsIgnore
public CSSProps flexDirection(Object value) {
this.flexDirection = value;
return this;
}
@JsIgnore
public CSSProps flexFlow(Object value) {
this.flexFlow = value;
return this;
}
@JsIgnore
public CSSProps flexItemAlign(Object value) {
this.flexItemAlign = value;
return this;
}
@JsIgnore
public CSSProps flexLinePack(Object value) {
this.flexLinePack = value;
return this;
}
@JsIgnore
public CSSProps flexOrder(Object value) {
this.flexOrder = value;
return this;
}
@JsIgnore
public CSSProps _float(Object value) {
this._float = value;
return this;
}
@JsIgnore
public CSSProps flowFrom(Object value) {
this.flowFrom = value;
return this;
}
@JsIgnore
public CSSProps font(Object value) {
this.font = value;
return this;
}
@JsIgnore
public CSSProps fontFamily(Object value) {
this.fontFamily = value;
return this;
}
@JsIgnore
public CSSProps fontKerning(Object value) {
this.fontKerning = value;
return this;
}
@JsIgnore
public CSSProps fontSizeAdjust(Object value) {
this.fontSizeAdjust = value;
return this;
}
@JsIgnore
public CSSProps fontStretch(Object value) {
this.fontStretch = value;
return this;
}
@JsIgnore
public CSSProps fontStyle(Object value) {
this.fontStyle = value;
return this;
}
@JsIgnore
public CSSProps fontSynthesis(Object value) {
this.fontSynthesis = value;
return this;
}
@JsIgnore
public CSSProps fontVariant(Object value) {
this.fontVariant = value;
return this;
}
@JsIgnore
public CSSProps fontVariantAlternates(Object value) {
this.fontVariantAlternates = value;
return this;
}
@JsIgnore
public CSSProps gridArea(Object value) {
this.gridArea = value;
return this;
}
@JsIgnore
public CSSProps gridColumn(Object value) {
this.gridColumn = value;
return this;
}
@JsIgnore
public CSSProps gridColumnEnd(Object value) {
this.gridColumnEnd = value;
return this;
}
@JsIgnore
public CSSProps gridColumnStart(Object value) {
this.gridColumnStart = value;
return this;
}
@JsIgnore
public CSSProps gridRow(Object value) {
this.gridRow = value;
return this;
}
@JsIgnore
public CSSProps gridRowEnd(Object value) {
this.gridRowEnd = value;
return this;
}
@JsIgnore
public CSSProps gridRowPosition(Object value) {
this.gridRowPosition = value;
return this;
}
@JsIgnore
public CSSProps gridRowSpan(Object value) {
this.gridRowSpan = value;
return this;
}
@JsIgnore
public CSSProps gridTemplateAreas(Object value) {
this.gridTemplateAreas = value;
return this;
}
@JsIgnore
public CSSProps gridTemplateColumns(Object value) {
this.gridTemplateColumns = value;
return this;
}
@JsIgnore
public CSSProps gridTemplateRows(Object value) {
this.gridTemplateRows = value;
return this;
}
@JsIgnore
public CSSProps height(Object value) {
this.height = value;
return this;
}
@JsIgnore
public CSSProps hyphenateLimitChars(Object value) {
this.hyphenateLimitChars = value;
return this;
}
@JsIgnore
public CSSProps hyphenateLimitLines(Object value) {
this.hyphenateLimitLines = value;
return this;
}
@JsIgnore
public CSSProps hyphenateLimitZone(Object value) {
this.hyphenateLimitZone = value;
return this;
}
@JsIgnore
public CSSProps hyphens(Object value) {
this.hyphens = value;
return this;
}
@JsIgnore
public CSSProps imeMode(Object value) {
this.imeMode = value;
return this;
}
@JsIgnore
public CSSProps layoutGrid(Object value) {
this.layoutGrid = value;
return this;
}
@JsIgnore
public CSSProps layoutGridChar(Object value) {
this.layoutGridChar = value;
return this;
}
@JsIgnore
public CSSProps layoutGridLine(Object value) {
this.layoutGridLine = value;
return this;
}
@JsIgnore
public CSSProps layoutGridMode(Object value) {
this.layoutGridMode = value;
return this;
}
@JsIgnore
public CSSProps layoutGridType(Object value) {
this.layoutGridType = value;
return this;
}
@JsIgnore
public CSSProps left(Object value) {
this.left = value;
return this;
}
@JsIgnore
public CSSProps letterSpacing(Object value) {
this.letterSpacing = value;
return this;
}
@JsIgnore
public CSSProps lineBreak(Object value) {
this.lineBreak = value;
return this;
}
@JsIgnore
public CSSProps listStyle(Object value) {
this.listStyle = value;
return this;
}
@JsIgnore
public CSSProps listStyleImage(Object value) {
this.listStyleImage = value;
return this;
}
@JsIgnore
public CSSProps listStylePosition(Object value) {
this.listStylePosition = value;
return this;
}
@JsIgnore
public CSSProps listStyleType(Object value) {
this.listStyleType = value;
return this;
}
@JsIgnore
public CSSProps margin(Object value) {
this.margin = value;
return this;
}
@JsIgnore
public CSSProps marginBottom(Object value) {
this.marginBottom = value;
return this;
}
@JsIgnore
public CSSProps marginLeft(Object value) {
this.marginLeft = value;
return this;
}
@JsIgnore
public CSSProps marginRight(Object value) {
this.marginRight = value;
return this;
}
@JsIgnore
public CSSProps marginTop(Object value) {
this.marginTop = value;
return this;
}
@JsIgnore
public CSSProps marqueeDirection(Object value) {
this.marqueeDirection = value;
return this;
}
@JsIgnore
public CSSProps marqueeStyle(Object value) {
this.marqueeStyle = value;
return this;
}
@JsIgnore
public CSSProps mask(Object value) {
this.mask = value;
return this;
}
@JsIgnore
public CSSProps maskBorder(Object value) {
this.maskBorder = value;
return this;
}
@JsIgnore
public CSSProps maskBorderRepeat(Object value) {
this.maskBorderRepeat = value;
return this;
}
@JsIgnore
public CSSProps maskBorderSlice(Object value) {
this.maskBorderSlice = value;
return this;
}
@JsIgnore
public CSSProps maskBorderSource(Object value) {
this.maskBorderSource = value;
return this;
}
@JsIgnore
public CSSProps maskBorderWidth(Object value) {
this.maskBorderWidth = value;
return this;
}
@JsIgnore
public CSSProps maskClip(Object value) {
this.maskClip = value;
return this;
}
@JsIgnore
public CSSProps maskOrigin(Object value) {
this.maskOrigin = value;
return this;
}
@JsIgnore
public CSSProps maxFontSize(Object value) {
this.maxFontSize = value;
return this;
}
@JsIgnore
public CSSProps maxHeight(Object value) {
this.maxHeight = value;
return this;
}
@JsIgnore
public CSSProps maxWidth(Object value) {
this.maxWidth = value;
return this;
}
@JsIgnore
public CSSProps minWidth(Object value) {
this.minWidth = value;
return this;
}
@JsIgnore
public CSSProps outline(Object value) {
this.outline = value;
return this;
}
@JsIgnore
public CSSProps outlineColor(Object value) {
this.outlineColor = value;
return this;
}
@JsIgnore
public CSSProps outlineOffset(Object value) {
this.outlineOffset = value;
return this;
}
@JsIgnore
public CSSProps overflow(Object value) {
this.overflow = value;
return this;
}
@JsIgnore
public CSSProps overflowStyle(Object value) {
this.overflowStyle = value;
return this;
}
@JsIgnore
public CSSProps overflowX(Object value) {
this.overflowX = value;
return this;
}
@JsIgnore
public CSSProps padding(Object value) {
this.padding = value;
return this;
}
@JsIgnore
public CSSProps paddingBottom(Object value) {
this.paddingBottom = value;
return this;
}
@JsIgnore
public CSSProps paddingLeft(Object value) {
this.paddingLeft = value;
return this;
}
@JsIgnore
public CSSProps paddingRight(Object value) {
this.paddingRight = value;
return this;
}
@JsIgnore
public CSSProps paddingTop(Object value) {
this.paddingTop = value;
return this;
}
@JsIgnore
public CSSProps pageBreakAfter(Object value) {
this.pageBreakAfter = value;
return this;
}
@JsIgnore
public CSSProps pageBreakBefore(Object value) {
this.pageBreakBefore = value;
return this;
}
@JsIgnore
public CSSProps pageBreakInside(Object value) {
this.pageBreakInside = value;
return this;
}
@JsIgnore
public CSSProps pause(Object value) {
this.pause = value;
return this;
}
@JsIgnore
public CSSProps pauseAfter(Object value) {
this.pauseAfter = value;
return this;
}
@JsIgnore
public CSSProps pauseBefore(Object value) {
this.pauseBefore = value;
return this;
}
@JsIgnore
public CSSProps perspective(Object value) {
this.perspective = value;
return this;
}
@JsIgnore
public CSSProps perspectiveOrigin(Object value) {
this.perspectiveOrigin = value;
return this;
}
@JsIgnore
public CSSProps pointerEvents(Object value) {
this.pointerEvents = value;
return this;
}
@JsIgnore
public CSSProps position(Object value) {
this.position = value;
return this;
}
@JsIgnore
public CSSProps punctuationTrim(Object value) {
this.punctuationTrim = value;
return this;
}
@JsIgnore
public CSSProps quotes(Object value) {
this.quotes = value;
return this;
}
@JsIgnore
public CSSProps regionFragment(Object value) {
this.regionFragment = value;
return this;
}
@JsIgnore
public CSSProps restAfter(Object value) {
this.restAfter = value;
return this;
}
@JsIgnore
public CSSProps restBefore(Object value) {
this.restBefore = value;
return this;
}
@JsIgnore
public CSSProps right(Object value) {
this.right = value;
return this;
}
@JsIgnore
public CSSProps rubyAlign(Object value) {
this.rubyAlign = value;
return this;
}
@JsIgnore
public CSSProps rubyPosition(Object value) {
this.rubyPosition = value;
return this;
}
@JsIgnore
public CSSProps shapeImageThreshold(Object value) {
this.shapeImageThreshold = value;
return this;
}
@JsIgnore
public CSSProps shapeInside(Object value) {
this.shapeInside = value;
return this;
}
@JsIgnore
public CSSProps shapeMargin(Object value) {
this.shapeMargin = value;
return this;
}
@JsIgnore
public CSSProps shapeOutside(Object value) {
this.shapeOutside = value;
return this;
}
@JsIgnore
public CSSProps speak(Object value) {
this.speak = value;
return this;
}
@JsIgnore
public CSSProps speakAs(Object value) {
this.speakAs = value;
return this;
}
@JsIgnore
public CSSProps tabSize(Object value) {
this.tabSize = value;
return this;
}
@JsIgnore
public CSSProps tableLayout(Object value) {
this.tableLayout = value;
return this;
}
@JsIgnore
public CSSProps textAlign(Object value) {
this.textAlign = value;
return this;
}
@JsIgnore
public CSSProps textAlignLast(Object value) {
this.textAlignLast = value;
return this;
}
@JsIgnore
public CSSProps textDecoration(Object value) {
this.textDecoration = value;
return this;
}
@JsIgnore
public CSSProps textDecorationColor(Object value) {
this.textDecorationColor = value;
return this;
}
@JsIgnore
public CSSProps textDecorationLine(Object value) {
this.textDecorationLine = value;
return this;
}
@JsIgnore
public CSSProps textDecorationLineThrough(Object value) {
this.textDecorationLineThrough = value;
return this;
}
@JsIgnore
public CSSProps textDecorationNone(Object value) {
this.textDecorationNone = value;
return this;
}
@JsIgnore
public CSSProps textDecorationOverline(Object value) {
this.textDecorationOverline = value;
return this;
}
@JsIgnore
public CSSProps textDecorationSkip(Object value) {
this.textDecorationSkip = value;
return this;
}
@JsIgnore
public CSSProps textDecorationStyle(Object value) {
this.textDecorationStyle = value;
return this;
}
@JsIgnore
public CSSProps textDecorationUnderline(Object value) {
this.textDecorationUnderline = value;
return this;
}
@JsIgnore
public CSSProps textEmphasis(Object value) {
this.textEmphasis = value;
return this;
}
@JsIgnore
public CSSProps textEmphasisColor(Object value) {
this.textEmphasisColor = value;
return this;
}
@JsIgnore
public CSSProps textEmphasisStyle(Object value) {
this.textEmphasisStyle = value;
return this;
}
@JsIgnore
public CSSProps textHeight(Object value) {
this.textHeight = value;
return this;
}
@JsIgnore
public CSSProps textIndent(Object value) {
this.textIndent = value;
return this;
}
@JsIgnore
public CSSProps textJustifyTrim(Object value) {
this.textJustifyTrim = value;
return this;
}
@JsIgnore
public CSSProps textKashidaSpace(Object value) {
this.textKashidaSpace = value;
return this;
}
@JsIgnore
public CSSProps textLineThrough(Object value) {
this.textLineThrough = value;
return this;
}
@JsIgnore
public CSSProps textLineThroughColor(Object value) {
this.textLineThroughColor = value;
return this;
}
@JsIgnore
public CSSProps textLineThroughMode(Object value) {
this.textLineThroughMode = value;
return this;
}
@JsIgnore
public CSSProps textLineThroughStyle(Object value) {
this.textLineThroughStyle = value;
return this;
}
@JsIgnore
public CSSProps textLineThroughWidth(Object value) {
this.textLineThroughWidth = value;
return this;
}
@JsIgnore
public CSSProps textOverflow(Object value) {
this.textOverflow = value;
return this;
}
@JsIgnore
public CSSProps textOverline(Object value) {
this.textOverline = value;
return this;
}
@JsIgnore
public CSSProps textOverlineColor(Object value) {
this.textOverlineColor = value;
return this;
}
@JsIgnore
public CSSProps textOverlineMode(Object value) {
this.textOverlineMode = value;
return this;
}
@JsIgnore
public CSSProps textOverlineStyle(Object value) {
this.textOverlineStyle = value;
return this;
}
@JsIgnore
public CSSProps textOverlineWidth(Object value) {
this.textOverlineWidth = value;
return this;
}
@JsIgnore
public CSSProps textRendering(Object value) {
this.textRendering = value;
return this;
}
@JsIgnore
public CSSProps textScript(Object value) {
this.textScript = value;
return this;
}
@JsIgnore
public CSSProps textShadow(Object value) {
this.textShadow = value;
return this;
}
@JsIgnore
public CSSProps textTransform(Object value) {
this.textTransform = value;
return this;
}
@JsIgnore
public CSSProps textUnderlinePosition(Object value) {
this.textUnderlinePosition = value;
return this;
}
@JsIgnore
public CSSProps textUnderlineStyle(Object value) {
this.textUnderlineStyle = value;
return this;
}
@JsIgnore
public CSSProps top(Object value) {
this.top = value;
return this;
}
@JsIgnore
public CSSProps touchAction(Object value) {
this.touchAction = value;
return this;
}
@JsIgnore
public CSSProps transform(Object value) {
this.transform = value;
return this;
}
@JsIgnore
public CSSProps transformOrigin(Object value) {
this.transformOrigin = value;
return this;
}
@JsIgnore
public CSSProps transformOriginZ(Object value) {
this.transformOriginZ = value;
return this;
}
@JsIgnore
public CSSProps transformStyle(Object value) {
this.transformStyle = value;
return this;
}
@JsIgnore
public CSSProps transition(Object value) {
this.transition = value;
return this;
}
@JsIgnore
public CSSProps transitionDelay(Object value) {
this.transitionDelay = value;
return this;
}
@JsIgnore
public CSSProps transitionDuration(Object value) {
this.transitionDuration = value;
return this;
}
@JsIgnore
public CSSProps transitionProperty(Object value) {
this.transitionProperty = value;
return this;
}
@JsIgnore
public CSSProps transitionTimingFunction(Object value) {
this.transitionTimingFunction = value;
return this;
}
@JsIgnore
public CSSProps unicodeBidi(Object value) {
this.unicodeBidi = value;
return this;
}
@JsIgnore
public CSSProps unicodeRange(Object value) {
this.unicodeRange = value;
return this;
}
@JsIgnore
public CSSProps userFocus(Object value) {
this.userFocus = value;
return this;
}
@JsIgnore
public CSSProps userInput(Object value) {
this.userInput = value;
return this;
}
@JsIgnore
public CSSProps verticalAlign(Object value) {
this.verticalAlign = value;
return this;
}
@JsIgnore
public CSSProps visibility(Object value) {
this.visibility = value;
return this;
}
@JsIgnore
public CSSProps voiceBalance(Object value) {
this.voiceBalance = value;
return this;
}
@JsIgnore
public CSSProps voiceDuration(Object value) {
this.voiceDuration = value;
return this;
}
@JsIgnore
public CSSProps voiceFamily(Object value) {
this.voiceFamily = value;
return this;
}
@JsIgnore
public CSSProps voicePitch(Object value) {
this.voicePitch = value;
return this;
}
@JsIgnore
public CSSProps voiceRange(Object value) {
this.voiceRange = value;
return this;
}
@JsIgnore
public CSSProps voiceRate(Object value) {
this.voiceRate = value;
return this;
}
@JsIgnore
public CSSProps voiceStress(Object value) {
this.voiceStress = value;
return this;
}
@JsIgnore
public CSSProps voiceVolume(Object value) {
this.voiceVolume = value;
return this;
}
@JsIgnore
public CSSProps whiteSpace(Object value) {
this.whiteSpace = value;
return this;
}
@JsIgnore
public CSSProps whiteSpaceTreatment(Object value) {
this.whiteSpaceTreatment = value;
return this;
}
@JsIgnore
public CSSProps width(Object value) {
this.width = value;
return this;
}
@JsIgnore
public CSSProps wordBreak(Object value) {
this.wordBreak = value;
return this;
}
@JsIgnore
public CSSProps wordSpacing(Object value) {
this.wordSpacing = value;
return this;
}
@JsIgnore
public CSSProps wordWrap(Object value) {
this.wordWrap = value;
return this;
}
@JsIgnore
public CSSProps wrapFlow(Object value) {
this.wrapFlow = value;
return this;
}
@JsIgnore
public CSSProps wrapMargin(Object value) {
this.wrapMargin = value;
return this;
}
@JsIgnore
public CSSProps wrapOption(Object value) {
this.wrapOption = value;
return this;
}
@JsIgnore
public CSSProps writingMode(Object value) {
this.writingMode = value;
return this;
}
} |
package javaslang.collection;
import javaslang.FilterMonadic;
import javaslang.Kind;
import javaslang.Kind.IterableKind;
import javaslang.Tuple2;
import javaslang.control.Match;
import javaslang.control.None;
import javaslang.control.Option;
import javaslang.control.Some;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Comparator;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.OptionalDouble;
import java.util.function.*;
import java.util.stream.StreamSupport;
public interface Traversable<T> extends TraversableOnce<T>, FilterMonadic<IterableKind<?>, T> {
/**
* Used by collections to compute the hashCode only once.
* <p>
* Idiom:
* <pre>
* <code>
* class MyCollection implements Serializable {
*
* // Not allowed to be serialized!
* private final transient Lazy<Integer> hashCode = Lazy.of(() -> Traversable.hash(this));
*
* @Override
* public int hashCode() {
* return hashCode.get();
* }
* }
* </code>
* </pre>
*
* <strong>Note:</strong> In the case of an empty collection, such as {@code List.Nil} it is recommended to
* directly return {@code Traversable.hash(this)} instead of asking a {@code Lazy} value:
* <pre>
* <code>
* interface List<T> {
*
* class Nil<T> {
*
* @Override
* public int hashCode() {
* return Traversable.hash(this);
* }
* }
* }
* </code>
* </pre>
*
* @param <T> Component type
* @param objects An Iterable
* @return The hashCode of the given Iterable
* @throws NullPointerException if objects is null
*/
static <T> int hash(Iterable<? extends T> objects) {
int hashCode = 1;
for (Object o : objects) {
hashCode = 31 * hashCode + Objects.hashCode(o);
}
return hashCode;
}
/**
* Calculates the average of this elements. Returns {@code None} if this is empty, otherwise {@code Some(average)}.
* Supported component types are {@code Byte}, {@code Double}, {@code Float}, {@code Integer}, {@code Long},
* {@code Short}, {@code BigInteger} and {@code BigDecimal}.
* <p>
* Examples:
* <pre>
* <code>
* List.empty().average() // = None
* List.of(1, 2, 3).average() // = Some(2.0)
* List.of(0.1, 0.2, 0.3).average() // = Some(0.2)
* List.of("apple", "pear").average() // throws
* </code>
* </pre>
*
* @return {@code Some(average)} or {@code None}, if there are no elements
* @throws UnsupportedOperationException if this elements are not numeric
*/
@SuppressWarnings("unchecked")
default Option<Double> average() {
if (isEmpty()) {
return None.instance();
} else {
final java.util.stream.Stream<Number> numbers = ((java.util.stream.Stream<Number>) toJavaStream());
return Match.of(head())
.whenTypeIn(Byte.class, Integer.class, Short.class).then(() -> numbers.mapToInt(Number::intValue).average())
.whenTypeIn(Double.class, Float.class, BigDecimal.class).then(() -> numbers.mapToDouble(Number::doubleValue).average())
.whenTypeIn(Long.class, BigInteger.class).then(() -> numbers.mapToLong(Number::longValue).average())
.otherwise(() -> {
throw new UnsupportedOperationException("not numeric");
})
.map(OptionalDouble::getAsDouble)
.toOption();
}
}
/**
* Calculates the cartesian product (, i.e. square) of {@code this x this}.
* <p>
* Example:
* <pre>
* <code>
* // = List of Tuples (1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)
* List.of(1, 2, 3).cartesianProduct();
* </code>
* </pre>
*
* @return a new Traversable containing the square of {@code this}
*/
Traversable<Tuple2<T, T>> cartesianProduct();
/**
* Calculates the cartesian product {@code this x that}.
* <p>
* Example:
* <pre>
* <code>
* // = List of Tuples (1, 'a'), (1, 'b'), (2, 'a'), (2, 'b'), (3, 'a'), (3, 'b')
* List.of(1, 2, 3).cartesianProduct(List.of('a', 'b');
* </code>
* </pre>
*
* @param that Another Traversable
* @param <U> Component type
* @return a new Traversable containing the cartesian product {@code this x that}
* @throws NullPointerException if that is null
*/
<U> Traversable<Tuple2<T, U>> cartesianProduct(Iterable<? extends U> that);
/**
* Returns an empty version of this traversable, i.e. {@code this.clear().isEmpty() == true}.
*
* @return an empty Traversable.
*/
Traversable<T> clear();
/**
* Tests if this Traversable contains a given value.
*
* @param element An Object of type A, may be null.
* @return true, if element is in this Traversable, false otherwise.
*/
default boolean contains(T element) {
return findFirst(e -> java.util.Objects.equals(e, element)).isDefined();
}
/**
* <p>
* Tests if this Traversable contains all given elements.
* </p>
* <p>
* The result is equivalent to
* {@code elements.isEmpty() ? true : contains(elements.head()) && containsAll(elements.tail())} but implemented
* without recursion.
* </p>
*
* @param elements A List of values of type T.
* @return true, if this List contains all given elements, false otherwise.
* @throws NullPointerException if {@code elements} is null
*/
default boolean containsAll(Iterable<? extends T> elements) {
Objects.requireNonNull(elements, "elements is null");
return List.ofAll(elements)
.distinct()
.findFirst(e -> !this.contains(e))
.isEmpty();
}
/**
* Returns a new version of this which contains no duplicates. Elements are compared using {@code equals}.
*
* @return a new {@code Traversable} containing this elements without duplicates
*/
Traversable<T> distinct();
/**
* Returns a new version of this which contains no duplicates. Elements are compared using the given
* {@code comparator}.
*
* @param comparator A comparator
* @return a new {@code Traversable} containing this elements without duplicates
*/
Traversable<T> distinctBy(Comparator<? super T> comparator);
/**
* Returns a new version of this which contains no duplicates. Elements mapped to keys which are compared using
* {@code equals}.
* <p>
* The elements of the result are determined in the order of their occurrence - first match wins.
*
* @param keyExtractor A key extractor
* @param <U> key type
* @return a new {@code Traversable} containing this elements without duplicates
* @throws NullPointerException if {@code keyExtractor} is null
*/
<U> Traversable<T> distinctBy(Function<? super T, ? extends U> keyExtractor);
/**
* Drops the first n elements of this or all elements, if this length < n.
*
* @param n The number of elements to drop.
* @return a new instance consisting of all elements of this except the first n ones, or else the empty instance,
* if this has less than n elements.
*/
Traversable<T> drop(int n);
/**
* Drops the last n elements of this or all elements, if this length < n.
*
* @param n The number of elements to drop.
* @return a new instance consisting of all elements of this except the last n ones, or else the empty instance,
* if this has less than n elements.
*/
Traversable<T> dropRight(int n);
/**
* Drops elements while the predicate holds for the current element.
*
* @param predicate A condition tested subsequently for this elements starting with the first.
* @return a new instance consisting of all elements starting from the first one which does not satisfy the
* given predicate.
* @throws NullPointerException if {@code predicate} is null
*/
Traversable<T> dropWhile(Predicate<? super T> predicate);
/**
* Returns a new traversable consisting of all elements which satisfy the given predicate.
*
* @param predicate A predicate
* @return a new traversable
* @throws NullPointerException if {@code predicate} is null
*/
@Override
Traversable<T> filter(Predicate<? super T> predicate);
@Override
Traversable<Some<T>> filterOption(Predicate<? super T> predicate);
/**
* Essentially the same as {@link #filter(Predicate)} but the result type may differ,
* i.e. tree.findAll() may be a List.
*
* @param predicate A predicate.
* @return all elements of this which satisfy the given predicate.
* @throws NullPointerException if {@code predicate} is null
*/
Traversable<T> findAll(Predicate<? super T> predicate);
/**
* Returns the first element of this which satisfies the given predicate.
*
* @param predicate A predicate.
* @return Some(element) or None, where element may be null (i.e. {@code List.of(null).findFirst(e -> e == null)}).
* @throws NullPointerException if {@code predicate} is null
*/
default Option<T> findFirst(Predicate<? super T> predicate) {
Objects.requireNonNull(predicate, "predicate is null");
for (T a : this) {
if (predicate.test(a)) {
return new Some<>(a); // may be Some(null)
}
}
return Option.none();
}
/**
* <p>
* Returns the last element of this which satisfies the given predicate.
* </p>
* <p>
* Same as {@code reverse().findFirst(predicate)}.
* </p>
*
* @param predicate A predicate.
* @return Some(element) or None, where element may be null (i.e. {@code List.of(null).findFirst(e -> e == null)}).
* @throws NullPointerException if {@code predicate} is null
*/
default Option<T> findLast(Predicate<? super T> predicate) {
Objects.requireNonNull(predicate, "predicate is null");
return reverse().findFirst(predicate);
}
<U> Traversable<U> flatMap(Function<? super T, ? extends Iterable<? extends U>> mapper);
@Override
<U> Traversable<U> flatMapM(Function<? super T, ? extends Kind<? extends IterableKind<?>, ? extends U>> mapper);
@Override
Traversable<Object> flatten();
/**
* <p>
* Accumulates the elements of this Traversable by successively calling the given operator {@code op}.
* </p>
* <p>
* Example: {@code List("a", "b", "c").fold("", (xs, x) -> xs + x) = "abc"}
* </p>
*
* @param zero Value to start the accumulation with.
* @param op The accumulator operator.
* @return an accumulated version of this.
* @throws NullPointerException if {@code op} is null
*/
default T fold(T zero, BiFunction<? super T, ? super T, ? extends T> op) {
Objects.requireNonNull(op, "op is null");
return foldLeft(zero, op);
}
/**
* Accumulates the elements of this Traversable by successively calling the given function {@code f} from the left,
* starting with a value {@code zero} of type B.
* <p>
* Example: Reverse and map a Traversable in one pass
* <pre><code>
* List.of("a", "b", "c").foldLeft(List.empty(), (xs, x) -> xs.prepend(x.toUpperCase()))
* // = List("C", "B", "A")
* </code></pre>
*
* @param zero Value to start the accumulation with.
* @param f The accumulator function.
* @param <U> Result type of the accumulator.
* @return an accumulated version of this.
* @throws NullPointerException if {@code f} is null
*/
default <U> U foldLeft(U zero, BiFunction<? super U, ? super T, ? extends U> f) {
Objects.requireNonNull(f, "f is null");
U xs = zero;
for (T x : this) {
xs = f.apply(xs, x);
}
return xs;
}
/**
* <p>
* Accumulates the elements of this Traversable by successively calling the given function {@code f} from the right,
* starting with a value {@code zero} of type B.
* </p>
* <p>
* Example: {@code List.of("a", "b", "c").foldRight("", (x, xs) -> x + xs) = "abc"}
* </p>
* <p>
* In order to prevent recursive calls, foldRight is implemented based on reverse and foldLeft. A recursive variant
* is based on foldMap, using the monoid of function composition (endo monoid).
* </p>
* <pre>
* <code>
* foldRight = reverse().foldLeft(zero, (b, a) -> f.apply(a, b));
* foldRight = foldMap(Algebra.Monoid.endoMonoid(), a -> b -> f.apply(a, b)).apply(zero);
* </code>
* </pre>
*
* @param zero Value to start the accumulation with.
* @param f The accumulator function.
* @param <U> Result type of the accumulator.
* @return an accumulated version of this.
* @throws NullPointerException if {@code f} is null
*/
default <U> U foldRight(U zero, BiFunction<? super T, ? super U, ? extends U> f) {
Objects.requireNonNull(f, "f is null");
return reverse().foldLeft(zero, (xs, x) -> f.apply(x, xs));
}
/**
* Groups this elements by classifying the elements.
*
* @param classifier A function which classifies elements into classes
* @param <C> classified class type
* @return A Map containing the grouped elements
*/
<C> Map<C, ? extends Traversable<T>> groupBy(Function<? super T, ? extends C> classifier);
Traversable<? extends Traversable<T>> grouped(int size);
/**
* Returns the first element of a non-empty Traversable.
*
* @return The first element of this Traversable.
* @throws NoSuchElementException if this is empty
*/
T head();
/**
* Returns the first element of a non-empty Traversable as {@code Option}.
*
* @return {@code Some(element)} or {@code None} if this is empty.
*/
Option<T> headOption();
/**
* Dual of {@linkplain #tail()}, returning all elements except the last.
*
* @return a new instance containing all elements except the last.
* @throws UnsupportedOperationException if this is empty
*/
Traversable<T> init();
/**
* Dual of {@linkplain #tailOption()}, returning all elements except the last as {@code Option}.
*
* @return {@code Some(traversable)} or {@code None} if this is empty.
*/
Option<? extends Traversable<T>> initOption();
/**
* Inserts an element between all elements of this Traversable.
*
* @param element An element.
* @return an interspersed version of this
*/
Traversable<T> intersperse(T element);
/**
* Checks if this Traversable is empty.
*
* @return true, if this Traversable contains no elements, falso otherwise.
*/
@Override
boolean isEmpty();
/**
* An iterator by means of head() and tail(). Subclasses may want to override this method.
*
* @return A new Iterator of this Traversable elements.
*/
@Override
default Iterator<T> iterator() {
return new Iterator<T>() {
Traversable<T> traversable = Traversable.this;
@Override
public boolean hasNext() {
return !traversable.isEmpty();
}
@Override
public T next() {
if (traversable.isEmpty()) {
throw new NoSuchElementException();
} else {
final T result = traversable.head();
traversable = traversable.tail();
return result;
}
}
};
}
/**
* Joins the elements of this by concatenating their string representations.
* <p>
* This has the same effect as calling {@code join("", "", "")}.
*
* @return a new String
*/
default String join() {
return join("", "", "");
}
/**
* Joins the string representations of this elements using a specific delimiter.
* <p>
* This has the same effect as calling {@code join(delimiter, "", "")}.
*
* @param delimiter A delimiter string put between string representations of elements of this
* @return A new String
*/
default String join(CharSequence delimiter) {
return join(delimiter, "", "");
}
/**
* Joins the string representations of this elements using a specific delimiter, prefix and suffix.
* <p>
* Example: {@code List.of("a", "b", "c").join(", ", "Chars(", ")") = "Chars(a, b, c)"}
*
* @param delimiter A delimiter string put between string representations of elements of this
* @param prefix prefix of the resulting string
* @param suffix suffix of the resulting string
* @return a new String
*/
default String join(CharSequence delimiter,
CharSequence prefix,
CharSequence suffix) {
final StringBuilder builder = new StringBuilder(prefix);
map(String::valueOf).intersperse(String.valueOf(delimiter)).forEach(builder::append);
return builder.append(suffix).toString();
}
/**
* Dual of {@linkplain #head()}, returning the last element.
*
* @return the last element.
* @throws NoSuchElementException is this is empty
*/
default T last() {
if (isEmpty()) {
throw new NoSuchElementException("last of Nil");
} else {
Traversable<T> traversable = this;
{ // don't let escape tail
Traversable<T> tail;
while (!(tail = traversable.tail()).isEmpty()) {
traversable = tail;
}
}
return traversable.head();
}
}
/**
* Dual of {@linkplain #headOption()}, returning the last element as {@code Opiton}.
*
* @return {@code Some(element)} or {@code None} if this is empty.
*/
default Option<T> lastOption() {
return isEmpty() ? None.instance() : new Some<>(last());
}
/**
* Computes the number of elements of this.
*
* @return the number of elements
*/
default int length() {
return foldLeft(0, (n, ignored) -> n + 1);
}
/**
* Maps the elements of this traversable to elements of a new type preserving their order, if any.
*
* @param mapper A mapper.
* @param <U> Component type of the target Traversable
* @return a mapped Traversable
* @throws NullPointerException if {@code mapper} is null
*/
@Override
<U> Traversable<U> map(Function<? super T, ? extends U> mapper);
/**
* Calculates the maximum of this elements according to their natural order.
*
* @return {@code Some(maximum)} of this elements or {@code None} if this is empty or this elements are not comparable
*/
@SuppressWarnings("unchecked")
default Option<T> max() {
if (isEmpty() || !(head() instanceof Comparable)) {
return None.instance();
} else {
return maxBy((o1, o2) -> ((Comparable<T>) o1).compareTo(o2));
}
}
/**
* Calculates the maximum of this elements using a specific comparator.
*
* @param comparator A non-null element comparator
* @return {@code Some(maximum)} of this elements or {@code None} if this is empty
* @throws NullPointerException if {@code comparator} is null
*/
default Option<T> maxBy(Comparator<? super T> comparator) {
Objects.requireNonNull(comparator, "comparator is null");
if (isEmpty()) {
return None.instance();
} else {
final T value = reduce((t1, t2) -> comparator.compare(t1, t2) >= 0 ? t1 : t2);
return new Some<>(value);
}
}
/**
* Calculates the maximum of this elements within the co-domain of a specific function.
*
* @param f A function that maps this elements to comparable elements
* @param <U> The type where elements are compared
* @return The element of type T which is the maximum within U
*/
default <U extends Comparable<? super U>> Option<T> maxBy(Function<? super T, ? extends U> f) {
Objects.requireNonNull(f, "f is null");
if (isEmpty()) {
return None.instance();
} else {
return maxBy((t1, t2) -> f.apply(t1).compareTo(f.apply(t2)));
}
}
/**
* Calculates the minimum of this elements according to their natural order.
*
* @return {@code Some(minimum)} of this elements or {@code None} if this is empty or this elements are not comparable
*/
@SuppressWarnings("unchecked")
default Option<T> min() {
if (isEmpty() || !(head() instanceof Comparable)) {
return None.instance();
} else {
return minBy((o1, o2) -> ((Comparable<T>) o1).compareTo(o2));
}
}
/**
* Calculates the minimum of this elements using a specific comparator.
*
* @param comparator A non-null element comparator
* @return {@code Some(minimum)} of this elements or {@code None} if this is empty
* @throws NullPointerException if {@code comparator} is null
*/
default Option<T> minBy(Comparator<? super T> comparator) {
Objects.requireNonNull(comparator, "comparator is null");
if (isEmpty()) {
return None.instance();
} else {
final T value = reduce((t1, t2) -> comparator.compare(t1, t2) <= 0 ? t1 : t2);
return new Some<>(value);
}
}
/**
* Calculates the minimum of this elements within the co-domain of a specific function.
*
* @param f A function that maps this elements to comparable elements
* @param <U> The type where elements are compared
* @return The element of type T which is the minimum within U
*/
default <U extends Comparable<? super U>> Option<T> minBy(Function<? super T, ? extends U> f) {
Objects.requireNonNull(f, "f is null");
if (isEmpty()) {
return None.instance();
} else {
return minBy((t1, t2) -> f.apply(t1).compareTo(f.apply(t2)));
}
}
/**
* Creates a partition of this {@code Traversable} by splitting this elements in two in distinct tarversables
* according to a predicate.
*
* @param predicate A predicate which classifies an element if it is in the first or the second traversable.
* @return A disjoint union of two traversables. The first {@code Traversable} contains all elements that satisfy the given {@code predicate}, the second {@code Traversable} contains all elements that don't. The original order of elements is preserved.
* @throws NullPointerException if predicate is null
*/
Tuple2<? extends Traversable<T>, ? extends Traversable<T>> partition(Predicate<? super T> predicate);
@Override
Traversable<T> peek(Consumer<? super T> action);
/**
* Calculates the product of this elements. Supported component types are {@code Byte}, {@code Double}, {@code Float},
* {@code Integer}, {@code Long}, {@code Short}, {@code BigInteger} and {@code BigDecimal}.
* <p>
* Examples:
* <pre>
* <code>
* List.empty().product() // = 1
* List.of(1, 2, 3).product() // = 6
* List.of(0.1, 0.2, 0.3).product() // = 0.006
* List.of("apple", "pear").product() // throws
* </code>
* </pre>
*
* @return a {@code Number} representing the sum of this elements
* @throws UnsupportedOperationException if this elements are not numeric
*/
@SuppressWarnings("unchecked")
default Number product() {
if (isEmpty()) {
return 1;
} else {
final java.util.stream.Stream<Number> numbers = ((java.util.stream.Stream<Number>) toJavaStream());
return Match.of(head()).as(Number.class)
.whenTypeIn(Byte.class, Integer.class, Short.class).then(() -> numbers.mapToInt(Number::intValue).reduce(1, (i1, i2) -> i1 * i2))
.whenTypeIn(Double.class, Float.class, BigDecimal.class).then(() -> numbers.mapToDouble(Number::doubleValue).reduce(1.0, (d1, d2) -> d1 * d2))
.whenTypeIn(Long.class, BigInteger.class).then(ignored -> numbers.mapToLong(Number::longValue).reduce(1L, (l1, l2) -> l1 * l2))
.orElseThrow(() -> new UnsupportedOperationException("not numeric"));
}
}
/**
* Removes the first occurrence of the given element.
*
* @param element An element to be removed from this Traversable.
* @return a Traversable containing all elements of this without the first occurrence of the given element.
*/
Traversable<T> remove(T element);
/**
* Removes all occurrences of the given element.
*
* @param element An element to be removed from this Traversable.
* @return a Traversable containing all elements of this but not the given element.
*/
Traversable<T> removeAll(T element);
/**
* Removes all occurrences of the given elements.
*
* @param elements Elements to be removed from this Traversable.
* @return a Traversable containing all elements of this but none of the given elements.
* @throws NullPointerException if {@code elements} is null
*/
Traversable<T> removeAll(Iterable<? extends T> elements);
/**
* Accumulates the elements of this Traversable by successively calling the given operation {@code op}.
* The order of element iteration is undetermined.
*
* @param op A BiFunction of type T
* @return the reduced value.
* @throws UnsupportedOperationException if this is empty
* @throws NullPointerException if {@code op} is null
*/
default T reduce(BiFunction<? super T, ? super T, ? extends T> op) {
Objects.requireNonNull(op, "op is null");
return reduceLeft(op);
}
/**
* Accumulates the elements of this Traversable by successively calling the given operation {@code op} from the left.
*
* @param op A BiFunction of type T
* @return the reduced value.
* @throws NoSuchElementException if this is empty
* @throws NullPointerException if {@code op} is null
*/
default T reduceLeft(BiFunction<? super T, ? super T, ? extends T> op) {
Objects.requireNonNull(op, "op is null");
if (isEmpty()) {
throw new NoSuchElementException("reduceLeft on Nil");
} else {
return tail().foldLeft(head(), op);
}
}
/**
* Accumulates the elements of this Traversable by successively calling the given operation {@code op} from the right.
*
* @param op An operation of type T
* @return the reduced value.
* @throws NoSuchElementException if this is empty
* @throws NullPointerException if {@code op} is null
*/
default T reduceRight(BiFunction<? super T, ? super T, ? extends T> op) {
Objects.requireNonNull(op, "op is null");
if (isEmpty()) {
throw new NoSuchElementException("reduceRight on Nil");
} else {
final Traversable<T> reversed = reverse();
return reversed.tail().foldLeft(reversed.head(), (xs, x) -> op.apply(x, xs));
}
}
/**
* Replaces the first occurrence (if exists) of the given currentElement with newElement.
*
* @param currentElement An element to be substituted.
* @param newElement A replacement for currentElement.
* @return a Traversable containing all elements of this where the first occurrence of currentElement is replaced with newELement.
*/
Traversable<T> replace(T currentElement, T newElement);
/**
* Replaces all occurrences of the given currentElement with newElement.
*
* @param currentElement An element to be substituted.
* @param newElement A replacement for currentElement.
* @return a Traversable containing all elements of this where all occurrences of currentElement are replaced with newELement.
*/
Traversable<T> replaceAll(T currentElement, T newElement);
/**
* Replaces all occurrences of this Traversable by applying the given operator to the elements, which is
* essentially a special case of {@link #map(Function)}.
*
* @param operator An operator.
* @return a Traversable containing all elements of this transformed within the same domain.
* @throws NullPointerException if {@code operator} is null
*/
Traversable<T> replaceAll(UnaryOperator<T> operator);
/**
* Keeps all occurrences of the given elements from this.
*
* @param elements Elements to be kept.
* @return a Traversable containing all occurreces of the given elements.
* @throws NullPointerException if {@code elements} is null
*/
Traversable<T> retainAll(Iterable<? extends T> elements);
/**
* Reverses the order of elements.
*
* @return the reversed elements.
*/
Traversable<T> reverse();
Traversable<? extends Traversable<T>> sliding(int size);
Traversable<? extends Traversable<T>> sliding(int size, int step);
/**
* Returns a tuple where the first element is the longest prefix of elements that satisfy p and the second element is the remainder.
*
* @param predicate A predicate.
* @return a Tuple containing the longest prefix of elements that satisfy p and the remainder.
* @throws NullPointerException if {@code predicate} is null
*/
Tuple2<? extends Traversable<T>, ? extends Traversable<T>> span(Predicate<? super T> predicate);
/**
* Calculates the sum of this elements. Supported component types are {@code Byte}, {@code Double}, {@code Float},
* {@code Integer}, {@code Long}, {@code Short}, {@code BigInteger} and {@code BigDecimal}.
* <p>
* Examples:
* <pre>
* <code>
* List.empty().sum() // = 0
* List.of(1, 2, 3).sum() // = 6
* List.of(0.1, 0.2, 0.3).sum() // = 0.6
* List.of("apple", "pear").sum() // throws
* </code>
* </pre>
*
* @return a {@code Number} representing the sum of this elements
* @throws UnsupportedOperationException if this elements are not numeric
*/
@SuppressWarnings("unchecked")
default Number sum() {
if (isEmpty()) {
return 0;
} else {
final java.util.stream.Stream<Number> numbers = ((java.util.stream.Stream<Number>) toJavaStream());
return Match.of(head()).as(Number.class)
.whenTypeIn(Byte.class, Integer.class, Short.class).then(() -> numbers.mapToInt(Number::intValue).sum())
.whenTypeIn(Double.class, Float.class, BigDecimal.class).then(() -> numbers.mapToDouble(Number::doubleValue).sum())
.whenTypeIn(Long.class, BigInteger.class).then(ignored -> numbers.mapToLong(Number::longValue).sum())
.orElseThrow(() -> new UnsupportedOperationException("not numeric"));
}
}
default void stderr() {
for (T t : this) {
System.err.println(String.valueOf(t));
if (System.err.checkError()) {
throw new IllegalStateException("Error writing to stderr");
}
}
}
default void stdout() {
for (T t : this) {
System.out.println(String.valueOf(t));
if (System.out.checkError()) {
throw new IllegalStateException("Error writing to stdout");
}
}
}
/**
* Drops the first element of a non-empty Traversable.
*
* @return A new instance of Traversable containing all elements except the first.
* @throws UnsupportedOperationException if this is empty
*/
Traversable<T> tail();
/**
* Drops the first element of a non-empty Traversable and returns an {@code Option}.
*
* @return {@code Some(traversable)} or {@code None} if this is empty.
*/
Option<? extends Traversable<T>> tailOption();
/**
* Takes the first n elements of this or all elements, if this length < n.
* <p>
* The result is equivalent to {@code sublist(0, max(0, min(length(), n)))} but does not throw if {@code n < 0} or
* {@code n > length()}.
* <p>
* In the case of {@code n < 0} the empty instance is returned, in the case of {@code n > length()} this is returned.
*
* @param n The number of elements to take.
* @return A new instance consisting the first n elements of this or all elements, if this has less than n elements.
*/
Traversable<T> take(int n);
/**
* Takes the last n elements of this or all elements, if this length < n.
* <p>
* The result is equivalent to {@code sublist(max(0, min(length(), length() - n)), n)}, i.e. takeRight will not
* throw if {@code n < 0} or {@code n > length()}.
* <p>
* In the case of {@code n < 0} the empty instance is returned, in the case of {@code n > length()} this is returned.
*
* @param n The number of elements to take.
* @return A new instance consisting the first n elements of this or all elements, if this has less than n elements.
*/
Traversable<T> takeRight(int n);
/**
* Takes elements while the predicate holds for the current element.
*
* @param predicate A condition tested subsequently for this elements starting with the last.
* @return a new instance consisting of all elements starting from the last one which does not satisfy the
* given predicate.
* @throws NullPointerException if {@code predicate} is null
*/
Traversable<T> takeWhile(Predicate<? super T> predicate);
/**
* Converts this to a Java array.
* <p>
* Tip: Given a {@code Traversable<M<T>> t} use {@code t.toJavaArray((Class<M<T>>) (Class) M.class)}.
*
* @param componentType Type of resulting array's elements.
* @return a new array containing this elements
* @throws NullPointerException if {@code componentType} is null
*/
@SuppressWarnings("unchecked")
default T[] toJavaArray(Class<T> componentType) {
Objects.requireNonNull(componentType, "componentType is null");
final java.util.List<T> list = toJavaList();
return list.toArray((T[]) java.lang.reflect.Array.newInstance(componentType, list.size()));
}
/**
* Converts this to a {@link java.util.List}.
*
* @return a new {@linkplain java.util.ArrayList} containing this elements
*/
default java.util.List<T> toJavaList() {
final java.util.List<T> result = new java.util.ArrayList<>();
for (T a : this) {
result.add(a);
}
return result;
}
/**
* Converts this to a {@link java.util.Map} by converting this elements to key-value pairs.
*
* @param <K> key type
* @param <V> value type
* @param f a function which converts elements of this to key-value pairs inserted into the resulting Map
* @return a new {@linkplain java.util.HashMap} containing this key-value representations of this elements
* @throws NullPointerException if {@code f} is null
*/
default <K, V> java.util.Map<K, V> toJavaMap(Function<? super T, Tuple2<K, V>> f) {
Objects.requireNonNull(f, "f is null");
final java.util.Map<K, V> map = new java.util.HashMap<>();
for (T a : this) {
final Tuple2<K, V> entry = f.apply(a);
map.put(entry._1, entry._2);
}
return map;
}
/**
* Converts this to a {@link java.util.Set}.
*
* @return a new {@linkplain java.util.HashSet} containing this elements
*/
default java.util.Set<T> toJavaSet() {
final java.util.Set<T> result = new java.util.HashSet<>();
for (T a : this) {
result.add(a);
}
return result;
}
/**
* Converts this to a sequential {@link java.util.stream.Stream} by calling {@code this.toJavaList().stream()}.
*
* @return a new {@linkplain java.util.stream.Stream} containing this elements
*/
default java.util.stream.Stream<T> toJavaStream() {
return StreamSupport.stream(spliterator(), false);
}
/**
* Creates an instance of this type of an {@code Iterable}.
*
* @param <U> Component type
* @param iterable an {@code Iterable}
* @return A new instance of this collection containing the elements of the given {@code iterable}.
*/
<U> Traversable<U> unit(Iterable<? extends U> iterable);
/**
* Unzips this elements by mapping this elements to pairs which are subsequentially split into to distinct
* traversables.
*
* @param unzipper a function which converts elements of this to pairs
* @param <T1> 1st element type of a pair returned by unzipper
* @param <T2> 2nd element type of a pair returned by unzipper
* @return A pair of traversables containing elements split by unzipper
* @throws NullPointerException if {@code unzipper} is null
*/
<T1, T2> Tuple2<? extends Traversable<T1>, ? extends Traversable<T2>> unzip(Function<? super T, Tuple2<? extends T1, ? extends T2>> unzipper);
/**
* Returns a Traversable formed from this Traversable and another Iterable collection by combining corresponding elements
* in pairs. If one of the two Traversables is longer than the other, its remaining elements are ignored.
* <p>
* The length of the returned collection is the minimum of the lengths of this Traversable and that.
*
* @param <U> The type of the second half of the returned pairs.
* @param that The Iterable providing the second half of each result pair.
* @return a new Traversable containing pairs consisting of corresponding elements of this list and that.
* @throws NullPointerException if {@code that} is null
*/
<U> Traversable<Tuple2<T, U>> zip(Iterable<U> that);
/**
* Returns a Traversable formed from this Traversable and another Iterable by combining corresponding elements in
* pairs. If one of the two collections is shorter than the other, placeholder elements are used to extend the
* shorter collection to the length of the longer.
* <p>
* The length of the returned Traversable is the maximum of the lengths of this Traversable and that.
* If this Traversable is shorter than that, thisElem values are used to fill the result.
* If that is shorter than this Traversable, thatElem values are used to fill the result.
*
* @param <U> The type of the second half of the returned pairs.
* @param that The Iterable providing the second half of each result pair.
* @param thisElem The element to be used to fill up the result if this Traversable is shorter than that.
* @param thatElem The element to be used to fill up the result if that is shorter than this Traversable.
* @return A new Traversable containing pairs consisting of corresponding elements of this Traversable and that.
* @throws NullPointerException if {@code that} is null
*/
<U> Traversable<Tuple2<T, U>> zipAll(Iterable<U> that, T thisElem, U thatElem);
/**
* Zips this List with its indices.
*
* @return A new List containing all elements of this List paired with their index, starting with 0.
*/
Traversable<Tuple2<T, Integer>> zipWithIndex();
} |
package lan.dk.podcastserver.entity;
import com.fasterxml.jackson.annotation.*;
import com.google.common.collect.Sets;
import lombok.*;
import lombok.experimental.Accessors;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.search.annotations.Boost;
import org.hibernate.search.annotations.DocumentId;
import org.hibernate.search.annotations.Field;
import org.hibernate.search.annotations.Indexed;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import org.springframework.web.util.UriComponentsBuilder;
import javax.persistence.*;
import javax.validation.constraints.AssertTrue;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.ZonedDateTime;
import java.util.Set;
import java.util.UUID;
import static java.util.Objects.isNull;
@Entity
@Indexed
@Slf4j
@Builder
@Getter @Setter
@Table(name = "item")
@Accessors(chain = true)
@NoArgsConstructor @AllArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true, value = { "numberOfTry", "localUri", "addATry", "deleteDownloadedFile", "localPath", "proxyURLWithoutExtention", "extention", "hasValidURL", "reset" })
@EntityListeners(AuditingEntityListener.class)
public class Item {
public static Path rootFolder;
public static String fileContainer;
public static final Item DEFAULT_ITEM = new Item();
private static final String PROXY_URL = "/api/podcast/%s/items/%s/download%s";
@Id
@DocumentId
@GeneratedValue(generator = "uuid2")
@GenericGenerator(name = "uuid2", strategy = "uuid2")
private UUID id;
@OneToOne(fetch = FetchType.EAGER, cascade=CascadeType.ALL, orphanRemoval=true)
private Cover cover;
@ManyToOne(cascade={CascadeType.MERGE}, fetch = FetchType.EAGER)
@JsonBackReference("podcast-item")
private Podcast podcast;
@Field @Boost(2.0F)
@JsonView(ItemSearchListView.class)
private String title;
@Column(length = 65535)
@JsonView(ItemSearchListView.class)
private String url;
@JsonView(ItemPodcastListView.class)
private ZonedDateTime pubdate;
@Field
@Column(length = 65535)
@JsonView(ItemPodcastListView.class)
private String description;
@Column(name = "mimetype")
@JsonView(ItemSearchListView.class)
private String mimeType;
@JsonView(ItemDetailsView.class)
private Long length;
@JsonView(ItemDetailsView.class)
private String fileName;
/* Value for the Download */
@Enumerated(EnumType.STRING)
@JsonView(ItemSearchListView.class)
private Status status = Status.NOT_DOWNLOADED;
@Transient
@JsonView(ItemDetailsView.class)
private Integer progression = 0;
@Transient
private Integer numberOfTry = 0;
@JsonView(ItemDetailsView.class)
private ZonedDateTime downloadDate;
@CreatedDate
private ZonedDateTime creationDate;
@JsonIgnore
@ManyToMany(mappedBy = "items", cascade = CascadeType.REFRESH)
private Set<WatchList> watchLists = Sets.newHashSet();
public String getLocalUri() {
return (fileName == null) ? null : getLocalPath().toString();
}
public Item setLocalUri(String localUri) {
fileName = FilenameUtils.getName(localUri);
return this;
}
public Item addATry() {
this.numberOfTry++;
return this;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Item)) return false;
if (this == DEFAULT_ITEM && o != DEFAULT_ITEM || this != DEFAULT_ITEM && o == DEFAULT_ITEM) return false;
Item item = (Item) o;
if (id != null && item.id != null)
return id.equals(item.id);
if (url != null && item.url != null) {
return url.equals(item.url) || FilenameUtils.getName(item.url).equals(FilenameUtils.getName(url));
}
return StringUtils.equals(getLocalUrl(), item.getLocalUrl());
}
@Override
public int hashCode() {
return new HashCodeBuilder(17, 37)
.append(url)
.append((pubdate != null) ? pubdate.toInstant() : null)
.toHashCode();
}
@Override
public String toString() {
return "Item{" +
"id=" + id +
", title='" + title + '\'' +
", url='" + url + '\'' +
", pubdate=" + pubdate +
", description='" + description + '\'' +
", mimeType='" + mimeType + '\'' +
", length=" + length +
", status='" + status + '\'' +
", progression=" + progression +
", downloaddate=" + downloadDate +
", podcast=" + podcast +
", numberOfTry=" + numberOfTry +
'}';
}
/* Helpers */
@Transient @JsonView(ItemSearchListView.class)
public String getLocalUrl() {
return (fileName == null) ? null : UriComponentsBuilder.fromHttpUrl(fileContainer)
.pathSegment(podcast.getTitle(), fileName)
.build()
.toString();
}
@Transient @JsonProperty("proxyURL") @JsonView(ItemSearchListView.class)
public String getProxyURL() {
return String.format(PROXY_URL, podcast.getId(), id, getExtention());
}
@Transient @JsonProperty("isDownloaded") @JsonView(ItemSearchListView.class)
public Boolean isDownloaded() {
return StringUtils.isNotEmpty(fileName);
}
//* CallBack Method JPA *//
@PreRemove
public void preRemove() {
checkAndDelete();
watchLists.forEach(watchList -> watchList.remove(this));
}
private void checkAndDelete() {
if (podcast.getHasToBeDeleted() && isDownloaded()) {
deleteFile();
}
}
private void deleteFile() {
try {
Files.deleteIfExists(getLocalPath());
} catch (IOException e) {
log.error("Error during deletion of {}", this, e);
}
}
@Transient @JsonIgnore
public Item deleteDownloadedFile() {
deleteFile();
status = Status.DELETED;
fileName = null;
return this;
}
public Path getLocalPath() {
return rootFolder.resolve(podcast.getTitle()).resolve(fileName);
}
public String getProxyURLWithoutExtention() {
return String.format(PROXY_URL, podcast.getId(), id, "");
}
private String getExtention() {
String ext = FilenameUtils.getExtension(fileName);
return (ext == null) ? "" : "."+ext;
}
@JsonProperty("cover") @JsonView(ItemSearchListView.class)
public Cover getCoverOfItemOrPodcast() {
return isNull(this.cover) ? podcast.getCover() : this.cover;
}
@JsonProperty("podcastId") @JsonView(ItemSearchListView.class)
public UUID getPodcastId() { return isNull(podcast) ? null : podcast.getId();}
@AssertTrue
public boolean hasValidURL() {
return (!StringUtils.isEmpty(this.url)) || "send".equals(this.podcast.getType());
}
public Item reset() {
checkAndDelete();
setStatus(Status.NOT_DOWNLOADED);
downloadDate = null;
fileName = null;
return this;
}
public interface ItemSearchListView {}
public interface ItemPodcastListView extends ItemSearchListView {}
public interface ItemDetailsView extends ItemPodcastListView {}
} |
package me.zero.client.api.module;
import me.zero.client.api.event.EventManager;
import me.zero.client.api.event.defaults.ModuleStateEvent;
import me.zero.client.api.exception.ActionNotSupportedException;
import me.zero.client.api.exception.UnexpectedOutcomeException;
import me.zero.client.api.manage.Node;
import me.zero.client.api.util.ClientUtils;
import me.zero.client.api.util.annotation.NoAnnotation;
import me.zero.client.api.util.keybind.Keybind;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static me.zero.client.api.util.keybind.Keybind.Action.*;
/**
* The base for all cheats
*
* @see me.zero.client.api.module.Category
*
* @author Brady
* @since 1/19/2017 12:00 PM
*/
public abstract class Module extends Node implements IModule {
/**
* The type/category of the module
*/
private final Class<?> type;
/**
* The Keybind of this Module
*/
private Keybind bind;
/**
* The state of the module, indicated whether it is on or off
*/
private boolean state;
/**
* List of Modes
*/
private List<ModuleMode> modes;
/**
* The Current Mode
*/
private ModuleMode mode;
public Module() {
Class<? extends Module> c = this.getClass();
boolean na = c.isAnnotationPresent(NoAnnotation.class);
if (c.isAnnotationPresent(Mod.class)) {
Mod data = c.getAnnotation(Mod.class);
this.name = data.name();
this.description = data.description();
this.bind = new Keybind(Keybind.Type.TOGGLE, data.bind(), type -> {
if (type == CLICK)
Module.this.toggle();
});
} else if (!na){
throw new UnexpectedOutcomeException("Modules are required to have a @Mod annotation if @NoAnnotation isn't present");
}
this.type = Arrays.stream(c.getInterfaces())
.filter(clazz -> clazz.isAnnotationPresent(Category.class))
.findFirst().orElse(Category.Default.class);
if (!na && ClientUtils.containsNull(name, description, type))
throw new NullPointerException("One or more Mod members were null!");
}
/**
* Sets the modes of this module
*
* @param modes Modes for this mod
*/
protected final void setModes(ModuleMode... modes) {
if (modes.length == 0) return;
this.modes = new ArrayList<>();
this.modes.addAll(Arrays.asList(modes));
this.setMode(this.modes.get(0));
}
/**
* Returns whether or not the module has modes
*
* @return True if this module has modes, false if not
*/
public final boolean hasModes() {
return this.modes != null;
}
/**
* Sets the module's mode to the specified mode.
* Null will be returned if the mode is unable to
* be set.
*
* @param mode Mode being set
* @return The new mode
*/
public final ModuleMode setMode(ModuleMode mode) {
checkModes();
if (mode == null || mode.getParent() != this)
return null;
if (this.mode != null)
this.mode.setState(false);
(this.mode = mode).setState(true);
return this.mode;
}
/**
* Sets the module's mode to the mode in the
* specified index. An IndexOutOfBoundsException
* will be thrown if the index is less than 0 or
* exceeds the maximum index of the mode array.
*
* @param index Index of the mode
* @return The new mode
*/
public final ModuleMode setMode(int index) {
checkModes();
return this.setMode(this.modes.get(index));
}
/**
* Sets the module's mode from the mode's name.
* Null will be returned if there isn't a mode
* with the specified name
*
* @param name The mode name
* @return The new mode
*/
public final ModuleMode setMode(String name) {
checkModes();
return this.setMode(getMode(name));
}
/**
* Gets a mode that belongs to this
* module from the mode's name
*
* @return Mode from name
*/
public final ModuleMode getMode(String name) {
checkModes();
return this.modes.stream().filter(mode -> mode.getName().equalsIgnoreCase(name)).findFirst().orElse(null);
}
/**
* Returns the list of modes that this module has,
* null will be returned if this module doesn't have
* any modes.
*
* @return List of modes
*/
public final List<ModuleMode> getModes() {
checkModes();
return new ArrayList<>(this.modes);
}
/**
* Switches the mode to the mode following
* the current mode in the list of modes.
*
* @return The new mode
*/
public final ModuleMode nextMode() {
checkModes();
int index = this.modes.indexOf(this.getMode());
if (++index > this.modes.size() - 1)
index = 0;
return setMode(index);
}
/**
* Switched the mode to the mode preceding
* the current mode in the list of modes.
* @return The new mode
*/
public final ModuleMode lastMode() {
checkModes();
int index = this.modes.indexOf(this.getMode());
if (--index < 0)
index = this.modes.size() - 1;
return setMode(index);
}
/**
* Returns this Module's mode, if it has modes
*
* @return The current mode
*/
public final ModuleMode getMode() {
checkModes();
return this.mode;
}
/**
* Called when mode related actions are carried out,
* throws an {@code ActionNotSupportedException} if
* modes aren't supported by this module.
*/
private void checkModes() {
if (!hasModes())
throw new ActionNotSupportedException("Cannot use mode required actions when modes aren't supported");
}
@Override
public final void setState(boolean state) {
if (state == this.state) return;
ModuleStateEvent event = new ModuleStateEvent(this, state);
EventManager.post(event);
if (event.isCancelled())
return;
if (this.state = state) {
onEnable();
EventManager.subscribe(this);
} else {
EventManager.unsubscribe(this);
onDisable();
}
if (hasModes() && mode != null)
mode.setState(state);
}
@Override
public final boolean getState() {
return this.state;
}
@Override
public final Class<?> getType() {
return this.type;
}
@Override
public final Keybind getBind() {
return this.bind;
}
} |
package net.cvcg.ian.tictactoe;
import javax.swing.*;
import java.util.concurrent.TimeUnit;
/*
* @author ian, @date 7/23/16 4:56 PM
*/
public class TicTacToe {
public static boolean turn = true;
public static void main(String[] args) throws InterruptedException {
TicTacToeBoard board = new TicTacToeBoard();
TicTacToeViewer viewer = new TicTacToeViewer(board);
while (true) {
viewer.refresh();
if (board.getWinner() == Player.X) {
int reply = JOptionPane.showConfirmDialog(null, "You Won! Play Again?", "Play Again?", JOptionPane.YES_NO_OPTION);
if (reply == JOptionPane.YES_OPTION) {
turn = true;
board.cleanBoard();
}
else {
System.exit(0);
}
}
else if (board.getWinner() == Player.O) {
int reply = JOptionPane.showConfirmDialog(null, "You Lost... Play Again?", "Play Again?", JOptionPane.YES_NO_OPTION);
if (reply == JOptionPane.YES_OPTION) {
turn = true;
board.cleanBoard();
}
else {
System.exit(0);
}
}
else if (board.checkSpaces()) {
int reply = JOptionPane.showConfirmDialog(null, "Draw... Play Again?", "Play Again?", JOptionPane.YES_NO_OPTION);
if (reply == JOptionPane.YES_OPTION) {
turn = true;
board.cleanBoard();
}
else {
System.exit(0);
}
}
else if (!turn){
TimeUnit.SECONDS.sleep(1);
board.nextMoveAI();
viewer.refresh();
turn = true;
}
}
}
} |
package net.imagej.legacy;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import org.scijava.app.AppService;
import org.scijava.command.Interactive;
import org.scijava.display.DisplayService;
import org.scijava.log.LogService;
import org.scijava.menu.MenuConstants;
import org.scijava.options.OptionsPlugin;
import org.scijava.platform.PlatformService;
import org.scijava.plugin.Attr;
import org.scijava.plugin.Menu;
import org.scijava.plugin.Parameter;
import org.scijava.plugin.Plugin;
import org.scijava.text.TextService;
import org.scijava.ui.DialogPrompt.MessageType;
import org.scijava.ui.UIService;
import org.scijava.welcome.WelcomeService;
import org.scijava.widget.Button;
/**
* Allows the setting and persisting of options relevant to ImageJ2, in ImageJ1.
* Not displayed in the IJ2 UI.
*
* @author Mark Hiner
*/
@Plugin(type = OptionsPlugin.class,
label = "ImageJ2 Options", menu = {
@Menu(label = MenuConstants.EDIT_LABEL, weight = MenuConstants.EDIT_WEIGHT,
mnemonic = MenuConstants.EDIT_MNEMONIC), @Menu(label = "Options"),
@Menu(label = "ImageJ2") }, attrs = { @Attr(name = "legacy-only") })
public class ImageJ2Options extends OptionsPlugin implements Interactive
{
// Fields
/**
* If true, SCIFIO will be used during {@code File > Open} IJ1 calls.
*/
@Parameter(label = "Use SCIFIO when opening files",
description = "Whether to use ImageJ2's file I/O mechanism when opening "
+ "files. Image files will be opened using the SCIFIO library "
+ "(SCientific Image Format Input and Output), which provides truly "
+ "extensible support for reading and writing image file formats.",
callback = "run")
private boolean newStyleIO = true;
@Parameter(label = "What is ImageJ2?", persist = false, callback = "help")
private Button help;
@Parameter
private DefaultLegacyService legacyService;
@Parameter(required = false)
private WelcomeService welcomeService;
@Parameter(required = false)
private AppService appService;
@Parameter(required = false)
private PlatformService platformService;
@Parameter(required = false)
private DisplayService displayService;
@Parameter(required = false)
private TextService textService;
@Parameter(required = false)
private UIService uiService;
@Parameter(required = false)
private LogService log;
private final static URL WELCOME_URL;
static {
URL url = null;
try {
url = new URL("https://github.com/imagej/imagej/blob/master/WELCOME.md#welcome-to-imagej2");
}
catch (MalformedURLException e) {
e.printStackTrace();
}
WELCOME_URL = url;
}
// -- Option accessors --
public boolean isNewStyleIO() {
return newStyleIO;
}
@SuppressWarnings("unused")
private void help() {
if (welcomeService != null) {
welcomeService.displayWelcome();
return;
}
if (appService != null && textService != null && displayService != null) {
final File baseDir = appService.getApp().getBaseDirectory();
final File welcomeFile = new File(baseDir, "WELCOME.md");
if (welcomeFile.exists()) try {
final String welcomeText = textService.asHTML(welcomeFile);
displayService.createDisplay(welcomeText);
return;
}
catch (final IOException e) {
if (log != null) {
log.error(e);
}
else {
e.printStackTrace();
}
}
}
// if local options fail, try the web browser
if (platformService != null && WELCOME_URL != null) {
try {
platformService.open(WELCOME_URL);
return;
}
catch (final IOException e) {
if (log != null) {
log.error(e);
}
else {
e.printStackTrace();
}
}
}
final String message =
"No appropriate service found to display the message";
if (uiService != null) {
uiService.showDialog(message, MessageType.ERROR_MESSAGE);
return;
}
if (log != null) {
log.error(message);
}
else {
System.err.println(message);
}
}
} |
package net.openhft.chronicle.wire;
import net.openhft.chronicle.bytes.Bytes;
import net.openhft.chronicle.bytes.RandomDataInput;
import net.openhft.chronicle.core.ClassLocal;
import net.openhft.chronicle.core.Jvm;
import net.openhft.chronicle.core.OS;
import net.openhft.chronicle.core.pool.ClassAliasPool;
import net.openhft.chronicle.core.pool.EnumInterner;
import net.openhft.chronicle.core.pool.StringBuilderPool;
import net.openhft.chronicle.core.pool.StringInterner;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.lang.reflect.Field;
import java.nio.BufferUnderflowException;
import java.util.ArrayList;
import java.util.List;
import static net.openhft.chronicle.wire.BinaryWire.toIntU30;
public enum Wires {
;
public static final int LENGTH_MASK = -1 >>> 2;
public static final StringInterner INTERNER = new StringInterner(128);
static final StringBuilderPool SBP = new StringBuilderPool();
static final StringBuilderPool ASBP = new StringBuilderPool();
static final StackTraceElement[] NO_STE = {};
static final ClassLocal<EnumInterner> ENUM_INTERNER = ClassLocal.withInitial(c -> new EnumInterner<>(c));
private static final int NOT_READY = 1 << 31;
private static final int META_DATA = 1 << 30;
private static final int UNKNOWN_LENGTH = 0x0;
private static final Field DETAILED_MESSAGE = Jvm.getField(Throwable.class, "detailMessage");
private static final Field STACK_TRACE = Jvm.getField(Throwable.class, "stackTrace");
static {
ClassAliasPool.CLASS_ALIASES.addAlias(WireSerializedLambda.class, "SerializedLambda");
ClassAliasPool.CLASS_ALIASES.addAlias(WireType.class);
}
public static <E extends Enum<E>> E internEnum(Class<E> eClass, CharSequence cs) {
return (E) ENUM_INTERNER.get(eClass).intern(cs);
}
public static StringBuilder acquireStringBuilder() {
return SBP.acquireStringBuilder();
}
public static StringBuilder acquireAnotherStringBuilder(CharSequence cs) {
StringBuilder sb = ASBP.acquireStringBuilder();
assert sb != cs;
return sb;
}
public static void writeData(@NotNull WireOut wireOut, boolean metaData, boolean notReady, @NotNull WriteMarshallable writer) {
Bytes bytes = wireOut.bytes();
long position = bytes.writePosition();
int metaDataBit = metaData ? META_DATA : 0;
bytes.writeOrderedInt(metaDataBit | NOT_READY | UNKNOWN_LENGTH);
writer.writeMarshallable(wireOut);
int length = metaDataBit | toIntU30(bytes.writePosition() - position - 4, "Document length %,d out of 30-bit int range.");
bytes.writeOrderedInt(position, length | (notReady ? NOT_READY : 0));
}
public static void writeDataOnce(@NotNull WireOut wireOut, boolean metaData, @NotNull WriteMarshallable writer) {
Bytes bytes = wireOut.bytes();
long position = bytes.writePosition();
int metaDataBit = metaData ? META_DATA : 0;
int value = metaDataBit | NOT_READY | UNKNOWN_LENGTH;
if (!bytes.compareAndSwapInt(position, 0, value))
return;
bytes.writeSkip(4);
writer.writeMarshallable(wireOut);
int length = metaDataBit | toIntU30(bytes.writePosition() - position - 4, "Document length %,d out of 30-bit int range.");
if (!bytes.compareAndSwapInt(position, value, length | META_DATA))
throw new AssertionError();
}
public static boolean readData(long offset,
@NotNull WireIn wireIn,
@Nullable ReadMarshallable metaDataConsumer,
@Nullable ReadMarshallable dataConsumer) {
final Bytes bytes = wireIn.bytes();
long position = bytes.readPosition();
long limit = bytes.readLimit();
try {
bytes.readLimit(bytes.isElastic() ? bytes.capacity() : bytes.realCapacity());
bytes.readPosition(offset);
return readData(wireIn, metaDataConsumer, dataConsumer);
} finally {
bytes.readLimit(limit);
bytes.readPosition(position);
}
}
public static boolean readData(@NotNull WireIn wireIn,
@Nullable ReadMarshallable metaDataConsumer,
@Nullable ReadMarshallable dataConsumer) {
final Bytes<?> bytes = wireIn.bytes();
boolean read = false;
while (bytes.readRemaining() >= 4) {
long position = bytes.readPosition();
int header = bytes.readVolatileInt(position);
if (!isKnownLength(header))
return read;
bytes.readSkip(4);
final boolean ready = isReady(header);
final int len = lengthOf(header);
if (isData(header)) {
if (dataConsumer == null) {
return false;
} else {
((InternalWireIn) wireIn).setReady(ready);
bytes.readWithLength(len, b -> dataConsumer.readMarshallable(wireIn));
return true;
}
} else {
if (metaDataConsumer == null) {
// skip the header
bytes.readSkip(len);
} else {
// bytes.readWithLength(len, b -> metaDataConsumer.accept(wireIn));
// inlined to avoid garbage
if ((long) len > bytes.readRemaining())
throw new BufferUnderflowException();
long limit0 = bytes.readLimit();
long limit = bytes.readPosition() + (long) len;
try {
bytes.readLimit(limit);
metaDataConsumer.readMarshallable(wireIn);
} finally {
bytes.readLimit(limit0);
bytes.readPosition(limit);
}
}
if (dataConsumer == null)
return true;
read = true;
}
}
return read;
}
public static void rawReadData(@NotNull WireIn wireIn, @NotNull ReadMarshallable dataConsumer) {
final Bytes<?> bytes = wireIn.bytes();
int header = bytes.readInt();
assert isReady(header) && isData(header);
final int len = lengthOf(header);
long limit0 = bytes.readLimit();
long limit = bytes.readPosition() + (long) len;
try {
bytes.readLimit(limit);
dataConsumer.readMarshallable(wireIn);
} finally {
bytes.readLimit(limit0);
}
}
public static String fromSizePrefixedBlobs(@NotNull Bytes bytes) {
long position = bytes.readPosition();
return fromSizePrefixedBlobs(bytes, position, bytes.readRemaining());
}
public static String fromSizePrefixedBinaryToText(@NotNull Bytes bytes) {
long position = bytes.readPosition();
return fromSizePrefixedBinaryToText(bytes, position, bytes.readRemaining());
}
public static int lengthOf(long len) {
return (int) (len & LENGTH_MASK);
}
public static boolean isReady(long len) {
return (len & NOT_READY) == 0;
}
public static boolean isData(long len) {
return (len & META_DATA) == 0;
}
@NotNull
private static String fromSizePrefixedBlobs(@NotNull Bytes bytes, long position, long length) {
StringBuilder sb = new StringBuilder();
final long limit0 = bytes.readLimit();
final long position0 = bytes.readPosition();
try {
bytes.readPosition(position);
long limit2 = Math.min(limit0, position + length);
bytes.readLimit(limit2);
long missing = position + length - limit2;
while (bytes.readRemaining() >= 4) {
long header = bytes.readUnsignedInt();
int len = lengthOf(header);
String type = isData(header)
? isReady(header) ? "!!data" : "!!not-ready-data!"
: isReady(header) ? "!!meta-data" : "!!not-ready-meta-data!";
boolean binary = bytes.readByte(bytes.readPosition()) < ' ';
sb.append("--- ").append(type).append(binary ? " #binary" : "");
if (missing > 0)
sb.append(" # missing: ").append(missing);
if (len > bytes.readRemaining())
sb.append(" # len: ").append(len).append(", remaining: ").append(bytes.readRemaining());
sb.append("\n");
try {
for (int i = 0; i < len; i++) {
int ch = bytes.readUnsignedByte();
if (binary)
sb.append(RandomDataInput.charToString[ch]);
else
sb.append((char) ch);
}
} catch (Exception e) {
sb.append(" ").append(e);
}
if (sb.charAt(sb.length() - 1) != '\n')
sb.append('\n');
}
return sb.toString();
} finally {
bytes.readLimit(limit0);
bytes.readPosition(position0);
}
}
@NotNull
private static String fromSizePrefixedBinaryToText(@NotNull Bytes bytes, long position, long length) {
StringBuilder sb = new StringBuilder();
final long limit0 = bytes.readLimit();
final long position0 = bytes.readPosition();
try {
bytes.readPosition(position);
long limit2 = Math.min(limit0, position + length);
bytes.readLimit(limit2);
long missing = position + length - limit2;
while (bytes.readRemaining() >= 4) {
long header = bytes.readUnsignedInt();
int len = lengthOf(header);
String type = isData(header)
? isReady(header) ? "!!data" : "!!not-ready-data!"
: isReady(header) ? "!!meta-data" : "!!not-ready-meta-data!";
boolean binary = bytes.readByte(bytes.readPosition()) < ' ';
sb.append("--- ").append(type).append(binary ? " #binary" : "");
if (missing > 0)
sb.append(" # missing: ").append(missing);
if (len > bytes.readRemaining())
sb.append(" # len: ").append(len).append(", remaining: ").append(bytes.readRemaining());
sb.append("\n");
Bytes textBytes = bytes;
if (binary) {
Bytes bytes2 = Bytes.elasticByteBuffer();
TextWire textWire = new TextWire(bytes2);
long readLimit = bytes.readLimit();
try {
bytes.readLimit(bytes.readPosition() + len);
new BinaryWire(bytes).copyTo(textWire);
} finally {
bytes.readLimit(readLimit);
}
textBytes = bytes2;
len = (int) textBytes.readRemaining();
}
try {
for (int i = 0; i < len; i++) {
int ch = textBytes.readUnsignedByte();
// if (binary)
// sb.append(RandomDataInput.charToString[ch]);
// else
sb.append((char) ch);
}
} catch (Exception e) {
sb.append(" ").append(e);
}
if (sb.charAt(sb.length() - 1) != '\n')
sb.append('\n');
}
return sb.toString();
} finally {
bytes.readLimit(limit0);
bytes.readPosition(position0);
}
}
private static boolean isKnownLength(long len) {
return (len & (META_DATA | LENGTH_MASK)) != UNKNOWN_LENGTH;
}
public static Throwable throwable(@NotNull ValueIn valueIn, boolean appendCurrentStack) {
StringBuilder type = Wires.acquireStringBuilder();
valueIn.type(type);
String preMessage = null;
Throwable throwable;
try {
//noinspection unchecked
throwable = OS.memory().allocateInstance((Class<Throwable>) Class.forName(INTERNER.intern(type)));
} catch (ClassNotFoundException e) {
preMessage = type.toString();
throwable = new RuntimeException();
}
final String finalPreMessage = preMessage;
final Throwable finalThrowable = throwable;
final List<StackTraceElement> stes = new ArrayList<>();
valueIn.marshallable(m -> {
final String message = merge(finalPreMessage, m.read(() -> "message").text());
if (message != null) {
try {
DETAILED_MESSAGE.set(finalThrowable, message);
} catch (IllegalAccessException e) {
throw Jvm.rethrow(e);
}
}
m.read(() -> "stackTrace").sequence(stackTrace -> {
while (stackTrace.hasNextSequenceItem()) {
stackTrace.marshallable(r -> {
final String declaringClass = r.read(() -> "class").text();
final String methodName = r.read(() -> "method").text();
final String fileName = r.read(() -> "file").text();
final int lineNumber = r.read(() -> "line").int32();
stes.add(new StackTraceElement(declaringClass, methodName,
fileName, lineNumber));
});
}
});
});
if (appendCurrentStack) {
stes.add(new StackTraceElement("~ remote", "tcp ~", "", 0));
StackTraceElement[] stes2 = Thread.currentThread().getStackTrace();
int first = 6;
int last = Jvm.trimLast(first, stes2);
//noinspection ManualArrayToCollectionCopy
for (int i = first; i <= last; i++)
stes.add(stes2[i]);
}
try {
//noinspection ToArrayCallWithZeroLengthArrayArgument
STACK_TRACE.set(finalThrowable, stes.toArray(NO_STE));
} catch (IllegalAccessException e) {
throw Jvm.rethrow(e);
}
return throwable;
}
@Nullable
static String merge(@Nullable String a, @Nullable String b) {
return a == null ? b : b == null ? a : a + " " + b;
}
} |
package org.attribyte.wp.model;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableMap;
import java.text.ParseException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class Shortcode {
/**
* Creates a shortcode without content.
* @param name The name.
* @param attributes The attributes.
*/
public Shortcode(final String name, final Map<String, String> attributes) {
this(name, attributes, null);
}
/**
* Creates a shortcode with content.
* @param name The name.
* @param attributes The attributes.
* @param content The content.
*/
public Shortcode(final String name, final Map<String, String> attributes,
final String content) {
this.name = name;
this.attributes = attributes != null ? ImmutableMap.copyOf(attributes) : ImmutableMap.of();
this.content = Strings.emptyToNull(content);
}
/**
* Adds content to a shortcode.
* @param content The content.
* @return The shortcode with content added.
*/
public Shortcode withContent(final String content) {
return new Shortcode(name, attributes, content);
}
/**
* The name.
*/
public final String name;
/**
* The attributes.
*/
public final ImmutableMap<String, String> attributes;
/**
* The content.
*/
public final String content;
/**
* Gets an attribute value.
* @param name The attribute name.
* @return The value or {@code null} if no value for this attribute.
*/
public final String value(final String name) {
return attributes.get(name.toLowerCase());
}
/**
* Gets a positional attribute value.
* @param pos The position.
* @return The value, or {@code null} if no value at the position.
*/
public final String positionalValue(final int pos) {
return attributes.get(String.format("$%d", pos));
}
/**
* Gets a list of any positional values.
* @return The list of values.
*/
public final List<String> positionalValues() {
return attributes.entrySet()
.stream()
.filter(kv -> kv.getKey().startsWith("$"))
.map(Map.Entry::getValue)
.collect(Collectors.toList());
}
@Override
public final String toString() {
StringBuilder buf = new StringBuilder("[");
buf.append(name);
attributes.entrySet().forEach(kv -> {
if(kv.getKey().startsWith("$")) {
buf.append(" ");
appendAttributeValue(kv.getValue(), buf);
} else {
buf.append(" ").append(kv.getKey()).append("=");
appendAttributeValue(kv.getValue(), buf);
}
});
buf.append("]");
if(content != null) {
buf.append(content);
buf.append("[/").append(name).append("]");
}
return buf.toString();
}
private StringBuilder appendAttributeValue(final String value, final StringBuilder buf) {
if(value.contains("\"")) {
buf.append("\'").append(escapeAttribute(value)).append("\'");
} else if(value.contains(" ") || value.contains("\'") || value.contains("=")) {
buf.append("\"").append(escapeAttribute(value)).append("\"");
} else {
buf.append(escapeAttribute(value));
}
return buf;
}
/**
* A handler for shortcode parse events.
*/
public static interface Handler {
/**
* Parsed a shortcode.
* @param shortcode The shortcode.
*/
public void shortcode(Shortcode shortcode);
/**
* A block of text between shortcodes.
* @param text The text.
*/
public void text(String text);
/**
* A shortcode parse error.
* @param text The text that could not be parsed as a shortcode.
* @param pe A parse exception, or {@code null} if none.
*/
public void parseError(String text, ParseException pe);
/**
* Override to indicate shortcodes where content (and an end-tag) is expected.
* @param shortcode The shortcode name.
* @return Is this a shortcode where content is expected?
*/
public boolean expectContent(final String shortcode);
}
/**
* State for parsing with a handler.
*/
private enum HandlerParseState {
TEXT,
START,
CONTENT,
START_END,
END_NAME;
}
/**
* Parse an arbitrary string.
* @param str The string.
* @param handler The handler for parse events.
*/
public static void parse(final String str, final Handler handler) {
if(str == null) {
return;
}
StringBuilder buf = new StringBuilder();
HandlerParseState state = HandlerParseState.TEXT;
Shortcode currCode = null;
String currContent = null;
for(char ch : str.toCharArray()) {
switch(state) {
case TEXT:
switch(ch) {
case '[':
if(buf.length() > 0) {
handler.text(buf.toString());
buf.setLength(0);
}
state = HandlerParseState.START;
buf.append(ch);
break;
default:
buf.append(ch);
break;
}
break;
case START:
switch(ch) {
case ']':
try {
buf.append(ch);
currCode = Parser.parseStart(buf.toString());
if(!handler.expectContent(currCode.name)) {
handler.shortcode(currCode);
currCode = null;
state = HandlerParseState.TEXT;
} else {
state = HandlerParseState.CONTENT;
}
} catch(ParseException pe) {
handler.parseError(buf.toString(), pe);
state = HandlerParseState.TEXT;
}
buf.setLength(0);
break;
default:
buf.append(ch);
break;
}
break;
case CONTENT:
switch(ch) {
case '[':
currContent = buf.toString();
buf.setLength(0);
state = HandlerParseState.START_END;
break;
default:
buf.append(ch);
break;
}
break;
case START_END:
switch(ch) {
case '/':
state = HandlerParseState.END_NAME;
break;
default:
buf.append('[').append(ch);
handler.parseError(buf.toString(), null);
buf.setLength(0);
state = HandlerParseState.TEXT;
break;
}
break;
case END_NAME:
switch(ch) {
case ']':
if(buf.toString().equals(currCode.name)) {
handler.shortcode(currCode.withContent(currContent));
buf.setLength(0);
currCode = null;
currContent = null;
} else {
handler.parseError(currCode.toString() + currContent + "[/" + buf.toString() + "]", new ParseException("Invalid end tag", 0));
buf.setLength(0);
}
state = HandlerParseState.TEXT;
break;
default:
buf.append(ch);
}
}
}
switch(state) {
case TEXT:
if(buf.length() > 0) {
handler.text(buf.toString());
}
break;
default:
handler.parseError(buf.toString(), null);
break;
}
}
/**
* Parses a shortcode
* @param shortcode The shortcode string.
* @return The parsed shortcode.
* @throws ParseException on invalid code.
*/
public static Shortcode parse(final String shortcode) throws ParseException {
String exp = shortcode.trim();
if(exp.length() < 3) {
throw new ParseException(String.format("Invalid shortcode ('%s')", exp), 0);
}
if(exp.charAt(0) != '[') {
throw new ParseException("Expecting '['", 0);
}
int end = exp.indexOf(']');
if(end == -1) {
throw new ParseException("Expecting ']", 0);
}
Shortcode startTag = Parser.parseStart(exp.substring(0, end + 1));
end = exp.lastIndexOf("[/");
if(end > 0) {
if(exp.endsWith("[/" + startTag.name + "]")) {
int start = shortcode.indexOf("]");
return startTag.withContent(exp.substring(start + 1, end));
} else {
throw new ParseException("Invalid shortcode end", 0);
}
} else {
return startTag;
}
}
/**
* Escapes an attribute value.
* @param val The value.
* @return The escaped value.
*/
private static String escapeAttribute(final String val) {
return Strings.nullToEmpty(val); //TODO?
}
private static class Parser {
private static boolean isNameCharacter(final char ch) {
return (Character.isLetterOrDigit(ch) || ch == '_' || ch == '-');
}
private static String validateName(final String str) throws ParseException {
for(char ch : str.toCharArray()) {
if(!isNameCharacter(ch)) {
throw new ParseException(String.format("Invalid name ('%s')", str), 0);
}
}
return str;
}
/**
* Parse '[shortcode attr0="val0" attr1="val1"]
* @param str The shortcode string.
* @return The shortcode.
* @throws ParseException on invalid shortcode.
*/
private static Shortcode parseStart(final String str) throws ParseException {
String exp = str.trim();
if(exp.length() < 3) {
throw new ParseException(String.format("Invalid shortcode ('%s')", str), 0);
}
if(exp.charAt(0) != '[') {
throw new ParseException("Expecting '['", 0);
}
if(exp.charAt(exp.length() -1) != ']') {
throw new ParseException("Expecting ']'", exp.length() - 1);
}
exp = exp.substring(1, exp.length() -1).trim();
if(exp.length() == 0) {
throw new ParseException(String.format("Invalid shortcode ('%s')", str), 0);
}
int attrStart = exp.indexOf(' ');
if(attrStart < 0) {
return new Shortcode(validateName(exp), ImmutableMap.of());
} else {
return new Shortcode(validateName(exp.substring(0, attrStart)), parseAttributes(exp.substring(attrStart).trim()));
}
}
/**
* Holds state for parsing attributes.
*/
private static class AttributeString {
AttributeString(final String str) {
this.chars = str.toCharArray();
this.buf = new StringBuilder();
}
/**
* The current state.
*/
enum StringState {
/**
* Before any recognized start character.
*/
BEFORE_START,
/**
* Inside a single-quoted value.
*/
SINGLE_QUOTED_VALUE,
/**
* Inside a double-quoted value.
*/
DOUBLE_QUOTED_VALUE,
/**
* A value.
*/
VALUE,
}
private String value() {
String val = buf.toString();
buf.setLength(0);
if(ch == ' ') { //Eat trailing spaces...
int currPos = pos;
while(currPos < chars.length) {
char currChar = chars[currPos];
if(currChar != ' ') {
pos = currPos;
ch = chars[pos];
break;
} else {
currPos++;
}
}
}
return val;
}
String nextString() throws ParseException {
StringState state = StringState.BEFORE_START;
while(pos < chars.length) {
ch = chars[pos++];
switch(ch) {
case '=':
switch(state) {
case BEFORE_START:
state = StringState.VALUE;
break;
case SINGLE_QUOTED_VALUE:
case DOUBLE_QUOTED_VALUE:
buf.append(ch);
break;
case VALUE:
return value();
}
break;
case ' ':
switch(state) {
case BEFORE_START:
break;
case SINGLE_QUOTED_VALUE:
case DOUBLE_QUOTED_VALUE:
buf.append(ch);
break;
case VALUE:
return value();
}
break;
case '\"':
switch(state) {
case BEFORE_START:
state = StringState.DOUBLE_QUOTED_VALUE;
break;
case SINGLE_QUOTED_VALUE:
buf.append(ch);
break;
case DOUBLE_QUOTED_VALUE:
return value();
case VALUE:
throw new ParseException("Unexpected '\"'", pos);
}
break;
case '\'':
switch(state) {
case BEFORE_START:
state = StringState.SINGLE_QUOTED_VALUE;
break;
case DOUBLE_QUOTED_VALUE:
buf.append(ch);
break;
case SINGLE_QUOTED_VALUE:
return value();
case VALUE:
throw new ParseException("Unexpected '\'", pos);
}
break;
default:
switch(state) {
case BEFORE_START:
state = StringState.VALUE;
break;
}
buf.append(ch);
break;
}
}
switch(state) {
case VALUE:
return buf.toString();
case SINGLE_QUOTED_VALUE:
throw new ParseException("Expected \'", pos);
case DOUBLE_QUOTED_VALUE:
throw new ParseException("Expected \"", pos);
default:
return null;
}
}
char ch;
int pos = 0;
String last;
final char[] chars;
final StringBuilder buf;
}
/**
* Parse attributes in a shortcode.
* @param attrString The attribute string.
* @return The map of attributes. Keys are <em>lower-case</em>.
* @throws ParseException on invalid shortcode.
*/
private static Map<String, String> parseAttributes(String attrString) throws ParseException {
AttributeString str = new AttributeString(attrString);
ImmutableMap.Builder<String, String> attributes = ImmutableMap.builder(); //Immutable map preserves entry order.
AttrState state = AttrState.NAME;
String currName = "";
String currString = "";
int currPos = 0;
while((currString = str.nextString()) != null) {
switch(state) {
case NAME:
if(str.ch == '=') {
currName = currString;
state = AttrState.VALUE;
} else {
attributes.put(String.format("$%d", currPos++), currString);
}
break;
case VALUE:
attributes.put(currName.toLowerCase(), currString);
state = AttrState.NAME;
break;
}
}
return attributes.build();
}
/**
* Attribute parse state.
*/
private enum AttrState {
/**
* Parsing a name.
*/
NAME,
/**
* Expecting a value.
*/
VALUE;
}
}
} |
package org.basex.http.restxq;
import java.io.*;
import java.util.*;
import org.basex.http.*;
import org.basex.io.serial.*;
import org.basex.query.value.item.*;
import org.basex.query.value.node.*;
import org.basex.util.*;
final class RestXqWadl {
/** WADL namespace. */
private static final byte[] WADL = Token.token("http://research.sun.com/wadl/2006/10");
/** Private constructor. */
RestXqWadl() { }
/**
* Lists all available URIs.
* @param http HTTP context
* @param modules available modules
* @throws IOException I/O exception
*/
synchronized void create(final HTTPContext http, final HashMap<String, RestXqModule>
modules) throws IOException {
// create root nodes
final Atts ns = new Atts(Token.EMPTY, WADL);
final FElem appl = new FElem(new QNm("application", WADL), ns);
final FElem ress = new FElem(new QNm("resources", WADL));
final String base = http.req.getRequestURL().toString().replaceAll(HTTPText.WADL, "");
appl.add(ress.add(new QNm("base"), base));
// create children
final TreeMap<String, FElem> map = new TreeMap<String, FElem>();
for(final RestXqModule mod : modules.values()) {
for(final RestXqFunction func : mod.functions) {
final FElem res = new FElem(new QNm("resource", WADL));
final String path = func.path.toString();
res.add(new QNm("path"), path);
map.put(path, res);
final FElem method = new FElem(new QNm("method", WADL));
final String mths = func.methods.toString().replaceAll("[^A-Z ]", "");
res.add(method.add(new QNm("name"), mths));
final FElem request = new FElem(new QNm("request", WADL));
method.add(request);
addParams(func.queryParams, "query", request);
addParams(func.formParams, "form", request);
final FElem response = new FElem(new QNm("response", WADL));
method.add(response);
final FElem representation = new FElem(new QNm("representation", WADL));
response.add(representation.add(new QNm("mediaType"),
HTTPContext.mediaType(func.output)));
}
}
for(final FElem elem : map.values()) ress.add(elem);
// serialize node
final Serializer ser = Serializer.get(http.res.getOutputStream());
ser.serialize(appl);
ser.close();
}
/**
* Adds parameters from the passed on request body.
* @param params parameters
* @param style style
* @param root root element
*/
private static void addParams(final ArrayList<RestXqParam> params,
final String style, final FElem root) {
for(final RestXqParam rxp : params) {
final FElem param = new FElem(new QNm("param", WADL));
param.add(new QNm("name"), rxp.key);
param.add(new QNm("style"), style);
root.add(param);
}
}
} |
package org.broad.igv.sam;
import org.broad.igv.Globals;
import org.broad.igv.event.AlignmentTrackEvent;
import org.broad.igv.event.IGVEventBus;
import org.broad.igv.event.IGVEventObserver;
import org.broad.igv.feature.FeatureUtils;
import org.broad.igv.feature.Locus;
import org.broad.igv.feature.Range;
import org.broad.igv.feature.Strand;
import org.broad.igv.feature.genome.ChromosomeNameComparator;
import org.broad.igv.feature.genome.Genome;
import org.broad.igv.jbrowse.CircularViewUtilities;
import org.broad.igv.lists.GeneList;
import org.broad.igv.logging.LogManager;
import org.broad.igv.logging.Logger;
import org.broad.igv.prefs.Constants;
import org.broad.igv.prefs.IGVPreferences;
import org.broad.igv.prefs.PreferencesManager;
import org.broad.igv.renderer.GraphicUtils;
import org.broad.igv.sashimi.SashimiPlot;
import org.broad.igv.session.Persistable;
import org.broad.igv.session.Session;
import org.broad.igv.tools.PFMExporter;
import org.broad.igv.track.*;
import org.broad.igv.ui.FontManager;
import org.broad.igv.ui.IGV;
import org.broad.igv.ui.InsertSizeSettingsDialog;
import org.broad.igv.ui.color.ColorTable;
import org.broad.igv.ui.color.ColorUtilities;
import org.broad.igv.ui.color.PaletteColorTable;
import org.broad.igv.ui.panel.FrameManager;
import org.broad.igv.ui.panel.IGVPopupMenu;
import org.broad.igv.ui.panel.ReferenceFrame;
import org.broad.igv.ui.util.MessageUtils;
import org.broad.igv.ui.util.UIUtilities;
import org.broad.igv.util.Pair;
import org.broad.igv.util.ResourceLocator;
import org.broad.igv.util.StringUtils;
import org.broad.igv.util.blat.BlatClient;
import org.broad.igv.util.collections.CollUtils;
import org.broad.igv.util.extview.ExtendViewClient;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import javax.swing.*;
import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.geom.Rectangle2D;
import java.util.List;
import java.util.*;
import static org.broad.igv.prefs.Constants.*;
/**
* @author jrobinso
*/
public class AlignmentTrack extends AbstractTrack implements IGVEventObserver {
// Alignment colors
static Color DEFAULT_ALIGNMENT_COLOR = new Color(185, 185, 185); //200, 200, 200);
public enum ColorOption {
INSERT_SIZE,
READ_STRAND,
FIRST_OF_PAIR_STRAND,
PAIR_ORIENTATION,
SAMPLE,
READ_GROUP,
LIBRARY,
MOVIE,
ZMW,
BISULFITE,
NOMESEQ,
TAG,
NONE,
UNEXPECTED_PAIR,
MAPPED_SIZE,
LINK_STRAND,
YC_TAG,
BASE_MODIFICATION
}
public enum SortOption {
START, STRAND, NUCLEOTIDE, QUALITY, SAMPLE, READ_GROUP, INSERT_SIZE, FIRST_OF_PAIR_STRAND, MATE_CHR, TAG,
SUPPLEMENTARY, NONE, HAPLOTYPE, READ_ORDER, READ_NAME
}
public enum GroupOption {
STRAND("read strand"),
SAMPLE("sample"),
READ_GROUP("read group"),
LIBRARY("library"),
FIRST_OF_PAIR_STRAND("first-in-pair strand"),
TAG("tag"),
PAIR_ORIENTATION("pair orientation"),
MATE_CHROMOSOME("chromosome of mate"),
NONE("none"),
SUPPLEMENTARY("supplementary flag"),
BASE_AT_POS("base at position"),
MOVIE("movie"),
ZMW("ZMW"),
HAPLOTYPE("haplotype"),
READ_ORDER("read order"),
LINKED("linked"),
PHASE("phase"),
REFERENCE_CONCORDANCE("reference concordance");
public String label;
GroupOption(String label) {
this.label = label;
}
}
public enum BisulfiteContext {
CG, CHH, CHG, HCG, GCH, WCG, NONE
}
enum OrientationType {
RR, LL, RL, LR, UNKNOWN
}
private static Logger log = LogManager.getLogger(AlignmentTrack.class);
private static final int GROUP_LABEL_HEIGHT = 10;
private static final int GROUP_MARGIN = 5;
private static final int TOP_MARGIN = 20;
private static final int DS_MARGIN_0 = 2;
private static final int DOWNAMPLED_ROW_HEIGHT = 3;
private static final int INSERTION_ROW_HEIGHT = 9;
private static final int DS_MARGIN_2 = 5;
private static int nClusters = 2;
private static final Map<BisulfiteContext, String> bisulfiteContextToPubString = new HashMap<>();
static {
bisulfiteContextToPubString.put(BisulfiteContext.CG, "CG");
bisulfiteContextToPubString.put(BisulfiteContext.CHH, "CHH");
bisulfiteContextToPubString.put(BisulfiteContext.CHG, "CHG");
bisulfiteContextToPubString.put(BisulfiteContext.HCG, "HCG");
bisulfiteContextToPubString.put(BisulfiteContext.GCH, "GCH");
bisulfiteContextToPubString.put(BisulfiteContext.WCG, "WCG");
bisulfiteContextToPubString.put(BisulfiteContext.NONE, "None");
}
private static final Map<BisulfiteContext, Pair<byte[], byte[]>> bisulfiteContextToContextString = new HashMap<>();
static {
bisulfiteContextToContextString.put(BisulfiteContext.CG, new Pair<>(new byte[]{}, new byte[]{'G'}));
bisulfiteContextToContextString.put(BisulfiteContext.CHH, new Pair<>(new byte[]{}, new byte[]{'H', 'H'}));
bisulfiteContextToContextString.put(BisulfiteContext.CHG, new Pair<>(new byte[]{}, new byte[]{'H', 'G'}));
bisulfiteContextToContextString.put(BisulfiteContext.HCG, new Pair<>(new byte[]{'H'}, new byte[]{'G'}));
bisulfiteContextToContextString.put(BisulfiteContext.GCH, new Pair<>(new byte[]{'G'}, new byte[]{'H'}));
bisulfiteContextToContextString.put(BisulfiteContext.WCG, new Pair<>(new byte[]{'W'}, new byte[]{'G'}));
}
public static boolean isBisulfiteColorType(ColorOption o) {
return (o.equals(ColorOption.BISULFITE) || o.equals(ColorOption.NOMESEQ));
}
private static String getBisulfiteContextPubStr(BisulfiteContext item) {
return bisulfiteContextToPubString.get(item);
}
public static byte[] getBisulfiteContextPreContext(BisulfiteContext item) {
Pair<byte[], byte[]> pair = AlignmentTrack.bisulfiteContextToContextString.get(item);
return pair.getFirst();
}
public static byte[] getBisulfiteContextPostContext(BisulfiteContext item) {
Pair<byte[], byte[]> pair = AlignmentTrack.bisulfiteContextToContextString.get(item);
return pair.getSecond();
}
private AlignmentDataManager dataManager;
private SequenceTrack sequenceTrack;
private CoverageTrack coverageTrack;
private SpliceJunctionTrack spliceJunctionTrack;
private final Genome genome;
private ExperimentType experimentType;
private final AlignmentRenderer renderer;
RenderOptions renderOptions;
private boolean removed = false;
private RenderRollback renderRollback;
private boolean showGroupLine;
private Map<ReferenceFrame, List<InsertionInterval>> insertionIntervalsMap;
private int expandedHeight = 14;
private final int collapsedHeight = 9;
private final int maxSquishedHeight = 5;
private int squishedHeight = maxSquishedHeight;
private final int minHeight = 50;
private Rectangle alignmentsRect;
private Rectangle downsampleRect;
private Rectangle insertionRect;
private ColorTable readNamePalette;
// Dynamic fields
protected final HashMap<String, Color> selectedReadNames = new HashMap<>();
/**
* Create a new alignment track
*
* @param locator
* @param dataManager
* @param genome
*/
public AlignmentTrack(ResourceLocator locator, AlignmentDataManager dataManager, Genome genome) {
super(locator);
this.dataManager = dataManager;
this.genome = genome;
renderer = new AlignmentRenderer(this);
renderOptions = new RenderOptions(this);
setColor(DEFAULT_ALIGNMENT_COLOR);
dataManager.setAlignmentTrack(this);
dataManager.subscribe(this);
IGVPreferences prefs = getPreferences();
minimumHeight = 50;
showGroupLine = prefs.getAsBoolean(SAM_SHOW_GROUP_SEPARATOR);
try {
setDisplayMode(DisplayMode.valueOf(prefs.get(SAM_DISPLAY_MODE).toUpperCase()));
} catch (Exception e) {
setDisplayMode(DisplayMode.EXPANDED);
}
if (prefs.getAsBoolean(SAM_SHOW_REF_SEQ)) {
sequenceTrack = new SequenceTrack("Reference sequence");
sequenceTrack.setHeight(14);
}
if (renderOptions.colorOption == ColorOption.BISULFITE) {
setExperimentType(ExperimentType.BISULFITE);
}
readNamePalette = new PaletteColorTable(ColorUtilities.getDefaultPalette());
insertionIntervalsMap = Collections.synchronizedMap(new HashMap<>());
dataManager.setViewAsPairs(prefs.getAsBoolean(SAM_DISPLAY_PAIRED), renderOptions);
IGVEventBus.getInstance().subscribe(FrameManager.ChangeEvent.class, this);
IGVEventBus.getInstance().subscribe(AlignmentTrackEvent.class, this);
}
public void init() {
if (experimentType == null) {
ExperimentType type = dataManager.inferType();
if (type != null) {
setExperimentType(type);
}
}
}
@Override
public void receiveEvent(Object event) {
if (event instanceof FrameManager.ChangeEvent) {
// Trim insertionInterval map to current frames
Map<ReferenceFrame, List<InsertionInterval>> newMap = Collections.synchronizedMap(new HashMap<>());
for (ReferenceFrame frame : ((FrameManager.ChangeEvent) event).getFrames()) {
if (insertionIntervalsMap.containsKey(frame)) {
newMap.put(frame, insertionIntervalsMap.get(frame));
}
}
insertionIntervalsMap = newMap;
} else if (event instanceof AlignmentTrackEvent) {
AlignmentTrackEvent e = (AlignmentTrackEvent) event;
AlignmentTrackEvent.Type eventType = e.getType();
switch (eventType) {
case ALLELE_THRESHOLD:
dataManager.alleleThresholdChanged();
break;
case RELOAD:
clearCaches();
repaint();
case REFRESH:
repaint();
break;
}
}
}
void setExperimentType(ExperimentType type) {
if (type != experimentType) {
experimentType = type;
boolean showJunction = getPreferences(type).getAsBoolean(Constants.SAM_SHOW_JUNCTION_TRACK);
if (showJunction != spliceJunctionTrack.isVisible()) {
spliceJunctionTrack.setVisible(showJunction);
if (IGV.hasInstance()) {
IGV.getInstance().revalidateTrackPanels();
}
}
boolean showCoverage = getPreferences(type).getAsBoolean(SAM_SHOW_COV_TRACK);
if (showCoverage != coverageTrack.isVisible()) {
coverageTrack.setVisible(showCoverage);
if (IGV.hasInstance()) {
IGV.getInstance().revalidateTrackPanels();
}
}
boolean showAlignments = getPreferences(type).getAsBoolean(SAM_SHOW_ALIGNMENT_TRACK);
if (showAlignments != isVisible()) {
setVisible(showAlignments);
if (IGV.hasInstance()) {
IGV.getInstance().revalidateTrackPanels();
}
}
//ExperimentTypeChangeEvent event = new ExperimentTypeChangeEvent(this, experimentType);
//IGVEventBus.getInstance().post(event);
}
}
ExperimentType getExperimentType() {
return experimentType;
}
public AlignmentDataManager getDataManager() {
return dataManager;
}
public void setCoverageTrack(CoverageTrack coverageTrack) {
this.coverageTrack = coverageTrack;
}
public CoverageTrack getCoverageTrack() {
return coverageTrack;
}
public void setSpliceJunctionTrack(SpliceJunctionTrack spliceJunctionTrack) {
this.spliceJunctionTrack = spliceJunctionTrack;
}
public SpliceJunctionTrack getSpliceJunctionTrack() {
return spliceJunctionTrack;
}
@Override
public IGVPopupMenu getPopupMenu(TrackClickEvent te) {
return new PopupMenu(te);
}
@Override
public void setHeight(int preferredHeight) {
super.setHeight(preferredHeight);
minimumHeight = preferredHeight;
}
@Override
public int getHeight() {
int nGroups = dataManager.getMaxGroupCount();
int h = Math.max(minHeight, getNLevels() * getRowHeight() + nGroups * GROUP_MARGIN + TOP_MARGIN
+ DS_MARGIN_0 + DOWNAMPLED_ROW_HEIGHT + DS_MARGIN_2);
//if (insertionRect != null) { // TODO - replace with expand insertions preference
h += INSERTION_ROW_HEIGHT + DS_MARGIN_0;
return Math.max(minimumHeight, h);
}
private int getRowHeight() {
if (getDisplayMode() == DisplayMode.EXPANDED) {
return expandedHeight;
} else if (getDisplayMode() == DisplayMode.COLLAPSED) {
return collapsedHeight;
} else {
return squishedHeight;
}
}
private int getNLevels() {
return dataManager.getNLevels();
}
@Override
public boolean isReadyToPaint(ReferenceFrame frame) {
if (frame.getChrName().equals(Globals.CHR_ALL) || frame.getScale() > dataManager.getMinVisibleScale()) {
return true; // Nothing to paint
} else {
List<InsertionInterval> insertionIntervals = getInsertionIntervals(frame);
insertionIntervals.clear();
return dataManager.isLoaded(frame);
}
}
@Override
public void load(ReferenceFrame referenceFrame) {
if (log.isDebugEnabled()) {
log.debug("Reading - thread: " + Thread.currentThread().getName());
}
dataManager.load(referenceFrame, renderOptions, true);
}
public void render(RenderContext context, Rectangle rect) {
int viewWindowSize = context.getReferenceFrame().getCurrentRange().getLength();
if (viewWindowSize > dataManager.getVisibilityWindow()) {
Rectangle visibleRect = context.getVisibleRect().intersection(rect);
Graphics2D g2 = context.getGraphic2DForColor(Color.gray);
GraphicUtils.drawCenteredText("Zoom in to see alignments.", visibleRect, g2);
return;
}
context.getGraphics2D("LABEL").setFont(FontManager.getFont(GROUP_LABEL_HEIGHT));
// Split track rectangle into sections.
int seqHeight = sequenceTrack == null ? 0 : sequenceTrack.getHeight();
if (seqHeight > 0) {
Rectangle seqRect = new Rectangle(rect);
seqRect.height = seqHeight;
sequenceTrack.render(context, seqRect);
}
// Top gap.
rect.y += DS_MARGIN_0;
downsampleRect = new Rectangle(rect);
downsampleRect.height = DOWNAMPLED_ROW_HEIGHT;
renderDownsampledIntervals(context, downsampleRect);
if (renderOptions.isShowInsertionMarkers()) {
insertionRect = new Rectangle(rect);
insertionRect.y += DOWNAMPLED_ROW_HEIGHT + DS_MARGIN_0;
insertionRect.height = INSERTION_ROW_HEIGHT;
renderInsertionIntervals(context, insertionRect);
rect.y = insertionRect.y + insertionRect.height;
}
alignmentsRect = new Rectangle(rect);
alignmentsRect.y += 2;
alignmentsRect.height -= (alignmentsRect.y - rect.y);
renderAlignments(context, alignmentsRect);
}
private void renderDownsampledIntervals(RenderContext context, Rectangle downsampleRect) {
// Might be offscreen
if (!context.getVisibleRect().intersects(downsampleRect)) return;
final AlignmentInterval loadedInterval = dataManager.getLoadedInterval(context.getReferenceFrame());
if (loadedInterval == null) return;
Graphics2D g = context.getGraphic2DForColor(Color.black);
List<DownsampledInterval> intervals = loadedInterval.getDownsampledIntervals();
for (DownsampledInterval interval : intervals) {
final double scale = context.getScale();
final double origin = context.getOrigin();
int x0 = (int) ((interval.getStart() - origin) / scale);
int x1 = (int) ((interval.getEnd() - origin) / scale);
int w = Math.max(1, x1 - x0);
// If there is room, leave a gap on one side
if (w > 5) w
// Greyscale from 0 -> 100 downsampled
//int gray = 200 - interval.getCount();
//Color color = (gray <= 0 ? Color.black : ColorUtilities.getGrayscaleColor(gray));
g.fillRect(x0, downsampleRect.y, w, downsampleRect.height);
}
}
private void renderAlignments(RenderContext context, Rectangle inputRect) {
final AlignmentInterval loadedInterval = dataManager.getLoadedInterval(context.getReferenceFrame(), true);
if (loadedInterval == null) {
return;
}
final AlignmentCounts alignmentCounts = loadedInterval.getCounts();
//log.debug("Render features");
PackedAlignments groups = dataManager.getGroups(loadedInterval, renderOptions);
if (groups == null) {
//Assume we are still loading.
//This might not always be true
return;
}
// Check for YC tag
if (renderOptions.colorOption == null && dataManager.hasYCTags()) {
renderOptions.colorOption = ColorOption.YC_TAG;
}
Map<String, PEStats> peStats = dataManager.getPEStats();
if (peStats != null) {
renderOptions.peStats = peStats;
}
Rectangle visibleRect = context.getVisibleRect();
// Divide rectangle into equal height levels
double y = inputRect.getY();
double h;
if (getDisplayMode() == DisplayMode.EXPANDED) {
h = expandedHeight;
} else if (getDisplayMode() == DisplayMode.COLLAPSED) {
h = collapsedHeight;
} else {
int visHeight = visibleRect.height;
int depth = dataManager.getNLevels();
if (depth == 0) {
squishedHeight = Math.min(maxSquishedHeight, Math.max(1, expandedHeight));
} else {
squishedHeight = Math.min(maxSquishedHeight, Math.max(1, Math.min(expandedHeight, visHeight / depth)));
}
h = squishedHeight;
}
// Loop through groups
Graphics2D groupBorderGraphics = context.getGraphic2DForColor(AlignmentRenderer.GROUP_DIVIDER_COLOR);
int nGroups = groups.size();
int groupNumber = 0;
GroupOption groupOption = renderOptions.getGroupByOption();
for (Map.Entry<String, List<Row>> entry : groups.entrySet()) {
groupNumber++;
double yGroup = y; // Remember this for label
// Loop through the alignment rows for this group
List<Row> rows = entry.getValue();
for (Row row : rows) {
if ((visibleRect != null && y > visibleRect.getMaxY())) {
break;
}
assert visibleRect != null;
if (y + h > visibleRect.getY()) {
Rectangle rowRectangle = new Rectangle(inputRect.x, (int) y, inputRect.width, (int) h);
renderer.renderAlignments(row.alignments, alignmentCounts, context, rowRectangle, renderOptions);
row.y = y;
row.h = h;
}
y += h;
}
if (groupOption != GroupOption.NONE) {
// Draw a subtle divider line between groups
if (showGroupLine) {
if (groupNumber < nGroups) {
int borderY = (int) y + GROUP_MARGIN / 2;
GraphicUtils.drawDottedDashLine(groupBorderGraphics, inputRect.x, borderY, inputRect.width, borderY);
}
}
// Label the group, if there is room
double groupHeight = rows.size() * h;
if (groupHeight > GROUP_LABEL_HEIGHT + 2) {
String groupName = entry.getKey();
Graphics2D g = context.getGraphics2D("LABEL");
FontMetrics fm = g.getFontMetrics();
Rectangle2D stringBouds = fm.getStringBounds(groupName, g);
Rectangle rect = new Rectangle(inputRect.x, (int) yGroup,
(int) stringBouds.getWidth() + 10, (int) stringBouds.getHeight());
GraphicUtils.drawVerticallyCenteredText(groupName, 5, rect, g, false, true);
}
}
y += GROUP_MARGIN;
}
final int bottom = inputRect.y + inputRect.height;
groupBorderGraphics.drawLine(inputRect.x, bottom, inputRect.width, bottom);
}
private List<InsertionInterval> getInsertionIntervals(ReferenceFrame frame) {
List<InsertionInterval> insertionIntervals = insertionIntervalsMap.computeIfAbsent(frame, k -> new ArrayList<>());
return insertionIntervals;
}
private void renderInsertionIntervals(RenderContext context, Rectangle rect) {
// Might be offscreen
if (!context.getVisibleRect().intersects(rect)) return;
List<InsertionMarker> intervals = context.getInsertionMarkers();
if (intervals == null) return;
InsertionMarker selected = InsertionManager.getInstance().getSelectedInsertion(context.getChr());
int w = (int) ((1.41 * rect.height) / 2);
boolean hideSmallIndels = renderOptions.isHideSmallIndels();
int smallIndelThreshold = renderOptions.getSmallIndelThreshold();
List<InsertionInterval> insertionIntervals = getInsertionIntervals(context.getReferenceFrame());
insertionIntervals.clear();
for (InsertionMarker insertionMarker : intervals) {
if (hideSmallIndels && insertionMarker.size < smallIndelThreshold) continue;
final double scale = context.getScale();
final double origin = context.getOrigin();
int midpoint = (int) ((insertionMarker.position - origin) / scale);
int x0 = midpoint - w;
int x1 = midpoint + w;
Rectangle iRect = new Rectangle(x0 + context.translateX, rect.y, 2 * w, rect.height);
insertionIntervals.add(new InsertionInterval(iRect, insertionMarker));
Color c = (selected != null && selected.position == insertionMarker.position) ? new Color(200, 0, 0, 80) : AlignmentRenderer.purple;
Graphics2D g = context.getGraphic2DForColor(c);
g.fillPolygon(new Polygon(new int[]{x0, x1, midpoint},
new int[]{rect.y, rect.y, rect.y + rect.height}, 3));
}
}
public void renderExpandedInsertion(InsertionMarker insertionMarker, RenderContext context, Rectangle inputRect) {
boolean leaveMargin = getDisplayMode() != DisplayMode.SQUISHED;
// Insertion interval
Graphics2D g = context.getGraphic2DForColor(Color.red);
Rectangle iRect = new Rectangle(inputRect.x, insertionRect.y, inputRect.width, insertionRect.height);
g.fill(iRect);
List<InsertionInterval> insertionIntervals = getInsertionIntervals(context.getReferenceFrame());
iRect.x += context.translateX;
insertionIntervals.add(new InsertionInterval(iRect, insertionMarker));
inputRect.y += DS_MARGIN_0 + DOWNAMPLED_ROW_HEIGHT + DS_MARGIN_0 + INSERTION_ROW_HEIGHT + DS_MARGIN_2;
//log.debug("Render features");
final AlignmentInterval loadedInterval = dataManager.getLoadedInterval(context.getReferenceFrame(), true);
PackedAlignments groups = dataManager.getGroups(loadedInterval, renderOptions);
if (groups == null) {
//Assume we are still loading.
//This might not always be true
return;
}
Rectangle visibleRect = context.getVisibleRect();
// Divide rectangle into equal height levels
double y = inputRect.getY() - 3;
double h;
if (getDisplayMode() == DisplayMode.EXPANDED) {
h = expandedHeight;
} else if (getDisplayMode() == DisplayMode.COLLAPSED) {
h = collapsedHeight;
} else {
int visHeight = visibleRect.height;
int depth = dataManager.getNLevels();
if (depth == 0) {
squishedHeight = Math.min(maxSquishedHeight, Math.max(1, expandedHeight));
} else {
squishedHeight = Math.min(maxSquishedHeight, Math.max(1, Math.min(expandedHeight, visHeight / depth)));
}
h = squishedHeight;
}
for (Map.Entry<String, List<Row>> entry : groups.entrySet()) {
// Loop through the alignment rows for this group
List<Row> rows = entry.getValue();
for (Row row : rows) {
if ((visibleRect != null && y > visibleRect.getMaxY())) {
return;
}
assert visibleRect != null;
if (y + h > visibleRect.getY()) {
Rectangle rowRectangle = new Rectangle(inputRect.x, (int) y, inputRect.width, (int) h);
renderer.renderExpandedInsertion(insertionMarker, row.alignments, context, rowRectangle, leaveMargin);
row.y = y;
row.h = h;
}
y += h;
}
y += GROUP_MARGIN;
}
}
private InsertionInterval getInsertionInterval(ReferenceFrame frame, int x, int y) {
List<InsertionInterval> insertionIntervals = getInsertionIntervals(frame);
for (InsertionInterval i : insertionIntervals) {
if (i.rect.contains(x, y)) return i;
}
return null;
}
/**
* Sort alignment rows based on alignments that intersect location
*
* @return Whether sorting was performed. If data is still loading, this will return false
*/
public boolean sortRows(SortOption option, ReferenceFrame referenceFrame, double location, String tag) {
return dataManager.sortRows(option, referenceFrame, location, tag);
}
private static void sortAlignmentTracks(SortOption option, String tag) {
IGV.getInstance().sortAlignmentTracks(option, tag);
Collection<IGVPreferences> allPrefs = PreferencesManager.getAllPreferences();
for (IGVPreferences prefs : allPrefs) {
prefs.put(SAM_SORT_OPTION, option.toString());
prefs.put(SAM_SORT_BY_TAG, tag);
}
}
/**
* Visually regroup alignments by the provided {@code GroupOption}.
*
* @param option
* @see AlignmentDataManager#packAlignments
*/
public void groupAlignments(GroupOption option, String tag, Range pos) {
if (option == GroupOption.TAG && tag != null) {
renderOptions.setGroupByTag(tag);
}
if (option == GroupOption.BASE_AT_POS && pos != null) {
renderOptions.setGroupByPos(pos);
}
renderOptions.setGroupByOption(option);
dataManager.packAlignments(renderOptions);
}
public void setBisulfiteContext(BisulfiteContext option) {
renderOptions.bisulfiteContext = option;
getPreferences().put(SAM_BISULFITE_CONTEXT, option.toString());
}
public void setColorOption(ColorOption option) {
renderOptions.setColorOption(option);
}
public void setColorByTag(String tag) {
renderOptions.setColorByTag(tag);
getPreferences(experimentType).put(SAM_COLOR_BY_TAG, tag);
}
public void packAlignments() {
dataManager.packAlignments(renderOptions);
}
/**
* Copy the contents of the popup text to the system clipboard.
*/
private void copyToClipboard(final TrackClickEvent e, Alignment alignment, double location, int mouseX) {
if (alignment != null) {
StringBuilder buf = new StringBuilder();
buf.append(alignment.getClipboardString(location, mouseX)
.replace("<b>", "")
.replace("</b>", "")
.replace("<br>", "\n")
.replace("<br/>", "\n")
.replace("<hr>", "\n
.replace("<hr/>", "\n
buf.append("\n");
buf.append("Alignment start position = ").append(alignment.getChr()).append(":").append(alignment.getAlignmentStart() + 1);
buf.append("\n");
buf.append(alignment.getReadSequence());
StringSelection stringSelection = new StringSelection(buf.toString());
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(stringSelection, null);
}
}
/**
* Jump to the mate region
*/
private void gotoMate(final TrackClickEvent te, Alignment alignment) {
if (alignment != null) {
ReadMate mate = alignment.getMate();
if (mate != null && mate.isMapped()) {
setSelected(alignment);
String chr = mate.getChr();
int start = mate.start - 1;
// Don't change scale
double range = te.getFrame().getEnd() - te.getFrame().getOrigin();
int newStart = (int) Math.max(0, (start + (alignment.getEnd() - alignment.getStart()) / 2 - range / 2));
int newEnd = newStart + (int) range;
te.getFrame().jumpTo(chr, newStart, newEnd);
te.getFrame().recordHistory();
} else {
MessageUtils.showMessage("Alignment does not have mate, or it is not mapped.");
}
}
}
/**
* Split the screen so the current view and mate region are side by side.
* Need a better name for this method.
*/
private void splitScreenMate(final TrackClickEvent te, Alignment alignment) {
if (alignment != null) {
ReadMate mate = alignment.getMate();
if (mate != null && mate.isMapped()) {
setSelected(alignment);
String mateChr = mate.getChr();
int mateStart = mate.start - 1;
ReferenceFrame frame = te.getFrame();
String locus1 = frame.getFormattedLocusString();
// Generate a locus string for the read mate. Keep the window width (in base pairs) == to the current range
Range range = frame.getCurrentRange();
int length = range.getLength();
int s2 = Math.max(0, mateStart - length / 2);
int e2 = s2 + length;
String startStr = String.valueOf(s2);
String endStr = String.valueOf(e2);
String mateLocus = mateChr + ":" + startStr + "-" + endStr;
Session currentSession = IGV.getInstance().getSession();
List<String> loci;
if (FrameManager.isGeneListMode()) {
loci = new ArrayList<>(FrameManager.getFrames().size());
for (ReferenceFrame ref : FrameManager.getFrames()) {
//If the frame-name is a locus, we use it unaltered
//Don't want to reprocess, easy to get off-by-one
String name = ref.getName();
if (Locus.fromString(name) != null) {
loci.add(name);
} else {
loci.add(ref.getFormattedLocusString());
}
}
loci.add(mateLocus);
} else {
loci = Arrays.asList(locus1, mateLocus);
}
StringBuilder listName = new StringBuilder();
for (String s : loci) {
listName.append(s + " ");
}
GeneList geneList = new GeneList(listName.toString(), loci, false);
currentSession.setCurrentGeneList(geneList);
Comparator<String> geneListComparator = (n0, n1) -> {
ReferenceFrame f0 = FrameManager.getFrame(n0);
ReferenceFrame f1 = FrameManager.getFrame(n1);
String chr0 = f0 == null ? "" : f0.getChrName();
String chr1 = f1 == null ? "" : f1.getChrName();
int s0 = f0 == null ? 0 : f0.getCurrentRange().getStart();
int s1 = f1 == null ? 0 : f1.getCurrentRange().getStart();
int chrComp = ChromosomeNameComparator.get().compare(chr0, chr1);
if (chrComp != 0) return chrComp;
return s0 - s1;
};
//Need to sort the frames by position
currentSession.sortGeneList(geneListComparator);
IGV.getInstance().resetFrames();
} else {
MessageUtils.showMessage("Alignment does not have mate, or it is not mapped.");
}
}
}
public boolean isLogNormalized() {
return false;
}
public float getRegionScore(String chr, int start, int end, int zoom, RegionScoreType type, String frameName) {
return 0.0f;
}
public String getValueStringAt(String chr, double position, int mouseX, int mouseY, ReferenceFrame frame) {
if (downsampleRect != null && mouseY > downsampleRect.y && mouseY <= downsampleRect.y + downsampleRect.height) {
AlignmentInterval loadedInterval = dataManager.getLoadedInterval(frame);
if (loadedInterval == null) {
return null;
} else {
List<DownsampledInterval> intervals = loadedInterval.getDownsampledIntervals();
DownsampledInterval interval = FeatureUtils.getFeatureAt(position, 0, intervals);
if (interval != null) {
return interval.getValueString();
}
return null;
}
} else {
InsertionInterval insertionInterval = getInsertionInterval(frame, mouseX, mouseY);
if (insertionInterval != null) {
return "Insertions (" + insertionInterval.insertionMarker.size + " bases)";
} else {
Alignment feature = getAlignmentAt(position, mouseY, frame);
if (feature != null) {
return feature.getAlignmentValueString(position, mouseX, renderOptions);
}
}
}
return null;
}
private Alignment getAlignment(final TrackClickEvent te) {
MouseEvent e = te.getMouseEvent();
final ReferenceFrame frame = te.getFrame();
if (frame == null) {
return null;
}
final double location = frame.getChromosomePosition(e.getX());
return getAlignmentAt(location, e.getY(), frame);
}
private Alignment getAlignmentAt(double position, int y, ReferenceFrame frame) {
if (alignmentsRect == null || dataManager == null) {
return null; // <= not loaded yet
}
PackedAlignments groups = dataManager.getGroupedAlignmentsContaining(position, frame);
if (groups == null || groups.isEmpty()) {
return null;
}
for (List<Row> rows : groups.values()) {
for (Row row : rows) {
if (y >= row.y && y <= row.y + row.h) {
List<Alignment> features = row.alignments;
// No buffer for alignments, you must zoom in far enough for them to be visible
int buffer = 0;
return FeatureUtils.getFeatureAt(position, buffer, features);
}
}
}
return null;
}
/**
* Get the most "specific" alignment at the specified location. Specificity refers to the smallest alignemnt
* in a group that contains the location (i.e. if a group of linked alignments overlap take the smallest one).
*
* @param te
* @return
*/
private Alignment getSpecficAlignment(TrackClickEvent te) {
Alignment alignment = getAlignment(te);
if (alignment != null) {
final ReferenceFrame frame = te.getFrame();
MouseEvent e = te.getMouseEvent();
final double location = frame.getChromosomePosition(e.getX());
if (alignment instanceof LinkedAlignment) {
Alignment sa = null;
for (Alignment a : ((LinkedAlignment) alignment).alignments) {
if (a.contains(location)) {
if (sa == null || (a.getAlignmentEnd() - a.getAlignmentStart() < sa.getAlignmentEnd() - sa.getAlignmentStart())) {
sa = a;
}
}
}
alignment = sa;
} else if (alignment instanceof PairedAlignment) {
Alignment sa = null;
if (((PairedAlignment) alignment).firstAlignment.contains(location)) {
sa = ((PairedAlignment) alignment).firstAlignment;
} else if (((PairedAlignment) alignment).secondAlignment.contains(location)) {
sa = ((PairedAlignment) alignment).secondAlignment;
}
alignment = sa;
}
}
return alignment;
}
@Override
public boolean handleDataClick(TrackClickEvent te) {
MouseEvent e = te.getMouseEvent();
if (Globals.IS_MAC && e.isMetaDown() || (!Globals.IS_MAC && e.isControlDown())) {
// Selection
final ReferenceFrame frame = te.getFrame();
if (frame != null) {
selectAlignment(e, frame);
IGV.getInstance().repaint(this);
return true;
}
}
InsertionInterval insertionInterval = getInsertionInterval(te.getFrame(), te.getMouseEvent().getX(), te.getMouseEvent().getY());
if (insertionInterval != null) {
final String chrName = te.getFrame().getChrName();
InsertionMarker currentSelection = InsertionManager.getInstance().getSelectedInsertion(chrName);
if (currentSelection != null && currentSelection.position == insertionInterval.insertionMarker.position) {
InsertionManager.getInstance().clearSelected();
} else {
InsertionManager.getInstance().setSelected(chrName, insertionInterval.insertionMarker.position);
}
IGVEventBus.getInstance().post(new InsertionSelectionEvent(insertionInterval.insertionMarker));
return true;
}
if (IGV.getInstance().isShowDetailsOnClick()) {
openTooltipWindow(te);
return true;
}
return false;
}
private void selectAlignment(MouseEvent e, ReferenceFrame frame) {
double location = frame.getChromosomePosition(e.getX());
Alignment alignment = this.getAlignmentAt(location, e.getY(), frame);
if (alignment != null) {
if (selectedReadNames.containsKey(alignment.getReadName())) {
selectedReadNames.remove(alignment.getReadName());
} else {
setSelected(alignment);
}
}
}
private void setSelected(Alignment alignment) {
Color c = readNamePalette.get(alignment.getReadName());
selectedReadNames.put(alignment.getReadName(), c);
}
private void clearCaches() {
if (dataManager != null) dataManager.clear();
if (spliceJunctionTrack != null) spliceJunctionTrack.clear();
}
public void setViewAsPairs(boolean vAP) {
// TODO -- generalize this test to all incompatible pairings
if (vAP && renderOptions.groupByOption == GroupOption.STRAND) {
boolean ungroup = MessageUtils.confirm("\"View as pairs\" is incompatible with \"Group by strand\". Ungroup?");
if (ungroup) {
renderOptions.setGroupByOption(null);
} else {
return;
}
}
dataManager.setViewAsPairs(vAP, renderOptions);
repaint();
}
public enum ExperimentType {OTHER, RNA, BISULFITE, THIRD_GEN}
class RenderRollback {
final ColorOption colorOption;
final GroupOption groupByOption;
final String groupByTag;
final String colorByTag;
final String linkByTag;
final DisplayMode displayMode;
final int expandedHeight;
final boolean showGroupLine;
RenderRollback(RenderOptions renderOptions, DisplayMode displayMode) {
this.colorOption = renderOptions.colorOption;
this.groupByOption = renderOptions.groupByOption;
this.colorByTag = renderOptions.colorByTag;
this.groupByTag = renderOptions.groupByTag;
this.displayMode = displayMode;
this.expandedHeight = AlignmentTrack.this.expandedHeight;
this.showGroupLine = AlignmentTrack.this.showGroupLine;
this.linkByTag = renderOptions.linkByTag;
}
void restore(RenderOptions renderOptions) {
renderOptions.colorOption = this.colorOption;
renderOptions.groupByOption = this.groupByOption;
renderOptions.colorByTag = this.colorByTag;
renderOptions.groupByTag = this.groupByTag;
renderOptions.linkByTag = this.linkByTag;
AlignmentTrack.this.expandedHeight = this.expandedHeight;
AlignmentTrack.this.showGroupLine = this.showGroupLine;
AlignmentTrack.this.setDisplayMode(this.displayMode);
}
}
public boolean isRemoved() {
return removed;
}
@Override
public boolean isVisible() {
return super.isVisible() && !removed;
}
IGVPreferences getPreferences() {
return getPreferences(experimentType);
}
public static IGVPreferences getPreferences(ExperimentType type) {
try {
// Disable experimentType preferences for 2.4
if (Globals.VERSION.contains("2.4")) {
return PreferencesManager.getPreferences(NULL_CATEGORY);
} else {
String prefKey = Constants.NULL_CATEGORY;
if (type == ExperimentType.THIRD_GEN) {
prefKey = Constants.THIRD_GEN;
} else if (type == ExperimentType.RNA) {
prefKey = Constants.RNA;
}
return PreferencesManager.getPreferences(prefKey);
}
} catch (NullPointerException e) {
String prefKey = Constants.NULL_CATEGORY;
if (type == ExperimentType.THIRD_GEN) {
prefKey = Constants.THIRD_GEN;
} else if (type == ExperimentType.RNA) {
prefKey = Constants.RNA;
}
return PreferencesManager.getPreferences(prefKey);
}
}
@Override
public void unload() {
super.unload();
if (dataManager != null) {
dataManager.unsubscribe(this);
}
removed = true;
setVisible(false);
}
private boolean isLinkedReads() {
return renderOptions != null && renderOptions.isLinkedReads();
}
private void setLinkedReadView(boolean linkedReads, String tag) {
if (!linkedReads || isLinkedReadView()) {
undoLinkedReadView();
}
renderOptions.setLinkedReads(linkedReads);
if (linkedReads) {
renderOptions.setLinkByTag(tag);
renderOptions.setColorOption(ColorOption.TAG);
renderOptions.setColorByTag(tag);
if (dataManager.isPhased()) {
renderOptions.setGroupByOption(GroupOption.TAG);
renderOptions.setGroupByTag("HP");
}
showGroupLine = false;
setDisplayMode(DisplayMode.SQUISHED);
}
dataManager.packAlignments(renderOptions);
repaint();
}
/**
* Detect if we are in linked-read view
*/
private boolean isLinkedReadView() {
return renderOptions != null &&
renderOptions.isLinkedReads() &&
renderOptions.getLinkByTag() != null &&
renderOptions.getColorOption() == ColorOption.TAG &&
renderOptions.getColorByTag() != null;
}
/**
* Link alignments by arbitrary tag, without the extra settings applied to link-read-view
*
* @param linkReads
* @param tag
*/
private void setLinkByTag(boolean linkReads, String tag) {
if (isLinkedReadView()) {
undoLinkedReadView();
}
if (linkReads) {
renderOptions.setLinkByTag(tag);
if (renderOptions.getGroupByOption() == GroupOption.NONE) {
renderOptions.setGroupByOption(GroupOption.LINKED);
}
} else {
renderOptions.setLinkByTag(null);
if (renderOptions.getGroupByOption() == GroupOption.LINKED) {
renderOptions.setGroupByOption(GroupOption.NONE);
}
}
renderOptions.setLinkedReads(linkReads);
dataManager.packAlignments(renderOptions);
repaint();
}
private void undoLinkedReadView() {
renderOptions.setLinkByTag(null);
renderOptions.setColorOption(ColorOption.NONE);
renderOptions.setColorByTag(null);
renderOptions.setGroupByOption(GroupOption.NONE);
renderOptions.setGroupByTag(null);
showGroupLine = true;
setDisplayMode(DisplayMode.EXPANDED);
}
private void sendPairsToCircularView(TrackClickEvent e) {
List<ReferenceFrame> frames = e.getFrame() != null ?
Arrays.asList(e.getFrame()) :
FrameManager.getFrames();
List<Alignment> inView = new ArrayList<>();
for (ReferenceFrame frame : frames) {
AlignmentInterval interval = AlignmentTrack.this.getDataManager().getLoadedInterval(frame);
if (interval != null) {
Iterator<Alignment> iter = interval.getAlignmentIterator();
Range r = frame.getCurrentRange();
while (iter.hasNext()) {
Alignment a = iter.next();
if (a.getEnd() > r.getStart() && a.getStart() < r.getEnd()) {
final boolean isDiscordantPair = a.isPaired() && a.getMate().isMapped() &&
(!a.getMate().getChr().equals(a.getChr()) || Math.abs(a.getInferredInsertSize()) > 10000);
if (isDiscordantPair) {
inView.add(a);
}
}
}
}
Color chordColor = AlignmentTrack.this.getColor().equals(DEFAULT_ALIGNMENT_COLOR) ? Color.BLUE : AlignmentTrack.this.getColor();
CircularViewUtilities.sendAlignmentsToJBrowse(inView, AlignmentTrack.this.getName(), chordColor);
}
}
private void sendSplitToCircularView(TrackClickEvent e) {
List<ReferenceFrame> frames = e.getFrame() != null ?
Arrays.asList(e.getFrame()) :
FrameManager.getFrames();
List<Alignment> inView = new ArrayList<>();
for (ReferenceFrame frame : frames) {
AlignmentInterval interval = AlignmentTrack.this.getDataManager().getLoadedInterval(frame);
if (interval != null) {
Iterator<Alignment> iter = interval.getAlignmentIterator();
Range r = frame.getCurrentRange();
while (iter.hasNext()) {
Alignment a = iter.next();
if (a.getEnd() > r.getStart() && a.getStart() < r.getEnd() && a.getAttribute("SA") != null) {
inView.add(a);
}
}
}
Color chordColor = AlignmentTrack.this.getColor().equals(DEFAULT_ALIGNMENT_COLOR) ? Color.BLUE : AlignmentTrack.this.getColor();
CircularViewUtilities.sendAlignmentsToJBrowse(inView, AlignmentTrack.this.getName(), chordColor);
}
}
/**
* Listener for deselecting one component when another is selected
*/
private static class Deselector implements ActionListener {
private final JMenuItem toDeselect;
private final JMenuItem parent;
Deselector(JMenuItem parent, JMenuItem toDeselect) {
this.parent = parent;
this.toDeselect = toDeselect;
}
@Override
public void actionPerformed(ActionEvent e) {
if (this.parent.isSelected()) {
this.toDeselect.setSelected(false);
}
}
}
private static class InsertionInterval {
final Rectangle rect;
final InsertionMarker insertionMarker;
InsertionInterval(Rectangle rect, InsertionMarker insertionMarker) {
this.rect = rect;
this.insertionMarker = insertionMarker;
}
}
/**
* Popup menu class for AlignmentTrack. The menu gets instantiated from TrackPanelComponent on right-click in the
* alignment track or its associated name panel.
*/
class PopupMenu extends IGVPopupMenu {
PopupMenu(final TrackClickEvent e) {
final MouseEvent me = e.getMouseEvent();
final ReferenceFrame frame = e.getFrame();
final Alignment clickedAlignment = (frame == null) ? null :
getAlignmentAt(frame.getChromosomePosition(me.getX()), me.getY(), frame);
// Title
JLabel popupTitle = new JLabel(" " + AlignmentTrack.this.getName(), JLabel.CENTER);
Font newFont = getFont().deriveFont(Font.BOLD, 12);
popupTitle.setFont(newFont);
add(popupTitle);
// Circular view items -- optional
if (PreferencesManager.getPreferences().getAsBoolean(CIRC_VIEW_ENABLED) && CircularViewUtilities.ping()) {
addSeparator();
JMenuItem item = new JMenuItem("Add Discordant Pairs to Circular View");
item.setEnabled(dataManager.isPairedEnd());
add(item);
item.addActionListener(ae -> AlignmentTrack.this.sendPairsToCircularView(e));
JMenuItem item2 = new JMenuItem("Add Split Reads to Circular View");
add(item2);
item2.addActionListener(ae -> AlignmentTrack.this.sendSplitToCircularView(e));
}
// Some generic items from TrackMenuUtils
Collection<Track> tracks = List.of(AlignmentTrack.this);
addSeparator();
add(TrackMenuUtils.getTrackRenameItem(tracks));
addCopyToClipboardItem(e, clickedAlignment);
addSeparator();
JMenuItem item = new JMenuItem("Change Track Color...");
item.addActionListener(evt -> TrackMenuUtils.changeTrackColor(tracks));
add(item);
// Experiment type (RNA, THIRD GEN, OTHER)
addSeparator();
addExperimentTypeMenuItem();
if (experimentType == ExperimentType.THIRD_GEN) {
addHaplotype(e);
}
// Linked read items
addLinkedReadItems();
// Group, sort, color, and pack
addSeparator();
addGroupMenuItem(e);
addSortMenuItem();
addColorByMenuItem();
//addFilterMenuItem();
addPackMenuItem();
// Shading and mismatch items
addSeparator();
addShadeBaseByMenuItem();
JMenuItem misMatchesItem = addShowMismatchesMenuItem();
JMenuItem showAllItem = addShowAllBasesMenuItem();
misMatchesItem.addActionListener(new Deselector(misMatchesItem, showAllItem));
showAllItem.addActionListener(new Deselector(showAllItem, misMatchesItem));
// Paired end items
addSeparator();
addViewAsPairsMenuItem();
if (clickedAlignment != null) {
addGoToMate(e, clickedAlignment);
showMateRegion(e, clickedAlignment);
}
addInsertSizeMenuItem();
// Third gen (primarily) items
addSeparator();
addThirdGenItems();
// Display mode items
addSeparator();
TrackMenuUtils.addDisplayModeItems(tracks, this);
// Select alignment items
addSeparator();
addSelectByNameItem();
addClearSelectionsMenuItem();
// Copy items
addSeparator();
addCopySequenceItems(e);
addConsensusSequence(e);
// Blat items
addSeparator();
addBlatItem(e);
addBlatClippingItems(e);
// Insertion items, only if clicked over an insertion
AlignmentBlock insertion = getInsertion(clickedAlignment, e.getMouseEvent().getX());
if (insertion != null) {
addSeparator();
addInsertionItems(insertion);
}
// Sashimi plot, probably should be depdenent on experimentType (RNA)
addSeparator();
JMenuItem sashimi = new JMenuItem("Sashimi Plot");
sashimi.addActionListener(e1 -> SashimiPlot.getSashimiPlot(null));
add(sashimi);
// Show alignments, coverage, splice junctions
addSeparator();
addShowItems();
}
private void addHaplotype(TrackClickEvent e) {
JMenuItem item = new JMenuItem("Cluster (phase) alignments");
final ReferenceFrame frame;
if (e.getFrame() == null && FrameManager.getFrames().size() == 1) {
frame = FrameManager.getFrames().get(0);
} else {
frame = e.getFrame();
}
item.setEnabled(frame != null);
add(item);
item.addActionListener(ae -> {
//This shouldn't ever be true, but just in case it's more user-friendly
if (frame == null) {
MessageUtils.showMessage("Unknown region bounds");
return;
}
String nString = MessageUtils.showInputDialog("Enter the number of clusters", String.valueOf(AlignmentTrack.nClusters));
if (nString == null) {
return;
}
try {
AlignmentTrack.nClusters = Integer.parseInt(nString);
} catch (NumberFormatException e1) {
MessageUtils.showMessage("Clusters size must be an integer");
return;
}
final int start = (int) frame.getOrigin();
final int end = (int) frame.getEnd();
AlignmentInterval interval = dataManager.getLoadedInterval(frame);
HaplotypeUtils haplotypeUtils = new HaplotypeUtils(interval, AlignmentTrack.this.genome);
boolean success = haplotypeUtils.clusterAlignments(frame.getChrName(), start, end, AlignmentTrack.nClusters);
if (success) {
AlignmentTrack.this.groupAlignments(GroupOption.HAPLOTYPE, null, null);
AlignmentTrack.this.repaint();
}
//dataManager.sortRows(SortOption.HAPLOTYPE, frame, (end + start) / 2, null);
//AlignmentTrack.repaint();
});
}
/**
* Item for exporting "consensus" sequence of region, based on loaded alignments.
*
* @param e
*/
private void addConsensusSequence(TrackClickEvent e) {
JMenuItem item = new JMenuItem("Copy consensus sequence");
final ReferenceFrame frame;
if (e.getFrame() == null && FrameManager.getFrames().size() == 1) {
frame = FrameManager.getFrames().get(0);
} else {
frame = e.getFrame();
}
item.setEnabled(frame != null);
add(item);
item.addActionListener(ae -> {
if (frame == null) { // Should never happen
MessageUtils.showMessage("Unknown region bounds, cannot export consensus");
return;
}
final int start = (int) frame.getOrigin();
final int end = (int) frame.getEnd();
if ((end - start) > 1000000) {
MessageUtils.showMessage("Cannot export region more than 1 Megabase");
return;
}
AlignmentInterval interval = dataManager.getLoadedInterval(frame);
AlignmentCounts counts = interval.getCounts();
String text = PFMExporter.createPFMText(counts, frame.getChrName(), start, end);
StringUtils.copyTextToClipboard(text);
});
}
private JMenu getBisulfiteContextMenuItem(ButtonGroup group) {
JMenu bisulfiteContextMenu = new JMenu("bisulfite mode");
JRadioButtonMenuItem nomeESeqOption = null;
boolean showNomeESeq = getPreferences().getAsBoolean(SAM_NOMESEQ_ENABLED);
if (showNomeESeq) {
nomeESeqOption = new JRadioButtonMenuItem("NOMe-seq bisulfite mode");
nomeESeqOption.setSelected(renderOptions.getColorOption() == ColorOption.NOMESEQ);
nomeESeqOption.addActionListener(aEvt -> {
setColorOption(ColorOption.NOMESEQ);
AlignmentTrack.this.repaint();
});
group.add(nomeESeqOption);
}
for (final BisulfiteContext item : BisulfiteContext.values()) {
String optionStr = getBisulfiteContextPubStr(item);
JRadioButtonMenuItem m1 = new JRadioButtonMenuItem(optionStr);
m1.setSelected(renderOptions.bisulfiteContext == item);
m1.addActionListener(aEvt -> {
setColorOption(ColorOption.BISULFITE);
setBisulfiteContext(item);
AlignmentTrack.this.repaint();
});
bisulfiteContextMenu.add(m1);
group.add(m1);
}
if (nomeESeqOption != null) {
bisulfiteContextMenu.add(nomeESeqOption);
}
return bisulfiteContextMenu;
}
void addSelectByNameItem() {
// Change track height by attribute
JMenuItem item = new JMenuItem("Select by name...");
item.addActionListener(aEvt -> {
String val = MessageUtils.showInputDialog("Enter read name: ");
if (val != null && val.trim().length() > 0) {
selectedReadNames.put(val, readNamePalette.get(val));
AlignmentTrack.this.repaint();
}
});
add(item);
}
void addExperimentTypeMenuItem() {
Map<String, ExperimentType> mappings = new LinkedHashMap<>();
mappings.put("Other", ExperimentType.OTHER);
mappings.put("RNA", ExperimentType.RNA);
mappings.put("3rd Gen", ExperimentType.THIRD_GEN);
//mappings.put("Bisulfite", ExperimentType.BISULFITE);
JMenu groupMenu = new JMenu("Experiment Type");
ButtonGroup group = new ButtonGroup();
for (Map.Entry<String, ExperimentType> el : mappings.entrySet()) {
JCheckBoxMenuItem mi = getExperimentTypeMenuItem(el.getKey(), el.getValue());
groupMenu.add(mi);
group.add(mi);
}
add(groupMenu);
}
private JCheckBoxMenuItem getExperimentTypeMenuItem(String label, final ExperimentType option) {
JCheckBoxMenuItem mi = new JCheckBoxMenuItem(label);
mi.setSelected(AlignmentTrack.this.getExperimentType() == option);
mi.addActionListener(aEvt -> AlignmentTrack.this.setExperimentType(option));
return mi;
}
void addGroupMenuItem(final TrackClickEvent te) {//ReferenceFrame frame) {
final MouseEvent me = te.getMouseEvent();
ReferenceFrame frame = te.getFrame();
if (frame == null) {
frame = FrameManager.getDefaultFrame(); // Clicked over name panel, not a specific frame
}
final Range range = frame.getCurrentRange();
final String chrom = range.getChr();
final int chromStart = (int) frame.getChromosomePosition(me.getX());
// Change track height by attribute
JMenu groupMenu = new JMenu("Group alignments by");
ButtonGroup group = new ButtonGroup();
GroupOption[] groupOptions = {
GroupOption.NONE, GroupOption.STRAND, GroupOption.FIRST_OF_PAIR_STRAND, GroupOption.SAMPLE,
GroupOption.LIBRARY, GroupOption.READ_GROUP, GroupOption.MATE_CHROMOSOME,
GroupOption.PAIR_ORIENTATION, GroupOption.SUPPLEMENTARY, GroupOption.REFERENCE_CONCORDANCE,
GroupOption.MOVIE, GroupOption.ZMW, GroupOption.READ_ORDER, GroupOption.LINKED, GroupOption.PHASE
};
for (final GroupOption option : groupOptions) {
JCheckBoxMenuItem mi = new JCheckBoxMenuItem(option.label);
mi.setSelected(renderOptions.getGroupByOption() == option);
mi.addActionListener(aEvt -> {
groupAlignments(option, null, null);
});
groupMenu.add(mi);
group.add(mi);
}
JCheckBoxMenuItem tagOption = new JCheckBoxMenuItem("tag");
tagOption.addActionListener(aEvt -> {
String tag = MessageUtils.showInputDialog("Enter tag", renderOptions.getGroupByTag());
if (tag != null) {
if (tag.trim().length() > 0) {
groupAlignments(GroupOption.TAG, tag, null);
} else {
groupAlignments(GroupOption.NONE, null, null);
}
}
});
tagOption.setSelected(renderOptions.getGroupByOption() == GroupOption.TAG);
groupMenu.add(tagOption);
group.add(tagOption);
Range oldGroupByPos = renderOptions.getGroupByPos();
if (oldGroupByPos != null && renderOptions.getGroupByOption() == GroupOption.BASE_AT_POS) { // already sorted by the base at a position
JCheckBoxMenuItem oldGroupByPosOption = new JCheckBoxMenuItem("base at " + oldGroupByPos.getChr() +
":" + Globals.DECIMAL_FORMAT.format(1 + oldGroupByPos.getStart()));
groupMenu.add(oldGroupByPosOption);
oldGroupByPosOption.setSelected(true);
}
if (renderOptions.getGroupByOption() != GroupOption.BASE_AT_POS || oldGroupByPos == null ||
!oldGroupByPos.getChr().equals(chrom) || oldGroupByPos.getStart() != chromStart) { // not already sorted by this position
JCheckBoxMenuItem newGroupByPosOption = new JCheckBoxMenuItem("base at " + chrom +
":" + Globals.DECIMAL_FORMAT.format(1 + chromStart));
newGroupByPosOption.addActionListener(aEvt -> {
Range groupByPos = new Range(chrom, chromStart, chromStart + 1);
groupAlignments(GroupOption.BASE_AT_POS, null, groupByPos);
});
groupMenu.add(newGroupByPosOption);
group.add(newGroupByPosOption);
}
add(groupMenu);
}
/**
* Sort menu
*/
void addSortMenuItem() {
JMenu sortMenu = new JMenu("Sort alignments by");
//LinkedHashMap is supposed to preserve order of insertion for iteration
Map<String, SortOption> mappings = new LinkedHashMap<>();
mappings.put("start location", SortOption.START);
mappings.put("read strand", SortOption.STRAND);
mappings.put("first-of-pair strand", SortOption.FIRST_OF_PAIR_STRAND);
mappings.put("base", SortOption.NUCLEOTIDE);
mappings.put("mapping quality", SortOption.QUALITY);
mappings.put("sample", SortOption.SAMPLE);
mappings.put("read group", SortOption.READ_GROUP);
mappings.put("read order", SortOption.READ_ORDER);
mappings.put("read name", SortOption.READ_NAME);
// mappings.put("supplementary flag", SortOption.SUPPLEMENTARY);
if (dataManager.isPairedEnd()) {
mappings.put("insert size", SortOption.INSERT_SIZE);
mappings.put("chromosome of mate", SortOption.MATE_CHR);
}
for (Map.Entry<String, SortOption> el : mappings.entrySet()) {
JMenuItem mi = new JMenuItem(el.getKey());
mi.addActionListener(aEvt -> sortAlignmentTracks(el.getValue(), null));
sortMenu.add(mi);
}
JMenuItem tagOption = new JMenuItem("tag");
tagOption.addActionListener(aEvt -> {
String tag = MessageUtils.showInputDialog("Enter tag", renderOptions.getSortByTag());
if (tag != null && tag.trim().length() > 0) {
renderOptions.setSortByTag(tag);
sortAlignmentTracks(SortOption.TAG, tag);
}
});
sortMenu.add(tagOption);
add(sortMenu);
}
public void addFilterMenuItem() {
JMenu filterMenu = new JMenu("Filter alignments by");
JMenuItem mi = new JMenuItem("mapping quality");
mi.addActionListener(aEvt -> {
// TODO -- use current value for default
String defString = PreferencesManager.getPreferences().get(SAM_QUALITY_THRESHOLD);
if (defString == null) defString = "";
String mqString = MessageUtils.showInputDialog("Minimum mapping quality: ", defString);
try {
int mq = Integer.parseInt(mqString);
// TODO do something with this
//System.out.println(mq);
} catch (NumberFormatException e) {
MessageUtils.showMessage("Mapping quality must be an integer");
}
});
filterMenu.add(mi);
add(filterMenu);
}
private JRadioButtonMenuItem getColorMenuItem(String label, final ColorOption option) {
JRadioButtonMenuItem mi = new JRadioButtonMenuItem(label);
mi.setSelected(renderOptions.getColorOption() == option);
mi.addActionListener(aEvt -> {
setColorOption(option);
AlignmentTrack.this.repaint();
});
return mi;
}
void addColorByMenuItem() {
// Change track height by attribute
JMenu colorMenu = new JMenu("Color alignments by");
ButtonGroup group = new ButtonGroup();
Map<String, ColorOption> mappings = new LinkedHashMap<>();
mappings.put("none", ColorOption.NONE);
if (dataManager.hasYCTags()) {
mappings.put("YC tag", ColorOption.YC_TAG);
}
if (dataManager.isPairedEnd()) {
mappings.put("insert size", ColorOption.INSERT_SIZE);
mappings.put("pair orientation", ColorOption.PAIR_ORIENTATION);
mappings.put("insert size and pair orientation", ColorOption.UNEXPECTED_PAIR);
}
mappings.put("read strand", ColorOption.READ_STRAND);
if (dataManager.isPairedEnd()) {
mappings.put("first-of-pair strand", ColorOption.FIRST_OF_PAIR_STRAND);
}
mappings.put("read group", ColorOption.READ_GROUP);
mappings.put("sample", ColorOption.SAMPLE);
mappings.put("library", ColorOption.LIBRARY);
mappings.put("movie", ColorOption.MOVIE);
mappings.put("ZMW", ColorOption.ZMW);
mappings.put("base modification", ColorOption.BASE_MODIFICATION);
for (Map.Entry<String, ColorOption> el : mappings.entrySet()) {
JRadioButtonMenuItem mi = getColorMenuItem(el.getKey(), el.getValue());
colorMenu.add(mi);
group.add(mi);
}
JRadioButtonMenuItem tagOption = new JRadioButtonMenuItem("tag");
tagOption.setSelected(renderOptions.getColorOption() == ColorOption.TAG);
tagOption.addActionListener(aEvt -> {
setColorOption(ColorOption.TAG);
String tag = MessageUtils.showInputDialog("Enter tag", renderOptions.getColorByTag());
if (tag != null && tag.trim().length() > 0) {
setColorByTag(tag);
AlignmentTrack.this.repaint();
}
});
colorMenu.add(tagOption);
group.add(tagOption);
colorMenu.add(getBisulfiteContextMenuItem(group));
add(colorMenu);
}
void addPackMenuItem() {
// Change track height by attribute
JMenuItem item = new JMenuItem("Re-pack alignments");
item.addActionListener(aEvt -> UIUtilities.invokeOnEventThread(() -> {
IGV.getInstance().packAlignmentTracks();
AlignmentTrack.this.repaint();
}));
add(item);
}
void addCopyToClipboardItem(final TrackClickEvent te, Alignment alignment) {
final MouseEvent me = te.getMouseEvent();
JMenuItem item = new JMenuItem("Copy read details to clipboard");
final ReferenceFrame frame = te.getFrame();
if (frame == null) {
item.setEnabled(false);
} else {
final double location = frame.getChromosomePosition(me.getX());
// Change track height by attribute
item.addActionListener(aEvt -> copyToClipboard(te, alignment, location, me.getX()));
if (alignment == null) {
item.setEnabled(false);
}
}
add(item);
}
void addViewAsPairsMenuItem() {
final JMenuItem item = new JCheckBoxMenuItem("View as pairs");
item.setSelected(renderOptions.isViewPairs());
item.addActionListener(aEvt -> {
boolean viewAsPairs = item.isSelected();
setViewAsPairs(viewAsPairs);
});
item.setEnabled(dataManager.isPairedEnd());
add(item);
}
void addGoToMate(final TrackClickEvent te, Alignment alignment) {
// Change track height by attribute
JMenuItem item = new JMenuItem("Go to mate");
MouseEvent e = te.getMouseEvent();
final ReferenceFrame frame = te.getFrame();
if (frame == null) {
item.setEnabled(false);
} else {
item.addActionListener(aEvt -> gotoMate(te, alignment));
if (alignment == null || !alignment.isPaired() || !alignment.getMate().isMapped()) {
item.setEnabled(false);
}
}
add(item);
}
void showMateRegion(final TrackClickEvent te, Alignment clickedAlignment) {
// Change track height by attribute
JMenuItem item = new JMenuItem("View mate region in split screen");
MouseEvent e = te.getMouseEvent();
final ReferenceFrame frame = te.getFrame();
if (frame == null) {
item.setEnabled(false);
} else {
double location = frame.getChromosomePosition(e.getX());
if (clickedAlignment instanceof PairedAlignment) {
Alignment first = ((PairedAlignment) clickedAlignment).getFirstAlignment();
Alignment second = ((PairedAlignment) clickedAlignment).getSecondAlignment();
if (first.contains(location)) {
clickedAlignment = first;
} else if (second.contains(location)) {
clickedAlignment = second;
} else {
clickedAlignment = null;
}
}
final Alignment alignment = clickedAlignment;
item.addActionListener(aEvt -> splitScreenMate(te, alignment));
if (alignment == null || !alignment.isPaired() || !alignment.getMate().isMapped()) {
item.setEnabled(false);
}
}
add(item);
}
void addClearSelectionsMenuItem() {
// Change track height by attribute
JMenuItem item = new JMenuItem("Clear selections");
item.addActionListener(aEvt -> {
selectedReadNames.clear();
AlignmentTrack.this.repaint();
});
add(item);
}
JMenuItem addShowAllBasesMenuItem() {
// Change track height by attribute
final JMenuItem item = new JCheckBoxMenuItem("Show all bases");
if (renderOptions.getColorOption() == ColorOption.BISULFITE || renderOptions.getColorOption() == ColorOption.NOMESEQ) {
// item.setEnabled(false);
} else {
item.setSelected(renderOptions.isShowAllBases());
}
item.addActionListener(aEvt -> {
renderOptions.setShowAllBases(item.isSelected());
AlignmentTrack.this.repaint();
});
add(item);
return item;
}
void addQuickConsensusModeItem() {
// Change track height by attribute
final JMenuItem item = new JCheckBoxMenuItem("Quick consensus mode");
item.setSelected(renderOptions.isQuickConsensusMode());
item.addActionListener(aEvt -> {
renderOptions.setQuickConsensusMode(item.isSelected());
AlignmentTrack.this.repaint();
});
add(item);
}
JMenuItem addShowMismatchesMenuItem() {
// Change track height by attribute
final JMenuItem item = new JCheckBoxMenuItem("Show mismatched bases");
item.setSelected(renderOptions.isShowMismatches());
item.addActionListener(aEvt -> {
renderOptions.setShowMismatches(item.isSelected());
AlignmentTrack.this.repaint();
});
add(item);
return item;
}
void addInsertSizeMenuItem() {
// Change track height by attribute
final JMenuItem item = new JCheckBoxMenuItem("Set insert size options ...");
item.addActionListener(aEvt -> {
InsertSizeSettingsDialog dlg = new InsertSizeSettingsDialog(IGV.getInstance().getMainFrame(), renderOptions);
dlg.setModal(true);
dlg.setVisible(true);
if (!dlg.isCanceled()) {
renderOptions.setComputeIsizes(dlg.isComputeIsize());
renderOptions.setMinInsertSizePercentile(dlg.getMinPercentile());
renderOptions.setMaxInsertSizePercentile(dlg.getMaxPercentile());
if (renderOptions.computeIsizes) {
dataManager.updatePEStats(renderOptions);
}
renderOptions.setMinInsertSize(dlg.getMinThreshold());
renderOptions.setMaxInsertSize(dlg.getMaxThreshold());
AlignmentTrack.this.repaint();
}
});
item.setEnabled(dataManager.isPairedEnd());
add(item);
}
void addShadeBaseByMenuItem() {
final JMenuItem item = new JCheckBoxMenuItem("Shade base by quality");
item.setSelected(renderOptions.getShadeBasesOption());
item.addActionListener(aEvt -> UIUtilities.invokeOnEventThread(() -> {
renderOptions.setShadeBasesOption(item.isSelected());
AlignmentTrack.this.repaint();
}));
add(item);
}
void addShowItems() {
if (coverageTrack != null) {
final JMenuItem item = new JCheckBoxMenuItem("Show Coverage Track");
item.setSelected(coverageTrack.isVisible());
item.setEnabled(!coverageTrack.isRemoved());
item.addActionListener(aEvt -> {
getCoverageTrack().setVisible(item.isSelected());
IGV.getInstance().repaint(Arrays.asList(coverageTrack));
});
add(item);
}
if (spliceJunctionTrack != null) {
final JMenuItem item = new JCheckBoxMenuItem("Show Splice Junction Track");
item.setSelected(spliceJunctionTrack.isVisible());
item.setEnabled(!spliceJunctionTrack.isRemoved());
item.addActionListener(aEvt -> {
spliceJunctionTrack.setVisible(item.isSelected());
IGV.getInstance().repaint(Arrays.asList(spliceJunctionTrack));
});
add(item);
}
final JMenuItem alignmentItem = new JCheckBoxMenuItem("Show Alignment Track");
alignmentItem.setSelected(true);
alignmentItem.addActionListener(e -> {
AlignmentTrack.this.setVisible(alignmentItem.isSelected());
IGV.getInstance().repaint(Arrays.asList(AlignmentTrack.this));
});
// Disable if this is the only visible track
if (!((coverageTrack != null && coverageTrack.isVisible()) ||
(spliceJunctionTrack != null && spliceJunctionTrack.isVisible()))) {
alignmentItem.setEnabled(false);
}
add(alignmentItem);
}
void addCopySequenceItems(final TrackClickEvent te) {
final JMenuItem item = new JMenuItem("Copy read sequence");
add(item);
final Alignment alignment = getSpecficAlignment(te);
if (alignment == null) {
item.setEnabled(false);
return;
}
final String seq = alignment.getReadSequence();
if (seq == null) {
item.setEnabled(false);
return;
}
item.addActionListener(aEvt -> StringUtils.copyTextToClipboard(seq));
/* Add a "Copy left clipped sequence" item if there is left clipping. */
int minimumBlatLength = BlatClient.MINIMUM_BLAT_LENGTH;
int[] clipping = SAMAlignment.getClipping(alignment.getCigarString());
if (clipping[1] > 0) {
String lcSeq = getClippedSequence(alignment.getReadSequence(), alignment.getReadStrand(), 0, clipping[1]);
final JMenuItem lccItem = new JMenuItem("Copy left-clipped sequence");
add(lccItem);
lccItem.addActionListener(aEvt -> StringUtils.copyTextToClipboard(lcSeq));
}
/* Add a "Copy right clipped sequence" item if there is right clipping. */
if (clipping[3] > 0) {
int seqLength = seq.length();
String rcSeq = getClippedSequence(
alignment.getReadSequence(),
alignment.getReadStrand(),
seqLength - clipping[3],
seqLength);
final JMenuItem rccItem = new JMenuItem("Copy right-clipped sequence");
add(rccItem);
rccItem.addActionListener(aEvt -> StringUtils.copyTextToClipboard(rcSeq));
}
}
void addBlatItem(final TrackClickEvent te) {
// Change track height by attribute
final JMenuItem item = new JMenuItem("BLAT read sequence");
add(item);
final Alignment alignment = getSpecficAlignment(te);
if (alignment == null) {
item.setEnabled(false);
return;
}
final String seq = alignment.getReadSequence();
if (seq == null || seq.equals("*")) {
item.setEnabled(false);
return;
}
item.addActionListener(aEvt -> {
String blatSeq = alignment.getReadStrand() == Strand.NEGATIVE ?
SequenceTrack.getReverseComplement(seq) : seq;
BlatClient.doBlatQuery(blatSeq, alignment.getReadName());
});
}
void addBlatClippingItems(final TrackClickEvent te) {
final Alignment alignment = getSpecficAlignment(te);
if (alignment == null) {
return;
}
int minimumBlatLength = BlatClient.MINIMUM_BLAT_LENGTH;
int[] clipping = SAMAlignment.getClipping(alignment.getCigarString());
/* Add a "BLAT left clipped sequence" item if there is significant left clipping. */
if (clipping[1] > minimumBlatLength) {
String lcSeq = getClippedSequence(alignment.getReadSequence(), alignment.getReadStrand(), 0, clipping[1]);
final JMenuItem lcbItem = new JMenuItem("BLAT left-clipped sequence");
add(lcbItem);
lcbItem.addActionListener(aEvt ->
BlatClient.doBlatQuery(lcSeq, alignment.getReadName() + " - left clip")
);
}
/* Add a "BLAT right clipped sequence" item if there is significant right clipping. */
if (clipping[3] > minimumBlatLength) {
String seq = alignment.getReadSequence();
int seqLength = seq.length();
String rcSeq = getClippedSequence(
alignment.getReadSequence(),
alignment.getReadStrand(),
seqLength - clipping[3],
seqLength);
final JMenuItem rcbItem = new JMenuItem("BLAT right-clipped sequence");
add(rcbItem);
rcbItem.addActionListener(aEvt ->
BlatClient.doBlatQuery(rcSeq, alignment.getReadName() + " - right clip")
);
}
}
private String getClippedSequence(String readSequence, Strand strand, int i, int i2) {
if (readSequence == null || readSequence.equals("*")) {
return "*";
}
String seq = readSequence.substring(i, i2);
if (strand == Strand.NEGATIVE) {
seq = SequenceTrack.getReverseComplement(seq);
}
return seq;
}
void addExtViewItem(final TrackClickEvent te) {
// Change track height by attribute
final JMenuItem item = new JMenuItem("ExtView");
add(item);
final Alignment alignment = getAlignment(te);
if (alignment == null) {
item.setEnabled(false);
return;
}
final String seq = alignment.getReadSequence();
if (seq == null) {
item.setEnabled(false);
return;
}
item.addActionListener(aEvt -> ExtendViewClient.postExtendView(alignment));
}
/**
* Add all menu items that link alignments by tag or readname. These are mutually exclusive. The
* list includes 2 items for 10X "Loupe link-read" style views, a supplementary alignment option,
* and linking by arbitrary tag.
*/
void addLinkedReadItems() {
addSeparator();
add(linkedReadViewItem("BX"));
add(linkedReadViewItem("MI"));
addSeparator();
final JCheckBoxMenuItem supplementalItem = new JCheckBoxMenuItem("Link supplementary alignments");
supplementalItem.setSelected(isLinkedReads() && "READNAME".equals(renderOptions.getLinkByTag()));
supplementalItem.addActionListener(aEvt -> {
boolean linkedReads = supplementalItem.isSelected();
setLinkByTag(linkedReads, "READNAME");
});
add(supplementalItem);
String linkedTagsString = PreferencesManager.getPreferences().get(SAM_LINK_BY_TAGS);
if (linkedTagsString != null) {
String[] t = Globals.commaPattern.split(linkedTagsString);
for (String tag : t) {
if (tag.length() > 0) {
add(linkedReadItem(tag));
}
}
}
final JMenuItem linkByTagItem = new JMenuItem("Link by tag...");
linkByTagItem.addActionListener(aEvt -> {
String tag = MessageUtils.showInputDialog("Link by tag:");
if (tag != null) {
setLinkByTag(true, tag);
String linkedTags = PreferencesManager.getPreferences().get(SAM_LINK_BY_TAGS);
if (linkedTags == null) {
linkedTags = tag;
} else {
linkedTags += "," + tag;
}
PreferencesManager.getPreferences().put(SAM_LINK_BY_TAGS, linkedTags);
}
});
add(linkByTagItem);
}
private JCheckBoxMenuItem linkedReadViewItem(String tag) {
final JCheckBoxMenuItem item = new JCheckBoxMenuItem("Linked read view (" + tag + ")");
item.setSelected(isLinkedReadView() && tag != null && tag.equals(renderOptions.getLinkByTag()));
item.addActionListener(aEvt -> {
boolean linkedReads = item.isSelected();
setLinkedReadView(linkedReads, tag);
});
return item;
}
private JCheckBoxMenuItem linkedReadItem(String tag) {
final JCheckBoxMenuItem item = new JCheckBoxMenuItem("Link by " + tag);
item.setSelected(!isLinkedReadView() && isLinkedReads() && tag.equals(renderOptions.getLinkByTag()));
item.addActionListener(aEvt -> {
boolean linkedReads = item.isSelected();
setLinkByTag(linkedReads, tag);
});
return item;
}
private void addInsertionItems(AlignmentBlock insertion) {
final JMenuItem item = new JMenuItem("Copy insert sequence");
add(item);
item.addActionListener(aEvt -> StringUtils.copyTextToClipboard(insertion.getBases().getString()));
if (insertion.getBases() != null && insertion.getBases().length >= 10) {
final JMenuItem blatItem = new JMenuItem("BLAT insert sequence");
add(blatItem);
blatItem.addActionListener(aEvt -> {
String blatSeq = insertion.getBases().getString();
BlatClient.doBlatQuery(blatSeq, "BLAT insert sequence");
});
}
}
void addThirdGenItems() {
final JMenuItem qcItem = new JCheckBoxMenuItem("Quick consensus mode");
qcItem.setSelected(renderOptions.isQuickConsensusMode());
qcItem.addActionListener(aEvt -> {
renderOptions.setQuickConsensusMode(qcItem.isSelected());
AlignmentTrack.this.repaint();
});
final JMenuItem thresholdItem = new JMenuItem("Small indel threshold...");
thresholdItem.addActionListener(evt -> UIUtilities.invokeOnEventThread(() -> {
String sith = MessageUtils.showInputDialog("Small indel threshold: ", String.valueOf(renderOptions.getSmallIndelThreshold()));
try {
renderOptions.setSmallIndelThreshold(Integer.parseInt(sith));
AlignmentTrack.this.repaint();
} catch (NumberFormatException e) {
log.error("Error setting small indel threshold - not an integer", e);
}
}));
thresholdItem.setEnabled(renderOptions.isHideSmallIndels());
final JMenuItem item = new JCheckBoxMenuItem("Hide small indels");
item.setSelected(renderOptions.isHideSmallIndels());
item.addActionListener(aEvt -> UIUtilities.invokeOnEventThread(() -> {
renderOptions.setHideSmallIndels(item.isSelected());
thresholdItem.setEnabled(item.isSelected());
AlignmentTrack.this.repaint();
}));
final JMenuItem imItem = new JCheckBoxMenuItem("Show insertion markers");
imItem.setSelected(renderOptions.isShowInsertionMarkers());
imItem.addActionListener(aEvt -> {
renderOptions.setShowInsertionMarkers(imItem.isSelected());
AlignmentTrack.this.repaint();
});
add(imItem);
add(qcItem);
add(item);
add(thresholdItem);
}
}
private AlignmentBlock getInsertion(Alignment alignment, int pixelX) {
if (alignment != null && alignment.getInsertions() != null) {
for (AlignmentBlock block : alignment.getInsertions()) {
if (block.containsPixel(pixelX)) {
return block;
}
}
}
return null;
}
@Override
public void unmarshalXML(Element element, Integer version) {
super.unmarshalXML(element, version);
if (element.hasAttribute("experimentType")) {
experimentType = ExperimentType.valueOf(element.getAttribute("experimentType"));
}
NodeList tmp = element.getElementsByTagName("RenderOptions");
if (tmp.getLength() > 0) {
Element renderElement = (Element) tmp.item(0);
renderOptions = new RenderOptions(this);
renderOptions.unmarshalXML(renderElement, version);
}
}
@Override
public void marshalXML(Document document, Element element) {
super.marshalXML(document, element);
if (experimentType != null) {
element.setAttribute("experimentType", experimentType.toString());
}
Element sourceElement = document.createElement("RenderOptions");
renderOptions.marshalXML(document, sourceElement);
element.appendChild(sourceElement);
}
static class InsertionMenu extends IGVPopupMenu {
final AlignmentBlock insertion;
InsertionMenu(AlignmentBlock insertion) {
this.insertion = insertion;
addCopySequenceItem();
if (insertion.getBases() != null && insertion.getBases().length > 10) {
addBlatItem();
}
}
void addCopySequenceItem() {
// Change track height by attribute
final JMenuItem item = new JMenuItem("Copy insert sequence");
add(item);
item.addActionListener(aEvt -> StringUtils.copyTextToClipboard(insertion.getBases().getString()));
}
void addBlatItem() {
// Change track height by attribute
final JMenuItem item = new JMenuItem("BLAT insert sequence");
add(item);
item.addActionListener(aEvt -> {
String blatSeq = insertion.getBases().getString();
BlatClient.doBlatQuery(blatSeq, "BLAT insert sequence");
});
item.setEnabled(insertion.getBases() != null && insertion.getBases().length >= 10);
}
@Override
public boolean includeStandardItems() {
return false;
}
}
public static class RenderOptions implements Cloneable, Persistable {
public static final String NAME = "RenderOptions";
private AlignmentTrack track;
private Boolean shadeBasesOption;
private Boolean shadeCenters;
private Boolean flagUnmappedPairs;
private Boolean showAllBases;
private Integer minInsertSize;
private Integer maxInsertSize;
private ColorOption colorOption;
private GroupOption groupByOption;
private boolean viewPairs = false;
private String colorByTag;
private String groupByTag;
private String sortByTag;
private String linkByTag;
private Boolean linkedReads;
private Boolean quickConsensusMode;
private Boolean showMismatches;
private Boolean computeIsizes;
private Double minInsertSizePercentile;
private Double maxInsertSizePercentile;
private Boolean pairedArcView;
private Boolean flagZeroQualityAlignments;
private Range groupByPos;
private Boolean showInsertionMarkers;
private Boolean hideSmallIndels;
private Integer smallIndelThreshold;
BisulfiteContext bisulfiteContext = BisulfiteContext.CG;
Map<String, PEStats> peStats;
public RenderOptions() {
}
RenderOptions(AlignmentTrack track) {
//updateColorScale();
this.track = track;
peStats = new HashMap<>();
}
IGVPreferences getPreferences() {
return this.track != null ? this.track.getPreferences() : AlignmentTrack.getPreferences(ExperimentType.OTHER);
}
void setShowAllBases(boolean showAllBases) {
this.showAllBases = showAllBases;
}
void setShowMismatches(boolean showMismatches) {
this.showMismatches = showMismatches;
}
void setMinInsertSize(int minInsertSize) {
this.minInsertSize = minInsertSize;
//updateColorScale();
}
public void setViewPairs(boolean viewPairs) {
this.viewPairs = viewPairs;
}
void setComputeIsizes(boolean computeIsizes) {
this.computeIsizes = computeIsizes;
}
void setMaxInsertSizePercentile(double maxInsertSizePercentile) {
this.maxInsertSizePercentile = maxInsertSizePercentile;
}
void setMaxInsertSize(int maxInsertSize) {
this.maxInsertSize = maxInsertSize;
}
void setMinInsertSizePercentile(double minInsertSizePercentile) {
this.minInsertSizePercentile = minInsertSizePercentile;
}
void setColorByTag(String colorByTag) {
this.colorByTag = colorByTag;
}
void setColorOption(ColorOption colorOption) {
this.colorOption = colorOption;
}
void setSortByTag(String sortByTag) {
this.sortByTag = sortByTag;
}
void setGroupByTag(String groupByTag) {
this.groupByTag = groupByTag;
}
void setGroupByPos(Range groupByPos) {
this.groupByPos = groupByPos;
}
void setLinkByTag(String linkByTag) {
this.linkByTag = linkByTag;
}
void setQuickConsensusMode(boolean quickConsensusMode) {
this.quickConsensusMode = quickConsensusMode;
}
public void setGroupByOption(GroupOption groupByOption) {
this.groupByOption = (groupByOption == null) ? GroupOption.NONE : groupByOption;
}
void setShadeBasesOption(boolean shadeBasesOption) {
this.shadeBasesOption = shadeBasesOption;
}
void setLinkedReads(boolean linkedReads) {
this.linkedReads = linkedReads;
}
public void setShowInsertionMarkers(boolean drawInsertionIntervals) {
this.showInsertionMarkers = drawInsertionIntervals;
}
public void setHideSmallIndels(boolean hideSmallIndels) {
this.hideSmallIndels = hideSmallIndels;
}
public void setSmallIndelThreshold(int smallIndelThreshold) {
this.smallIndelThreshold = smallIndelThreshold;
}
// getters
public int getMinInsertSize() {
return minInsertSize == null ? getPreferences().getAsInt(SAM_MIN_INSERT_SIZE_THRESHOLD) : minInsertSize;
}
public int getMaxInsertSize() {
return maxInsertSize == null ? getPreferences().getAsInt(SAM_MAX_INSERT_SIZE_THRESHOLD) : maxInsertSize;
}
public boolean isFlagUnmappedPairs() {
return flagUnmappedPairs == null ? getPreferences().getAsBoolean(SAM_FLAG_UNMAPPED_PAIR) : flagUnmappedPairs;
}
public boolean getShadeBasesOption() {
return shadeBasesOption == null ? getPreferences().getAsBoolean(SAM_SHADE_BASES) : shadeBasesOption;
}
public boolean isShowMismatches() {
return showMismatches == null ? getPreferences().getAsBoolean(SAM_SHOW_MISMATCHES) : showMismatches;
}
public boolean isShowAllBases() {
return showAllBases == null ? getPreferences().getAsBoolean(SAM_SHOW_ALL_BASES) : showAllBases;
}
public boolean isShadeCenters() {
return shadeCenters == null ? getPreferences().getAsBoolean(SAM_SHADE_CENTER) : shadeCenters;
}
boolean isShowInsertionMarkers() {
return showInsertionMarkers == null ? getPreferences().getAsBoolean(SAM_SHOW_INSERTION_MARKERS) : showInsertionMarkers;
}
public boolean isFlagZeroQualityAlignments() {
return flagZeroQualityAlignments == null ? getPreferences().getAsBoolean(SAM_FLAG_ZERO_QUALITY) : flagZeroQualityAlignments;
}
public boolean isViewPairs() {
return viewPairs;
}
public boolean isComputeIsizes() {
return computeIsizes == null ? getPreferences().getAsBoolean(SAM_COMPUTE_ISIZES) : computeIsizes;
}
public double getMinInsertSizePercentile() {
return minInsertSizePercentile == null ? getPreferences().getAsFloat(SAM_MIN_INSERT_SIZE_PERCENTILE) : minInsertSizePercentile;
}
public double getMaxInsertSizePercentile() {
return maxInsertSizePercentile == null ? getPreferences().getAsFloat(SAM_MAX_INSERT_SIZE_PERCENTILE) : maxInsertSizePercentile;
}
public ColorOption getColorOption() {
return colorOption == null ?
CollUtils.valueOf(ColorOption.class, getPreferences().get(SAM_COLOR_BY), ColorOption.NONE) :
colorOption;
}
public String getColorByTag() {
return colorByTag == null ? getPreferences().get(SAM_COLOR_BY_TAG) : colorByTag;
}
String getSortByTag() {
return sortByTag == null ? getPreferences().get(SAM_SORT_BY_TAG) : sortByTag;
}
public String getGroupByTag() {
return groupByTag == null ? getPreferences().get(SAM_GROUP_BY_TAG) : groupByTag;
}
public Range getGroupByPos() {
if (groupByPos == null) {
String pos = getPreferences().get(SAM_GROUP_BY_POS);
if (pos != null) {
String[] posParts = pos.split(" ");
if (posParts.length != 2) {
groupByPos = null;
} else {
int posChromStart = Integer.parseInt(posParts[1]);
groupByPos = new Range(posParts[0], posChromStart, posChromStart + 1);
}
}
}
return groupByPos;
}
public String getLinkByTag() {
return linkByTag;
}
public GroupOption getGroupByOption() {
GroupOption gbo = groupByOption;
// Interpret null as the default option.
gbo = (gbo == null) ?
CollUtils.valueOf(GroupOption.class, getPreferences().get(SAM_GROUP_OPTION), GroupOption.NONE) :
gbo;
// Add a second check for null in case defaultValues.groupByOption == null
gbo = (gbo == null) ? GroupOption.NONE : gbo;
return gbo;
}
public boolean isLinkedReads() {
return linkedReads != null && linkedReads;
}
public boolean isQuickConsensusMode() {
return quickConsensusMode == null ? getPreferences().getAsBoolean(SAM_QUICK_CONSENSUS_MODE) : quickConsensusMode;
}
public boolean isHideSmallIndels() {
return hideSmallIndels == null ? getPreferences().getAsBoolean(SAM_HIDE_SMALL_INDEL) : hideSmallIndels;
}
public int getSmallIndelThreshold() {
return smallIndelThreshold == null ? getPreferences().getAsInt(SAM_SMALL_INDEL_BP_THRESHOLD) : smallIndelThreshold;
}
@Override
public void marshalXML(Document document, Element element) {
if (shadeBasesOption != null) {
element.setAttribute("shadeBasesOption", shadeBasesOption.toString());
}
if (shadeCenters != null) {
element.setAttribute("shadeCenters", shadeCenters.toString());
}
if (flagUnmappedPairs != null) {
element.setAttribute("flagUnmappedPairs", flagUnmappedPairs.toString());
}
if (showAllBases != null) {
element.setAttribute("showAllBases", showAllBases.toString());
}
if (minInsertSize != null) {
element.setAttribute("minInsertSize", minInsertSize.toString());
}
if (maxInsertSize != null) {
element.setAttribute("maxInsertSize", maxInsertSize.toString());
}
if (colorOption != null) {
element.setAttribute("colorOption", colorOption.toString());
}
if (groupByOption != null) {
element.setAttribute("groupByOption", groupByOption.toString());
}
if (viewPairs != false) {
element.setAttribute("viewPairs", Boolean.toString(viewPairs));
}
if (colorByTag != null) {
element.setAttribute("colorByTag", colorByTag);
}
if (groupByTag != null) {
element.setAttribute("groupByTag", groupByTag);
}
if (sortByTag != null) {
element.setAttribute("sortByTag", sortByTag);
}
if (linkByTag != null) {
element.setAttribute("linkByTag", linkByTag);
}
if (linkedReads != null) {
element.setAttribute("linkedReads", linkedReads.toString());
}
if (quickConsensusMode != null) {
element.setAttribute("quickConsensusMode", quickConsensusMode.toString());
}
if (showMismatches != null) {
element.setAttribute("showMismatches", showMismatches.toString());
}
if (computeIsizes != null) {
element.setAttribute("computeIsizes", computeIsizes.toString());
}
if (minInsertSizePercentile != null) {
element.setAttribute("minInsertSizePercentile", minInsertSizePercentile.toString());
}
if (maxInsertSizePercentile != null) {
element.setAttribute("maxInsertSizePercentile", maxInsertSizePercentile.toString());
}
if (pairedArcView != null) {
element.setAttribute("pairedArcView", pairedArcView.toString());
}
if (flagZeroQualityAlignments != null) {
element.setAttribute("flagZeroQualityAlignments", flagZeroQualityAlignments.toString());
}
if (groupByPos != null) {
element.setAttribute("groupByPos", groupByPos.toString());
}
if (hideSmallIndels != null) {
element.setAttribute("hideSmallIndels", hideSmallIndels.toString());
}
if (smallIndelThreshold != null) {
element.setAttribute("smallIndelThreshold", smallIndelThreshold.toString());
}
if (showInsertionMarkers != null) {
element.setAttribute("showInsertionMarkers", showInsertionMarkers.toString());
}
}
@Override
public void unmarshalXML(Element element, Integer version) {
if (element.hasAttribute("shadeBasesOption")) {
String v = element.getAttribute("shadeBasesOption");
if (v != null) {
shadeBasesOption = v.equalsIgnoreCase("quality") || v.equalsIgnoreCase("true");
}
}
if (element.hasAttribute("shadeCenters")) {
shadeCenters = Boolean.parseBoolean(element.getAttribute("shadeCenters"));
}
if (element.hasAttribute("showAllBases")) {
showAllBases = Boolean.parseBoolean(element.getAttribute("showAllBases"));
}
if (element.hasAttribute("flagUnmappedPairs")) {
flagUnmappedPairs = Boolean.parseBoolean(element.getAttribute("flagUnmappedPairs"));
}
if (element.hasAttribute("minInsertSize")) {
minInsertSize = Integer.parseInt(element.getAttribute("minInsertSize"));
}
if (element.hasAttribute("maxInsertSize")) {
maxInsertSize = Integer.parseInt(element.getAttribute("maxInsertSize"));
}
if (element.hasAttribute("colorOption")) {
colorOption = ColorOption.valueOf(element.getAttribute("colorOption"));
}
if (element.hasAttribute("groupByOption")) {
groupByOption = GroupOption.valueOf(element.getAttribute("groupByOption"));
}
if (element.hasAttribute("viewPairs")) {
viewPairs = Boolean.parseBoolean(element.getAttribute("viewPairs"));
}
if (element.hasAttribute("colorByTag")) {
colorByTag = element.getAttribute("colorByTag");
}
if (element.hasAttribute("groupByTag")) {
groupByTag = element.getAttribute("groupByTag");
}
if (element.hasAttribute("sortByTag")) {
sortByTag = element.getAttribute("sortByTag");
}
if (element.hasAttribute("linkByTag")) {
linkByTag = element.getAttribute("linkByTag");
}
if (element.hasAttribute("linkedReads")) {
linkedReads = Boolean.parseBoolean(element.getAttribute("linkedReads"));
}
if (element.hasAttribute("quickConsensusMode")) {
quickConsensusMode = Boolean.parseBoolean(element.getAttribute("quickConsensusMode"));
}
if (element.hasAttribute("showMismatches")) {
showMismatches = Boolean.parseBoolean(element.getAttribute("showMismatches"));
}
if (element.hasAttribute("computeIsizes")) {
computeIsizes = Boolean.parseBoolean(element.getAttribute("computeIsizes"));
}
if (element.hasAttribute("minInsertSizePercentile")) {
minInsertSizePercentile = Double.parseDouble(element.getAttribute("minInsertSizePercentile"));
}
if (element.hasAttribute("maxInsertSizePercentile")) {
maxInsertSizePercentile = Double.parseDouble(element.getAttribute("maxInsertSizePercentile"));
}
if (element.hasAttribute("pairedArcView")) {
pairedArcView = Boolean.parseBoolean(element.getAttribute("pairedArcView"));
}
if (element.hasAttribute("flagZeroQualityAlignments")) {
flagZeroQualityAlignments = Boolean.parseBoolean(element.getAttribute("flagZeroQualityAlignments"));
}
if (element.hasAttribute("groupByPos")) {
groupByPos = Range.fromString(element.getAttribute("groupByPos"));
}
if (element.hasAttribute("hideSmallIndels")) {
hideSmallIndels = Boolean.parseBoolean(element.getAttribute("hideSmallIndels"));
}
if (element.hasAttribute("smallIndelThreshold")) {
smallIndelThreshold = Integer.parseInt(element.getAttribute("smallIndelThreshold"));
}
if (element.hasAttribute("showInsertionMarkers")) {
showInsertionMarkers = Boolean.parseBoolean(element.getAttribute("showInsertionMarkers"));
}
}
}
} |
package org.jfree.chart.util;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import javax.imageio.ImageIO;
import org.jfree.ui.Drawable;
/**
* Utility functions for exporting charts to SVG and PDF format.
*
* @since 1.0.18
*/
public class ExportUtils {
public static boolean isJFreeSVGAvailable() {
Class<?> svgClass = null;
try {
svgClass = Class.forName("org.jfree.graphics2d.svg.SVGGraphics2D");
} catch (ClassNotFoundException e) {
// svgClass will be null so the function will return false
}
return (svgClass != null);
}
public static boolean isOrsonPDFAvailable() {
Class<?> pdfDocumentClass = null;
try {
pdfDocumentClass = Class.forName("com.orsonpdf.PDFDocument");
} catch (ClassNotFoundException e) {
// pdfDocumentClass will be null so the function will return false
}
return (pdfDocumentClass != null);
}
/**
* Writes the current content to the specified file in SVG format. This
* will only work when the JFreeSVG library is found on the classpath.
* Reflection is used to ensure there is no compile-time dependency on
* JFreeSVG.
*
* @param drawable the drawable ({@code null} not permitted).
* @param w the chart width.
* @param h the chart height.
* @param file the output file ({@code null} not permitted).
*/
public static void writeAsSVG(Drawable drawable, int w, int h,
File file) {
if (!ExportUtils.isJFreeSVGAvailable()) {
throw new IllegalStateException(
"JFreeSVG is not present on the classpath.");
}
ParamChecks.nullNotPermitted(drawable, "drawable");
ParamChecks.nullNotPermitted(file, "file");
try {
Class<?> svg2Class = Class.forName(
"org.jfree.graphics2d.svg.SVGGraphics2D");
Constructor<?> c1 = svg2Class.getConstructor(int.class, int.class);
Graphics2D svg2 = (Graphics2D) c1.newInstance(w, h);
Rectangle2D drawArea = new Rectangle2D.Double(0, 0, w, h);
drawable.draw(svg2, drawArea);
Class<?> svgUtilsClass = Class.forName(
"org.jfree.graphics2d.svg.SVGUtils");
Method m1 = svg2Class.getMethod("getSVGElement", (Class[]) null);
String element = (String) m1.invoke(svg2, (Object[]) null);
Method m2 = svgUtilsClass.getMethod("writeToSVG", File.class,
String.class);
m2.invoke(svgUtilsClass, file, element);
} catch (ClassNotFoundException ex) {
throw new RuntimeException(ex);
} catch (InstantiationException ex) {
throw new RuntimeException(ex);
} catch (IllegalAccessException ex) {
throw new RuntimeException(ex);
} catch (NoSuchMethodException ex) {
throw new RuntimeException(ex);
} catch (SecurityException ex) {
throw new RuntimeException(ex);
} catch (IllegalArgumentException ex) {
throw new RuntimeException(ex);
} catch (InvocationTargetException ex) {
throw new RuntimeException(ex);
}
}
/**
* Writes a {@link Drawable} to the specified file in PDF format. This
* will only work when the OrsonPDF library is found on the classpath.
* Reflection is used to ensure there is no compile-time dependency on
* OrsonPDF.
*
* @param drawable the drawable ({@code null} not permitted).
* @param w the chart width.
* @param h the chart height.
* @param file the output file ({@code null} not permitted).
*/
public static final void writeAsPDF(Drawable drawable,
int w, int h, File file) {
if (!ExportUtils.isOrsonPDFAvailable()) {
throw new IllegalStateException(
"OrsonPDF is not present on the classpath.");
}
ParamChecks.nullNotPermitted(drawable, "drawable");
ParamChecks.nullNotPermitted(file, "file");
try {
Class<?> pdfDocClass = Class.forName("com.orsonpdf.PDFDocument");
Object pdfDoc = pdfDocClass.newInstance();
Method m = pdfDocClass.getMethod("createPage", Rectangle2D.class);
Rectangle2D rect = new Rectangle(w, h);
Object page = m.invoke(pdfDoc, rect);
Method m2 = page.getClass().getMethod("getGraphics2D");
Graphics2D g2 = (Graphics2D) m2.invoke(page);
Rectangle2D drawArea = new Rectangle2D.Double(0, 0, w, h);
drawable.draw(g2, drawArea);
Method m3 = pdfDocClass.getMethod("writeToFile", File.class);
m3.invoke(pdfDoc, file);
} catch (ClassNotFoundException ex) {
throw new RuntimeException(ex);
} catch (InstantiationException ex) {
throw new RuntimeException(ex);
} catch (IllegalAccessException ex) {
throw new RuntimeException(ex);
} catch (NoSuchMethodException ex) {
throw new RuntimeException(ex);
} catch (SecurityException ex) {
throw new RuntimeException(ex);
} catch (IllegalArgumentException ex) {
throw new RuntimeException(ex);
} catch (InvocationTargetException ex) {
throw new RuntimeException(ex);
}
}
/**
* Writes the current content to the specified file in PNG format.
*
* @param drawable the drawable ({@code null} not permitted).
* @param w the chart width.
* @param h the chart height.
* @param file the output file ({@code null} not permitted).
*
* @throws FileNotFoundException if the file is not found.
* @throws IOException if there is an I/O problem.
*/
public static void writeAsPNG(Drawable drawable, int w, int h,
File file) throws FileNotFoundException, IOException {
BufferedImage image = new BufferedImage(w, h,
BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = image.createGraphics();
drawable.draw(g2, new Rectangle(w, h));
OutputStream out = new BufferedOutputStream(new FileOutputStream(file));
try {
ImageIO.write(image, "png", out);
}
finally {
out.close();
}
}
/**
* Writes the current content to the specified file in JPEG format.
*
* @param drawable the drawable ({@code null} not permitted).
* @param w the chart width.
* @param h the chart height.
* @param file the output file ({@code null} not permitted).
*
* @throws FileNotFoundException if the file is not found.
* @throws IOException if there is an I/O problem.
*/
public static void writeAsJPEG(Drawable drawable, int w, int h,
File file) throws FileNotFoundException, IOException {
BufferedImage image = new BufferedImage(w, h,
BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = image.createGraphics();
drawable.draw(g2, new Rectangle(w, h));
OutputStream out = new BufferedOutputStream(new FileOutputStream(file));
try {
ImageIO.write(image, "jpg", out);
}
finally {
out.close();
}
}
} |
package org.mastodon.trackmate;
import java.util.Map;
import org.mastodon.HasErrorMessage;
import org.mastodon.detection.mamut.SpotDetectorOp;
import org.mastodon.linking.mamut.SpotLinkerOp;
import org.mastodon.revised.model.mamut.Link;
import org.mastodon.revised.model.mamut.Model;
import org.mastodon.revised.model.mamut.ModelGraph;
import org.mastodon.revised.model.mamut.Spot;
import org.scijava.Cancelable;
import org.scijava.app.StatusService;
import org.scijava.command.ContextCommand;
import org.scijava.log.LogService;
import org.scijava.plugin.Parameter;
import bdv.spimdata.SpimDataMinimal;
import net.imagej.ops.Op;
import net.imagej.ops.OpService;
import net.imagej.ops.special.hybrid.Hybrids;
import net.imagej.ops.special.inplace.Inplaces;
import net.imglib2.algorithm.Benchmark;
public class TrackMate extends ContextCommand implements HasErrorMessage
{
@Parameter
private OpService ops;
@Parameter
private StatusService statusService;
@Parameter
LogService log;
private final Settings settings;
private final Model model;
private Op currentOp;
private boolean succesful;
private String errorMessage;
public TrackMate( final Settings settings )
{
this.settings = settings;
this.model = createModel();
}
public TrackMate( final Settings settings, final Model model )
{
this.settings = settings;
this.model = model;
}
protected Model createModel()
{
return new Model();
}
public Model getModel()
{
return model;
}
public Settings getSettings()
{
return settings;
}
public boolean execDetection()
{
succesful = true;
errorMessage = null;
if ( isCanceled() )
return true;
final ModelGraph graph = model.getGraph();
final SpimDataMinimal spimData = settings.values.getSpimData();
if ( null == spimData )
{
errorMessage = "Cannot start detection: SpimData obect is null.";
log.error( errorMessage );
succesful = false;
return false;
}
/*
* Clear previous content.
*/
for ( final Spot spot : model.getGraph().vertices() )
model.getGraph().remove( spot );
/*
* Exec detection.
*/
final Class< ? extends SpotDetectorOp > cl = settings.values.getDetector();
final Map< String, Object > detectorSettings = settings.values.getDetectorSettings();
final SpotDetectorOp detector = ( SpotDetectorOp ) Hybrids.unaryCF( ops, cl,
graph, spimData,
detectorSettings );
this.currentOp = detector;
log.info( "Detection with " + detector );
detector.compute( spimData, graph );
if ( !detector.isSuccessful() )
{
log.error( "Detection failed:\n" + detector.getErrorMessage() );
succesful = false;
errorMessage = detector.getErrorMessage();
return false;
}
currentOp = null;
model.getGraphFeatureModel().declareFeature( detector.getQualityFeature() );
if ( detector instanceof Benchmark )
{
final Benchmark bm = ( Benchmark ) detector;
log.info( "Detection completed in " + bm.getProcessingTime() + " ms." );
}
else
{
log.info( "Detection completed." );
}
log.info( "Found " + graph.vertices().size() + " spots." );
return true;
}
public boolean execParticleLinking()
{
succesful = true;
errorMessage = null;
if ( isCanceled() )
return true;
/*
* Clear previous content.
*/
for ( final Link link : model.getGraph().edges() )
model.getGraph().remove( link );
/*
* Exec particle linking.
*/
final Class< ? extends SpotLinkerOp > linkerCl = settings.values.getLinker();
final Map< String, Object > linkerSettings = settings.values.getLinkerSettings();
final SpotLinkerOp linker =
( SpotLinkerOp ) Inplaces.binary1( ops, linkerCl, model.getGraph(), model.getSpatioTemporalIndex(),
linkerSettings, model.getGraphFeatureModel() );
log.info( "Particle-linking with " + linker );
this.currentOp = linker;
linker.mutate1( model.getGraph(), model.getSpatioTemporalIndex() );
if ( !linker.isSuccessful() )
{
log.error( "Particle-linking failed:\n" + linker.getErrorMessage() );
succesful = false;
errorMessage = linker.getErrorMessage();
return false;
}
currentOp = null;
model.getGraphFeatureModel().declareFeature( linker.getLinkCostFeature() );
if ( linker instanceof Benchmark )
log.info( "Particle-linking completed in " + ( ( Benchmark ) linker ).getProcessingTime() + " ms." );
else
log.info( "Particle-linking completed." );
return true;
}
@Override
public void run()
{
if ( execDetection() && execParticleLinking() )
;
}
@Override
public void cancel( final String reason )
{
super.cancel( reason );
if ( null != currentOp && ( currentOp instanceof Cancelable ) )
{
final Cancelable cancelable = ( Cancelable ) currentOp;
cancelable.cancel( reason );
}
}
@Override
public String getErrorMessage()
{
return errorMessage;
}
@Override
public boolean isSuccessful()
{
return succesful;
}
} |
package org.newdawn.slick.geom;
import org.newdawn.slick.util.FastTrig;
/**
* A 2 dimensional transformation that can be applied to <code>Shape</code> implemenations.
*
* @author Mark
*/
public class Transform {
/**
* Value for each position in the matrix
*
* |0 1 2|
* |3 4 5|
* |6 7 8|
*/
private float matrixPosition[];
/**
* Create and identity transform
*
*/
public Transform() {
matrixPosition = new float[]{1, 0, 0, 0, 1, 0, 0, 0, 1};
}
/**
* Copy a transform
*
* @param other The other transform to copy
*/
public Transform(Transform other) {
matrixPosition = new float[9];
System.arraycopy(other.matrixPosition, 0, matrixPosition, 0, 9);
}
/**
* Concatanate to transform into one
*
* @param t1 The first transform to join
* @param t2 The second transform to join
*/
public Transform(Transform t1, Transform t2) {
this(t1);
concatenate(t2);
}
/**
* Create a transform for the given positions
*
* @param matrixPosition An array of float[6] to set up a transform
* @throws RuntimeException if the array is not of length 6
*/
public Transform(float matrixPosition[]) {
if(matrixPosition.length != 6) {
throw new RuntimeException("The parameter must be a float array of length 6.");
}
this.matrixPosition = new float[]{matrixPosition[0], matrixPosition[1], matrixPosition[2],
matrixPosition[3], matrixPosition[4], matrixPosition[5],
0, 0, 1};
}
/**
* Create a transform for the given positions
*
* @param point00 float for the first position
* @param point01 float for the second position
* @param point02 float for the third position
* @param point10 float for the fourth position
* @param point11 float for the fifth position
* @param point12 float for the sixth position
*/
public Transform(float point00, float point01, float point02, float point10, float point11, float point12) {
matrixPosition = new float[]{point00, point01, point02, point10, point11, point12, 0, 0, 1};
}
/**
* Transform the point pairs in the source array and store them in the destination array.
* All operations will be done before storing the results in the destination. This way the source
* and destination array can be the same without worry of overwriting information before it is transformed.
*
* @param source Array of floats containing the points to be transformed
* @param sourceOffset Where in the array to start processing
* @param destination Array of floats to store the results.
* @param destOffset Where in the array to start storing
* @param numberOfPoints Number of points to be transformed
* @throws ArrayIndexOutOfBoundsException if sourceOffset + numberOfPoints * 2 > source.length or the same operation on the destination array
*/
public void transform(float source[], int sourceOffset, float destination[], int destOffset, int numberOfPoints) {
//TODO performance can be improved by removing the safety to the destination array
float result[] = source == destination ? new float[numberOfPoints * 2] : destination;
for(int i=0;i<numberOfPoints * 2;i+=2) {
for(int j=0;j<6;j+=3) {
result[i + (j / 3)] = source[i + sourceOffset] * matrixPosition[j] + source[i + sourceOffset + 1] * matrixPosition[j + 1] + 1 * matrixPosition[j + 2];
}
}
if (source == destination) {
//for safety of the destination, the results are copied after the entire operation.
for(int i=0;i<numberOfPoints * 2;i+=2) {
destination[i + destOffset] = result[i];
destination[i + destOffset + 1] = result[i + 1];
}
}
}
/**
* Update this Transform by concatenating the given Transform to this one.
*
* @param tx The Transfrom to concatenate to this one.
* @return The resulting Transform
*/
public Transform concatenate(Transform tx) {
float[] mp = new float[9];
float n00 = matrixPosition[0] * tx.matrixPosition[0] + matrixPosition[1] * tx.matrixPosition[3];
float n01 = matrixPosition[0] * tx.matrixPosition[1] + matrixPosition[1] * tx.matrixPosition[4];
float n02 = matrixPosition[0] * tx.matrixPosition[2] + matrixPosition[1] * tx.matrixPosition[5] + matrixPosition[2];
float n10 = matrixPosition[3] * tx.matrixPosition[0] + matrixPosition[4] * tx.matrixPosition[3];
float n11 = matrixPosition[3] * tx.matrixPosition[1] + matrixPosition[4] * tx.matrixPosition[4];
float n12 = matrixPosition[3] * tx.matrixPosition[2] + matrixPosition[4] * tx.matrixPosition[5] + matrixPosition[5];
mp[0] = n00;
mp[1] = n01;
mp[2] = n02;
mp[3] = n10;
mp[4] = n11;
mp[5] = n12;
// mp[0] = matrixPosition[0] * transform.matrixPosition[0] + matrixPosition[0] * transform.matrixPosition[3] + matrixPosition[0] * transform.matrixPosition[6];
// mp[1] = matrixPosition[1] * transform.matrixPosition[1] + matrixPosition[1] * transform.matrixPosition[4] + matrixPosition[1] * transform.matrixPosition[7];
// mp[2] = matrixPosition[2] * transform.matrixPosition[2] + matrixPosition[2] * transform.matrixPosition[5] + matrixPosition[2] * transform.matrixPosition[8];
// mp[3] = matrixPosition[3] * transform.matrixPosition[0] + matrixPosition[3] * transform.matrixPosition[3] + matrixPosition[3] * transform.matrixPosition[6];
// mp[4] = matrixPosition[4] * transform.matrixPosition[1] + matrixPosition[4] * transform.matrixPosition[4] + matrixPosition[4] * transform.matrixPosition[7];
// mp[5] = matrixPosition[5] * transform.matrixPosition[2] + matrixPosition[5] * transform.matrixPosition[5] + matrixPosition[5] * transform.matrixPosition[8];
matrixPosition = mp;
return this;
}
/**
* Convert this Transform to a String.
*
* @return This Transform in human readable format.
*/
public String toString() {
String result = "Transform[[" + matrixPosition[0] + "," + matrixPosition[1] + "," + matrixPosition[2] +
"][" + matrixPosition[3] + "," + matrixPosition[4] + "," + matrixPosition[5] +
"][" + matrixPosition[6] + "," + matrixPosition[7] + "," + matrixPosition[8] + "]]";
return result.toString();
}
/**
* Get an array representing this Transform.
*
* @return an array representing this Transform.
*/
public float[] getMatrixPosition() {
return matrixPosition;
}
/**
* Create a new rotation Transform
*
* @param angle The angle in radians to set the transform.
* @return The resulting Transform
*/
public static Transform createRotateTransform(float angle) {
return new Transform((float)FastTrig.cos(angle), -(float)FastTrig.sin(angle), 0, (float)FastTrig.sin(angle), (float)FastTrig.cos(angle), 0);
}
/**
* Create a new rotation Transform around the specified point
*
* @param angle The angle in radians to set the transform.
* @param x The x coordinate around which to rotate.
* @param y The y coordinate around which to rotate.
* @return The resulting Transform
*/
public static Transform createRotateTransform(float angle, float x, float y) {
Transform temp = Transform.createRotateTransform(angle);
float sinAngle = temp.matrixPosition[3];
float oneMinusCosAngle = 1.0f - temp.matrixPosition[4];
temp.matrixPosition[2] = x * oneMinusCosAngle + y * sinAngle;
temp.matrixPosition[5] = y * oneMinusCosAngle - x * sinAngle;
return temp;
}
/**
* Create a new translation Transform
*
* @param xOffset The amount to move in the x direction
* @param yOffset The amount to move in the y direction
* @return The resulting Transform
*/
public static Transform createTranslateTransform(float xOffset, float yOffset) {
return new Transform(1, 0, xOffset, 0, 1, yOffset);
}
/**
* Create an new scaling Transform
*
* @param xScale The amount to scale in the x coordinate
* @param yScale The amount to scale in the x coordinate
* @return The resulting Transform
*/
public static Transform createScaleTransform(float xScale, float yScale) {
return new Transform(xScale, 0, 0, 0, yScale, 0);
}
/**
* Transform the vector2f based on the matrix defined in this transform
*
* @param pt The point to be transformed
* @return The resulting point transformed by this matrix
*/
public Vector2f transform(Vector2f pt) {
float[] in = new float[] {pt.x, pt.y};
float[] out = new float[2];
transform(in, 0, out, 0, 1);
return new Vector2f(out[0], out[1]);
}
} |
package org.owasp.esapi;
import org.owasp.esapi.errors.AccessControlException;
public interface AccessController {
/**
* Checks if the current user is authorized to access the referenced URL. Generally, this method should be invoked in the
* application's controller or a filter as follows:
* <PRE>ESAPI.accessController().isAuthorizedForURL(request.getRequestURI().toString());</PRE>
*
* The implementation of this method should call assertAuthorizedForURL(String url), and if an AccessControlException is
* not thrown, this method should return true. This way, if the user is not authorized, false would be returned, and the
* exception would be logged.
*
* @param url
* the URL as returned by request.getRequestURI().toString()
*
* @return
* true, if is authorized for URL
*/
boolean isAuthorizedForURL(String url);
/**
* Checks if the current user is authorized to access the referenced function.
*
* The implementation of this method should call assertAuthorizedForFunction(String functionName), and if an
* AccessControlException is not thrown, this method should return true.
*
* @param functionName
* the name of the function
*
* @return
* true, if is authorized for function
*/
boolean isAuthorizedForFunction(String functionName);
/**
* Checks if the current user is authorized to access the referenced data, represented as an Object.
*
* The implementation of this method should call assertAuthorizedForData(String action, Object data), and if an
* AccessControlException is not thrown, this method should return true.
*
* @param action
* The action to verify for an access control decision, such as a role, or an action being performed on the object
* (e.g., Read, Write, etc.), or the name of the function the data is being passed to.
*
* @param data
* The actual object or object identifier being accessed or a reference to the object being accessed.
*
* @return
* true, if is authorized for the data
*/
boolean isAuthorizedForData(String action, Object data);
/**
* Checks if the current user is authorized to access the referenced file.
*
* The implementation of this method should call assertAuthorizedForFile(String filepath), and if an AccessControlException
* is not thrown, this method should return true.
*
* @param filepath
* the path of the file to be checked, including filename
*
* @return
* true, if is authorized for the file
*/
boolean isAuthorizedForFile(String filepath);
/**
* Checks if the current user is authorized to access the referenced service. This can be used in applications that
* provide access to a variety of back end services.
*
* The implementation of this method should call assertAuthorizedForService(String serviceName), and if an
* AccessControlException is not thrown, this method should return true.
*
* @param serviceName
* the service name
*
* @return
* true, if is authorized for the service
*/
boolean isAuthorizedForService(String serviceName);
/**
* Checks if the current user is authorized to access the referenced URL. The implementation should allow
* access to be granted to any part of the URL. Generally, this method should be invoked in the
* application's controller or a filter as follows:
* <PRE>ESAPI.accessController().assertAuthorizedForURL(request.getRequestURI().toString());</PRE>
*
* This method throws an AccessControlException if access is not authorized, or if the referenced URL does not exist.
* If the User is authorized, this method simply returns.
* <P>
* Specification: The implementation should do the following:
* <ol>
* <li>Check to see if the resource exists and if not, throw an AccessControlException</li>
* <li>Use available information to make an access control decision</li>
* <ol type="a">
* <li>Ideally, this policy would be data driven</li>
* <li>You can use the current User, roles, data type, data name, time of day, etc.</li>
* <li>Access control decisions must deny by default</li>
* </ol>
* <li>If access is not permitted, throw an AccessControlException with details</li>
* </ol>
* @param url
* the URL as returned by request.getRequestURI().toString()
*
* @throws AccessControlException
* if access is not permitted
*/
void assertAuthorizedForURL(String url) throws AccessControlException;
/**
* Checks if the current user is authorized to access the referenced function. The implementation should define the
* function "namespace" to be enforced. Choosing something simple like the class name of action classes or menu item
* names will make this implementation easier to use.
* <P>
* This method throws an AccessControlException if access is not authorized, or if the referenced function does not exist.
* If the User is authorized, this method simply returns.
* <P>
* Specification: The implementation should do the following:
* <ol>
* <li>Check to see if the function exists and if not, throw an AccessControlException</li>
* <li>Use available information to make an access control decision</li>
* <ol type="a">
* <li>Ideally, this policy would be data driven</li>
* <li>You can use the current User, roles, data type, data name, time of day, etc.</li>
* <li>Access control decisions must deny by default</li>
* </ol>
* <li>If access is not permitted, throw an AccessControlException with details</li>
* </ol>
*
* @param functionName
* the function name
*
* @throws AccessControlException
* if access is not permitted
*/
void assertAuthorizedForFunction(String functionName) throws AccessControlException;
/**
* Checks if the current user is authorized to access the referenced data. This method simply returns if access is authorized.
* It throws an AccessControlException if access is not authorized, or if the referenced data does not exist.
* <P>
* Specification: The implementation should do the following:
* <ol>
* <li>Check to see if the resource exists and if not, throw an AccessControlException</li>
* <li>Use available information to make an access control decision</li>
* <ol type="a">
* <li>Ideally, this policy would be data driven</li>
* <li>You can use the current User, roles, data type, data name, time of day, etc.</li>
* <li>Access control decisions must deny by default</li>
* </ol>
* <li>If access is not permitted, throw an AccessControlException with details</li>
* </ol>
*
* @param action
* The action to verify for an access control decision, such as a role, or an action being performed on the object
* (e.g., Read, Write, etc.), or the name of the function the data is being passed to.
*
* @param data
* The actual object or object identifier being accessed or a reference to the object being accessed.
*
* @throws AccessControlException
* if access is not permitted
*/
void assertAuthorizedForData(String action, Object data) throws AccessControlException;
/**
* Checks if the current user is authorized to access the referenced file. The implementation should validate and canonicalize the
* input to be sure the filepath is not malicious.
* <P>
* This method throws an AccessControlException if access is not authorized, or if the referenced File does not exist.
* If the User is authorized, this method simply returns.
* <P>
* Specification: The implementation should do the following:
* <ol>
* <li>Check to see if the File exists and if not, throw an AccessControlException</li>
* <li>Use available information to make an access control decision</li>
* <ol type="a">
* <li>Ideally, this policy would be data driven</li>
* <li>You can use the current User, roles, data type, data name, time of day, etc.</li>
* <li>Access control decisions must deny by default</li>
* </ol>
* <li>If access is not permitted, throw an AccessControlException with details</li>
* </ol>
*
* @param filepath
* Path to the file to be checked
* @throws AccessControlException if access is denied
*/
void assertAuthorizedForFile(String filepath) throws AccessControlException;
/**
* Checks if the current user is authorized to access the referenced service. This can be used in applications that
* provide access to a variety of backend services.
* <P>
* This method throws an AccessControlException if access is not authorized, or if the referenced service does not exist.
* If the User is authorized, this method simply returns.
* <P>
* Specification: The implementation should do the following:
* <ol>
* <li>Check to see if the service exists and if not, throw an AccessControlException</li>
* <li>Use available information to make an access control decision</li>
* <ol type="a">
* <li>Ideally, this policy would be data driven</li>
* <li>You can use the current User, roles, data type, data name, time of day, etc.</li>
* <li>Access control decisions must deny by default</li>
* </ol>
* <li>If access is not permitted, throw an AccessControlException with details</li>
* </ol>
*
* @param serviceName
* the service name
*
* @throws AccessControlException
* if access is not permitted
*/
void assertAuthorizedForService(String serviceName) throws AccessControlException;
} |
package org.rspspin.util;
import java.util.ArrayList;
import java.util.List;
import org.apache.jena.query.ParameterizedSparqlString;
import org.apache.jena.query.Query;
import org.apache.jena.query.QueryExecution;
import org.apache.jena.query.QueryExecutionFactory;
import org.apache.jena.query.QueryFactory;
import org.apache.jena.query.QuerySolutionMap;
import org.apache.jena.query.Syntax;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.NodeIterator;
import org.apache.jena.rdf.model.Property;
import org.apache.jena.rdf.model.RDFNode;
import org.apache.jena.rdf.model.Resource;
import org.apache.jena.vocabulary.RDF;
import org.rspspin.lang.rspql.ParserRSPQL;
import org.topbraid.spin.arq.ARQ2SPIN;
import org.topbraid.spin.arq.ARQFactory;
import org.topbraid.spin.model.Argument;
import org.topbraid.spin.model.Command;
import org.topbraid.spin.model.Module;
import org.topbraid.spin.model.Template;
import org.topbraid.spin.system.SPINArgumentChecker;
import org.topbraid.spin.system.SPINModuleRegistry;
import org.topbraid.spin.vocabulary.ARG;
import org.topbraid.spin.vocabulary.SP;
import org.topbraid.spin.vocabulary.SPIN;
import org.topbraid.spin.vocabulary.SPL;
public class TemplateManager {
private static TemplateManager instance = null;
private Model model;
private Syntax syntax = ParserRSPQL.syntax;
private ARQ2SPIN arq2spin;
/**
* Initialize
*/
private TemplateManager() {
ParserRSPQL.register();
SPINModuleRegistry.get().init();
ARQFactory.setSyntax(syntax);
model = Utils.createDefaultModel();
arq2spin = new ARQ2SPIN(model, true);
// Install the argument checker
SPINArgumentChecker.set(new SPINArgumentChecker() {
@Override
public void handleErrors(Module module, QuerySolutionMap bindings, List<String> errors)
throws ArgumentConstraintException {
throw new ArgumentConstraintException(errors);
}
});
}
/**
* Get singleton.
*/
public static TemplateManager get() {
if (instance == null) {
instance = new TemplateManager();
}
return instance;
}
/**
* Set template manager model.
*
* @param model
*/
public void setModel(Model model) {
this.model = model;
}
/**
* Get template manager model.
*
* @return
*/
public Model getModel() {
return model;
}
/**
* Create template
*
* @param templateUri
* @param queryString
* @return
*/
public Template createTemplate(String templateUri, String queryString) {
if (templateUri == null) {
System.err.println("Template identifier must be a valid URI");
return null;
}
Query arqQuery = QueryFactory.create(queryString, ParserRSPQL.syntax);
// Get template type
Resource templateType;
if (arqQuery.isSelectType()) {
templateType = SPIN.SelectTemplate;
} else if (arqQuery.isAskType()) {
templateType = SPIN.AskTemplate;
} else if (arqQuery.isConstructType()) {
templateType = SPIN.ConstructTemplate;
} else {
System.err.println("Invalid query type for template: " + arqQuery.getQueryType());
return null;
}
// Use a blank node identifier for the query
org.topbraid.spin.model.Query spinQuery = arq2spin.createQuery(arqQuery, null);
Template template = createResource(templateUri, templateType).as(Template.class);
template.addProperty(SPIN.body, spinQuery);
return template;
}
/**
* Create a resource.
*
* @param uri
* @return
*/
public Resource createResource(String uri) {
return model.createResource(uri);
}
/**
* Create a typed resource.
*
* @param type
* @return
*/
public Resource createResource(Resource type) {
return model.createResource(type);
}
/**
* Create a typed resource.
*
* @param uri
* @return
*/
public Resource createResource(String uri, Resource type) {
return model.createResource(uri, type);
}
/**
* Create a property.
*
* @param uri
* @return
*/
public Property createProperty(String uri) {
return model.createProperty(uri);
}
/**
* Create an argument constraint.
*
* @param varName
* Name of variable
* @param valueType
* Value type of variable binding
* @param defaultValue
* Default value for variable (or null)
* @param optional
* States whether the argument is required
* @return argument
* @throws ArgumentConstraintException
*/
public Resource addArgumentConstraint(String varName, RDFNode valueType, RDFNode defaultValue, boolean optional,
Template template) throws ArgumentConstraintException {
// Check if argument is variable in template
QueryExecution qe = QueryExecutionFactory.create(String.format(
"" + "PREFIX sp: <http://spinrdf.org/sp#> " + "ASK WHERE { <%s> (!<:>)*/sp:varName \"%s\" }",
template.getURI(), varName), template.getModel());
if (!qe.execAsk()) {
template.getModel().write(System.out, "TTL");
List<String> errors = new ArrayList<String>();
errors.add("Argument " + varName + " is not a variable in the query");
throw new ArgumentConstraintException(errors);
}
// Create argument
Resource arg = createResource(SPL.Argument);
arg.addProperty(SPL.predicate, createResource(ARG.NS + varName));
if (valueType != null)
arg.addProperty(SPL.valueType, valueType);
if (defaultValue != null)
arg.addProperty(SPL.defaultValue, defaultValue);
arg.addProperty(SPL.optional, model.createTypedLiteral(optional));
// Add constraint to template
template.addProperty(SPIN.constraint, arg);
return arg;
}
/**
* Get template from the current model based on a URI identifier.
*
* @return
*/
public Template getTemplate(String uri) {
// Find template type
NodeIterator iter = model.listObjectsOfProperty(model.createResource(uri), RDF.type);
if (iter.hasNext()) {
Resource r = iter.next().asResource();
if (r.equals(SPIN.SelectTemplate)) {
return model.createResource(uri, SPIN.SelectTemplate).as(Template.class);
} else if (r.equals(SPIN.ConstructTemplate)) {
return model.createResource(uri, SPIN.ConstructTemplate).as(Template.class);
} else if (r.equals(SPIN.AskTemplate)) {
return model.createResource(uri, SPIN.AskTemplate).as(Template.class);
} else {
return model.createResource(uri, SPIN.Template).as(Template.class);
}
}
return null;
}
/**
* Get a query from a template and a set of bindings.
*
* @param template
* @param bindings
* @return query
*/
public Query getQuery(Template template, QuerySolutionMap bindings) {
Query arq;
if (template.getBody() != null) {
Command spinQuery = template.getBody();
arq = ARQFactory.get().createQuery((org.topbraid.spin.model.Query) spinQuery);
} else {
arq = ARQFactory.get().createQuery(template.getProperty(SP.text).getObject().toString());
}
// Add default values
for (Argument arg : template.getArguments(false)) {
if (bindings.contains(arg.getVarName()) && arg.getDefaultValue() != null) {
bindings.add(arg.getVarName(), arg.getDefaultValue());
}
}
// Parameterized
ParameterizedSparqlString pss = new ParameterizedSparqlString(arq.toString(), bindings);
return pss.asQuery(syntax);
}
public void check(Template template, QuerySolutionMap bindings) throws ArgumentConstraintException {
SPINArgumentChecker.get().check(template, bindings);
}
/**
* Set the syntax used by the template manager.
*
* @param syntax
*/
public void setSyntax(Syntax syntax) {
this.syntax = syntax;
ARQFactory.setSyntax(syntax);
}
/**
* Get the syntax used by the template manager.
*
* @param syntax
* @return
*/
public Syntax getSyntax() {
return syntax;
}
} |
package org.semanticweb.yars.nx.cli;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.util.Iterator;
import java.util.logging.Logger;
import org.apache.commons.cli.BasicParser;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.semanticweb.yars.nx.Node;
import org.semanticweb.yars.nx.NodeComparator;
import org.semanticweb.yars.nx.NodeComparator.NodeComparatorArgs;
import org.semanticweb.yars.nx.parser.Callback;
import org.semanticweb.yars.nx.parser.NxParser;
import org.semanticweb.yars.nx.sort.SortIterator;
import org.semanticweb.yars.nx.sort.SortIterator.SortArgs;
import org.semanticweb.yars.util.CallbackNxBufferedWriter;
import org.semanticweb.yars.util.CheckSortedIterator;
import org.semanticweb.yars.util.SniffIterator;
public class Sort {
static transient Logger _log = Logger.getLogger(Sort.class.getName());
/**
* @param args
* @throws IOException
* @throws org.semanticweb.yars.nx.parser.ParseException
*/
public static void main(String[] args) throws org.semanticweb.yars.nx.parser.ParseException, IOException {
Options options = Main.getStandardOptions();
Option sortOrderO = new Option("so", "sort order: e.g. 0123 for SPOC 3012 for CSPO (written order preserved)");
sortOrderO.setArgs(1);
sortOrderO.setRequired(false);
options.addOption(sortOrderO);
Option numericOrderO = new Option("no", "numeric order: e.g. 2 for objects of order SPOC/0123, 21 for objects and predicates (independent of sort order)");
numericOrderO.setArgs(1);
numericOrderO.setRequired(false);
options.addOption(numericOrderO);
Option reverseOrderO = new Option("ro", "reverse order: e.g. 2 for objects of order SPOC/0123, 21 for objects and predicates (independent of sort order)");
reverseOrderO.setArgs(1);
reverseOrderO.setRequired(false);
options.addOption(reverseOrderO);
Option tmpO = new Option("tmp", "tmp folder for batches");
tmpO.setArgs(1);
tmpO.setRequired(false);
options.addOption(tmpO);
Option adO = new Option("ad", "allow duplicates");
adO.setArgs(0);
adO.setRequired(false);
options.addOption(adO);
Option batchO = new Option("b", "set batch size (default calculated based on magic numbers, tuple length and heap space)");
batchO.setArgs(1);
batchO.setRequired(false);
options.addOption(batchO);
Option nogzipbO = new Option("nbz", "no batch gzipping, takes more disk, less time (default gzipped)");
nogzipbO.setArgs(0);
nogzipbO.setRequired(false);
options.addOption(nogzipbO);
Option adaptiveO = new Option("ab", "adaptive batching based on monitoring of heap-space (default static batches, experimental/not recommended)");
adaptiveO.setArgs(0);
adaptiveO.setRequired(false);
options.addOption(adaptiveO);
Option flyweightO = new Option("fw", "flyweight cache size for input iterator (default off, experimental/not recommended)");
flyweightO.setArgs(1);
flyweightO.setRequired(false);
options.addOption(flyweightO);
Option verifyO = new Option("v", "verify sort order (debug mode)");
verifyO.setArgs(0);
verifyO.setRequired(false);
options.addOption(verifyO);
CommandLineParser parser = new BasicParser();
CommandLine cmd = null;
try {
cmd = parser.parse(options, args);
} catch (ParseException e) {
System.err.println("***ERROR: " + e.getClass() + ": " + e.getMessage());
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("parameters:", options );
return;
}
if (cmd.hasOption("h")) {
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("parameters:", options );
return;
}
if(cmd.hasOption("b") && cmd.hasOption("ab")){
System.err.println("***ERROR: Please set -b *OR* -ab.");
}
InputStream is = Main.getMainInputStream(cmd);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(Main.getMainOutputStream(cmd)));
int ticks = Main.getTicks(cmd);
Iterator<Node[]> it = new NxParser(is);
Callback cb = new CallbackNxBufferedWriter(bw);
NodeComparatorArgs nca = new NodeComparatorArgs();
if(cmd.hasOption("so")){
nca.setOrder(NodeComparatorArgs.getIntegerMask(cmd.getOptionValue("so")));
}
if(cmd.hasOption("no")){
nca.setNumeric(NodeComparatorArgs.getBooleanMask(cmd.getOptionValue("no")));
}
if(cmd.hasOption("ro")){
nca.setReverse(NodeComparatorArgs.getBooleanMask(cmd.getOptionValue("ro")));
}
if(cmd.hasOption("ad")){
nca.setNoEquals(true);
nca.setNoZero(true);
}
String tmp = null;
if(cmd.hasOption("tmp")){
tmp = cmd.getOptionValue("tmp");
if(!tmp.endsWith("/")&&!tmp.endsWith("\\")){
tmp = tmp+"/";
}
File f = new File(tmp);
f.mkdirs();
}
SniffIterator sit = new SniffIterator(it);
NodeComparator nc = new NodeComparator(nca);
SortArgs sa = new SortArgs(sit, sit.nxLength());
sa.setTicks(ticks);
sa.setComparator(nc);
sa.setTmpDir(tmp);
if(cmd.hasOption("b"))
sa.setLinesPerBatch(Integer.parseInt(cmd.getOptionValue("b")));
else if(cmd.hasOption("ab"))
sa.setAdaptiveBatches();
if(cmd.hasOption("fw"))
sa.setFlyWeight(Integer.parseInt(cmd.getOptionValue("fw")));
if(cmd.hasOption("nbz"))
sa.setGzipBatches(false);
SortIterator si = new SortIterator(sa);
Iterator<Node[]> iter = si;
if(cmd.hasOption("v")){
iter = new CheckSortedIterator(si, nc);
}
while(iter.hasNext()){
cb.processStatement(iter.next());
}
_log.info("Finished sort. Sorted "+si.count()+" with "+si.duplicates()+" duplicates.");
is.close();
bw.close();
}
} |
package org.whitesource.fs;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whitesource.agent.ConfigPropertyKeys;
import org.whitesource.agent.FileSystemScanner;
import org.whitesource.agent.api.model.AgentProjectInfo;
import org.whitesource.agent.dependency.resolver.DependencyResolutionService;
import org.whitesource.fs.configuration.ConfigurationSerializer;
import org.whitesource.fs.configuration.ResolverConfiguration;
import java.util.*;
public class ComponentScan {
private static final Logger logger = LoggerFactory.getLogger(ComponentScan.class);
public static final String DIRECTORY_NOT_SET = "Directory parameter 'd' is not set" + StatusCode.ERROR;
public static final String EMPTY_PROJECT_TOKEN = "";
public static final String SPACE = " ";
private Properties config;
public ComponentScan(Properties config) {
this.config = config;
}
public String scan() {
logger.info("Starting Analysis - component scan has started");
String directory = config.getProperty("d");
String[] directories = directory.split(SPACE);
ArrayList<String> scannerBaseDirs = new ArrayList<>(Arrays.asList(directories));
if (!scannerBaseDirs.isEmpty()) {
logger.info("Getting properties");
// configure properties
// List<String> scannerBaseDirs = Collections.singletonList(directory);
FSAConfiguration fsaConfiguration = new FSAConfiguration(config);
// set default values in case of missing parameters
ResolverConfiguration resolverConfiguration = new ResolverConfiguration(config);
String[] includes = config.getProperty(ConfigPropertyKeys.INCLUDES_PATTERN_PROPERTY_KEY) != null ?
config.getProperty(ConfigPropertyKeys.INCLUDES_PATTERN_PROPERTY_KEY).split(FSAConfiguration.INCLUDES_EXCLUDES_SEPARATOR_REGEX) : ExtensionUtils.INCLUDES;
String[] excludes = config.getProperty(ConfigPropertyKeys.EXCLUDES_PATTERN_PROPERTY_KEY) != null ?
config.getProperty(ConfigPropertyKeys.EXCLUDES_PATTERN_PROPERTY_KEY).split(FSAConfiguration.INCLUDES_EXCLUDES_SEPARATOR_REGEX) : ExtensionUtils.EXCLUDES;
boolean globCaseSensitive = config.getProperty(ConfigPropertyKeys.CASE_SENSITIVE_GLOB_PROPERTY_KEY) != null ?
Boolean.valueOf(config.getProperty(ConfigPropertyKeys.CASE_SENSITIVE_GLOB_PROPERTY_KEY)) : false;
boolean followSymlinks = config.getProperty(ConfigPropertyKeys.CASE_SENSITIVE_GLOB_PROPERTY_KEY) != null ?
Boolean.valueOf(config.getProperty(ConfigPropertyKeys.CASE_SENSITIVE_GLOB_PROPERTY_KEY)) : false;
Collection<String> excludedCopyrights = new ArrayList<>(Arrays.asList(fsaConfiguration.getExcludedCopyrightsValue().split(",")));
excludedCopyrights.remove("");
//todo hasScmConnectors[0] in future - no need for cx
// Resolving dependencies
logger.info("Resolving dependencies");
Collection<AgentProjectInfo> projects = new FileSystemScanner(true, new DependencyResolutionService(resolverConfiguration)).createProjects(
scannerBaseDirs, false, includes, excludes, globCaseSensitive, fsaConfiguration.getArchiveExtractionDepth(),
fsaConfiguration.getArchiveIncludes(), fsaConfiguration.getArchiveExcludes(), fsaConfiguration.isArchiveFastUnpack(), followSymlinks, excludedCopyrights,
fsaConfiguration.isPartialSha1Match(), fsaConfiguration.isCalculateHints(), fsaConfiguration.isCalculateMd5());
logger.info("Finished dependency resolution");
for (AgentProjectInfo project : projects) {
// project.setCoordinates(new Coordinates());
project.setProjectToken(EMPTY_PROJECT_TOKEN);
}
// Return dependencies
String jsonString = new ConfigurationSerializer<>().getAsString((Collection<AgentProjectInfo>)projects);
return jsonString;
} else
return "";// new ConfigurationSerializer<>().getAsString(new Collection<AgentProjectInfo>);
}
} |
package refinedstorage.tile.solderer;
import io.netty.buffer.ByteBuf;
import net.minecraft.inventory.Container;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.EnumFacing;
import net.minecraft.world.World;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.items.CapabilityItemHandler;
import net.minecraftforge.items.IItemHandler;
import net.minecraftforge.items.wrapper.CombinedInvWrapper;
import refinedstorage.RefinedStorageItems;
import refinedstorage.RefinedStorageUtils;
import refinedstorage.container.ContainerSolderer;
import refinedstorage.inventory.BasicItemHandler;
import refinedstorage.inventory.BasicItemValidator;
import refinedstorage.inventory.SoldererItemHandler;
import refinedstorage.item.ItemUpgrade;
import refinedstorage.tile.TileMachine;
public class TileSolderer extends TileMachine {
public static final String NBT_WORKING = "Working";
public static final String NBT_PROGRESS = "Progress";
private BasicItemHandler items = new BasicItemHandler(4, this);
private BasicItemHandler upgrades = new BasicItemHandler(4, this, new BasicItemValidator(RefinedStorageItems.UPGRADE, ItemUpgrade.TYPE_SPEED));
private SoldererItemHandler[] itemsFacade = new SoldererItemHandler[EnumFacing.values().length];
private ISoldererRecipe recipe;
private boolean working = false;
private int progress = 0;
private int duration;
@Override
public int getEnergyUsage() {
return 3;
}
@Override
public void updateMachine() {
boolean wasWorking = working;
if (items.getStackInSlot(1) == null && items.getStackInSlot(2) == null && items.getStackInSlot(3) == null) {
stop();
} else {
ISoldererRecipe newRecipe = SoldererRegistry.getRecipe(items);
if (newRecipe == null) {
stop();
} else if (newRecipe != recipe) {
boolean isSameItem = items.getStackInSlot(3) != null ? RefinedStorageUtils.compareStackNoQuantity(items.getStackInSlot(3), newRecipe.getResult()) : false;
if (items.getStackInSlot(3) == null || (isSameItem && ((items.getStackInSlot(3).stackSize + newRecipe.getResult().stackSize) <= items.getStackInSlot(3).getMaxStackSize()))) {
recipe = newRecipe;
progress = 0;
working = true;
markDirty();
}
} else if (working) {
progress += 1 + RefinedStorageUtils.getUpgradeCount(upgrades, ItemUpgrade.TYPE_SPEED);
if (progress >= recipe.getDuration()) {
if (items.getStackInSlot(3) != null) {
items.getStackInSlot(3).stackSize += recipe.getResult().stackSize;
} else {
items.setStackInSlot(3, recipe.getResult());
}
for (int i = 0; i < 3; ++i) {
if (recipe.getRow(i) != null) {
items.extractItem(i, recipe.getRow(i).stackSize, false);
}
}
recipe = null;
progress = 0;
// Don't set working to false yet, wait till the next update because we may have
// another stack waiting.
markDirty();
}
}
}
if (wasWorking != working) {
RefinedStorageUtils.updateBlock(worldObj, pos);
}
}
@Override
public void onDisconnected(World world) {
super.onDisconnected(world);
stop();
}
public void stop() {
progress = 0;
working = false;
recipe = null;
markDirty();
}
@Override
public void read(NBTTagCompound nbt) {
super.read(nbt);
RefinedStorageUtils.readItems(items, 0, nbt);
RefinedStorageUtils.readItems(upgrades, 1, nbt);
recipe = SoldererRegistry.getRecipe(items);
if (nbt.hasKey(NBT_WORKING)) {
working = nbt.getBoolean(NBT_WORKING);
}
if (nbt.hasKey(NBT_PROGRESS)) {
progress = nbt.getInteger(NBT_PROGRESS);
}
}
@Override
public NBTTagCompound write(NBTTagCompound tag) {
super.write(tag);
RefinedStorageUtils.writeItems(items, 0, tag);
RefinedStorageUtils.writeItems(upgrades, 1, tag);
tag.setBoolean(NBT_WORKING, working);
tag.setInteger(NBT_PROGRESS, progress);
return tag;
}
@Override
public NBTTagCompound writeUpdate(NBTTagCompound tag) {
super.writeUpdate(tag);
tag.setBoolean(NBT_WORKING, working);
return tag;
}
@Override
public void readUpdate(NBTTagCompound tag) {
working = tag.getBoolean(NBT_WORKING);
super.readUpdate(tag);
}
@Override
public void readContainerData(ByteBuf buf) {
super.readContainerData(buf);
progress = buf.readInt();
duration = buf.readInt();
}
@Override
public void writeContainerData(ByteBuf buf) {
super.writeContainerData(buf);
buf.writeInt(progress);
buf.writeInt(recipe != null ? recipe.getDuration() : 0);
}
@Override
public Class<? extends Container> getContainer() {
return ContainerSolderer.class;
}
public boolean isWorking() {
return working;
}
public int getProgressScaled(int i) {
if (progress > duration) {
return i;
}
return (int) ((float) progress / (float) duration * (float) i);
}
public BasicItemHandler getItems() {
return items;
}
public IItemHandler getUpgrades() {
return upgrades;
}
@Override
public IItemHandler getDroppedItems() {
return new CombinedInvWrapper(items, upgrades);
}
@Override
public <T> T getCapability(Capability<T> capability, EnumFacing facing) {
if (capability == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY) {
int i = facing.ordinal();
if (itemsFacade[i] == null) {
itemsFacade[i] = new SoldererItemHandler(this, facing);
}
return (T) itemsFacade[i];
}
return super.getCapability(capability, facing);
}
@Override
public boolean hasCapability(Capability<?> capability, EnumFacing facing) {
return capability == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY || super.hasCapability(capability, facing);
}
} |
package systems.crigges.jmpq3;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import systems.crigges.jmpq3.BlockTable.Block;
import systems.crigges.jmpq3.compression.RecompressOptions;
import systems.crigges.jmpq3.security.MPQEncryption;
import systems.crigges.jmpq3.security.MPQHashGenerator;
import java.io.EOFException;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileChannel.MapMode;
import java.nio.channels.NonWritableChannelException;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
import java.nio.file.*;
import java.util.*;
import static systems.crigges.jmpq3.MpqFile.*;
/**
* Provides an interface for using MPQ archive files. MPQ archive files contain
* a virtual file system used by some old games to hold data, primarily those
* from Blizzard Entertainment.
* <p>
* MPQ archives are not intended as a general purpose file system. File access
* and reading is highly efficient. File manipulation and writing is not
* efficient and may require rebuilding a large portion of the archive file.
* Empty directories are not supported. The full contents of the archive might
* not be discoverable, but such files can still be accessed if their full path
* is known. File attributes are optional.
* <p>
* For platform independence the implementation is pure Java.
*/
public class JMpqEditor implements AutoCloseable {
private Logger log = LoggerFactory.getLogger(this.getClass().getName());
public static final int ARCHIVE_HEADER_MAGIC = ByteBuffer.wrap(new byte[]{'M', 'P', 'Q', 0x1A}).order(ByteOrder.LITTLE_ENDIAN).getInt();
public static final int USER_DATA_HEADER_MAGIC = ByteBuffer.wrap(new byte[]{'M', 'P', 'Q', 0x1B}).order(ByteOrder.LITTLE_ENDIAN).getInt();
/**
* Encryption key for hash table data.
*/
private static final int KEY_HASH_TABLE;
/**
* Encryption key for block table data.
*/
private static final int KEY_BLOCK_TABLE;
static {
final MPQHashGenerator hasher = MPQHashGenerator.getFileKeyGenerator();
hasher.process("(hash table)");
KEY_HASH_TABLE = hasher.getHash();
hasher.reset();
hasher.process("(block table)");
KEY_BLOCK_TABLE = hasher.getHash();
}
public static File tempDir;
private AttributesFile attributes;
/** MPQ format version 0 forced compatibility is being used. */
private final boolean legacyCompatibility;
/** The fc. */
private FileChannel fc;
/** The header offset. */
private long headerOffset = -1;
/** The header size. */
private int headerSize;
/** The archive size. */
private long archiveSize;
/** The format version. */
private int formatVersion;
/** The sector size shift */
private int sectorSizeShift;
/** The disc block size. */
private int discBlockSize;
/** The hash table file position. */
private long hashPos;
/** The block table file position. */
private long blockPos;
/** The hash size. */
private int hashSize;
/** The block size. */
private int blockSize;
/** The hash table. */
private HashTable hashTable;
/** The block table. */
private BlockTable blockTable;
/** The list file. */
private Listfile listFile = new Listfile();
/** The internal filename. */
private IdentityHashMap<String, ByteBuffer> filenameToData = new IdentityHashMap<>();
/** The files to add. */
/** The keep header offset. */
private boolean keepHeaderOffset = true;
/** The new header size. */
private int newHeaderSize;
/** The new archive size. */
private long newArchiveSize;
/** The new format version. */
private int newFormatVersion;
/** The new disc block size. */
private int newSectorSizeShift;
/** The new disc block size. */
private int newDiscBlockSize;
/** The new hash pos. */
private long newHashPos;
/** The new block pos. */
private long newBlockPos;
/** The new hash size. */
private int newHashSize;
/** The new block size. */
private int newBlockSize;
/** If write operations are supported on the archive. */
private boolean canWrite;
public JMpqEditor(Path mpqArchive, MPQOpenOption... openOptions) throws JMpqException {
// process open options
canWrite = !Arrays.asList(openOptions).contains(MPQOpenOption.READ_ONLY);
legacyCompatibility = Arrays.asList(openOptions).contains(MPQOpenOption.FORCE_V0);
log.debug(mpqArchive.toString());
try {
setupTempDir();
final OpenOption[] fcOptions = canWrite ? new OpenOption[]{StandardOpenOption.CREATE, StandardOpenOption.READ, StandardOpenOption.WRITE}
: new OpenOption[]{StandardOpenOption.READ};
fc = FileChannel.open(mpqArchive, fcOptions);
headerOffset = searchHeader();
readHeaderSize();
readHeader();
checkLegacyCompat();
readHashTable();
readBlockTable();
readListFile();
readAttributesFile();
} catch (IOException e) {
throw new JMpqException(mpqArchive.toAbsolutePath().toString() + ": " + e.getMessage());
}
}
/**
* See {@link #JMpqEditor(Path, MPQOpenOption...)} }
*
* @param mpqArchive a MPQ archive file.
* @param openOptions options to use when opening the archive.
* @throws JMpqException if mpq is damaged or not supported.
*/
public JMpqEditor(File mpqArchive, MPQOpenOption... openOptions) throws IOException {
this(mpqArchive.toPath(), openOptions);
}
/**
* See {@link #JMpqEditor(Path, MPQOpenOption...)} }
* Kept for backwards compatibility, but deprecated
*
* @param mpqArchive a MPQ archive file.
* @throws JMpqException if mpq is damaged or not supported.
*/
@Deprecated
public JMpqEditor(File mpqArchive) throws IOException {
this(mpqArchive.toPath(), MPQOpenOption.FORCE_V0);
}
private void checkLegacyCompat() throws IOException {
if (legacyCompatibility) {
// limit end of archive by end of file
archiveSize = Math.min(archiveSize, fc.size() - headerOffset);
// limit block table size by end of archive
blockSize = (int) (Math.min(blockSize, (archiveSize - blockPos) / 16));
}
}
private void readAttributesFile() {
if (hasFile("(attributes)")) {
try {
attributes = new AttributesFile(extractFileAsBytes("(attributes)"));
} catch (Exception e) {
}
}
}
private void readListFile() {
if (hasFile("(listfile)")) {
try {
File tempFile = File.createTempFile("list", "file", JMpqEditor.tempDir);
tempFile.deleteOnExit();
extractFile("(listfile)", tempFile);
listFile = new Listfile(Files.readAllBytes(tempFile.toPath()));
int hiddenFiles = (hasFile("(attributes)") ? 2 : 1) + (hasFile("(signature)") ? 1 : 0);
if (canWrite) {
if (listFile.getFiles().size() >= blockTable.getAllVaildBlocks().size() - hiddenFiles) {
log.warn("mpq's listfile is incomplete. Blocks without listfile entry will be discarded");
}
for (String fileName : listFile.getFiles()) {
if (!hasFile(fileName)) {
log.warn("listfile entry does not exist in archive and will be discarded: " + fileName);
}
}
listFile.getFileMap().entrySet().removeIf(file -> !hasFile(file.getValue()));
}
} catch (Exception e) {
log.warn("Extracting the mpq's listfile failed. It cannot be rebuild.", e);
}
} else {
log.warn("The mpq doesn't contain a listfile. It cannot be rebuild.");
canWrite = false;
}
}
private void readBlockTable() throws IOException {
ByteBuffer blockBuffer = ByteBuffer.allocate(blockSize * 16).order(ByteOrder.LITTLE_ENDIAN);
fc.position(headerOffset + blockPos);
readFully(blockBuffer, fc);
blockBuffer.rewind();
blockTable = new BlockTable(blockBuffer);
}
private void readHashTable() throws IOException {
// read hash table
ByteBuffer hashBuffer = ByteBuffer.allocate(hashSize * 16);
fc.position(headerOffset + hashPos);
readFully(hashBuffer, fc);
hashBuffer.rewind();
// decrypt hash table
final MPQEncryption decrypt = new MPQEncryption(KEY_HASH_TABLE, true);
decrypt.processSingle(hashBuffer);
hashBuffer.rewind();
// create hash table
hashTable = new HashTable(hashSize);
hashTable.readFromBuffer(hashBuffer);
}
private void readHeaderSize() throws IOException {
// probe to sample file with
ByteBuffer probe = ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN);
// read header size
fc.position(headerOffset + 4);
readFully(probe, fc);
headerSize = probe.getInt(0);
if (legacyCompatibility) {
// force version 0 header size
headerSize = 32;
} else if (headerSize < 32 || 208 < headerSize) {
// header too small or too big
throw new JMpqException("Bad header size.");
}
}
private void setupTempDir() throws JMpqException {
try {
Path path = Paths.get(System.getProperty("java.io.tmpdir") + "jmpq");
JMpqEditor.tempDir = path.toFile();
if (!JMpqEditor.tempDir.exists())
Files.createDirectory(path);
File[] files = JMpqEditor.tempDir.listFiles();
for (File f : files) {
f.delete();
}
} catch (IOException e) {
try {
JMpqEditor.tempDir = Files.createTempDirectory("jmpq").toFile();
} catch (IOException e1) {
throw new JMpqException(e1);
}
}
}
// /**
// * Loads a default listfile for mpqs that have none
// * Makes the archive readonly.
// */
// private void loadDefaultListFile() throws IOException {
// log.warn("The mpq doesn't come with a listfile so it cannot be rebuild");
// InputStream resource = getClass().getClassLoader().getResourceAsStream("DefaultListfile.txt");
// if (resource != null) {
// File tempFile = File.createTempFile("jmpq", "lf", tempDir);
// tempFile.deleteOnExit();
// try (FileOutputStream out = new FileOutputStream(tempFile)) {
// //copy stream
// byte[] buffer = new byte[1024];
// int bytesRead;
// while ((bytesRead = resource.read(buffer)) != -1) {
// out.write(buffer, 0, bytesRead);
// listFile = new Listfile(Files.readAllBytes(tempFile.toPath()));
// canWrite = false;
/**
* Searches the file for the MPQ archive header.
*
* @return the file position at which the MPQ archive starts.
* @throws IOException if an error occurs while searching.
* @throws JMpqException if file does not contain a MPQ archive.
*/
private long searchHeader() throws IOException {
// probe to sample file with
ByteBuffer probe = ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN);
final long fileSize = fc.size();
for (long filePos = 0; filePos + probe.capacity() < fileSize; filePos += 0x200) {
probe.rewind();
fc.position(filePos);
readFully(probe, fc);
final int sample = probe.getInt(0);
if (sample == ARCHIVE_HEADER_MAGIC) {
// found archive header
return filePos;
} else if (sample == USER_DATA_HEADER_MAGIC && !legacyCompatibility) {
// MPQ user data header with redirect to MPQ header
// ignore in legacy compatibility mode
// TODO process these in some meaningful way
probe.rewind();
fc.position(filePos + 8);
readFully(probe, fc);
// add header offset and align
filePos += (probe.getInt(0) & 0xFFFFFFFFL);
filePos &= ~(0x200 - 1);
}
}
throw new JMpqException("No MPQ archive in file.");
}
/**
* Read the MPQ archive header from the header chunk.
*/
private void readHeader() throws IOException {
ByteBuffer buffer = ByteBuffer.allocate(headerSize).order(ByteOrder.LITTLE_ENDIAN);
readFully(buffer, fc);
buffer.rewind();
archiveSize = buffer.getInt() & 0xFFFFFFFFL;
formatVersion = buffer.getShort();
if (legacyCompatibility) {
// force version 0 interpretation
formatVersion = 0;
}
sectorSizeShift = buffer.getShort();
discBlockSize = 512 * (1 << sectorSizeShift);
hashPos = buffer.getInt() & 0xFFFFFFFFL;
blockPos = buffer.getInt() & 0xFFFFFFFFL;
hashSize = buffer.getInt();
blockSize = buffer.getInt();
// version 1 extension
if (formatVersion >= 1) {
// TODO add high block table support
buffer.getLong();
// high 16 bits of file pos
hashPos |= (buffer.getShort() & 0xFFFFL) << 32;
blockPos |= (buffer.getShort() & 0xFFFFL) << 32;
}
// version 2 extension
if (formatVersion >= 2) {
// 64 bit archive size
archiveSize = buffer.getLong();
// TODO add support for BET and HET tables
buffer.getLong();
buffer.getLong();
}
// version 3 extension
if (formatVersion >= 3) {
// TODO add support for compression and checksums
buffer.getLong();
buffer.getLong();
buffer.getLong();
buffer.getLong();
buffer.getLong();
buffer.getInt();
final byte[] md5 = new byte[16];
buffer.get(md5);
buffer.get(md5);
buffer.get(md5);
buffer.get(md5);
buffer.get(md5);
buffer.get(md5);
}
}
/**
* Write header.
*
* @param buffer the buffer
*/
private void writeHeader(MappedByteBuffer buffer) {
buffer.putInt(newHeaderSize);
buffer.putInt((int) newArchiveSize);
buffer.putShort((short) newFormatVersion);
buffer.putShort((short) newSectorSizeShift);
buffer.putInt((int) newHashPos);
buffer.putInt((int) newBlockPos);
buffer.putInt(newHashSize);
buffer.putInt(newBlockSize);
// TODO add full write support for versions above 1
}
/**
* Calc new table size.
*/
private void calcNewTableSize() {
int target = listFile.getFiles().size() + 2;
int current = 2;
while (current < target) {
current *= 2;
}
newHashSize = current * 2;
newBlockSize = listFile.getFiles().size() + 2;
}
/**
* Extract all files.
*
* @param dest the dest
* @throws JMpqException the j mpq exception
*/
public void extractAllFiles(File dest) throws JMpqException {
if (!dest.isDirectory()) {
throw new JMpqException("Destination location isn't a directory");
}
if (hasFile("(listfile)") && listFile != null) {
for (String s : listFile.getFiles()) {
log.debug("extracting: " + (dest.separatorChar == '\\' ? s : s.replace("\\", dest.separator)));
File temp = new File(dest.getAbsolutePath() + dest.separator + (dest.separatorChar == '\\' ? s : s.replace("\\", dest.separator)));
temp.getParentFile().mkdirs();
if (hasFile(s)) {
// Prevent exception due to nonexistent listfile entries
try {
extractFile(s, temp);
} catch (JMpqException e) {
log.warn("File possibly corrupted and could not be extracted: " + s);
}
}
}
if (hasFile("(attributes)")) {
File temp = new File(dest.getAbsolutePath() + dest.separator + "(attributes)");
extractFile("(attributes)", temp);
}
File temp = new File(dest.getAbsolutePath() + dest.separator + "(listfile)");
extractFile("(listfile)", temp);
} else {
ArrayList<Block> blocks = blockTable.getAllVaildBlocks();
try {
int i = 0;
for (Block b : blocks) {
if ((b.getFlags() & MpqFile.ENCRYPTED) == MpqFile.ENCRYPTED) {
continue;
}
ByteBuffer buf = ByteBuffer.allocate(b.getCompressedSize()).order(ByteOrder.LITTLE_ENDIAN);
fc.position(headerOffset + b.getFilePos());
readFully(buf, fc);
buf.rewind();
MpqFile f = new MpqFile(buf, b, discBlockSize, "");
f.extractToFile(new File(dest.getAbsolutePath() + dest.separator + i));
i++;
}
} catch (IOException e) {
throw new JMpqException(e);
}
}
}
/**
* Gets the total file count.
*
* @return the total file count
* @throws JMpqException the j mpq exception
*/
public int getTotalFileCount() throws JMpqException {
return blockTable.getAllVaildBlocks().size();
}
/**
* Extracts the specified file out of the mpq to the target location.
*
* @param name name of the file
* @param dest destination to that the files content is written
* @throws JMpqException if file is not found or access errors occur
*/
public void extractFile(String name, File dest) throws JMpqException {
try {
MpqFile f = getMpqFile(name);
f.extractToFile(dest);
} catch (Exception e) {
throw new JMpqException(e);
}
}
/**
* Extracts the specified file out of the mpq to the target location.
*
* @param name name of the file
* @throws JMpqException if file is not found or access errors occur
*/
public byte[] extractFileAsBytes(String name) throws JMpqException {
try {
MpqFile f = getMpqFile(name);
return f.extractToBytes();
} catch (IOException e) {
throw new JMpqException(e);
}
}
public String extractFileAsString(String name) throws JMpqException {
try {
byte[] f = extractFileAsBytes(name);
return new String(f);
} catch (IOException e) {
throw new JMpqException(e);
}
}
/**
* Checks for file.
*
* @param name the name
* @return true, if successful
*/
public boolean hasFile(String name) {
try {
hashTable.getBlockIndexOfFile(name);
} catch (IOException e) {
return false;
}
return true;
}
/**
* Gets the file names.
*
* @return the file names
*/
public List<String> getFileNames() {
return new ArrayList<>(listFile.getFiles());
}
/**
* Extracts the specified file out of the mpq and writes it to the target
* outputstream.
*
* @param name name of the file
* @param dest the outputstream where the file's content is written
* @throws JMpqException if file is not found or access errors occur
*/
public void extractFile(String name, OutputStream dest) throws JMpqException {
try {
MpqFile f = getMpqFile(name);
f.extractToOutputStream(dest);
} catch (IOException e) {
throw new JMpqException(e);
}
}
/**
* Gets the mpq file.
*
* @param name the name
* @return the mpq file
* @throws IOException Signals that an I/O exception has occurred.
*/
public MpqFile getMpqFile(String name) throws IOException {
int pos = hashTable.getBlockIndexOfFile(name);
Block b = blockTable.getBlockAtPos(pos);
ByteBuffer buffer = ByteBuffer.allocate(b.getCompressedSize()).order(ByteOrder.LITTLE_ENDIAN);
fc.position(headerOffset + b.getFilePos());
readFully(buffer, fc);
buffer.rewind();
return new MpqFile(buffer, b, discBlockSize, name);
}
/**
* Deletes the specified file out of the mpq once you rebuild the mpq.
*
* @param name of the file inside the mpq
* @throws JMpqException if file is not found or access errors occur
*/
public void deleteFile(String name) {
if (!canWrite) {
throw new NonWritableChannelException();
}
if (listFile.containsFile(name)) {
listFile.removeFile(name);
filenameToData.remove(name);
}
}
/**
* Inserts the specified byte array into the mpq once you close the editor.
*
* @param name of the file inside the mpq
* @param input the input byte array
* @throws JMpqException if file is not found or access errors occur
*/
public void insertByteArray(String name, byte[] input) throws NonWritableChannelException, IllegalArgumentException {
if (!canWrite) {
throw new NonWritableChannelException();
}
if (listFile.containsFile(name)) {
throw new IllegalArgumentException("Archive already contains file with name: " + name);
}
listFile.addFile(name);
ByteBuffer data = ByteBuffer.wrap(input);
filenameToData.put(name, data);
}
/**
* Inserts the specified file into the mpq once you close the editor.
*
* @param name of the file inside the mpq
* @param file the file
* @param backupFile if true the editors creates a copy of the file to add, so
* further changes won't affect the resulting mpq
* @throws JMpqException if file is not found or access errors occur
*/
public void insertFile(String name, File file, boolean backupFile) throws IOException, IllegalArgumentException {
if (!canWrite) {
throw new NonWritableChannelException();
}
log.info("insert file: " + name);
if (listFile.containsFile(name)) {
throw new IllegalArgumentException("Archive already contains file with name: " + name);
}
try {
listFile.addFile(name);
if (backupFile) {
File temp = File.createTempFile("jmpq", "backup", JMpqEditor.tempDir);
temp.deleteOnExit();
Files.copy(file.toPath(), temp.toPath(), StandardCopyOption.REPLACE_EXISTING);
ByteBuffer data = ByteBuffer.wrap(Files.readAllBytes(temp.toPath()));
filenameToData.put(name, data);
} else {
ByteBuffer data = ByteBuffer.wrap(Files.readAllBytes(file.toPath()));
filenameToData.put(name, data);
}
} catch (IOException e) {
throw new JMpqException(e);
}
}
public void closeReadOnly() throws IOException {
fc.close();
}
public void close() throws IOException {
close(true, true, false);
}
public void close(boolean buildListfile, boolean buildAttributes, boolean recompress) throws IOException {
close(buildListfile, buildAttributes, new RecompressOptions(recompress));
}
/**
* @param buildListfile whether or not to add a (listfile) to this mpq
* @param buildAttributes whether or not to add a (attributes) file to this mpq
* @throws IOException
*/
public void close(boolean buildListfile, boolean buildAttributes, RecompressOptions options) throws IOException {
// only rebuild if allowed
if (!canWrite || !fc.isOpen()) {
fc.close();
log.debug("closed readonly mpq.");
return;
}
long t = System.nanoTime();
log.debug("Building mpq");
if (listFile == null) {
fc.close();
return;
}
File temp = File.createTempFile("jmpq", "temp", JMpqEditor.tempDir);
temp.deleteOnExit();
FileChannel writeChannel = FileChannel.open(temp.toPath(), StandardOpenOption.CREATE, StandardOpenOption.WRITE, StandardOpenOption.READ);
ByteBuffer headerReader = ByteBuffer.allocate((int) ((keepHeaderOffset ? headerOffset : 0) + 4)).order(ByteOrder.LITTLE_ENDIAN);
fc.position((keepHeaderOffset ? 0 : headerOffset));
readFully(headerReader, fc);
headerReader.rewind();
writeChannel.write(headerReader);
newFormatVersion = formatVersion;
switch (newFormatVersion) {
case 0:
newHeaderSize = 32;
break;
case 1:
newHeaderSize = 44;
break;
case 2:
case 3:
newHeaderSize = 208;
break;
}
newSectorSizeShift = options.recompress ? Math.min(options.newSectorSizeShift, 15) : sectorSizeShift;
newDiscBlockSize = options.recompress ? 512 * (1 << newSectorSizeShift) : discBlockSize;
calcNewTableSize();
ArrayList<Block> newBlocks = new ArrayList<>();
ArrayList<String> newFiles = new ArrayList<>();
ArrayList<String> existingFiles = new ArrayList<>(listFile.getFiles());
sortListfileEntries(existingFiles);
log.debug("Sorted blocks");
if (attributes != null) {
attributes.setNames(existingFiles);
}
long currentPos = (keepHeaderOffset ? headerOffset : 0) + headerSize;
for (String fileName : filenameToData.keySet()) {
existingFiles.remove(fileName);
}
for (String existingName : existingFiles) {
if (options.recompress && !existingName.endsWith(".wav")) {
ByteBuffer extracted = ByteBuffer.wrap(extractFileAsBytes(existingName));
filenameToData.put(existingName, extracted);
} else {
newFiles.add(existingName);
int pos = hashTable.getBlockIndexOfFile(existingName);
Block b = blockTable.getBlockAtPos(pos);
ByteBuffer buf = ByteBuffer.allocate(b.getCompressedSize()).order(ByteOrder.LITTLE_ENDIAN);
fc.position(headerOffset + b.getFilePos());
readFully(buf, fc);
buf.rewind();
MpqFile f = new MpqFile(buf, b, discBlockSize, existingName);
MappedByteBuffer fileWriter = writeChannel.map(MapMode.READ_WRITE, currentPos, b.getCompressedSize());
Block newBlock = new Block(currentPos - (keepHeaderOffset ? headerOffset : 0), 0, 0, b.getFlags());
newBlocks.add(newBlock);
f.writeFileAndBlock(newBlock, fileWriter);
currentPos += b.getCompressedSize();
}
}
log.debug("Added existing files");
HashMap<String, ByteBuffer> newFileMap = new HashMap<>();
for (String newFileName : filenameToData.keySet()) {
ByteBuffer newFile = filenameToData.get(newFileName);
newFiles.add(newFileName);
newFileMap.put(newFileName, newFile);
MappedByteBuffer fileWriter = writeChannel.map(MapMode.READ_WRITE, currentPos, newFile.limit() * 2);
Block newBlock = new Block(currentPos - (keepHeaderOffset ? headerOffset : 0), 0, 0, 0);
newBlocks.add(newBlock);
MpqFile.writeFileAndBlock(newFile.array(), newBlock, fileWriter, newDiscBlockSize, options);
currentPos += newBlock.getCompressedSize();
log.debug("Added file " + newFileName);
}
log.debug("Added new files");
if (buildListfile && !listFile.getFiles().isEmpty()) {
// Add listfile
newFiles.add("(listfile)");
byte[] listfileArr = listFile.asByteArray();
MappedByteBuffer fileWriter = writeChannel.map(MapMode.READ_WRITE, currentPos, listfileArr.length * 2);
Block newBlock = new Block(currentPos - (keepHeaderOffset ? headerOffset : 0), 0, 0, EXISTS | COMPRESSED | ENCRYPTED | ADJUSTED_ENCRYPTED);
newBlocks.add(newBlock);
MpqFile.writeFileAndBlock(listfileArr, newBlock, fileWriter, newDiscBlockSize, "(listfile)", options);
currentPos += newBlock.getCompressedSize();
log.debug("Added listfile");
}
// if (attributes != null) {
// newFiles.add("(attributes)");
// // Only generate attributes file when there has been one before
// AttributesFile attributesFile = new AttributesFile(newFiles.size());
// // Generate new values
// long time = (new Date().getTime() + 11644473600000L) * 10000L;
// for (int i = 0; i < newFiles.size() - 1; i++) {
// String name = newFiles.get(i);
// int entry = attributes.getEntry(name);
// if (newFileMap.containsKey(name)){
// // new file
// attributesFile.setEntry(i, getCrc32(newFileMap.get(name)), time);
// }else if (entry >= 0) {
// // has timestamp
// attributesFile.setEntry(i, getCrc32(name),
// attributes.getTimestamps()[entry]);
// } else {
// // doesnt have timestamp
// attributesFile.setEntry(i, getCrc32(name), time);
// // newfiles don't contain the attributes file yet, hence -1
// System.out.println("added attributes");
// byte[] attrArr = attributesFile.buildFile();
// fileWriter = writeChannel.map(MapMode.READ_WRITE, currentPos,
// attrArr.length);
// newBlock = new Block(currentPos - headerOffset, 0, 0, EXISTS |
// COMPRESSED | ENCRYPTED | ADJUSTED_ENCRYPTED);
// newBlocks.add(newBlock);
// MpqFile.writeFileAndBlock(attrArr, newBlock, fileWriter,
// newDiscBlockSize, "(attributes)");
// currentPos += newBlock.getCompressedSize();
newBlockSize = newBlocks.size();
newHashPos = currentPos - (keepHeaderOffset ? headerOffset : 0);
newBlockPos = newHashPos + newHashSize * 16;
// generate new hash table
final int hashSize = newHashSize;
HashTable hashTable = new HashTable(hashSize);
int blockIndex = 0;
for (String file : newFiles) {
hashTable.setFileBlockIndex(file, HashTable.DEFAULT_LOCALE, blockIndex++);
}
// prepare hashtable for writing
final ByteBuffer hashTableBuffer = ByteBuffer.allocate(hashSize * 16);
hashTable.writeToBuffer(hashTableBuffer);
hashTableBuffer.flip();
// encrypt hash table
final MPQEncryption encrypt = new MPQEncryption(KEY_HASH_TABLE, false);
encrypt.processSingle(hashTableBuffer);
hashTableBuffer.flip();
// write out hash table
writeChannel.position(currentPos);
writeFully(hashTableBuffer, writeChannel);
currentPos = writeChannel.position();
// write out block table
MappedByteBuffer blocktableWriter = writeChannel.map(MapMode.READ_WRITE, currentPos, newBlockSize * 16);
blocktableWriter.order(ByteOrder.LITTLE_ENDIAN);
BlockTable.writeNewBlocktable(newBlocks, newBlockSize, blocktableWriter);
currentPos += newBlockSize * 16;
newArchiveSize = currentPos + 1 - (keepHeaderOffset ? headerOffset : 0);
MappedByteBuffer headerWriter = writeChannel.map(MapMode.READ_WRITE, (keepHeaderOffset ? headerOffset : 0) + 4, headerSize + 4);
headerWriter.order(ByteOrder.LITTLE_ENDIAN);
writeHeader(headerWriter);
MappedByteBuffer tempReader = writeChannel.map(MapMode.READ_WRITE, 0, currentPos + 1);
tempReader.position(0);
fc.position(0);
fc.write(tempReader);
fc.truncate(fc.position());
fc.close();
writeChannel.close();
t = System.nanoTime() - t;
log.debug("Rebuild complete. Took: " + (t / 1000000) + "ms");
}
private void sortListfileEntries(ArrayList<String> remainingFiles) {
// Sort entries to preserve block table order
remainingFiles.sort((o1, o2) -> {
int pos1 = 999999999;
int pos2 = 999999999;
try {
pos1 = hashTable.getBlockIndexOfFile(o1);
} catch (IOException ignored) {
}
try {
pos2 = hashTable.getBlockIndexOfFile(o2);
} catch (IOException ignored) {
}
return pos1 - pos2;
});
}
/**
* Utility method to fill a buffer from the given channel.
*
* @param buffer buffer to fill.
* @param src channel to fill from.
* @throws IOException if an exception occurs when reading.
* @throws EOFException if EoF is encountered before buffer is full or channel is non
* blocking.
*/
private static void readFully(ByteBuffer buffer, ReadableByteChannel src) throws IOException {
while (buffer.hasRemaining()) {
if (src.read(buffer) < 1)
throw new EOFException("Cannot read enough bytes.");
}
}
/**
* Utility method to write out a buffer to the given channel.
*
* @param buffer buffer to write out.
* @param dest channel to write to.
* @throws IOException if an exception occurs when writing.
*/
private static void writeFully(ByteBuffer buffer, WritableByteChannel dest) throws IOException {
while (buffer.hasRemaining()) {
if (dest.write(buffer) < 1)
throw new EOFException("Cannot write enough bytes.");
}
}
/**
* @return Whether the map can be modified or not
*/
public boolean isCanWrite() {
return canWrite;
}
/**
* Whether or not to keep the data before the actual mpq in the file
*
* @param keepHeaderOffset
*/
public void setKeepHeaderOffset(boolean keepHeaderOffset) {
this.keepHeaderOffset = keepHeaderOffset;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "JMpqEditor [headerSize=" + headerSize + ", archiveSize=" + archiveSize + ", formatVersion=" + formatVersion + ", discBlockSize=" + discBlockSize
+ ", hashPos=" + hashPos + ", blockPos=" + blockPos + ", hashSize=" + hashSize + ", blockSize=" + blockSize + ", hashMap=" + hashTable + "]";
}
} |
package tigase.xmpp.impl;
import java.util.Arrays;
import java.util.List;
import java.util.Queue;
import java.util.Map;
import java.util.logging.Logger;
import java.util.Comparator;
import java.util.Collections;
import tigase.server.Packet;
import tigase.xmpp.Authorization;
import tigase.xmpp.NotAuthorizedException;
import tigase.xmpp.StanzaType;
import tigase.xmpp.XMPPProcessor;
import tigase.xmpp.XMPPProcessorIfc;
import tigase.xmpp.XMPPPreprocessorIfc;
import tigase.xmpp.XMPPResourceConnection;
import tigase.xmpp.XMPPException;
import tigase.xml.Element;
import tigase.db.NonAuthUserRepository;
import static tigase.xmpp.impl.Privacy.*;
/**
* Describe class JabberIqPrivacy here.
*
*
* Created: Mon Oct 9 18:18:11 2006
*
* @author <a href="mailto:artur.hefczyc@tigase.org">Artur Hefczyc</a>
* @version $Rev$
*/
public class JabberIqPrivacy extends XMPPProcessor
implements XMPPProcessorIfc, XMPPPreprocessorIfc {
/**
* Private logger for class instancess.
*/
private static Logger log =
Logger.getLogger("tigase.xmpp.impl.JabberIqPrivacy");
private static final String XMLNS = "jabber:iq:privacy";
private static final String ID = XMLNS;
private static final String[] ELEMENTS = {"query"};
private static final String[] XMLNSS = {XMLNS};
private static final Element[] DISCO_FEATURES = {
new Element("feature", new String[] {"var"}, new String[] {XMLNS})
};
public Element[] supDiscoFeatures(final XMPPResourceConnection session)
{ return DISCO_FEATURES; }
private enum ITEM_TYPE { jid, group, subscription, all };
private enum ITEM_ACTION { allow, deny };
private enum ITEM_SUBSCRIPTIONS { both, to, from, none };
private static final Comparator<Element> compar =
new Comparator<Element>() {
public int compare(Element el1, Element el2) {
String or1 = el1.getAttribute(ORDER);
String or2 = el2.getAttribute(ORDER);
return or1.compareTo(or2);
}
};
public String id() { return ID; }
public String[] supElements()
{ return ELEMENTS; }
public String[] supNamespaces()
{ return XMLNSS; }
/**
* <code>preProcess</code> method checks only incoming stanzas
* so it doesn't check for presence-out at all.
*
* @param packet a <code>Packet</code> value
* @param session a <code>XMPPResourceConnection</code> value
* @param repo a <code>NonAuthUserRepository</code> value
* @return a <code>boolean</code> value
*/
public boolean preProcess(Packet packet, XMPPResourceConnection session,
NonAuthUserRepository repo, Queue<Packet> results) {
if (session == null || !session.isAuthorized()) {
return false;
} // end of if (session == null)
try {
Element list = Privacy.getActiveList(session);
if (list == null && session.getSessionData("privacy-init") == null) {
String lName = Privacy.getDefaultList(session);
if (lName != null) {
Privacy.setActiveList(session, lName);
list = Privacy.getActiveList(session);
} // end of if (lName != null)
session.putSessionData("privacy-init", "");
} // end of if (lName == null)
if (list != null) {
List<Element> items = list.getChildren();
Collections.sort(items, compar);
for (Element item: items) {
boolean type_matched = false;
boolean elem_matched = false;
ITEM_TYPE type = ITEM_TYPE.all;
if (item.getAttribute(TYPE) != null) {
type = ITEM_TYPE.valueOf(item.getAttribute(TYPE));
} // end of if (item.getAttribute(TYPE) != null)
String value = item.getAttribute(VALUE);
String from = packet.getElemFrom();
if (from != null) {
switch (type) {
case jid:
type_matched = from.contains(value);
break;
case group:
String[] groups = Roster.getBuddyGroups(session, from);
if (groups != null) {
for (String group: groups) {
if (type_matched = group.equals(value)) {
break;
} // end of if (group.equals(value))
} // end of for (String group: groups)
}
break;
case subscription:
ITEM_SUBSCRIPTIONS subscr = ITEM_SUBSCRIPTIONS.valueOf(value);
switch (subscr) {
case to:
type_matched = Roster.isSubscribedTo(session, from);
break;
case from:
type_matched = Roster.isSubscribedFrom(session, from);
break;
case none:
type_matched = (!Roster.isSubscribedFrom(session, from)
&& !Roster.isSubscribedTo(session, from));
break;
case both:
type_matched = (Roster.isSubscribedFrom(session, from)
&& Roster.isSubscribedTo(session, from));
break;
default:
break;
} // end of switch (subscr)
break;
case all:
default:
type_matched = true;
break;
} // end of switch (type)
} else {
if (type == ITEM_TYPE.all) {
type_matched = true;
}
} // end of if (from != null) else
if (!type_matched) {
break;
} // end of if (!type_matched)
List<Element> elems = item.getChildren();
if (elems == null || elems.size() == 0) {
elem_matched = true;
} else {
for (Element elem: elems) {
if (elem.getName().equals("presence-in")) {
if (packet.getElemName().equals("presence")
&& (packet.getType() == null
|| packet.getType() == StanzaType.unavailable)) {
elem_matched = true;
break;
}
} else {
if (elem.getName().equals(packet.getElemName())) {
elem_matched = true;
break;
} // end of if (elem.getName().equals(packet.getElemName()))
} // end of if (elem.getName().equals("presence-in")) else
} // end of for (Element elem: elems)
} // end of else
if (!elem_matched) {
break;
} // end of if (!elem_matched)
ITEM_ACTION action = ITEM_ACTION.valueOf(item.getAttribute(ACTION));
switch (action) {
case allow:
return false;
case deny:
return true;
default:
break;
} // end of switch (action)
} // end of for (Element item: items)
} // end of if (lName != null)
} catch (NotAuthorizedException e) {
// results.offer(Authorization.NOT_AUTHORIZED.getResponseMessage(packet,
// "You must authorize session first.", true));
} // end of try-catch
return false;
}
public void process(final Packet packet, final XMPPResourceConnection session,
final NonAuthUserRepository repo, final Queue<Packet> results,
final Map<String, Object> settings)
throws XMPPException {
if (session == null) {
return;
} // end of if (session == null)
try {
StanzaType type = packet.getType();
switch (type) {
case get:
processGetRequest(packet, session, results);
break;
case set:
processSetRequest(packet, session, results);
break;
case result:
// Ignore
break;
default:
results.offer(Authorization.BAD_REQUEST.getResponseMessage(packet,
"Request type is incorrect", false));
break;
} // end of switch (type)
} catch (NotAuthorizedException e) {
log.warning(
"Received privacy request but user session is not authorized yet: " +
packet.getStringData());
results.offer(Authorization.NOT_AUTHORIZED.getResponseMessage(packet,
"You must authorize session first.", true));
} // end of try-catch
}
private void processSetRequest(final Packet packet,
final XMPPResourceConnection session, final Queue<Packet> results)
throws NotAuthorizedException, XMPPException {
List<Element> children = packet.getElemChildren("/iq/query");
if (children != null && children.size() == 1) {
Element child = children.get(0);
if (child.getName().equals("list")) {
// Broken privacy implementation sends list without name set
// instead of sending BAD_REQUEST error I can just assign
// 'default' name here.
String name = child.getAttribute(NAME);
if (name == null || name.length() == 0) {
child.setAttribute(NAME, "default");
} // end of if (name == null || name.length() == 0)
Privacy.addList(session, child);
results.offer(packet.okResult((String)null, 0));
} // end of if (child.getName().equals("list))
if (child.getName().equals("default")) {
Privacy.setDefaultList(session, child);
results.offer(packet.okResult((String)null, 0));
} // end of if (child.getName().equals("list))
if (child.getName().equals("active")) {
Privacy.setActiveList(session, child.getAttribute(NAME));
results.offer(packet.okResult((String)null, 0));
} // end of if (child.getName().equals("list))
} else {
results.offer(Authorization.BAD_REQUEST.getResponseMessage(packet,
"Only 1 element is allowed in privacy set request.", true));
} // end of else
}
private void processGetRequest(final Packet packet,
final XMPPResourceConnection session, final Queue<Packet> results)
throws NotAuthorizedException, XMPPException {
List<Element> children = packet.getElemChildren("/iq/query");
if (children == null || children.size() == 0) {
String[] lists = Privacy.getLists(session);
if (lists != null) {
StringBuilder sblists = new StringBuilder();
for (String list : lists) {
sblists.append("<list name=\"" + list + "\"/>");
}
String list = Privacy.getDefaultList(session);
if (list != null) {
sblists.append("<default name=\"" + list + "\"/>");
} // end of if (defList != null)
list = Privacy.getActiveListName(session);
if (list != null) {
sblists.append("<active name=\"" + list + "\"/>");
} // end of if (defList != null)
results.offer(packet.okResult(sblists.toString(), 1));
} else {
results.offer(packet.okResult((String)null, 1));
} // end of if (buddies != null) else
} else {
if (children.size() > 1) {
results.offer(Authorization.BAD_REQUEST.getResponseMessage(packet,
"You can retrieve only one list at a time.", true));
} else {
Element eList = Privacy.getList(session,
children.get(0).getAttribute("name"));
if (eList != null) {
results.offer(packet.okResult(eList, 1));
} else {
results.offer(Authorization.ITEM_NOT_FOUND.getResponseMessage(packet,
"Requested list not found.", true));
} // end of if (eList != null) else
} // end of else
} // end of else
}
} // JabberIqPrivacy |
package tigase.xmpp.impl;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;
import java.util.TimeZone;
import java.util.logging.Level;
import java.util.logging.Logger;
import tigase.db.MsgRepositoryIfc;
import tigase.db.NonAuthUserRepository;
import tigase.db.TigaseDBException;
import tigase.db.UserNotFoundException;
import tigase.osgi.ModulesManagerImpl;
import static tigase.server.Message.ELEM_NAME;
import tigase.server.Packet;
import tigase.util.DNSResolver;
import tigase.util.TigaseStringprepException;
import tigase.xml.DomBuilderHandler;
import tigase.xml.Element;
import tigase.xml.SimpleParser;
import tigase.xml.SingletonFactory;
import tigase.xmpp.JID;
import tigase.xmpp.NotAuthorizedException;
import tigase.xmpp.StanzaType;
import tigase.xmpp.XMPPPostprocessorIfc;
import tigase.xmpp.XMPPProcessor;
import tigase.xmpp.XMPPProcessorIfc;
import tigase.xmpp.XMPPResourceConnection;
public class OfflineMessages
extends XMPPProcessor
implements XMPPPostprocessorIfc, XMPPProcessorIfc {
/** Field holds default client namespace for stanzas. In case of
* {@code msgoffline} plugin it is <em>jabber:client</em> */
protected static final String XMLNS = "jabber:client";
/** Field holds identification string for the plugin. In case of
* {@code msgoffline} plugin it is <em>msgoffline</em> */
private static final String ID = "msgoffline";
/** Private logger for class instances. */
private static final Logger log = Logger.getLogger( OfflineMessages.class.getName() );
/** Field holds an array for element paths for which the plugin offers
* processing capabilities. In case of {@code msgoffline} plugin it is
* <em>presence</em> stanza */
private static final String[][] ELEMENTS = {
{ Presence.PRESENCE_ELEMENT_NAME } };
/** Field holds an array of name-spaces for stanzas which can be processed by
* this plugin. In case of {@code msgoffline} plugin it is
* <em>jabber:client</em> */
private static final String[] XMLNSS = { XMLNS };
/** Field holds an array of XML Elements with service discovery features which
* have to be returned to the client uppon request. In case of
* {@code msgoffline} plugin it is the same as plugin name -
* <em>msgoffline</em> */
private static final Element[] DISCO_FEATURES = {
new Element( "feature", new String[] { "var" }, new String[] { "msgoffline" } ) };
/** Field holds the default hostname of the machine. */
private static final String defHost = DNSResolver.getDefaultHostname();
/** Field holds an array for element paths for which the plugin offers message
* saving capabilities. In case of {@code msgoffline} plugin it is
* <em>presence</em> stanza */
public static final String[] MESSAGE_EVENT_PATH = { ELEM_NAME, "event" };
/** Field holds an array for element paths for which the plugin offers
* processing capabilities. In case of {@code msgoffline} plugin it is
* <em>presence</em> stanza */
public static final String[] MESSAGE_HEADER_PATH = { ELEM_NAME, "header" };
private static final String MSG_REPO_CLASS_KEY = "msg-repo-class";
/** Field holds class for formatting and parsing dates in a locale-sensitive
* manner */
private final SimpleDateFormat formatter;
private String msgRepoCls = null;
private Message message = new Message();
{
this.formatter = new SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" );
this.formatter.setTimeZone( TimeZone.getTimeZone( "UTC" ) );
}
@Override
public int concurrentQueuesNo() {
return Runtime.getRuntime().availableProcessors();
}
@Override
public String id() {
return ID;
}
@Override
public void init(Map<String, Object> settings) throws TigaseDBException {
super.init(settings);
msgRepoCls = (String) settings.get(MSG_REPO_CLASS_KEY);
}
/**
* {@inheritDoc}
*
* <br><br>
*
* OfflineMessages postprocessor simply calls {@code savePacketForOffLineUser}
* method to store packet to offline repository.
*/
@Override
public void postProcess( final Packet packet, final XMPPResourceConnection conn,
final NonAuthUserRepository repo, final Queue<Packet> queue,
Map<String, Object> settings ) {
if ( conn == null || !message.hasConnectionForMessageDelivery(conn) ){
try {
MsgRepositoryIfc msg_repo = getMsgRepoImpl( repo, conn );
savePacketForOffLineUser( packet, msg_repo );
} catch ( UserNotFoundException e ) {
if ( log.isLoggable( Level.FINEST ) ){
log.finest(
"UserNotFoundException at trying to save packet for off-line user."
+ packet );
}
} // end of try-catch
} // end of if (conn == null)
}
/**
* {@inheritDoc}
*
* <br><br>
*
* {@code OfflineMessages} processor is triggered by {@code <presence>}
* stanza. Upon receiving it plugin tries to load messages from repository
* and, if the result is not empty, sends them to the user
*/
@Override
public void process( final Packet packet, final XMPPResourceConnection conn,
final NonAuthUserRepository repo, final Queue<Packet> results,
final Map<String, Object> settings )
throws NotAuthorizedException {
if ( loadOfflineMessages( packet, conn ) ){
try {
MsgRepositoryIfc msg_repo = getMsgRepoImpl( repo, conn );
Queue<Packet> packets = restorePacketForOffLineUser( conn, msg_repo );
if ( packets != null ){
if ( log.isLoggable( Level.FINER ) ){
log.finer( "Sending off-line messages: " + packets.size() );
}
results.addAll( packets );
} // end of if (packets != null)
} catch ( UserNotFoundException e ) {
log.info( "Something wrong, DB problem, cannot load offline messages. " + e );
} // end of try-catch
}
}
/**
* Method restores all messages from repository for the JID of the current
* session. All retrieved elements are then instantiated as {@code Packet}
* objects added to {@code LinkedList} collection and, if possible, sorted by
* timestamp.
*
* @param conn user session which keeps all the user session data and also
* gives an access to the user's repository data.
* @param repo an implementation of {@link MsgRepositoryIfc} interface
*
*
* @return a {@link Queue} of {@link Packet} objects based on all stored
* payloads for the JID of the current session.
*
* @throws UserNotFoundException
* @throws NotAuthorizedException
*/
public Queue<Packet> restorePacketForOffLineUser( XMPPResourceConnection conn,
MsgRepositoryIfc repo )
throws UserNotFoundException, NotAuthorizedException {
Queue<Element> elems = repo.loadMessagesToJID( conn.getJID(), true );
if ( elems != null ){
LinkedList<Packet> pacs = new LinkedList<Packet>();
Element elem = null;
while ( ( elem = elems.poll() ) != null ) {
try {
pacs.offer( Packet.packetInstance( elem ) );
} catch ( TigaseStringprepException ex ) {
log.warning( "Packet addressing problem, stringprep failed: " + elem );
}
} // end of while (elem = elems.poll() != null)
try {
Collections.sort( pacs, new StampComparator() );
} catch ( NullPointerException e ) {
try {
log.warning( "Can not sort off line messages: " + pacs + ",\n" + e );
} catch ( Exception exc ) {
log.log( Level.WARNING, "Can not print log message.", exc );
}
}
return pacs;
}
return null;
}
/**
* Method stores messages to offline repository with the following rules
* applied, i.e. saves only:
* <ul>
* <li> message stanza with either nonempty {@code <body>}, {@code <event>} or
* {@code <header>} child element and only messages of type normal, chat.</li>
* <li> presence stanza of type subscribe, subscribed, unsubscribe and
* unsubscribed.</li>
* </ul>
* <br>
* Processed messages are stamped with the {@code delay} element and
* appropriate timestamp.
* <br>
*
*
* @param pac a {@link Packet} object containing packet that should be
* verified and saved
* @param repo a {@link MsgRepositoryIfc} repository handler responsible for
* storing messages
*
* @return {@code true} if the packet was correctly saved to repository,
* {@code false} otherwise.
*
* @throws UserNotFoundException
*/
public boolean savePacketForOffLineUser( Packet pac, MsgRepositoryIfc repo )
throws UserNotFoundException {
StanzaType type = pac.getType();
// save only:
// message stanza with either {@code <body>} or {@code <event>} child element and only of type normal, chat
// presence stanza of type subscribe, subscribed, unsubscribe and unsubscribed
if ( ( pac.getElemName().equals( "message" )
&& ( ( pac.getElemCDataStaticStr( tigase.server.Message.MESSAGE_BODY_PATH ) != null )
|| ( pac.getElemChildrenStaticStr( MESSAGE_EVENT_PATH ) != null )
|| ( pac.getElemChildrenStaticStr( MESSAGE_HEADER_PATH ) != null )
|| ( pac.getElement().getChild("request", "urn:xmpp:receipts") != null )
|| ( pac.getElement().getChild("received", "urn:xmpp:receipts") != null ) )
&& ( ( type == null ) || ( type == StanzaType.normal ) || ( type == StanzaType.chat ) ) )
|| ( pac.getElemName().equals( "presence" )
&& ( ( type == StanzaType.subscribe ) || ( type == StanzaType.subscribed )
|| ( type == StanzaType.unsubscribe ) || ( type == StanzaType.unsubscribed ) ) ) ){
if ( log.isLoggable( Level.FINEST ) ){
log.log( Level.FINEST, "Storing packet for offline user: {0}", pac );
}
Element elem = pac.getElement().clone();
String stamp = null;
synchronized ( formatter ) {
stamp = formatter.format( new Date() );
}
// remove any previous delay element
Element delay = elem.getChild("delay", "urn:xmpp:delay");
if (delay != null) {
log.log( Level.WARNING, "Restoring packet, possible offline storage loop? {0}", pac );
elem.removeChild(delay);
}
String from = pac.getStanzaTo().getDomain();
Element x = new Element( "delay", "Offline Storage - " + defHost, new String[] {
"from",
"stamp", "xmlns" }, new String[] { from, stamp, "urn:xmpp:delay" } );
elem.addChild( x );
repo.storeMessage( pac.getStanzaFrom(), pac.getStanzaTo(), null, elem );
pac.processedBy( ID );
return true;
} else {
if ( log.isLoggable( Level.FINEST ) ){
log.log( Level.FINEST, "Packet for offline user not suitable for storing: {0}",
pac );
}
}
return false;
}
@Override
public Element[] supDiscoFeatures( final XMPPResourceConnection session ) {
return DISCO_FEATURES;
}
@Override
public String[][] supElementNamePaths() {
return ELEMENTS;
}
@Override
public String[] supNamespaces() {
return XMLNSS;
}
/**
* Method allows obtaining instance of {@link MsgRepositoryIfc} interface
* implementation.
*
* @param conn user session which keeps all the user session data and also
* gives an access to the user's repository data.
* @param repo an implementation of {@link MsgRepositoryIfc} interface
*
* @return instance of {@link MsgRepositoryIfc} interface implementation.
*/
protected MsgRepositoryIfc getMsgRepoImpl( NonAuthUserRepository repo,
XMPPResourceConnection conn ) {
if (msgRepoCls == null) {
return new MsgRepositoryImpl( repo, conn );
} else {
try {
OfflineMsgRepositoryIfc msgRepo = (OfflineMsgRepositoryIfc) ModulesManagerImpl.getInstance().forName(msgRepoCls).newInstance();
msgRepo.init(repo, conn);
return msgRepo;
} catch (Exception ex) {
return null;
}
}
}
/**
* Method determines whether offline messages should be loaded - the process
* should be run only once per user session and only for available/null
* presence with priority greater than 0.
*
*
* @param packet a {@link Packet} object containing packet that should be
* verified and saved
* @param conn user session which keeps all the user session data and also
* gives an access to the user's repository data.
*
* @return {@code true} if the messages should be loaded, {@code false}
* otherwise.
*/
protected boolean loadOfflineMessages( Packet packet, XMPPResourceConnection conn ) {
// If the user session is null or the user is anonymous just
// ignore it.
if ( ( conn == null ) || conn.isAnonymous() ){
return false;
} // end of if (session == null)
// Try to restore the offline messages only once for the user session
if ( conn.getSessionData( ID ) != null ){
return false;
}
// make sure this is broadcast presence as only in this case we should sent offline messages
if (packet.getStanzaTo() != null)
return false;
// if we are using XEP-0013: Flexible offline messages retrieval then we skip loading
if ( conn.getCommonSessionData(FlexibleOfflineMessageRetrieval.FLEXIBLE_OFFLINE_XMLNS) != null ){
return false;
}
StanzaType type = packet.getType();
if ( ( type == null ) || ( type == StanzaType.available ) ){
// Should we send off-line messages now?
// Let's try to do it here and maybe later I find better place.
String priority_str = packet.getElemCDataStaticStr( tigase.server.Presence.PRESENCE_PRIORITY_PATH );
int priority = 0;
if ( priority_str != null ){
try {
priority = Integer.decode( priority_str );
} catch ( NumberFormatException e ) {
priority = 0;
} // end of try-catch
} // end of if (priority != null)
if ( priority >= 0 ){
conn.putSessionData( ID, ID );
return true;
} // end of if (priority >= 0)
} // end of if (type == null || type == StanzaType.available)
return false;
}
public static interface OfflineMsgRepositoryIfc extends MsgRepositoryIfc {
void init( NonAuthUserRepository repo, XMPPResourceConnection conn);
}
/**
* Implementation of {@code MsgRepositoryIfc} interface providing basic
* support for storing and loading of Elements from repository.
*/
private class MsgRepositoryImpl implements OfflineMsgRepositoryIfc {
/** Field holds user session which keeps all the user session data and also
* gives an access to the user's repository data. */
private XMPPResourceConnection conn = null;
/** Field holds a reference to user session which keeps all the user session
* data and also gives an access to the user's repository data. */
private SimpleParser parser = SingletonFactory.getParserInstance();
/** Field holds reference to an implementation of {@link MsgRepositoryIfc}
* interface */
private NonAuthUserRepository repo = null;
/**
* Constructs {@code MsgRepositoryImpl} object referencing user session and
* having handle to user repository.
*
* @param repo an implementation of {@link MsgRepositoryIfc} interface
* @param conn user session which keeps all the user session data and also
* gives an access to the user's repository data.
*/
private MsgRepositoryImpl(NonAuthUserRepository repo, XMPPResourceConnection conn) {
init(repo, conn);
}
@Override
public void init(NonAuthUserRepository repo, XMPPResourceConnection conn) {
this.repo = repo;
this.conn = conn;
}
@Override
public void initRepository(String conn_str, Map<String, String> map) {
// nothing to do here as we base on UserRepository which is already initialized
}
@Override
public Element getMessageExpired( long time, boolean delete ) {
throw new UnsupportedOperationException( "Not supported yet." );
}
@Override
public Queue<Element> loadMessagesToJID( JID to, boolean delete )
throws UserNotFoundException {
try {
DomBuilderHandler domHandler = new DomBuilderHandler();
String[] msgs = conn.getOfflineDataList( ID, "messages" );
if ( ( msgs != null ) && ( msgs.length > 0 ) ){
conn.removeOfflineData( ID, "messages" );
StringBuilder sb = new StringBuilder();
for ( String msg : msgs ) {
sb.append( msg );
}
char[] data = sb.toString().toCharArray();
parser.parse( domHandler, data, 0, data.length );
return domHandler.getParsedElements();
} // end of while (elem = elems.poll() != null)
} catch ( NotAuthorizedException ex ) {
log.info( "User not authrized to retrieve offline messages, "
+ "this happens quite often on some installations where there"
+ " are a very short living client connections. They can "
+ "disconnect at any time. " + ex );
} catch ( TigaseDBException ex ) {
log.warning( "Error accessing database for offline message: " + ex );
}
return null;
}
@Override
public void storeMessage( JID from, JID to, Date expired, Element msg )
throws UserNotFoundException {
repo.addOfflineDataList( to.getBareJID(), ID, "messages",
new String[] { msg.toString() } );
}
}
/**
* {@link Comparator} interface implementation for the purpose of sorting
* Elements retrieved from the repository by the timestamp stored in
* {@code delay} element.
*/
public class StampComparator
implements Comparator<Packet> {
@Override
public int compare( Packet p1, Packet p2 ) {
String stamp1 = "";
String stamp2 = "";
// Try XEP-0203 - the new XEP...
Element stamp_el1 = p1.getElement().getChild( "delay", "urn:xmpp:delay" );
if ( stamp_el1 == null ){
// XEP-0091 support - the old one...
stamp_el1 = p1.getElement().getChild( "x", "jabber:x:delay" );
}
stamp1 = stamp_el1.getAttributeStaticStr( "stamp" );
// Try XEP-0203 - the new XEP...
Element stamp_el2 = p2.getElement().getChild( "delay", "urn:xmpp:delay" );
if ( stamp_el2 == null ){
// XEP-0091 support - the old one...
stamp_el2 = p2.getElement().getChild( "x", "jabber:x:delay" );
}
stamp2 = stamp_el2.getAttributeStaticStr( "stamp" );
return stamp1.compareTo( stamp2 );
}
}
} // OfflineMessages |
package tw.kewang.testserver.api;
import com.google.gson.Gson;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.Response;
import java.util.ArrayList;
import java.util.List;
@Path("data")
public class DataApi {
private volatile List<Members> user = new ArrayList<Members>();
private Gson gson = new Gson();
private Answer noResult = new Answer("");
private Answer yesResult = new Answer("");
@Produces("application/json")
@POST
public Response post(String body) {
Members mem = gson.fromJson(body, Members.class);
user.add(mem);
System.out.println(gson.toJson(mem));
return Response.ok().entity(gson.toJson(yesResult)).build();
}
@Path("{keywordGet}")
@GET
public Response get(@Context HttpHeaders headers, @PathParam("keywordGet") String keyword) {
if (detect(keyword)!=-1) {
String jsonStr = gson.toJson(user.get(detect(keyword)));
return Response.ok().entity(jsonStr).build();
} else {
return Response.ok().entity(gson.toJson(noResult)).build();
}
}
@Path("{keywordDel}")
@DELETE
public Response del(@Context HttpHeaders headers, @PathParam("keywordDel") String keyword) {
if (detect(keyword)!=-1) {
user.remove(detect(keyword));
return Response.ok().entity(gson.toJson(yesResult)).build();
} else {
return Response.ok().entity(gson.toJson(noResult)).build();
}
}
@Path("{keywordPut}")
@PUT
public Response put(@Context HttpHeaders headers, @PathParam("keywordPut") String keyword, String body) {
int detRes = detect(keyword);
if (detRes!=-1) {
Members newstr = gson.fromJson(body, Members.class);
user.set(detRes, newstr);
return Response.ok().entity((gson.toJson(yesResult)) + "\n" + gson.toJson(user.get(detRes))).build();
} else {
return Response.ok().entity(gson.toJson(noResult)).build();
}
}
private int detect(String key) {
for (int numberOfIndex = 0; numberOfIndex < user.size(); numberOfIndex++) {
if (user.get(numberOfIndex).getPhoneNumber().equals(key) || user.get(numberOfIndex).getName().equals(key) || user.get(numberOfIndex).getEmail().equals(key)) {
return numberOfIndex;
}
}
return -1;
}
public class Members {
private String name;
private String sex;
private String phoneNumber;
private String email;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Members(String _name, String _sex, int _age, String _phoneNumber, String _email) {
name = _name;
sex = _sex;
age = _age;
phoneNumber = _phoneNumber;
email = _email;
}
}
public class Answer {
private String ans;
public String getAns() {
return ans;
}
public void setAns(String ans) {
this.ans = ans;
}
public Answer(String _ans) {
ans = _ans;
}
}
} |
package uk.co.jemos.podam.api;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.HashSet;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import uk.co.jemos.podam.common.PodamExclude;
/**
* PODAM Utilities class.
*
* @author mtedone
*
* @since 1.0.0
*
*/
public final class PodamUtils {
private static final int SETTER_IDENTIFIER_LENGTH = 3;
/** The application logger. */
private static final Logger LOG = LoggerFactory.getLogger(PodamUtils.class);
/** Non instantiable constructor */
private PodamUtils() {
throw new AssertionError();
}
/**
* It returns a {@link ClassInfo} object for the given class
*
* @param clazz
* The class to retrieve info from
* @return a {@link ClassInfo} object for the given class
*/
public static ClassInfo getClassInfo(Class<?> clazz) {
return getClassInfo(clazz, null);
}
/**
* It returns a {@link ClassInfo} object for the given class
*
* @param clazz
* The class to retrieve info from
* @param excludeFieldAnnotations
* the fields marked with any of these annotations will not be
* included in the class info
* @return a {@link ClassInfo} object for the given class
*/
public static ClassInfo getClassInfo(Class<?> clazz,
Set<Class<? extends Annotation>> excludeFieldAnnotations) {
Set<String> classFields = getDeclaredInstanceFields(clazz, excludeFieldAnnotations);
Set<Method> classSetters = getPojoSetters(clazz, classFields);
return new ClassInfo(clazz, classFields, classSetters);
}
/**
* Given a class, it returns a Set of its declared instance field names.
*
* @param clazz
* The class to analyse to retrieve declared fields
* @return Set of a class declared field names.
*/
public static Set<String> getDeclaredInstanceFields(Class<?> clazz) {
return getDeclaredInstanceFields(clazz, null);
}
/**
* Given a class, it returns a Set of its declared instance field names.
*
* @param clazz
* The class to analyse to retrieve declared fields
* @param excludeAnnotations
* fields marked with any of the mentioned annotations will be
* skipped
* @return Set of a class declared field names.
*/
public static Set<String> getDeclaredInstanceFields(Class<?> clazz,
Set<Class<? extends Annotation>> excludeAnnotations) {
if (excludeAnnotations == null) {
excludeAnnotations = new HashSet<Class<? extends Annotation>>();
}
excludeAnnotations.add(PodamExclude.class);
Class<?> workClass = clazz;
Set<String> classFields = new HashSet<String>();
while (workClass != null) {
Field[] declaredFields = workClass.getDeclaredFields();
for (Field field : declaredFields) {
// If users wanted to skip this field, we grant their wishes
if (containsAnyAnnotation(field, excludeAnnotations)) {
continue;
}
int modifiers = field.getModifiers();
if (!Modifier.isStatic(modifiers)) {
classFields.add(field.getName());
}
}
workClass = workClass.getSuperclass();
}
return classFields;
}
/**
* Checks if the given field has any one of the annotations
*
* @param field
* the field to check for
* @param annotations
* the set of annotations to look for in the field
* @return true if the field is marked with any of the given annotations
*/
public static boolean containsAnyAnnotation(Field field,
Set<Class<? extends Annotation>> annotations) {
Method method = getGetterFor(field);
for (Class<? extends Annotation> annotation : annotations) {
if (field.getAnnotation(annotation) != null) {
return true;
}
if (method != null && method.getAnnotation(annotation) != null) {
return true;
}
}
return false;
}
/**
* It returns the getter for the given field.
*
* @param field
* The {@link Field} for which the getter is required
* @return the getter for the given field or null if no getter was found
*/
public static Method getGetterFor(Field field) {
String name = field.getName().substring(0, 1).toUpperCase()
+ field.getName().substring(1);
String methodName;
if (boolean.class.isAssignableFrom(field.getType()) ||
Boolean.class.isAssignableFrom(field.getType())) {
methodName = "is" + name;
} else {
methodName = "get" + name;
}
try {
return field.getDeclaringClass().getMethod(methodName);
} catch (NoSuchMethodException e) {
LOG.debug("No getter {}() for field {}[{}]", methodName,
field.getDeclaringClass().getName(), field.getName());
if (methodName.startsWith("is")) {
methodName = "get" + name;
try {
return field.getDeclaringClass().getMethod(methodName);
} catch (NoSuchMethodException e2) {
LOG.debug("No getter {}() for field {}[{}]", methodName,
field.getDeclaringClass().getName(), field.getName());
}
}
return null;
}
}
/**
* Given a class and a set of class declared fields it returns a Set of
* setters matching the declared fields
* <p>
* If present, a setter method is considered if and only if the
* {@code classFields} argument contains an attribute whose name matches the
* setter, according to JavaBean standards.
* </p>
*
* @param clazz
* The class to analyse for setters
* @param classFields
* A Set of field names for which setters are to be found
* @return A Set of setters matching the class declared field names
*
*/
public static Set<Method> getPojoSetters(Class<?> clazz,
Set<String> classFields) {
Class<?> workClass = clazz;
Set<Method> classSetters = new HashSet<Method>();
while (workClass != null) {
Method[] declaredMethods = workClass.getDeclaredMethods();
String candidateField = null;
for (Method method : declaredMethods) {
/* Bridge methods are automatically generated by compiler to
deal with type erasure and they are not type safe.
That why they should be ignored */
if (!method.isBridge()
&& method.getName().startsWith("set")
&& method.getReturnType().equals(void.class)) {
candidateField = extractFieldNameFromSetterMethod(method);
if (classFields.contains(candidateField)) {
classSetters.add(method);
}
}
}
workClass = workClass.getSuperclass();
}
return classSetters;
}
/**
* Given a setter {@link Method}, it extracts the field name, according to
* JavaBean standards
* <p>
* This method, given a setter method, it returns the corresponding
* attribute name. For example: given setIntField the method would return
* intField. The correctness of the return value depends on the adherence to
* JavaBean standards.
* </p>
*
* @param method
* The setter method from which the field name is required
* @return The field name corresponding to the setter
*/
public static String extractFieldNameFromSetterMethod(Method method) {
String candidateField = null;
candidateField = method.getName().substring(SETTER_IDENTIFIER_LENGTH);
if (!"".equals(candidateField)) {
candidateField = Character.toLowerCase(candidateField.charAt(0))
+ candidateField.substring(1);
} else {
LOG.warn("Encountered method {}. This will be ignored.",
method);
}
return candidateField;
}
} |
package vc.inreach.aws.request;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSCredentialsProvider;
import com.amazonaws.auth.AWSSessionCredentials;
import com.google.common.base.*;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import org.apache.commons.codec.binary.Hex;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.temporal.ChronoField;
import java.util.Map;
import java.util.TreeMap;
public class AWSSigner {
private final static char[] BASE16MAP = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
private static final String HMAC_SHA256 = "HmacSHA256";
private static final String SLASH = "/";
private static final String X_AMZ_DATE = "x-amz-date";
private static final String RETURN = "\n";
private static final String AWS4_HMAC_SHA256 = "AWS4-HMAC-SHA256\n";
private static final String AWS4_REQUEST = "/aws4_request";
private static final String AWS4_HMAC_SHA256_CREDENTIAL = "AWS4-HMAC-SHA256 Credential=";
private static final String SIGNED_HEADERS = ", SignedHeaders=";
private static final String SIGNATURE = ", Signature=";
private static final String SHA_256 = "SHA-256";
private static final String AWS4 = "AWS4";
private static final String AWS_4_REQUEST = "aws4_request";
private static final Joiner JOINER = Joiner.on(';');
private static final String CONNECTION = "connection";
private static final String CLOSE = ":close";
private static final DateTimeFormatter BASIC_TIME_FORMAT = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.appendValue(ChronoField.YEAR, 4)
.appendValue(ChronoField.MONTH_OF_YEAR, 2)
.appendValue(ChronoField.DAY_OF_MONTH, 2)
.appendLiteral('T')
.appendValue(ChronoField.HOUR_OF_DAY, 2)
.appendValue(ChronoField.MINUTE_OF_HOUR, 2)
.appendValue(ChronoField.SECOND_OF_MINUTE, 2)
.appendLiteral('Z')
.toFormatter();
private static final String EMPTY = "";
private static final String ZERO = "0";
private static final Joiner AMPERSAND_JOINER = Joiner.on('&');
private static final String CONTENT_LENGTH = "Content-Length";
private static final String AUTHORIZATION = "Authorization";
private static final String SESSION_TOKEN = "x-amz-security-token";
private static final String DATE = "date";
private final AWSCredentialsProvider credentialsProvider;
private final String region;
private final String service;
private final Supplier<LocalDateTime> clock;
public AWSSigner(AWSCredentialsProvider credentialsProvider,
String region,
String service,
Supplier<LocalDateTime> clock) {
this.credentialsProvider = credentialsProvider;
this.region = region;
this.service = service;
this.clock = clock;
}
public Map<String, Object> getSignedHeaders(String uri, String method, Map<String, String> queryParams, Map<String, Object> headers, Optional<byte[]> payload) {
final LocalDateTime now = clock.get();
final AWSCredentials credentials = credentialsProvider.getCredentials();
final Map<String, Object> result = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
result.putAll(headers);
if (!result.containsKey(DATE)) {
result.put(X_AMZ_DATE, now.format(BASIC_TIME_FORMAT));
}
if (AWSSessionCredentials.class.isAssignableFrom(credentials.getClass())) {
result.put(SESSION_TOKEN, ((AWSSessionCredentials) credentials).getSessionToken());
}
final StringBuilder headersString = new StringBuilder();
final ImmutableList.Builder<String> signedHeaders = ImmutableList.builder();
for (Map.Entry<String, Object> entry : result.entrySet()) {
headersString.append(headerAsString(entry)).append(RETURN);
signedHeaders.add(entry.getKey().toLowerCase());
}
final String signedHeaderKeys = JOINER.join(signedHeaders.build());
final String canonicalRequest = method + RETURN +
uri + RETURN +
queryParamsString(queryParams) + RETURN +
headersString.toString() + RETURN +
signedHeaderKeys + RETURN +
toBase16(hash(payload.or(EMPTY.getBytes(Charsets.UTF_8))));
final String stringToSign = createStringToSign(canonicalRequest, now);
final String signature = sign(stringToSign, now, credentials);
final String autorizationHeader = AWS4_HMAC_SHA256_CREDENTIAL + credentials.getAWSAccessKeyId() + SLASH + getCredentialScope(now) +
SIGNED_HEADERS + signedHeaderKeys +
SIGNATURE + signature;
result.put(AUTHORIZATION, autorizationHeader);
return ImmutableMap.copyOf(result);
}
private String queryParamsString(Map<String, String> queryParams) {
final ImmutableList.Builder<String> result = ImmutableList.builder();
for (Map.Entry<String, String> param : new TreeMap<>(queryParams).entrySet()) {
result.add(param.getKey() + '=' + param.getValue());
}
return AMPERSAND_JOINER.join(result.build());
}
private String headerAsString(Map.Entry<String, Object> header) {
if (header.getKey().equalsIgnoreCase(CONNECTION)) {
return CONNECTION + CLOSE;
}
if (header.getKey().equalsIgnoreCase(CONTENT_LENGTH) &&
header.getValue().equals(ZERO)) {
return header.getKey().toLowerCase() + ':';
}
return header.getKey().toLowerCase() + ':' + header.getValue();
}
private String sign(String stringToSign, LocalDateTime now, AWSCredentials credentials) {
return Hex.encodeHexString(hmacSHA256(stringToSign, getSignatureKey(now, credentials)));
}
private String createStringToSign(String canonicalRequest, LocalDateTime now) {
return AWS4_HMAC_SHA256 +
now.format(BASIC_TIME_FORMAT) + RETURN +
getCredentialScope(now) + RETURN +
toBase16(hash(canonicalRequest.getBytes(Charsets.UTF_8)));
}
private String getCredentialScope(LocalDateTime now) {
return now.format(DateTimeFormatter.BASIC_ISO_DATE) + SLASH + region + SLASH + service + AWS4_REQUEST;
}
private byte[] hash(byte[] payload) {
try {
final MessageDigest md = MessageDigest.getInstance(SHA_256);
md.update(payload);
return md.digest();
} catch (NoSuchAlgorithmException e) {
throw Throwables.propagate(e);
}
}
private String toBase16(byte[] data) {
final StringBuilder hexBuffer = new StringBuilder(data.length * 2);
for (byte aData : data) {
hexBuffer.append(BASE16MAP[(aData >> (4)) & 0xF]);
hexBuffer.append(BASE16MAP[(aData) & 0xF]);
}
return hexBuffer.toString();
}
private byte[] getSignatureKey(LocalDateTime now, AWSCredentials credentials) {
final byte[] kSecret = (AWS4 + credentials.getAWSSecretKey()).getBytes(Charsets.UTF_8);
final byte[] kDate = hmacSHA256(now.format(DateTimeFormatter.BASIC_ISO_DATE), kSecret);
final byte[] kRegion = hmacSHA256(region, kDate);
final byte[] kService = hmacSHA256(service, kRegion);
return hmacSHA256(AWS_4_REQUEST, kService);
}
private byte[] hmacSHA256(String data, byte[] key) {
try {
final Mac mac = Mac.getInstance(HMAC_SHA256);
mac.init(new SecretKeySpec(key, HMAC_SHA256));
return mac.doFinal(data.getBytes(Charsets.UTF_8));
} catch (NoSuchAlgorithmException | InvalidKeyException e) {
throw Throwables.propagate(e);
}
}
} |
package cn.sharesdk;
import java.util.ArrayList;
import java.util.HashMap;
import m.framework.utils.Hashon;
import m.framework.utils.UIHandler;
import org.cocos2dx.lib.Cocos2dxActivity;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.Platform.ShareParams;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;
import android.content.Context;
import android.os.Message;
import android.os.Handler.Callback;
public class ShareSDKUtils {
private static boolean DEBUG = true;
private static Context context;
private static PlatformActionListener paListaner;
private static Hashon hashon;
private ShareSDKUtils() {
}
public static void prepare() {
UIHandler.prepare();
context = Cocos2dxActivity.getContext().getApplicationContext();
hashon = new Hashon();
final Callback cb = new Callback() {
public boolean handleMessage(Message msg) {
onJavaCallback((String) msg.obj);
return false;
}
};
paListaner = new PlatformActionListener() {
public void onComplete(Platform platform, int action, HashMap<String, Object> res) {
if (DEBUG) {
System.out.println("onComplete");
}
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("platform", ShareSDK.platformNameToId(platform.getName()));
map.put("action", action);
map.put("status", 1); // Success = 1, Fail = 2, Cancel = 3
map.put("res", res);
Message msg = new Message();
msg.obj = hashon.fromHashMap(map);
UIHandler.sendMessage(msg, cb);
}
public void onError(Platform platform, int action, Throwable t) {
if (DEBUG) {
System.out.println("onError");
}
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("platform", ShareSDK.platformNameToId(platform.getName()));
map.put("action", action);
map.put("status", 2); // Success = 1, Fail = 2, Cancel = 3
map.put("res", throwableToMap(t));
Message msg = new Message();
msg.obj = hashon.fromHashMap(map);
UIHandler.sendMessage(msg, cb);
}
public void onCancel(Platform platform, int action) {
if (DEBUG) {
System.out.println("onCancel");
}
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("platform", ShareSDK.platformNameToId(platform.getName()));
map.put("action", action);
map.put("status", 3); // Success = 1, Fail = 2, Cancel = 3
Message msg = new Message();
msg.obj = hashon.fromHashMap(map);
UIHandler.sendMessage(msg, cb);
}
};
}
private static native void onJavaCallback(String resp);
private static HashMap<String, Object> throwableToMap(Throwable t) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("msg", t.getMessage());
ArrayList<HashMap<String, Object>> traces = new ArrayList<HashMap<String, Object>>();
for (StackTraceElement trace : t.getStackTrace()) {
HashMap<String, Object> element = new HashMap<String, Object>();
element.put("cls", trace.getClassName());
element.put("method", trace.getMethodName());
element.put("file", trace.getFileName());
element.put("line", trace.getLineNumber());
traces.add(element);
}
map.put("stack", traces);
Throwable cause = t.getCause();
if (cause != null) {
map.put("cause", throwableToMap(cause));
}
return map;
}
public static void initSDK(final String appKey, final boolean enableStatistics) {
if (DEBUG) {
System.out.println("initSDK");
}
UIHandler.sendEmptyMessage(1, new Callback() {
@Override
public boolean handleMessage(Message msg) {
ShareSDK.initSDK(context, appKey, enableStatistics);
return true;
}
});
}
public static void stopSDK() {
if (DEBUG) {
System.out.println("stopSDK");
}
ShareSDK.stopSDK(context);
}
public static void setPlatformConfig(int platformId, String configs) {
if (DEBUG) {
System.out.println("setPlatformConfig");
}
String name = ShareSDK.platformIdToName(platformId);
HashMap<String, Object> conf = new Hashon().fromJson(configs);
ShareSDK.setPlatformDevInfo(name, conf);
}
public static void authorize(int platformId) {
if (DEBUG) {
System.out.println("authorize");
}
String name = ShareSDK.platformIdToName(platformId);
Platform plat = ShareSDK.getPlatform(context, name);
plat.setPlatformActionListener(paListaner);
plat.authorize();
}
public static void removeAccount(int platformId) {
if (DEBUG) {
System.out.println("removeAccount");
}
String name = ShareSDK.platformIdToName(platformId);
Platform plat = ShareSDK.getPlatform(context, name);
plat.removeAccount();
}
public static boolean isValid(int platformId) {
if (DEBUG) {
System.out.println("isValid");
}
String name = ShareSDK.platformIdToName(platformId);
Platform plat = ShareSDK.getPlatform(context, name);
return plat.isValid();
}
public static void showUser(int platformId) {
if (DEBUG) {
System.out.println("showUser");
}
String name = ShareSDK.platformIdToName(platformId);
Platform plat = ShareSDK.getPlatform(context, name);
plat.setPlatformActionListener(paListaner);
plat.showUser(null);
}
public static void share(int platformId, String contentJson) {
if (DEBUG) {
System.out.println("share");
}
String name = ShareSDK.platformIdToName(platformId);
Platform plat = ShareSDK.getPlatform(context, name);
plat.setPlatformActionListener(paListaner);
try {
HashMap<String, Object> content = hashon.fromJson(contentJson);
content = nativeMapToJavaMap(content);
ShareParams sp = new ShareParams(content);
plat.share(sp);
} catch (Throwable t) {
paListaner.onError(plat, Platform.ACTION_SHARE, t);
}
}
private static HashMap<String, Object> nativeMapToJavaMap(
HashMap<String, Object> content) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("text", content.get("content"));
String image = (String) content.get("image");
if (image != null && image.startsWith("/")) {
map.put("imagePath", image);
} else {
map.put("imageUrl", image);
}
map.put("title", content.get("title"));
map.put("comment", content.get("description"));
map.put("url", content.get("url"));
map.put("titleUrl", content.get("url"));
map.put("site",content.get("site"));
map.put("siteUrl",content.get("siteUrl"));
String type = (String) content.get("type");
if (type != null) {
int shareType = iosTypeToAndroidType(Integer.parseInt(type));
map.put("shareType", shareType);
}
return map;
}
private static int iosTypeToAndroidType(int type) {
switch (type) {
case 1: return Platform.SHARE_IMAGE;
case 2: return Platform.SHARE_WEBPAGE;
case 3: return Platform.SHARE_MUSIC;
case 4: return Platform.SHARE_VIDEO;
case 5: return Platform.SHARE_APPS;
case 6:
case 7: return Platform.SHARE_EMOJI;
case 8: return Platform.SHARE_FILE;
}
return Platform.SHARE_TEXT;
}
public static void onekeyShare(String contentJson) {
onekeyShare(0, contentJson);
}
public static void onekeyShare(int platformId, String contentJson) {
if (DEBUG) {
System.out.println("OnekeyShare");
}
HashMap<String, Object> content = hashon.fromJson(contentJson);
content = nativeMapToJavaMap(content);
HashMap<String, Object> map = nativeMapToJavaMap(content);
OnekeyShare oks = new OnekeyShare();
if (map.containsKey("text")) {
oks.setText(String.valueOf(map.get("text")));
}
if (map.containsKey("imagePath")) {
oks.setImagePath(String.valueOf(map.get("imagePath")));
}
if (map.containsKey("imageUrl")) {
oks.setImageUrl(String.valueOf(map.get("imageUrl")));
}
if (map.containsKey("title")) {
oks.setTitle(String.valueOf(map.get("title")));
}
if (map.containsKey("comment")) {
oks.setComment(String.valueOf(map.get("comment")));
}
if (map.containsKey("url")) {
oks.setUrl(String.valueOf(map.get("url")));
}
if (map.containsKey("titleUrl")) {
oks.setTitleUrl(String.valueOf(map.get("titleUrl")));
}
if (map.containsKey("site")) {
oks.setSite(String.valueOf(map.get("site")));
}
if (map.containsKey("siteUrl")) {
oks.setSiteUrl(String.valueOf(map.get("siteUrl")));
}
oks.setCallback(paListaner);
if (platformId > 0) {
oks.setPlatform(ShareSDK.platformIdToName(platformId));
}
oks.show(context);
}
} |
package wof.gui;
import java.applet.Applet;
import java.applet.AudioClip;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.Timer;
import wof.game.WheelOfFortuneGame;
public class WheelOfFortuneWheelPanel extends JPanel {
private static final String IMAGES_DIR = "/resources/images/",
SOUNDS_DIR = "/resources/sounds/";
private static final String[] IMAGE_NAMES;
private static final Map<String, Color> WHEEL_COLORS;
private static final int DEGREES_EACH = 20;
private final Map<String, Image> IMAGES;
private final AudioClip SPINNING_WHEEL_CLIP, GOOD_GUESS_CLIP,
BAD_GUESS_CLIP, BANKRUPT_CLIP, NO_MORE_VOWELS_CLIP;
private WheelOfFortuneGame game;
private WheelOfFortuneTopPanel topPanel;
private WheelOfFortunePuzzlePanel puzzlePanel;
private Timer wheelTimer;
private ButtonListener buttonListener;
private List<String> imageNames;
private String spaceLanded;
private JPanel lettersPanel;
private JButton[] letterButtons;
private JButton spinWheel, solvePuzzle, newGame, howToPlay, about;
private JTextArea statusArea;
static {
// Store the image names for image construction later
IMAGE_NAMES =
new String[] {"300.png", "750.png", "500.png", "loseATurn.png",
"1000.png", "600.png", "350.png", "950.png", "800.png",
"550.png", "450.png", "700.png", "bankrupt.png", "650.png",
"250.png", "900.png", "400.png", "850.png"};
WHEEL_COLORS = new HashMap<String, Color>();
WHEEL_COLORS.put("300", Color.BLUE);
WHEEL_COLORS.put("750", Color.RED);
WHEEL_COLORS.put("500", Color.ORANGE);
WHEEL_COLORS.put("loseATurn", Color.WHITE);
WHEEL_COLORS.put("1000", Color.MAGENTA);
WHEEL_COLORS.put("600", new Color(255, 107, 36));
WHEEL_COLORS.put("350", new Color(192, 192, 192));
WHEEL_COLORS.put("950", new Color(128, 64, 0));
WHEEL_COLORS.put("800", new Color(128, 0, 255));
WHEEL_COLORS.put("550", new Color(0, 128, 128));
WHEEL_COLORS.put("450", new Color(255, 0, 128));
WHEEL_COLORS.put("700", new Color(0, 128, 0));
WHEEL_COLORS.put("bankrupt", Color.BLACK);
WHEEL_COLORS.put("650", Color.YELLOW);
WHEEL_COLORS.put("250", Color.GREEN);
WHEEL_COLORS.put("900", Color.PINK);
WHEEL_COLORS.put("400", Color.GRAY);
WHEEL_COLORS.put("850", Color.CYAN);
}
public WheelOfFortuneWheelPanel(WheelOfFortuneGame game,
WheelOfFortuneTopPanel topPanel,
WheelOfFortunePuzzlePanel puzzlePanel) {
super();
this.game = game;
this.topPanel = topPanel;
this.puzzlePanel = puzzlePanel;
SPINNING_WHEEL_CLIP =
Applet.newAudioClip(getClass().getResource(
SOUNDS_DIR + "spinningWheel.wav"));
GOOD_GUESS_CLIP =
Applet.newAudioClip(getClass().getResource(
SOUNDS_DIR + "goodGuess.wav"));
BAD_GUESS_CLIP =
Applet.newAudioClip(getClass().getResource(
SOUNDS_DIR + "badGuess.wav"));
BANKRUPT_CLIP =
Applet.newAudioClip(getClass().getResource(
SOUNDS_DIR + "bankrupt.wav"));
NO_MORE_VOWELS_CLIP =
Applet.newAudioClip(getClass().getResource(
SOUNDS_DIR + "noMoreVowels.wav"));
// Store the toolkit for easier access and fewer calls
Toolkit defaultToolkit = Toolkit.getDefaultToolkit();
IMAGES = new HashMap<String, Image>();
for (String imageName : IMAGE_NAMES) {
IMAGES.put(
imageName,
defaultToolkit.getImage(getClass().getResource(
IMAGES_DIR + imageName)));
}
IMAGES.put(
"arrow.png",
defaultToolkit.getImage(getClass().getResource(
IMAGES_DIR + "arrow.png")));
wheelTimer = new Timer(25, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String value = imageNames.get(0);
imageNames.remove(0);
imageNames.add(value);
repaint();
}
});
letterButtons = new JButton[26];
buttonListener = new ButtonListener();
for (int i = 0; i < letterButtons.length; i++) {
letterButtons[i] = new JButton("" + (char)(i + 65));
letterButtons[i].addActionListener(buttonListener);
letterButtons[i].setEnabled(false);
}
lettersPanel = new JPanel();
lettersPanel.setPreferredSize(new Dimension(100, 200));
lettersPanel.setLayout(new GridLayout(6, 5, 2, 2));
// Vowel buttons are red, consonant buttons are blue
for (int i = 0; i < letterButtons.length; i++) {
letterButtons[i].setBackground((i == 0 || i == 4 || i == 8
|| i == 14 || i == 20) ? Color.RED : Color.BLUE);
lettersPanel.add(letterButtons[i]);
}
spinWheel = new JButton("Spin Wheel");
spinWheel.addActionListener(buttonListener);
solvePuzzle = new JButton("Solve Puzzle");
solvePuzzle.addActionListener(buttonListener);
newGame = new JButton("New Game");
newGame.addActionListener(buttonListener);
howToPlay = new JButton("How to Play");
howToPlay.addActionListener(buttonListener);
about = new JButton("About");
about.addActionListener(buttonListener);
statusArea = new JTextArea();
statusArea.setFont(new Font("Tahoma", Font.PLAIN, 11));
statusArea.setEditable(false);
statusArea.setBorder(BorderFactory.createLineBorder(Color.GRAY));
statusArea.setLineWrap(true);
statusArea.setWrapStyleWord(true);
Box optionButtonsBox = Box.createVerticalBox();
optionButtonsBox.add(spinWheel);
optionButtonsBox.add(Box.createVerticalStrut(15));
optionButtonsBox.add(solvePuzzle);
optionButtonsBox.add(Box.createVerticalStrut(60));
optionButtonsBox.add(newGame);
optionButtonsBox.add(Box.createVerticalStrut(15));
optionButtonsBox.add(howToPlay);
optionButtonsBox.add(Box.createVerticalStrut(15));
optionButtonsBox.add(about);
optionButtonsBox.add(Box.createVerticalStrut(250));
Box letterButtonsBox = Box.createVerticalBox();
letterButtonsBox.add(lettersPanel);
letterButtonsBox.add(Box.createVerticalStrut(10));
letterButtonsBox.add(statusArea);
letterButtonsBox.add(Box.createVerticalStrut(235));
Box outsideBox = Box.createHorizontalBox();
outsideBox.add(Box.createHorizontalStrut(20));
outsideBox.add(optionButtonsBox);
outsideBox.add(Box.createHorizontalStrut(550));
outsideBox.add(letterButtonsBox);
outsideBox.add(Box.createHorizontalStrut(20));
outsideBox.setPreferredSize(new Dimension(900, 500));
add(outsideBox);
setPreferredSize(new Dimension(900, 300));
newGame();
}
public void newGame() {
statusArea.setText("Welcome to Wheel of Fortune!\n"
+ "You may spin the wheel or solve the puzzle.");
topPanel.resetValues();
puzzlePanel.newGame();
imageNames = new ArrayList<String>();
for (String name : IMAGE_NAMES) {
imageNames.add(name);
}
setEnabledConsonants(false);
setEnabledVowels(false);
spinWheel.setEnabled(true);
repaint();
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2D = (Graphics2D)g.create();
// Draw each space
for (int i = 0, degrees = 0; i < imageNames.size() / 2; ++i) {
g2D.setColor(WHEEL_COLORS.get(imageNames.get(i).substring(0,
imageNames.get(i).indexOf('.'))));
g2D.fillArc(150, 45, 480, 480, degrees, DEGREES_EACH);
degrees += DEGREES_EACH;
}
// Set the origin and rotate before drawing the images
g2D.translate(390, 285);
g2D.rotate(Math.toRadians(-100));
// Draw wheel spaces
for (int i = 0; i < imageNames.size() / 2; ++i) {
g2D.drawImage(IMAGES.get(imageNames.get(i)), -42, 0, this);
g2D.rotate(Math.toRadians(-DEGREES_EACH));
}
// Reset origin
g2D.translate(-390, -285);
// Draw the arrow to indicate where the wheel stopped
g.drawImage(IMAGES.get("arrow.png"), 370, 10, this);
}
private void setEnabledConsonants(boolean b) {
for (int i = 0; i < letterButtons.length; ++i) {
if (!(i == 0 || i == 4 || i == 8 || i == 14 || i == 20)) {
letterButtons[i].setEnabled(b);
}
}
}
private void setEnabledVowels(boolean b) {
letterButtons[0].setEnabled(b);
letterButtons[4].setEnabled(b);
letterButtons[8].setEnabled(b);
letterButtons[14].setEnabled(b);
letterButtons[20].setEnabled(b);
}
private void setEnabledGuessedLetters(boolean b) {
for (char c : game.getGuessedLetters()) {
letterButtons[c - 65].setEnabled(b);
}
}
private void handleWin() {
game.revealPuzzle();
JOptionPane.showMessageDialog(null,
"Congratulations, you win $" + game.getScore() + "!\n\n",
"You Win!", JOptionPane.INFORMATION_MESSAGE);
newGame();
}
private void handleLoss(String message) {
game.revealPuzzle();
JOptionPane.showMessageDialog(null, message + "\nSorry, you lose.",
"You Lose!", JOptionPane.INFORMATION_MESSAGE);
newGame();
}
private void showHowToPlay() {
JOptionPane.showMessageDialog(null,
"To guess a consonant, you must first spin the wheel (Press "
+ "\"Spin Wheel\" to\nspin it, and \"Stop Wheel\" to "
+ "stop it). You will be awarded the amount on the\n"
+ "space times the number of appearances of the "
+ "consonant in the puzzle. You\nlose a turn if the "
+ "consonant does not appear in the puzzle.\n\nYou may "
+ "buy a vowel at any time if you have at least $250. "
+ "Vowels cost a flat\nrate of $250; extra money will "
+ "not be deducted for multiple occurrences of the\n"
+ "vowel in the puzzle. If the vowel does not appear "
+ "in the puzzle, you lose a turn\nin addition to the "
+ "$250.\n\nThere are two non-cash amount spaces on "
+ "the wheel: \"Bankrupt\" and \"Lose a\nTurn\", both "
+ "of which make you lose a turn. In addition, "
+ "\"Bankrupt\" brings your\nscore down to 0.\n\nIn "
+ "order to win the game, you must solve the puzzle "
+ "within 7 turns. If you fail\nto do this, you lose. "
+ "You may solve the puzzle at any time during the "
+ "game,\nbut you lose if your guess is incorrect.",
"How to Play", JOptionPane.INFORMATION_MESSAGE);
}
private void showAbout() {
JOptionPane.showMessageDialog(null,
"Created by Nikita Kouevda and Jenny Shen\nJuly 12, 2015",
"About", JOptionPane.INFORMATION_MESSAGE);
}
private class ButtonListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
JButton source = (JButton)e.getSource();
for (int c = 0; c < letterButtons.length; c++) {
if (source == letterButtons[c]) {
int occurrences = game.revealLetter((char)(c + 65));
if (c == 0 || c == 4 || c == 8 || c == 14 || c == 20) {
// Subtract $250 (flat rate for vowels)
topPanel.addScore(-250);
if (occurrences > 0) {
GOOD_GUESS_CLIP.play();
statusArea.setText("There "
+ (occurrences == 1 ? "is" : "are") + " "
+ occurrences + " " + (char)(c + 65)
+ (occurrences == 1 ? "" : "'s")
+ " in the puzzle! Please spin the"
+ "wheel or buy another vowel.");
} else {
BAD_GUESS_CLIP.play();
topPanel.subtractTurn();
statusArea.setText("Sorry, there are no "
+ (char)(c + 65) + "'s in the puzzle. "
+ "Please spin the wheel or buy another "
+ "vowel.");
}
if (game.isAllVowelsGuessed()) {
NO_MORE_VOWELS_CLIP.play();
game.disableVowels();
JOptionPane.showMessageDialog(null,
"There are no more vowels left in "
+ "the puzzle.", "No More Vowels!",
JOptionPane.WARNING_MESSAGE);
}
} else {
spinWheel.setEnabled(true);
if (occurrences > 0) {
GOOD_GUESS_CLIP.play();
int amount =
Integer.parseInt(spaceLanded.substring(0,
spaceLanded.indexOf('.')));
topPanel.addScore(amount * occurrences);
statusArea.setText("There "
+ (occurrences == 1 ? "is" : "are") + " "
+ occurrences + " " + (char)(c + 65)
+ (occurrences == 1 ? "" : "'s")
+ " in the puzzle! You earn $" + amount
* occurrences
+ "! Please spin the wheel again "
+ "or buy a vowel.");
} else {
BAD_GUESS_CLIP.play();
topPanel.subtractTurn();
statusArea.setText("Sorry, there are no "
+ (char)(c + 65) + "'s in the puzzle. "
+ "Please spin the wheel again or buy a "
+ "vowel.");
}
}
setEnabledConsonants(false);
setEnabledVowels(game.getScore() >= 250);
setEnabledGuessedLetters(false);
}
}
if (source == spinWheel) {
String cmd = e.getActionCommand();
if (cmd.equals("Spin Wheel")) {
SPINNING_WHEEL_CLIP.loop();
solvePuzzle.setEnabled(false);
setEnabledVowels(false);
wheelTimer.start();
statusArea.setText("The wheel is spinning...");
spinWheel.setText("Stop Wheel");
} else if (cmd.equals("Stop Wheel")) {
SPINNING_WHEEL_CLIP.stop();
wheelTimer.stop();
solvePuzzle.setEnabled(true);
spinWheel.setText("Spin Wheel");
spaceLanded = imageNames.get(4);
if (spaceLanded.equals("loseATurn.png")) {
topPanel.subtractTurn();
statusArea.setText("Sorry, you lose a turn.");
setEnabledConsonants(false);
setEnabledVowels(game.getScore() >= 250);
setEnabledGuessedLetters(false);
} else if (spaceLanded.equals("bankrupt.png")) {
BANKRUPT_CLIP.play();
topPanel.subtractTurn();
topPanel.resetScore();
statusArea.setText("Sorry, you lose a turn, and "
+ "your score has been brought down to 0.");
setEnabledConsonants(false);
setEnabledVowels(game.getScore() >= 250);
setEnabledGuessedLetters(false);
} else {
spinWheel.setEnabled(false);
statusArea.setText("Please select a consonant.");
setEnabledConsonants(true);
setEnabledVowels(false);
setEnabledGuessedLetters(false);
}
}
} else if (source == solvePuzzle) {
String solveAttempt =
JOptionPane.showInputDialog(null,
"Please solve the puzzle:", "Solve the Puzzle",
JOptionPane.PLAIN_MESSAGE);
StringBuilder trimmedAttempt = new StringBuilder();
String phrase = game.getPhrase();
StringBuilder trimmedPhrase = new StringBuilder();
for (int i = 0; i < phrase.length(); ++i) {
if (phrase.charAt(i) != ' ') {
trimmedPhrase.append(phrase.charAt(i));
}
}
if (solveAttempt != null) {
for (int i = 0; i < solveAttempt.length(); ++i) {
if (solveAttempt.charAt(i) != ' ') {
trimmedAttempt.append(solveAttempt.charAt(i));
}
}
}
if (trimmedAttempt.toString() != "") {
if (trimmedAttempt.toString().compareToIgnoreCase(
trimmedPhrase.toString()) == 0) {
handleWin();
} else {
handleLoss("That is incorrect.");
}
}
} else if (source == newGame) {
newGame();
} else if (source == howToPlay) {
showHowToPlay();
} else if (source == about) {
showAbout();
}
if (game.getTurnsLeft() == 0) {
handleLoss("You have no turns left.");
} else if (game.isSolved()) {
handleWin();
}
puzzlePanel.repaint();
}
}
} |
import java.awt.*;
import java.awt.image.*;
import javax.swing.*;
import org.opencv.core.*;
import org.opencv.core.Point;
import org.opencv.highgui.Highgui;
import org.opencv.highgui.VideoCapture;
import org.opencv.imgproc.Imgproc;
import org.opencv.objdetect.CascadeClassifier;
/**
* This is the main class of the Face Detector program. This program experiments with Face Detection
* using OpenCV. It contains example code to:
* - Capture video with the default camera.
* - Detect faces with OpenCV using the FrontalFace CascadeSpecifier.
* - Scale an image to a different size.
* - Overlay an image onto another image with transparency.
* - Translate between the OpenCV Mat image format and the BufferedImage format for display.
*/
public class FaceDetector extends JPanel
{
private static final long serialVersionUID = 1L;
private static final String programTitle = "OpenCV Face Detector";
private static final String classifierPath = "cascade-files/haarcascade_frontalface_alt.xml";
private static final String overlayImagePath = "images/Mustache.png";
private VideoCapture camera;
private Mat image;
private MatOfRect faceRects;
private Mat overlayImage;
private CascadeClassifier faceDetector;
/**
* This is the entry point of the program. It creates and initializes the main window. It also
* creates and initializes the FaceDetector class.
*
* @param args specifies an array of command arguments (not used).
*/
public static void main(String[] args)
{
EventQueue.invokeLater(
new Runnable()
{
@Override
public void run()
{
JFrame frame = new JFrame(programTitle);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(null);
frame.setResizable(false);
frame.setContentPane(new FaceDetector(frame));
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
} //main
/**
* Constructor: Creates an instance of the object.
*
* @param frame specifies the parent window.
*/
private FaceDetector(JFrame frame)
{
// Load OpenCV library.
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
// Open the default camera.
camera = new VideoCapture(0);
if (!camera.isOpened())
{
throw new RuntimeException("Failed to open camera");
}
// Preallocated some global variables.
image = new Mat();
faceRects = new MatOfRect();
// Load the overlay image and preserves the alpha channel (i.e. transparency).
overlayImage = Highgui.imread(overlayImagePath, -1);
// Load the Frontal Face cascade specifier as the face detector.
faceDetector = new CascadeClassifier(classifierPath);
if (faceDetector.empty())
{
throw new RuntimeException("Failed to load Cascade Classifier <" + classifierPath + ">");
}
// Determine the camera image size and make the window size to match.
camera.read(image);
frame.setSize(image.width(), image.height() + 35);
// Create the Refresh thread to refresh the video pane at 30fps.
new RefreshThread(this).start();
} //FaceDetector
/**
* This method is called whenever Java VM determined that the JPanel needs to be repainted.
*
* @param g specifies the graphics object to be repainted.
*/
public void paint(Graphics g)
{
// Capture an image and subject it for face detection. The face detector produces an array
// of rectangles representing faces detected.
camera.read(image);
faceDetector.detectMultiScale(image, faceRects);
// We may want to overlay a circle or rectangle on each detected faces or
// we can overlay a fun image onto a detected face. Play with the code in
// this for-loop and let your imagination run wild.
Rect[] rects = faceRects.toArray();
for (int i = 0; i < rects.length; i++)
{
/*
//
// Draw a circle around the detected face.
//
Core.ellipse(
image,
new RotatedRect(
new Point(rects[i].x + rects[i].width/2, rects[i].y + rects[i].height/2),
rects[i].size(),
0.0),
new Scalar(0, 255, 0));
*/
/*
//
// Draw a rectangle around the detected face.
//
Core.rectangle(
image,
new Point(rects[i].x, rects[i].y),
new Point(rects[i].x + rects[i].width, rects[i].y + rects[i].height),
new Scalar(0, 255, 0));
*/
// Only overlay fun image to the first detected face.
if (i == 0)
{
// Scale the fun image to the same size as the face.
Mat scaledOverlay = new Mat();
Imgproc.resize(overlayImage, scaledOverlay, rects[i].size());
// Overlay the scaled image to the camera image.
// overlayImage(image, scaledOverlay, new Point(rects[i].x, rects[i].y - rects[i].height));
overlayImage(image, scaledOverlay, new Point(rects[i].x, rects[i].y));
}
}
// Convert the OpenCV Mat image format to BufferedImage format and draw it on the video pane.
g.drawImage(MatToBufferedImage(image), 0, 0, null);
} //paint
/**
* This method combines an overlay image to the given background image at the specified location.
* It is expecting both the background and overlay are color images. It also expects the overlay
* image contains an alpha channel for opacity information.
*
* @param background specifies the background image.
* @param overlay specifies the overlay image.
* @param location specifies the location on the background image where the upper left corner of
* the overlay image should be at.
*/
private void overlayImage(Mat background, Mat overlay, Point location)
{
// Make sure the background image has 3 channels and the overlay image has 4 channels.
if (background.channels() == 3 && overlay.channels() == 4)
{
// For each row of the overlay image.
for (int row = 0; row < overlay.rows(); row++)
{
// Calculate the corresponding row number of the background image.
// Skip the row if it is outside of the background image.
int destRow = (int)location.y + row;
if (destRow < 0 || destRow >= background.rows()) continue;
// For each column of the overlay image.
for (int col = 0; col < overlay.cols(); col++)
{
// Calculate the corresponding column number of background image.
// Skip the column if it is outside of the background image.
int destCol = (int)location.x + col;
if (destCol < 0 || destCol >= background.cols()) continue;
// Get the source pixel from the overlay image and the destination pixel from the
// background image. Calculate the opacity as a percentage.
double[] srcPixel = overlay.get(row, col);
double[] destPixel = background.get(destRow, destCol);
double opacity = srcPixel[3]/255.0;
// Merge the source pixel to the destination pixel with the proper opacity.
for (int channel = 0; channel < background.channels(); channel++)
{
destPixel[channel] = destPixel[channel]*(1.0 - opacity) + srcPixel[channel]*opacity;
}
// Put the resulting pixel into the background image.
background.put(destRow, destCol, destPixel);
}
}
}
else
{
throw new RuntimeException("Invalid image format.");
}
} //overlayImage
/**
* This method converts an OpenCV image (i.e. Mat) into a BufferedImage that can be drawn on
* a Java graphics object.
*
* @param mat specifies an OpenCV image.
* @return converted BufferedImage object.
*/
public BufferedImage MatToBufferedImage(Mat mat)
{
BufferedImage image = new BufferedImage(mat.width(), mat.height(), BufferedImage.TYPE_3BYTE_BGR);
WritableRaster raster = image.getRaster();
DataBufferByte dataBuffer = (DataBufferByte)raster.getDataBuffer();
byte[] data = dataBuffer.getData();
mat.get(0, 0, data);
return image;
} //MatToBufferedImage
} //class FaceDetector |
package kg.apc.jmeter.config;
import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import kg.apc.jmeter.JMeterPluginsUtils;
import org.apache.jmeter.config.gui.AbstractConfigGui;
import org.apache.jmeter.testelement.TestElement;
import org.apache.jorphan.logging.LoggingManager;
import org.apache.log.Logger;
/**
*
* @author Direvius
*/
public class LockFileGui extends AbstractConfigGui {
public static final String WIKIPAGE = "LockFile";
public static Logger log = LoggingManager.getLoggerForClass();
private JTextField tfFileName;
private JTextField tfFileMask;
public LockFileGui() {
super();
init();
initFields();
}
@Override
public String getStaticLabel() {
return JMeterPluginsUtils.prefixLabel("Lock File Config");
}
@Override
public String getLabelResource() {
return getClass().getCanonicalName();
}
@Override
public void configure(TestElement te) {
log.debug("[Lockfile plugin] configure");
super.configure(te);
LockFile lf = (LockFile) te;
tfFileName.setText(lf.getFilename());
tfFileMask.setText(lf.getFilemask());
}
@Override
public TestElement createTestElement() {
log.debug("[Lockfile plugin] createTestElement");
LockFile lockFile = new LockFile();
modifyTestElement(lockFile);
lockFile.setComment(JMeterPluginsUtils.getWikiLinkText(WIKIPAGE));
return lockFile;
}
@Override
public void modifyTestElement(TestElement te) {
log.debug("[Lockfile plugin] modifyTestElement");
configureTestElement(te);
LockFile lf = (LockFile) te;
lf.setFilename(tfFileName.getText());
lf.setFilemask(tfFileMask.getText());
}
@Override
public void clearGui() {
super.clearGui();
initFields();
}
private void init() {
log.debug("[Lockfile plugin] init");
setLayout(new BorderLayout(0, 5));
setBorder(makeBorder());
add(JMeterPluginsUtils.addHelpLinkToPanel(makeTitlePanel(), WIKIPAGE), BorderLayout.NORTH);
JPanel mainPanel = new JPanel(new GridBagLayout());
GridBagConstraints labelConstraints = new GridBagConstraints();
labelConstraints.anchor = GridBagConstraints.FIRST_LINE_END;
GridBagConstraints editConstraints = new GridBagConstraints();
editConstraints.anchor = GridBagConstraints.FIRST_LINE_START;
editConstraints.weightx = 1.0;
editConstraints.fill = GridBagConstraints.HORIZONTAL;
editConstraints.insets = new java.awt.Insets(2, 0, 0, 0);
labelConstraints.insets = new java.awt.Insets(2, 0, 0, 0);
addToPanel(mainPanel, labelConstraints, 0, 0, new JLabel("Lock file name: ", JLabel.RIGHT));
addToPanel(mainPanel, editConstraints, 1, 0, tfFileName = new JTextField(20));
addToPanel(mainPanel, labelConstraints, 0, 1, new JLabel("Also check filemask: ", JLabel.RIGHT));
addToPanel(mainPanel, editConstraints, 1, 1, tfFileMask = new JTextField(20));
JPanel container = new JPanel(new BorderLayout());
container.add(mainPanel, BorderLayout.NORTH);
add(container, BorderLayout.CENTER);
}
private void addToPanel(JPanel panel, GridBagConstraints constraints, int col, int row, JComponent component) {
constraints.gridx = col;
constraints.gridy = row;
panel.add(component, constraints);
}
private void initFields() {
log.debug("[Lockfile plugin] initFields");
tfFileName.setText("");
tfFileMask.setText("");
}
} |
package eu.europa.esig.dss;
import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
* This class encapsulates an org.w3c.dom.Document. Its integrates the ability to execute XPath queries on XML
* documents.
*/
public class XmlDom {
private static final Logger LOG = LoggerFactory.getLogger(XmlDom.class);
public static final String NAMESPACE = "http://dss.esig.europa.eu/validation/diagnostic";
private static final String NS_PREFIX = "dss";
private static final XPathFactory factory = XPathFactory.newInstance();
private static final NamespaceContextMap nsContext;
private static final Map<String, String> namespaces;
static {
namespaces = new HashMap<String, String>();
namespaces.put(NS_PREFIX, NAMESPACE);
nsContext = new NamespaceContextMap();
nsContext.registerNamespace(NS_PREFIX, NAMESPACE);
}
public final Element rootElement;
String nameSpace;
public XmlDom(final Document document) {
this.rootElement = document.getDocumentElement();
nameSpace = rootElement.getNamespaceURI();
}
public XmlDom(final Element element) {
this.rootElement = element;
}
private static XPathExpression createXPathExpression(final String xpathString) {
final XPath xpath = factory.newXPath();
xpath.setNamespaceContext(nsContext);
try {
final XPathExpression expr = xpath.compile(xpathString);
return expr;
} catch (XPathExpressionException ex) {
throw new RuntimeException(ex);
}
}
private static NodeList getNodeList(final Node xmlNode, final String xpathString) {
try {
final XPathExpression expr = createXPathExpression(xpathString);
return (NodeList) expr.evaluate(xmlNode, XPathConstants.NODESET);
} catch (XPathExpressionException e) {
throw new RuntimeException(e);
}
}
/**
* The list of elements corresponding the given XPath query and parameters.
*
* @param xPath
* @param params
* @return
*/
public List<XmlDom> getElements(final String xPath, final Object... params) {
try {
String xPath_ = format(xPath, params);
NodeList nodeList = getNodeList(rootElement, xPath_);
List<XmlDom> list = new ArrayList<XmlDom>();
for (int ii = 0; ii < nodeList.getLength(); ii++) {
Node node = nodeList.item(ii);
if ((node != null) && (node.getNodeType() == Node.ELEMENT_NODE)) {
list.add(new XmlDom((Element) node));
}
}
return list;
} catch (Exception e) {
String message = "XPath error: '" + xPath + "'.";
throw new DSSException(message, e);
}
}
public XmlDom getElement(final String xPath, final Object... params) {
try {
String xPath_ = format(xPath, params);
NodeList nodeList = getNodeList(rootElement, xPath_);
for (int ii = 0; ii < nodeList.getLength(); ii++) {
Node node = nodeList.item(ii);
if ((node != null) && (node.getNodeType() == Node.ELEMENT_NODE)) {
return new XmlDom((Element) node);
}
}
return null;
} catch (Exception e) {
String message = "XPath error: '" + xPath + "'.";
throw new DSSException(message, e);
}
}
/**
* @param xPath
* @param params
* @return
*/
private static String format(final String xPath, final Object... params) {
String formattedXPath;
if (params.length > 0) {
formattedXPath = String.format(xPath, params);
} else {
formattedXPath = xPath;
}
formattedXPath = addNamespacePrefix(formattedXPath);
return formattedXPath;
}
private static String addNamespacePrefix(final String formatedXPath) {
if (formatedXPath.startsWith("/dss:") || formatedXPath.startsWith("./dss:")) {
// Already formated.
return formatedXPath;
}
String formatedXPath_ = formatedXPath;
CharSequence from = "
CharSequence to = "{#double}/";
boolean special = formatedXPath_.indexOf("
if (special) {
formatedXPath_ = formatedXPath_.replace(from, to);
}
StringTokenizer tokenizer = new StringTokenizer(formatedXPath_, "/");
StringBuilder stringBuilder = new StringBuilder();
while (tokenizer.hasMoreTokens())
{
String token = tokenizer.nextToken();
final boolean isDot = ".".equals(token);
final boolean isCount = "count(".equals(token) || "count(.".equals(token);
final boolean isDoubleDot = "..".equals(token);
final boolean isAt = token.startsWith("@");
final boolean isText = token.equals("text()");
final boolean isDoubleSlash = token.equals("{#double}");
final String slash = isDot || isCount || isDoubleSlash ? "" : "/";
String prefix = isDot || isCount || isDoubleDot || isAt || isText || isDoubleSlash ? "" : "dss:";
stringBuilder.append(slash).append(prefix).append(token);
}
String normalizedXPath = stringBuilder.toString();
if (special) {
normalizedXPath = normalizedXPath.replace(to, from);
}
return normalizedXPath;
}
/**
* This method never returns null.
*
* @param xPath
* @param params
* @return {@code String} value or empty string
*/
public String getValue(final String xPath, final Object... params) {
String xPath_ = format(xPath, params);
NodeList nodeList = getNodeList(rootElement, xPath_);
if (nodeList.getLength() == 1) {
Node node = nodeList.item(0);
if (node.getNodeType() != Node.ELEMENT_NODE) {
String value = nodeList.item(0).getTextContent();
return value.trim();
}
}
return "";
}
public int getIntValue(final String xPath, final Object... params) {
String value = getValue(xPath, params);
try {
return Integer.parseInt(value);
} catch (Exception e) {
throw new DSSException(e);
}
}
public long getLongValue(final String xPath, final Object... params) {
String value = getValue(xPath, params);
try {
value = value.trim();
return Long.parseLong(value);
} catch (Exception e) {
throw new DSSException(e);
}
}
public boolean getBoolValue(final String xPath, final Object... params) {
String value = getValue(xPath, params);
if (value.equals("true")) {
return true;
} else if (value.isEmpty() || value.equals("false")) {
return false;
}
throw new DSSException("Expected values are: true, false and not '" + value + "'.");
}
public long getCountValue(final String xPath, final Object... params) {
String xpathString = format(xPath, params);
try {
XPathExpression xPathExpression = createXPathExpression(xpathString);
Double number = (Double) xPathExpression.evaluate(rootElement, XPathConstants.NUMBER);
return number.intValue();
} catch (XPathExpressionException e) {
throw new RuntimeException(e);
}
}
public boolean exists(final String xPath, final Object... params) {
XmlDom element = getElement(xPath, params);
return element != null;
}
public Date getTimeValue(final String xPath, final Object... params) {
String value = getValue(xPath, params);
return DSSUtils.parseDate(value);
}
public Date getTimeValueOrNull(final String xPath, final Object... params) {
String value = getValue(xPath, params);
if (value.isEmpty()) {
return null;
}
return DSSUtils.parseDate(value);
}
public String getText() {
try {
if (rootElement != null) {
return rootElement.getTextContent().trim();
}
} catch (Exception e) {
}
return null;
}
/**
* The name of this node, depending on its type;
*
* @return
*/
public String getName() {
return rootElement.getNodeName();
}
/**
* Retrieves an attribute value by name.
*
* @param attributeName
* @return
*/
public String getAttribute(final String attributeName) {
return rootElement.getAttribute(attributeName);
}
/**
* Retrieves an attribute value by name.
*
* @return
*/
public NamedNodeMap getAttributes() {
return rootElement.getAttributes();
}
/**
* Converts the list of {@code XmlDom} to {@code List} of {@code String}. The children of the node are not taken
* into account.
*
* @param xmlDomList the list of {@code XmlDom} to convert
* @return converted {@code List} of {@code String}.
*/
public static List<String> convertToStringList(final List<XmlDom> xmlDomList) {
final List<String> stringList = new ArrayList<String>();
for (final XmlDom xmlDom : xmlDomList) {
stringList.add(xmlDom.getText());
}
return stringList;
}
/**
* Converts the list of {@code XmlDom} to {@code Map} of {@code String}, {@code String}. The children of the node are not taken
* into account.
*
* @param xmlDomList the list of {@code XmlDom} to convert
* @param attributeName the name of the attribute to use as value
* @return converted {@code Map} of {@code String}, {@code String} corresponding to the element content and the attribute value.
*/
public static Map<String, String> convertToStringMap(final List<XmlDom> xmlDomList, final String attributeName) {
final Map<String, String> stringMap = new HashMap<String, String>();
for (final XmlDom xmlDom : xmlDomList) {
final String key = xmlDom.getText();
final String value = xmlDom.getAttribute(attributeName);
stringMap.put(key, value);
}
return stringMap;
}
/**
* Converts the list of {@code XmlDom} to {@code Map} of {@code String}, {@code Date}. The children of the node are not taken
* into account. If a problem is encountered during the conversion the pair key, value is ignored and a warning is logged.
*
* @param xmlDomList the list of {@code XmlDom} to convert
* @param attributeName the name of the attribute to use as value
* @return converted {@code Map} of {@code String}, {@code Date} corresponding to the element content and the attribute value.
*/
public static Map<String, Date> convertToStringDateMap(final List<XmlDom> xmlDomList, final String attributeName) {
final Map<String, Date> stringMap = new HashMap<String, Date>();
for (final XmlDom xmlDom : xmlDomList) {
final String key = xmlDom.getText();
final String dateString = xmlDom.getAttribute(attributeName);
String format = xmlDom.getAttribute("Format");
if (StringUtils.isBlank(format)) {
format = "yyyy-MM-dd";
}
if (StringUtils.isBlank(dateString)) {
LOG.warn(String.format("The date is not defined for key '%s'!", key));
continue;
}
final Date date;
try {
date = DSSUtils.parseDate(format, dateString);
} catch (DSSException e) {
LOG.warn("The date conversion is not possible.", e);
continue;
}
stringMap.put(key, date);
}
return stringMap;
}
public byte[] toByteArray() {
if (rootElement != null) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
printDocument(rootElement, byteArrayOutputStream, false);
return byteArrayOutputStream.toByteArray();
}
return DSSUtils.EMPTY_BYTE_ARRAY;
}
@Override
public String toString() {
if (rootElement != null) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
printDocument(rootElement, byteArrayOutputStream, false);
return getUtf8String(byteArrayOutputStream.toByteArray());
}
return super.toString();
}
private static String getUtf8String(byte[] bytes) {
if (bytes == null) {
return null;
}
try {
return new String(bytes, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new DSSException(e);
}
}
/**
* This method writes formatted {@link org.w3c.dom.Node} to the outputStream.
*
* @param node
* @param out
*/
private static void printDocument(final Node node, final OutputStream out, final boolean raw) {
try {
final TransformerFactory tf = TransformerFactory.newInstance();
final Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
if (!raw) {
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "3");
}
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
final DOMSource xmlSource = new DOMSource(node);
final OutputStreamWriter writer = new OutputStreamWriter(out, "UTF-8");
final StreamResult outputTarget = new StreamResult(writer);
transformer.transform(xmlSource, outputTarget);
} catch (Exception e) {
throw new DSSException(e);
}
}
public Element getRootElement() {
return rootElement;
}
} |
package com.sunteam.ebook.view;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Locale;
import com.sunteam.common.utils.Tools;
import com.sunteam.ebook.R;
import com.sunteam.ebook.entity.ReadMode;
import com.sunteam.ebook.entity.ReverseInfo;
import com.sunteam.ebook.entity.SplitInfo;
import com.sunteam.ebook.util.CodeTableUtils;
import com.sunteam.ebook.util.EbookConstants;
import com.sunteam.ebook.util.PublicUtils;
import com.sunteam.ebook.util.TTSUtils;
import com.sunteam.ebook.util.TTSUtils.OnTTSListener;
import com.sunteam.ebook.util.TTSUtils.SpeakStatus;
import com.sunteam.ebook.util.WordExplainUtils;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.graphics.Paint.FontMetrics;
import android.graphics.RectF;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.GestureDetector.OnDoubleTapListener;
import android.view.GestureDetector.OnGestureListener;
import android.view.MotionEvent;
import android.view.View;
/**
* Txt
*
* @author wzp
*
*/
public class TextReaderView extends View implements OnGestureListener, OnDoubleTapListener, OnTTSListener
{
private static final String TAG = "TextReaderView";
private static final int MSG_SPEAK_COMPLETED = 100;
private static final int MSG_SPEAK_ERROR = 200;
private static final int MSG_SPEAK_CONTINUE = 300;
private static final float MARGIN_WIDTH = 0;
private static final float MARGIN_HEIGHT = 0;
private static final String CHARSET_NAME = "GB18030";//GB18030
private static final char[] CN_SEPARATOR = {
0xA3BA,
0xA6DC,
0xA955,
0xA973,
0xA3AC,
0xA6D9,
0xA96F,
0xA3BB,
0xA6DD,
0xA972,
0xA1A3,
0xA3BF,
0xA974,
0xA3A1,
0xA6DE,
0xA975,
//0xA1AD, //
0xA1A2,
0xA970,
};
private static final char[] EN_SEPARATOR = {
0x3A,
0x2C,
0x3B,
0x3F,
//0x2E, //
0x21,
};
private Context mContext = null;
private Bitmap mCurPageBitmap = null;
private Canvas mCurPageCanvas = null;
private Paint mPaint = null;
private float mLineSpace = 3.6f;
private float mTextSize = 20.0f;
private int mTextColor = Color.WHITE;
private int mBkColor = Color.BLACK;
private int mReverseColor = Color.RED;
private int mLineCount = 0;
private int mWidth = 0;
private int mHeight = 0;
private float mVisibleWidth;
private float mVisibleHeight;
private boolean mIsFirstPage = false;
private boolean mIsLastPage = false;
private ArrayList<SplitInfo> mSplitInfoList = new ArrayList<SplitInfo>();
private byte[] mMbBuf = null;
private int mOffset = 0; //BOM
private int mLineNumber = 0;
private int mMbBufLen = 0;
private int mCurPage = 1;
private GestureDetector mGestureDetector = null;
private OnPageFlingListener mOnPageFlingListener = null;
private ReadMode mReadMode = ReadMode.READ_MODE_ALL;
private ReverseInfo mReverseInfo = new ReverseInfo();
private WordExplainUtils mWordExplainUtils = new WordExplainUtils();
private HashMap<Character, ArrayList<String> > mMapWordExplain = new HashMap<Character, ArrayList<String>>();
private int mCurReadExplainIndex = 0;
private int mCheckSum = 0; //bufferchecksum
private int mParagraphStartPos = 0;
private int mParagraphLength = 0;
private ReverseInfo mSelectInfo = new ReverseInfo();
private String mFilename = null;
private boolean mIsAuto = false;
public interface OnPageFlingListener
{
public void onLoadCompleted( int pageCount, int curPage );
public void onPageFlingToTop();
public void onPageFlingToBottom();
public void onPageFlingCompleted( int curPage );
}
public TextReaderView(Context context)
{
super(context);
initReaderView( context );
}
public TextReaderView(Context context, AttributeSet attrs)
{
super(context, attrs);
initReaderView( context );
}
public TextReaderView(Context context, AttributeSet attrs, int defStyle)
{
super(context, attrs, defStyle);
initReaderView( context );
}
private void initReaderView( Context context )
{
mContext = context;
mGestureDetector = new GestureDetector( context, this );
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaint.setTextAlign(Align.LEFT);
final float fontSize = new Tools(context).getFontSize();
mTextSize = fontSize-2*EbookConstants.LINE_SPACE;
final float scale = context.getResources().getDisplayMetrics().density/0.75f; //ldpi
mLineSpace *= scale;
mTextSize *= scale;
mWordExplainUtils.init(mContext);
TTSUtils.getInstance().OnTTSListener(this);
}
public void startSelect()
{
if( mReadMode != ReadMode.READ_MODE_CHARACTER )
{
return;
}
mSelectInfo.startPos = mReverseInfo.startPos;
}
public void endSelect()
{
if( mReadMode != ReadMode.READ_MODE_CHARACTER )
{
return;
}
mSelectInfo.len = mReverseInfo.startPos+mReverseInfo.len-mSelectInfo.startPos;
if( ( mSelectInfo.startPos >= mOffset ) && ( mSelectInfo.len > 0 ) )
{
mReverseInfo.startPos = mSelectInfo.startPos;
mReverseInfo.len = mSelectInfo.len;
mSelectInfo.startPos = -1;
mSelectInfo.len = -1;
this.invalidate();
}
}
public String getReverseText()
{
try
{
return new String(mMbBuf, mReverseInfo.startPos, mReverseInfo.len, CHARSET_NAME);
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
return "";
}
public void setOnPageFlingListener( OnPageFlingListener listener )
{
mOnPageFlingListener = listener;
}
public void setReadMode( ReadMode rm )
{
mReadMode = rm;
mCurReadExplainIndex = 0;
}
@Override
public void setBackgroundColor( int color )
{
mBkColor = color;
}
public void setTextColor( int color )
{
mTextColor = color;
}
public void setReverseColor( int color )
{
mReverseColor = color;
}
public void setTextSize( float size )
{
mTextSize = size;
}
public void setSpaceSize( int size )
{
mLineSpace = size;
}
public int getBackgroundColor()
{
return mBkColor;
}
public int getTextColor()
{
return mTextColor;
}
public int getReverseColor()
{
return mReverseColor;
}
public float getTextSize()
{
return mTextSize;
}
public float getSpaceSize()
{
return mLineSpace;
}
public int getLineCount()
{
return mLineCount;
}
public boolean isFirstPage()
{
return mIsFirstPage;
}
public boolean isLastPage()
{
return mIsLastPage;
}
public String getFirstLineText()
{
return getLineText(mLineNumber);
}
public ReverseInfo getReverseInfo()
{
return mReverseInfo;
}
public int getLineNumber()
{
return mLineNumber;
}
//bufferCheckSum
public int getCheckSum()
{
return mCheckSum;
}
private int calcCheckSum( byte[] buffer )
{
int checksum = 0;
int len = buffer.length;
int shang = len / 4;
int yu = len % 4;
for( int i = 0; i < shang; i++ )
{
checksum += PublicUtils.byte2int(buffer, i*4);
}
byte[] data = new byte[4];
for( int i = 0; i < yu; i++ )
{
data[i] = buffer[i];
}
checksum += PublicUtils.byte2int(data, 0);
return checksum;
}
private String getLineText( final int lineNumber )
{
int size = mSplitInfoList.size();
if( lineNumber >= 0 && lineNumber < size )
{
SplitInfo li = mSplitInfoList.get(lineNumber);
try
{
String str = new String(mMbBuf, li.startPos, li.len, CHARSET_NAME);
if( str != null )
{
str = str.replaceAll("\n", "");
str = str.replaceAll("\r", "");
return str;
}
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
return "";
}
public boolean openBook( String content )
{
byte[] buf = null;
try
{
buf = content.getBytes(CHARSET_NAME);
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
return openBook( buf, CHARSET_NAME, 0, 0, 0, 0, false, "" );
}
/**
*
* @param buffer
* buffer
* @param charsetName
*
* @param lineNumber
* ()
* @param startPos
*
* @param len
*
* @param checksum
*
*/
public boolean openBook(byte[] buffer, String charsetName, int lineNumber, int startPos, int len, int checksum, boolean isAuto, String filename)
{
mFilename = filename;
mIsAuto = isAuto;
mOffset = 0;
mReverseInfo.startPos = startPos;
if( CHARSET_NAME.equalsIgnoreCase(charsetName) )
{
mMbBuf = buffer;
}
else
{
try
{
mMbBuf = new String(buffer, charsetName).getBytes(CHARSET_NAME);
//gb18030BOMgb18030BOM0x84 0x31 0x95 0x33BOM
if( ( mMbBuf.length >= 4 ) && ( -124 == mMbBuf[0] ) && ( 49 == mMbBuf[1] ) && ( -107 == mMbBuf[2] ) && ( 51 == mMbBuf[3] ) )
{
mOffset = 4;
if( mReverseInfo.startPos < mOffset )
{
mReverseInfo.startPos = mOffset;
}
}
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
mMbBufLen = (int)mMbBuf.length;
mLineNumber = lineNumber;
mCheckSum = 0;//calcCheckSum( mMbBuf ); //CheckSum
if( ( checksum != 0 ) && ( mCheckSum != checksum ) )
{
//return false;
}
mReverseInfo.len = len;
mSelectInfo.startPos = -1;
mSelectInfo.len = -1;
mSplitInfoList.clear();
this.invalidate();
return true;
}
/**
*
* @param endPos
* @return len
*/
private int getPreParagraphLength( final int endPos )
{
int nEnd = endPos;
int i;
int count = 0;
byte b0, b1;
if( CHARSET_NAME.equals("utf-16le") )
{
i = nEnd - 2;
while (i > 0)
{
b0 = mMbBuf[i];
b1 = mMbBuf[i + 1];
//if( b0 == 0x0a && b1 == 0x00 && i != nEnd - 2 )
if( b0 == 0x0a && b1 == 0x00 )
{
count++;
if( count >= 2 )
{
i += 2;
break;
}
}
i
}
}
else if( CHARSET_NAME.equals("utf-16be") )
{
i = nEnd - 2;
while( i > 0 )
{
b0 = mMbBuf[i];
b1 = mMbBuf[i + 1];
//if( b0 == 0x00 && b1 == 0x0a && i != nEnd - 2 )
if( b0 == 0x00 && b1 == 0x0a )
{
count++;
if( count >= 2 )
{
i += 2;
break;
}
}
i
}
}
else
{
i = nEnd - 1;
while( i > mOffset )
{
b0 = mMbBuf[i];
//if( b0 == 0x0a && i != nEnd - 1 )
if( b0 == 0x0a )
{ // 0x0a
count++;
if( count >= 2 && mMbBuf[i+1] != 0x0d && mMbBuf[i+1] != 0x0a )
{
i++;
break;
}
}
i
}
}
if( i < 0 )
i = 0;
int nParaSize = nEnd - i;
return nParaSize;
}
/**
*
*
* @param startPos
*
* @return int
*/
private int getNextParagraphLength( final int startPos )
{
int i = startPos;
byte b0, b1;
if( CHARSET_NAME.equals("utf-16le") )
{
while( i < mMbBufLen - 1 )
{
b0 = mMbBuf[i++];
b1 = mMbBuf[i++];
if( b0 == 0x0a && b1 == 0x00 )
{
break;
}
}
}
else if( CHARSET_NAME.equals("utf-16be") )
{
while( i < mMbBufLen - 1 )
{
b0 = mMbBuf[i++];
b1 = mMbBuf[i++];
if( b0 == 0x00 && b1 == 0x0a )
{
break;
}
}
}
else
{
while( i < mMbBufLen )
{
b0 = mMbBuf[i++];
if( b0 == 0x0a )
{
break;
}
}
}
int len = i - startPos;
return len;
}
private void divideLines()
{
mPaint.setTextSize(mTextSize);
mPaint.setTypeface(Typeface.MONOSPACE);
float asciiWidth = mPaint.measureText(" "); //ascii
int startPos = mOffset;
while( startPos < mMbBufLen )
{
int len = getNextParagraphLength(startPos);
if( len <= 0 )
{
break;
}
else if( 1 == len )
{
if( 0x0a == mMbBuf[startPos+len-1] )
{
SplitInfo li = new SplitInfo(startPos, len);
mSplitInfoList.add(li);
startPos += len;
continue;
}
}
else if( 2 == len )
{
if( 0x0d == mMbBuf[startPos+len-2] && 0x0a == mMbBuf[startPos+len-1] )
{
SplitInfo li = new SplitInfo(startPos, len);
mSplitInfoList.add(li);
startPos += len;
continue;
}
}
byte[] buffer = new byte[len];
for( int i = 0; i < len; i++ )
{
buffer[i] = mMbBuf[startPos+i];
}
int textWidth = 0;
int start = startPos;
int home = 0;
int i = 0;
for( i = 0; i < buffer.length; i++ )
{
if( 0x0d == buffer[i] || 0x0a == buffer[i] )
{
continue;
}
if( buffer[i] < 0x80 && buffer[i] >= 0x0 ) //ascii
{
textWidth += ((int)asciiWidth);
if( textWidth > mVisibleWidth )
{
int length = i-home;
SplitInfo li = new SplitInfo(start, length);
mSplitInfoList.add(li);
start += length;
home = i;
i
textWidth = 0;
continue;
}
}
else
{
textWidth += (int)mTextSize;
if( textWidth > mVisibleWidth )
{
int length = i-home;
SplitInfo li = new SplitInfo(start, length);
mSplitInfoList.add(li);
start += length;
home = i;
i
textWidth = 0;
continue;
}
i++;
}
}
if( textWidth > 0 )
{
int length = i-home;
SplitInfo li = new SplitInfo(start, length);
mSplitInfoList.add(li);
start += length;
textWidth = 0;
}
startPos += len;
}
calcCurPage();
}
private void calcCurPage()
{
//mCurPage = mLineNumber / mLineCount + 1; //
class PageInfo
{
int page;
int count;
public PageInfo( int p, int c )
{
page = p;
count = c;
}
}
int size = mSplitInfoList.size();
int maxLine = Math.min( size, mLineNumber+mLineCount );
HashMap<Integer, PageInfo> pageMap = new HashMap<Integer, PageInfo>();
for( int i = mLineNumber; i < maxLine; i++ )
{
int curPage = i / mLineCount + 1;
PageInfo pi = pageMap.get(curPage);
if( null == pi )
{
pi = new PageInfo( curPage, 1 );
pageMap.put(curPage, pi);
}
else
{
pi.count++;
pageMap.remove(curPage);
pageMap.put(curPage, pi);
}
}
ArrayList<PageInfo> list = new ArrayList<PageInfo>();
Iterator<Integer> iterator = pageMap.keySet().iterator();
while(iterator.hasNext())
{
list.add(pageMap.get(iterator.next()));
}
size = list.size();
PageInfo pi = null;
for( int i = 0; i < size; i++ )
{
if( null == pi )
{
pi = list.get(i);
}
else
{
if( pi.count < list.get(i).count )
{
pi = list.get(i);
}
}
}
mCurPage = pi.page;
}
public int getCurPage()
{
return mCurPage;
}
public int getPageCount()
{
return ( mSplitInfoList.size() + mLineCount - 1 ) / mLineCount;
}
public boolean setCurPage( int page )
{
if( ( page < 1 ) || ( page > getPageCount() ) )
{
return false;
}
TTSUtils.getInstance().stop();
mCurPage = page;
mLineNumber = (mCurPage-1)*mLineCount;
mReverseInfo.startPos = mOffset;
mReverseInfo.len = 0;
this.invalidate();
initReverseInfo();
if( mOnPageFlingListener != null )
{
mOnPageFlingListener.onLoadCompleted(getPageCount(), mCurPage);
}
return true;
}
private boolean nextLine()
{
if( mLineNumber+mLineCount >= mSplitInfoList.size() )
{
mIsLastPage = true;
return false;
}
else
{
mIsLastPage = false;
}
mLineNumber++;
calcCurPage();
return true;
}
private boolean preLine()
{
if( mLineNumber <= 0 )
{
mLineNumber = 0;
mIsFirstPage = true;
return false;
}
else
{
mIsFirstPage = false;
}
mLineNumber
calcCurPage();
return true;
}
private boolean nextPage()
{
if( mLineNumber+mLineCount >= mSplitInfoList.size() )
{
mIsLastPage = true;
return false;
}
else
{
mIsLastPage = false;
}
mLineNumber += mLineCount;
calcCurPage();
return true;
}
private boolean prePage()
{
if( mLineNumber <= 0 )
{
mLineNumber = 0;
mIsFirstPage = true;
return false;
}
else
{
mIsFirstPage = false;
}
mLineNumber -= mLineCount;
if( mLineNumber < 0 )
{
mLineNumber = 0;
}
calcCurPage();
return true;
}
private void init(Context context)
{
mWidth = getWidth();
mHeight = getHeight();
mVisibleWidth = mWidth - MARGIN_WIDTH * 2;
mVisibleHeight = mHeight - MARGIN_HEIGHT * 2;
mLineCount = (int)( mVisibleHeight / (mTextSize+mLineSpace ) );
if( null == mCurPageBitmap )
{
mCurPageBitmap = Bitmap.createBitmap(mWidth, mHeight, Bitmap.Config.ARGB_8888);
}
if( null == mCurPageCanvas )
{
mCurPageCanvas = new Canvas(mCurPageBitmap);
}
if( 0 == mSplitInfoList.size() )
{
divideLines();
initReverseInfo();
if( mOnPageFlingListener != null )
{
mOnPageFlingListener.onLoadCompleted(getPageCount(), mCurPage);
}
}
}
private void initReverseInfo()
{
switch( mReadMode )
{
case READ_MODE_ALL:
case READ_MODE_PARAGRAPH:
nextSentence(true);
break;
case READ_MODE_WORD:
nextWord(true);
break;
case READ_MODE_CHARACTER:
nextCharacter(true);
break;
default:
break;
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
int width;
int height ;
Drawable bgDrawable = this.getBackground();
if (widthMode == MeasureSpec.EXACTLY) //MATCH_PARENT
{
width = widthSize;
}
else //WARP_CONTENT
{
float bgWidth = bgDrawable.getIntrinsicWidth();
int desired = (int) (getPaddingLeft() + bgWidth + getPaddingRight());
width = desired;
}
if (heightMode == MeasureSpec.EXACTLY) //MATCH_PARENT
{
height = heightSize;
}
else //WARP_CONTENT
{
float bgHeight = bgDrawable.getIntrinsicHeight();
int desired = (int) (getPaddingTop() + bgHeight + getPaddingBottom());
height = desired;
}
setMeasuredDimension(width, height);
}
@Override
protected void onDraw(Canvas canvas)
{
// TODO Auto-generated method stub
super.onDraw(canvas);
TTSUtils.getInstance().OnTTSListener(this);
init(mContext);
mCurPageCanvas.drawColor(mBkColor);
mPaint.setTextSize(mTextSize);
mPaint.setColor(mTextColor);
int size = mSplitInfoList.size();
if( size > 0 )
{
Paint paint = new Paint();
paint.setColor(mReverseColor);
//FontMetrics
FontMetrics fontMetrics = mPaint.getFontMetrics();
/*
//
float baseX = MARGIN_WIDTH;
float baseY = MARGIN_HEIGHT;
float topY = baseY + fontMetrics.top;
float ascentY = baseY + fontMetrics.ascent;
float descentY = baseY + fontMetrics.descent;
float bottomY = baseY + fontMetrics.bottom;
*/
float x = MARGIN_WIDTH;
float y = MARGIN_HEIGHT;
for( int i = mLineNumber, j = 0; i < size && j < mLineCount; i++, j++ )
{
if( mReverseInfo.len > 0 )
{
SplitInfo si = mSplitInfoList.get(i);
if( ( mReverseInfo.startPos >= si.startPos ) && ( mReverseInfo.startPos < si.startPos+si.len ) )
{
float xx = x;
String str = null;
try
{
str = new String(mMbBuf, si.startPos, mReverseInfo.startPos-si.startPos, CHARSET_NAME);
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
if( !TextUtils.isEmpty(str) )
{
xx += mPaint.measureText(str);
}
int len = Math.min(mReverseInfo.len, si.startPos+si.len-mReverseInfo.startPos);
try
{
str = new String(mMbBuf, mReverseInfo.startPos, len, CHARSET_NAME);
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
if( "\r\n".equals(str) || "\n".equals(str) )
{
RectF rect = new RectF(xx, y+(fontMetrics.ascent-fontMetrics.top)-1, getWidth()-MARGIN_WIDTH, y+(fontMetrics.descent-fontMetrics.top)+1 );
mCurPageCanvas.drawRect(rect, paint);
}
else
{
RectF rect = new RectF(xx, y+(fontMetrics.ascent-fontMetrics.top)-1, (xx+mPaint.measureText(str)), y+(fontMetrics.descent-fontMetrics.top)+1 );
mCurPageCanvas.drawRect(rect, paint);
}
}
else if( ( mReverseInfo.startPos < si.startPos ) && ( mReverseInfo.startPos+mReverseInfo.len-1 >= si.startPos ) )
{
float xx = x;
String str = null;
int len = Math.min( si.len, mReverseInfo.startPos + mReverseInfo.len - si.startPos );
try
{
str = new String(mMbBuf, si.startPos, len, CHARSET_NAME);
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
if( "\r\n".equals(str) || "\n".equals(str) )
{
RectF rect = new RectF(xx, y+(fontMetrics.ascent-fontMetrics.top)-1, getWidth()-MARGIN_WIDTH, y+(fontMetrics.descent-fontMetrics.top)+1 );
mCurPageCanvas.drawRect(rect, paint);
}
else
{
RectF rect = new RectF(xx, y+(fontMetrics.ascent-fontMetrics.top)-1, (xx+mPaint.measureText(str)), y+(fontMetrics.descent-fontMetrics.top)+1 );
mCurPageCanvas.drawRect(rect, paint);
}
}
}
float baseY = y - fontMetrics.top;
mCurPageCanvas.drawText(getLineText(i), x, baseY, mPaint); //drawTextbaseXbaseY
y += mTextSize;
y += mLineSpace;
}
}
canvas.drawBitmap(mCurPageBitmap, 0, 0, null);
}
@Override
public boolean onTouchEvent(MotionEvent event)
{
return mGestureDetector.onTouchEvent(event);
}
@Override
public boolean onDown(MotionEvent e)
{
// TODO Auto-generated method stub
return true;
}
@Override
public void onShowPress(MotionEvent e)
{
// TODO Auto-generated method stub
}
@Override
public boolean onSingleTapUp(MotionEvent e)
{
//TODO Auto-generated method stub
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY)
{
// TODO Auto-generated method stub
return false;
}
@Override
public void onLongPress(MotionEvent e)
{
// TODO Auto-generated method stub
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY)
{
// TODO Auto-generated method stub
final int FLING_MIN_DISTANCE_X = getWidth()/3;
final int FLING_MIN_DISTANCE_Y = getHeight()/3;
if( e1.getX() - e2.getX() > FLING_MIN_DISTANCE_X )
{
right();
}
else if( e2.getX() - e1.getX() > FLING_MIN_DISTANCE_X )
{
left();
}
else if( e1.getY() - e2.getY() > FLING_MIN_DISTANCE_Y )
{
down();
}
else if( e2.getY() - e1.getY() > FLING_MIN_DISTANCE_Y )
{
up();
}
return false;
}
@Override
public boolean onSingleTapConfirmed(MotionEvent e)
{
// TODO Auto-generated method stub
return false;
}
@Override
public boolean onDoubleTap(MotionEvent e)
{
// TODO Auto-generated method stub
enter();
return false;
}
@Override
public boolean onDoubleTapEvent(MotionEvent e)
{
// TODO Auto-generated method stub
return false;
}
public void up()
{
SpeakStatus status = TTSUtils.getInstance().getSpeakStatus();
TTSUtils.getInstance().stop();
setReadMode(ReadMode.READ_MODE_ALL);
mReverseInfo.startPos = mOffset;
mReverseInfo.len = 0;
if( preLine() )
{
mCurReadExplainIndex = 0;
this.invalidate();
if( mOnPageFlingListener != null )
{
mOnPageFlingListener.onPageFlingCompleted(mCurPage);
}
}
else
{
if( mOnPageFlingListener != null )
{
mOnPageFlingListener.onPageFlingToTop();
}
}
if( SpeakStatus.SPEAK == status )
{
nextSentence(false);
}
else
{
ReverseInfo ri = getNextReverseCharacterInfo( mSplitInfoList.get(mLineNumber).startPos );
if( null == ri )
{
if( mOnPageFlingListener != null )
{
mOnPageFlingListener.onPageFlingToBottom();
}
}
else
{
mReverseInfo.startPos = ri.startPos;
mReverseInfo.len = ri.len;
}
String tips = String.format(mContext.getResources().getString(R.string.page_read_tips2), mCurPage );
TTSUtils.getInstance().speakTips(tips);
}
}
public void down()
{
SpeakStatus status = TTSUtils.getInstance().getSpeakStatus();
TTSUtils.getInstance().stop();
setReadMode(ReadMode.READ_MODE_ALL);
mReverseInfo.startPos = mOffset;
mReverseInfo.len = 0;
if( nextLine() )
{
mCurReadExplainIndex = 0;
this.invalidate();
if( mOnPageFlingListener != null )
{
mOnPageFlingListener.onPageFlingCompleted(mCurPage);
}
if( SpeakStatus.SPEAK == status )
{
nextSentence(false);
}
else
{
ReverseInfo ri = getNextReverseCharacterInfo( mSplitInfoList.get(mLineNumber).startPos );
if( null == ri )
{
if( mOnPageFlingListener != null )
{
mOnPageFlingListener.onPageFlingToBottom();
}
}
else
{
mReverseInfo.startPos = ri.startPos;
mReverseInfo.len = ri.len;
}
String tips = String.format(mContext.getResources().getString(R.string.page_read_tips2), mCurPage );
TTSUtils.getInstance().speakTips(tips);
}
}
else
{
if( mOnPageFlingListener != null )
{
mOnPageFlingListener.onPageFlingToBottom();
}
}
}
public void left()
{
SpeakStatus status = TTSUtils.getInstance().getSpeakStatus();
TTSUtils.getInstance().stop();
setReadMode(ReadMode.READ_MODE_ALL);
mReverseInfo.startPos = mOffset;
mReverseInfo.len = 0;
if( prePage() )
{
mCurReadExplainIndex = 0;
this.invalidate();
if( mOnPageFlingListener != null )
{
mOnPageFlingListener.onPageFlingCompleted(mCurPage);
}
}
else
{
if( mOnPageFlingListener != null )
{
mOnPageFlingListener.onPageFlingToTop();
}
}
if( SpeakStatus.SPEAK == status )
{
nextSentence(false);
}
else
{
ReverseInfo ri = getNextReverseCharacterInfo( mSplitInfoList.get(mLineNumber).startPos );
if( null == ri )
{
if( mOnPageFlingListener != null )
{
mOnPageFlingListener.onPageFlingToBottom();
}
}
else
{
mReverseInfo.startPos = ri.startPos;
mReverseInfo.len = ri.len;
}
String tips = String.format(mContext.getResources().getString(R.string.page_read_tips2), mCurPage );
TTSUtils.getInstance().speakTips(tips);
}
}
public void right()
{
SpeakStatus status = TTSUtils.getInstance().getSpeakStatus();
TTSUtils.getInstance().stop();
setReadMode(ReadMode.READ_MODE_ALL);
mReverseInfo.startPos = mOffset;
mReverseInfo.len = 0;
if( nextPage() )
{
mCurReadExplainIndex = 0;
this.invalidate();
if( mOnPageFlingListener != null )
{
mOnPageFlingListener.onPageFlingCompleted(mCurPage);
}
if( SpeakStatus.SPEAK == status )
{
nextSentence(false);
}
else
{
ReverseInfo ri = getNextReverseCharacterInfo( mSplitInfoList.get(mLineNumber).startPos );
if( null == ri )
{
if( mOnPageFlingListener != null )
{
mOnPageFlingListener.onPageFlingToBottom();
}
}
else
{
mReverseInfo.startPos = ri.startPos;
mReverseInfo.len = ri.len;
}
String tips = String.format(mContext.getResources().getString(R.string.page_read_tips2), mCurPage );
TTSUtils.getInstance().speakTips(tips);
}
}
else
{
if( mOnPageFlingListener != null )
{
mOnPageFlingListener.onPageFlingToBottom();
}
}
}
public void enter()
{
SpeakStatus status = TTSUtils.getInstance().getSpeakStatus();
if( ReadMode.READ_MODE_ALL == mReadMode )
{
if( status == SpeakStatus.SPEAK )
{
TTSUtils.getInstance().pause();
}
else if( status == SpeakStatus.PAUSE )
{
TTSUtils.getInstance().resume();
}
else if( status == SpeakStatus.STOP )
{
nextSentence(false);
}
}
else
{
setReadMode(ReadMode.READ_MODE_ALL);
if( status == SpeakStatus.STOP )
{
nextSentence(false);
}
else
{
TTSUtils.getInstance().stop();
}
}
}
public void intensiveReading()
{
SpeakStatus status = TTSUtils.getInstance().getSpeakStatus();
if( SpeakStatus.SPEAK == status )
{
TTSUtils.getInstance().pause();
}
else if( status == SpeakStatus.PAUSE )
{
TTSUtils.getInstance().resume();
}
else if( status == SpeakStatus.STOP )
{
switch( mReadMode )
{
case READ_MODE_ALL:
case READ_MODE_PARAGRAPH:
nextSentence(false);
break;
case READ_MODE_WORD:
nextWord(false);
break;
case READ_MODE_CHARACTER:
readExplain();
break;
default:
break;
}
}
}
private void readExplain()
{
if( mReverseInfo.len > 0 )
{
char ch = PublicUtils.byte2char(mMbBuf, mReverseInfo.startPos);
if( ( ch >= 'A' ) && ( ch <= 'Z') )
{
ch += 0x20;
}
ArrayList<String> list = mMapWordExplain.get(ch);
if( ( null == list ) || ( 0 == list.size() ) )
{
byte[] explain = null;
if( mMbBuf[mReverseInfo.startPos] < 0 )
{
explain = mWordExplainUtils.getWordExplain(0, ch);
}
else
{
explain = mWordExplainUtils.getWordExplain(1, ch);
}
if( null == explain )
{
TTSUtils.getInstance().speakTips(mContext.getString(R.string.no_explain));
return;
}
else
{
String txt = null;
try
{
txt = new String(explain, CHARSET_NAME);
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
if( TextUtils.isEmpty(txt) )
{
TTSUtils.getInstance().speakTips(mContext.getString(R.string.no_explain));
return;
}
else
{
String[] str = txt.split("=");
if( ( null == str ) || ( str.length < 2 ) )
{
TTSUtils.getInstance().speakTips(mContext.getString(R.string.no_explain));
return;
}
String[] strExplain = str[1].split(" ");
if( ( null == strExplain ) || ( 0 == strExplain.length ) )
{
TTSUtils.getInstance().speakTips(mContext.getString(R.string.no_explain));
return;
}
ArrayList<String> list2 = new ArrayList<String>();
if( ( ch >= 'a' ) && ( ch <= 'z') )
{
for( int i = 0; i < strExplain.length; i++ )
{
list2.add(strExplain[i]);
}
list2.add(String.format(mContext.getResources().getString(R.string.en_explain_tips), ch-'a'+1));
}
else
{
for( int i = 0; i < strExplain.length; i++ )
{
list2.add(strExplain[i]+mContext.getResources().getString(R.string.cn_explain_tips)+str[0]);
}
}
mMapWordExplain.put(ch, list2);
}
}
}
list = mMapWordExplain.get(ch);
if( ( list != null ) && ( list.size() > 0 ) )
{
TTSUtils.getInstance().speakTips(list.get(mCurReadExplainIndex));
if( mCurReadExplainIndex == list.size()-1 )
{
mCurReadExplainIndex = 0;
}
else
{
mCurReadExplainIndex++;
}
}
}
}
public void preCharacter()
{
TTSUtils.getInstance().stop();
setReadMode(ReadMode.READ_MODE_CHARACTER);
int start = mReverseInfo.startPos;
if( start == mOffset )
{
if( mOnPageFlingListener != null )
{
mOnPageFlingListener.onPageFlingToTop();
}
return;
}
ReverseInfo oldReverseInfo = null;
for( int i = mOffset; i < mMbBufLen; )
{
ReverseInfo ri = getNextReverseCharacterInfo( i );
if( null == ri )
{
if( mOnPageFlingListener != null )
{
mOnPageFlingListener.onPageFlingToTop();
}
break;
}
else if( ri.startPos + ri.len == mReverseInfo.startPos )
{
mReverseInfo.startPos = ri.startPos;
mReverseInfo.len = ri.len;
readReverseText(false);
recalcLineNumber(Action.PRE_LINE);
this.invalidate();
break;
}
else if( ri.startPos >= mReverseInfo.startPos )
{
mReverseInfo.startPos = oldReverseInfo.startPos;
mReverseInfo.len = oldReverseInfo.len;
readReverseText(false);
recalcLineNumber(Action.PRE_LINE);
this.invalidate();
break;
}
i = ri.startPos+ri.len;
oldReverseInfo = ri;
}
}
public void nextCharacter( boolean isSpeakPage )
{
TTSUtils.getInstance().stop();
setReadMode(ReadMode.READ_MODE_CHARACTER);
ReverseInfo ri = getNextReverseCharacterInfo( mReverseInfo.startPos+mReverseInfo.len );
if( null == ri )
{
if( mOnPageFlingListener != null )
{
mOnPageFlingListener.onPageFlingToBottom();
}
}
else
{
mReverseInfo.startPos = ri.startPos;
mReverseInfo.len = ri.len;
readReverseText(isSpeakPage);
recalcLineNumber(Action.NEXT_LINE);
this.invalidate();
}
}
public void preWord()
{
TTSUtils.getInstance().stop();
setReadMode(ReadMode.READ_MODE_WORD);
int start = mReverseInfo.startPos;
if( start == mOffset )
{
if( mOnPageFlingListener != null )
{
mOnPageFlingListener.onPageFlingToTop();
}
return;
}
ReverseInfo oldReverseInfo = null;
for( int i = mOffset; i < mMbBufLen; )
{
ReverseInfo ri = getNextReverseWordInfo( i );
if( null == ri )
{
if( mOnPageFlingListener != null )
{
mOnPageFlingListener.onPageFlingToTop();
}
break;
}
else if( ri.startPos + ri.len == mReverseInfo.startPos )
{
mReverseInfo.startPos = ri.startPos;
mReverseInfo.len = ri.len;
readReverseText(false);
recalcLineNumber(Action.PRE_LINE);
this.invalidate();
break;
}
else if( ri.startPos >= mReverseInfo.startPos )
{
if( null == oldReverseInfo )
{
mReverseInfo.startPos = mOffset;
mReverseInfo.len = 0;
}
else
{
mReverseInfo.startPos = oldReverseInfo.startPos;
mReverseInfo.len = oldReverseInfo.len;
}
readReverseText(false);
recalcLineNumber(Action.PRE_LINE);
this.invalidate();
break;
}
i = ri.startPos+ri.len;
oldReverseInfo = ri;
}
}
public void nextWord( boolean isSpeakPage )
{
TTSUtils.getInstance().stop();
setReadMode(ReadMode.READ_MODE_WORD);
ReverseInfo ri = getNextReverseWordInfo( mReverseInfo.startPos+mReverseInfo.len );
if( null == ri )
{
if( mOnPageFlingListener != null )
{
mOnPageFlingListener.onPageFlingToBottom();
}
}
else
{
mReverseInfo.startPos = ri.startPos;
mReverseInfo.len = ri.len;
readReverseText(isSpeakPage);
recalcLineNumber(Action.NEXT_LINE);
this.invalidate();
}
}
public void preParagraph()
{
TTSUtils.getInstance().stop();
setReadMode(ReadMode.READ_MODE_PARAGRAPH);
int end = mReverseInfo.startPos;
if( ( mOffset == mReverseInfo.startPos ) && ( 0 == mReverseInfo.len ) )
{
end = mSplitInfoList.get(mLineNumber).startPos;
}
int len = getPreParagraphLength( end );
if( 0 == len )
{
if( mOnPageFlingListener != null )
{
mOnPageFlingListener.onPageFlingToTop();
}
}
else
{
end -= len;
for( int i = 0; i < mSplitInfoList.size(); i++ )
{
if( mSplitInfoList.get(i).startPos == end )
{
mReverseInfo.startPos = mOffset;
mReverseInfo.len = 0;
mLineNumber = i;
mParagraphStartPos = end;
mParagraphLength = getNextParagraphLength(mParagraphStartPos);
nextSentence( false );
return;
}
}
if( mOnPageFlingListener != null )
{
mOnPageFlingListener.onPageFlingToTop();
}
}
}
public void nextParagraph( boolean isSpeakPage )
{
TTSUtils.getInstance().stop();
setReadMode(ReadMode.READ_MODE_PARAGRAPH);
int start = mReverseInfo.startPos;
if( ( mOffset == mReverseInfo.startPos ) && ( 0 == mReverseInfo.len ) )
{
start = mSplitInfoList.get(mLineNumber).startPos;
}
int len = getNextParagraphLength( start );
if( 0 == len )
{
if( mOnPageFlingListener != null )
{
mOnPageFlingListener.onPageFlingToBottom();
}
}
else
{
start += len;
for( int i = mLineNumber; i < mSplitInfoList.size(); i++ )
{
if( mSplitInfoList.get(i).startPos == start )
{
mReverseInfo.startPos = mOffset;
mReverseInfo.len = 0;
mLineNumber = i;
mParagraphStartPos = start;
mParagraphLength = getNextParagraphLength(mParagraphStartPos);
nextSentence( isSpeakPage );
return;
}
}
if( mOnPageFlingListener != null )
{
mOnPageFlingListener.onPageFlingToBottom();
}
}
}
private void preSentence()
{
int start = mReverseInfo.startPos;
if( start == mOffset )
{
if( mOnPageFlingListener != null )
{
mOnPageFlingListener.onPageFlingToTop();
}
return;
}
ReverseInfo oldReverseInfo = null;
for( int i = mOffset; i < mMbBufLen; )
{
ReverseInfo ri = getNextReverseSentenceInfo( i );
if( null == ri )
{
if( mOnPageFlingListener != null )
{
mOnPageFlingListener.onPageFlingToTop();
}
break;
}
else if( ri.startPos + ri.len == mReverseInfo.startPos )
{
mReverseInfo.startPos = ri.startPos;
mReverseInfo.len = ri.len;
readReverseText(false);
recalcLineNumber(Action.PRE_LINE);
this.invalidate();
break;
}
else if( ri.startPos >= mReverseInfo.startPos )
{
mReverseInfo.startPos = oldReverseInfo.startPos;
mReverseInfo.len = oldReverseInfo.len;
readReverseText(false);
recalcLineNumber(Action.PRE_LINE);
this.invalidate();
break;
}
i = ri.startPos+ri.len;
oldReverseInfo = ri;
}
}
private void nextSentence( boolean isSpeakPage )
{
int start = mReverseInfo.startPos + mReverseInfo.len;
if( ( mOffset == mReverseInfo.startPos ) && ( 0 == mReverseInfo.len ) )
{
start = mSplitInfoList.get(mLineNumber).startPos;
}
if( ( ReadMode.READ_MODE_PARAGRAPH == mReadMode ) && ( start >= mParagraphStartPos + mParagraphLength ) )
{
return;
}
ReverseInfo ri = getNextReverseSentenceInfo( start );
if( null == ri )
{
if( mOnPageFlingListener != null )
{
mOnPageFlingListener.onPageFlingToBottom();
}
}
else
{
if( ( ReadMode.READ_MODE_PARAGRAPH == mReadMode ) && ( ri.startPos + ri.len >= mParagraphStartPos + mParagraphLength ) )
{
return;
}
mReverseInfo.startPos = ri.startPos;
mReverseInfo.len = ri.len;
readReverseText(isSpeakPage);
recalcLineNumber(Action.NEXT_LINE);
this.invalidate();
}
}
private ReverseInfo getNextReverseCharacterInfo( int start )
{
if( start == mMbBufLen-1 )
{
return null;
}
for( int i = start; i < mMbBufLen; i++ )
{
if( mMbBuf[i] < 0 )
{
ReverseInfo ri = new ReverseInfo(i, 2);
return ri;
}
else if( mMbBuf[i] >= 0x0 && mMbBuf[i] < 0x20 )
{
if( 0x0d == mMbBuf[i] )
{
if( ( i+1 < mMbBufLen ) && ( 0x0a == mMbBuf[i+1] ) )
{
ReverseInfo ri = new ReverseInfo(i, 2);
return ri;
}
else
{
ReverseInfo ri = new ReverseInfo(i, 1);
return ri;
}
}
else if( 0x0a == mMbBuf[i] )
{
ReverseInfo ri = new ReverseInfo(i, 1);
return ri;
}
else
{
continue;
}
}
else
{
ReverseInfo ri = new ReverseInfo(i, 1);
return ri;
}
}
return null;
}
private ReverseInfo getNextReverseWordInfo( int start )
{
if( start == mMbBufLen-1 )
{
return null;
}
for( int i = start; i < mMbBufLen; i++ )
{
if( mMbBuf[i] < 0 )
{
ReverseInfo ri = new ReverseInfo(i, 2);
char ch = PublicUtils.byte2char(mMbBuf, i);
for( int k = 0; k < CodeTableUtils.CODE.length; k++ )
{
if( ( CodeTableUtils.CODE[k] == ch ) && ( 0xA1A1 != ch ) )
{
return ri;
}
}
for( int j = i+2; j < mMbBufLen; j+=2 )
{
if( mMbBuf[j] < 0 )
{
ch = PublicUtils.byte2char(mMbBuf, j);
for( int k = 0; k < CodeTableUtils.CODE.length; k++ )
{
if( ( CodeTableUtils.CODE[k] == ch ) && ( 0xA1A1 != ch ) )
{
return ri;
}
}
ri.len += 2;
}
else
{
break;
}
}
return ri;
}
else if( isAlpha( mMbBuf[i] ) || isNumber( mMbBuf[i] ) )
{
ReverseInfo ri = new ReverseInfo(i, 1);
for( int j = i+1; j < mMbBufLen; j++ )
{
if( isEscape( mMbBuf[j] ) )
{
break;
}
else if( mMbBuf[j] < 0x0 )
{
break;
}
else if( 0x20 == mMbBuf[j] )
{
break;
}
else
{
ri.len++;
}
}
return ri;
}
else if( mMbBuf[i] >= 0x0 && mMbBuf[i] < 0x20 )
{
if( 0x0d == mMbBuf[i] )
{
if( ( i+1 < mMbBufLen ) && ( 0x0a == mMbBuf[i+1] ) )
{
ReverseInfo ri = new ReverseInfo(i, 2);
return ri;
}
else
{
ReverseInfo ri = new ReverseInfo(i, 1);
return ri;
}
}
else if( 0x0a == mMbBuf[i] )
{
ReverseInfo ri = new ReverseInfo(i, 1);
return ri;
}
else
{
continue;
}
}
else if( 0x20 == mMbBuf[i] )
{
continue;
}
else
{
ReverseInfo ri = new ReverseInfo(i, 1);
return ri;
}
}
return null;
}
private ReverseInfo getNextReverseSentenceInfo( int start )
{
if( start == mMbBufLen-1 )
{
return null;
}
for( int i = start; i < mMbBufLen; )
{
if( mMbBuf[i] < 0 )
{
ReverseInfo ri = new ReverseInfo(i, 2);
boolean isBreak = false;
char ch = PublicUtils.byte2char(mMbBuf, i);
for( int k = 0; k < CN_SEPARATOR.length; k++ )
{
if( CN_SEPARATOR[k] == ch )
{
isBreak = true;
break;
}
}
i += 2;
if( isBreak )
{
continue;
}
for( int j = i; j < mMbBufLen; )
{
if( mMbBuf[j] < 0 )
{
ri.len += 2;
ch = PublicUtils.byte2char(mMbBuf, j);
for( int k = 0; k < CN_SEPARATOR.length; k++ )
{
if( CN_SEPARATOR[k] == ch )
{
return ri;
}
}
j += 2;
}
else if( isEscape( mMbBuf[j] ) )
{
return ri;
}
else
{
ri.len++;
for( int k = 0; k < EN_SEPARATOR.length; k++ )
{
if( EN_SEPARATOR[k] == mMbBuf[j] )
{
return ri;
}
}
if( ( 0x2E == mMbBuf[j] ) && ( j+1 < mMbBufLen ) && ( 0x20 == mMbBuf[j+1] ) )
{
return ri;
}
j++;
}
}
return ri;
}
else if( isAlpha( mMbBuf[i] ) || isNumber( mMbBuf[i] ) )
{
ReverseInfo ri = new ReverseInfo(i, 1);
i++;
for( int j = i; j < mMbBufLen; )
{
if( mMbBuf[j] < 0 )
{
ri.len += 2;
char ch = PublicUtils.byte2char(mMbBuf, j);
for( int k = 0; k < CN_SEPARATOR.length; k++ )
{
if( CN_SEPARATOR[k] == ch )
{
return ri;
}
}
j += 2;
}
else if( isEscape( mMbBuf[j] ) )
{
return ri;
}
else
{
ri.len++;
for( int k = 0; k < EN_SEPARATOR.length; k++ )
{
if( EN_SEPARATOR[k] == mMbBuf[j] )
{
return ri;
}
}
if( ( 0x2E == mMbBuf[j] ) && ( j+1 < mMbBufLen ) && ( 0x20 == mMbBuf[j+1] ) )
{
return ri;
}
j++;
}
}
return ri;
}
else
{
i++;
}
}
return null;
}
private void readReverseText( boolean isSpeakPage )
{
if( mReverseInfo.len <= 0 )
{
if( isSpeakPage )
{
String tips = String.format(mContext.getResources().getString(R.string.page_read_tips), mCurPage, getPageCount() );
if( mIsAuto && !TextUtils.isEmpty(mFilename))
{
mIsAuto = false;
tips = mFilename+""+tips;
}
TTSUtils.getInstance().speakTips(tips);
}
return;
}
Locale locale = mContext.getResources().getConfiguration().locale;
String language = locale.getLanguage();
char code = PublicUtils.byte2char(mMbBuf, mReverseInfo.startPos);
String str = null;
if( "en".equalsIgnoreCase(language) )
{
str = CodeTableUtils.getEnString(code);
}
else
{
str = CodeTableUtils.getCnString(code);
}
if( null != str )
{
TTSUtils.getInstance().speakContent(str);
}
else
{
try
{
String text = new String(mMbBuf, mReverseInfo.startPos, mReverseInfo.len, CHARSET_NAME);
if( isSpeakPage )
{
String tips = String.format(mContext.getResources().getString(R.string.page_read_tips), mCurPage, getPageCount() );
if( mIsAuto && !TextUtils.isEmpty(mFilename))
{
mIsAuto = false;
tips = mFilename+""+tips;
}
TTSUtils.getInstance().speakTipsAndContent(tips, text);
}
else
{
TTSUtils.getInstance().speakContent(text);
}
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
}
private void recalcLineNumber( Action action )
{
if( mReverseInfo.len <= 0 )
{
return;
}
int size = mSplitInfoList.size();
SplitInfo si = null;
switch( action )
{
case NEXT_LINE:
case NEXT_PAGE:
while( true )
{
int curPageLine = Math.min( mLineCount, (size-mLineNumber) );
si = mSplitInfoList.get(mLineNumber+curPageLine-1);
if( ( mReverseInfo.startPos >= si.startPos+si.len ) || ( mReverseInfo.startPos + mReverseInfo.len > si.startPos + si.len ) )
{
if( Action.NEXT_LINE == action )
{
if( nextLine() )
{
if( mOnPageFlingListener != null )
{
mOnPageFlingListener.onPageFlingCompleted(mCurPage);
}
}
else
{
if( mOnPageFlingListener != null )
{
mOnPageFlingListener.onPageFlingToBottom();
}
break;
}
}
else
{
if( nextPage() )
{
if( mOnPageFlingListener != null )
{
mOnPageFlingListener.onPageFlingCompleted(mCurPage);
}
}
else
{
if( mOnPageFlingListener != null )
{
mOnPageFlingListener.onPageFlingToBottom();
}
break;
}
}
}
else
{
calcCurPage();
if( mOnPageFlingListener != null )
{
mOnPageFlingListener.onPageFlingCompleted(mCurPage);
}
break;
}
}
break;
case PRE_LINE:
case PRE_PAGE:
while( true )
{
si = mSplitInfoList.get(mLineNumber);
if( mReverseInfo.startPos < si.startPos )
{
if( Action.PRE_LINE == action )
{
if( preLine() )
{
if( mOnPageFlingListener != null )
{
mOnPageFlingListener.onPageFlingCompleted(mCurPage);
}
}
else
{
if( mOnPageFlingListener != null )
{
mOnPageFlingListener.onPageFlingToTop();
}
break;
}
}
else
{
if( prePage() )
{
if( mOnPageFlingListener != null )
{
mOnPageFlingListener.onPageFlingCompleted(mCurPage);
}
}
else
{
if( mOnPageFlingListener != null )
{
mOnPageFlingListener.onPageFlingToTop();
}
break;
}
}
}
else
{
calcCurPage();
if( mOnPageFlingListener != null )
{
mOnPageFlingListener.onPageFlingCompleted(mCurPage);
}
break;
}
}
break;
default:
break;
}
}
private boolean isAlpha( byte ch )
{
if( ( ch >= 'a' && ch <= 'z' ) || ( ch >= 'A' && ch <= 'Z' ) )
{
return true;
}
return false;
}
private boolean isNumber( byte ch )
{
if( ch >= '0' && ch <= '9' )
{
return true;
}
return false;
}
private boolean isEscape( byte ch )
{
if( 0x07 == ch || 0x08 == ch || 0x09 == ch || 0x0a == ch || 0x0b == ch || 0x0c == ch || 0x0d == ch )
{
return true;
}
return false;
}
private enum Action
{
NEXT_LINE,
NEXT_PAGE,
PRE_LINE,
PRE_PAGE,
}
@Override
public void onSpeakCompleted()
{
// TODO Auto-generated method stub
mHandler.sendEmptyMessage(MSG_SPEAK_COMPLETED);
}
@Override
public void onSpeakError()
{
// TODO Auto-generated method stub
mHandler.sendEmptyMessage(MSG_SPEAK_ERROR);
}
@Override
public void onSpeakCompleted(String content) {
// TODO Auto-generated method stub
Message msg = mHandler.obtainMessage();
msg.what = MSG_SPEAK_CONTINUE;
msg.obj = content;
mHandler.sendMessage(msg);
}
@Override
public void onSpeakError(String content) {
// TODO Auto-generated method stub
Message msg = mHandler.obtainMessage();
msg.what = MSG_SPEAK_CONTINUE;
msg.obj = content;
mHandler.sendMessage(msg);
}
private Handler mHandler = new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(Message msg)
{
switch (msg.what)
{
case MSG_SPEAK_COMPLETED:
switch( mReadMode )
{
case READ_MODE_ALL:
case READ_MODE_PARAGRAPH:
nextSentence(false);
break;
case READ_MODE_WORD:
break;
case READ_MODE_CHARACTER:
break;
default:
break;
}
break;
case MSG_SPEAK_ERROR:
break;
case MSG_SPEAK_CONTINUE:
TTSUtils.getInstance().speakContent(msg.obj.toString());
break;
default:
break;
}
return false;
}
});
} |
package music_thing;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
import org.controlsfx.control.Rating;
/**
* FXML Controller class
*
* @author joshuakaplan
*/
public class EditTrackController implements Initializable {
@FXML
private TextField editName;
@FXML
private TextField editArtist;
@FXML
private TextField editComposer;
@FXML
private TextField editGenre;
@FXML
private TextField editAlbum;
@FXML
private Rating editRating;
private Track track;
private Stage dialogStage;
private boolean okClicked = false;
/**
* Sets the stage of this dialog.
* @param dialogStage
*/
public void setDialogStage(Stage dialogStage) {
this.dialogStage = dialogStage;
}
/**
* Returns true if the user clicked OK, false otherwise.
* @return
*/
public boolean isOkClicked() {
return okClicked;
}
/**
* Called when the user clicks ok.
*/
@FXML
private void handleOk() {
track.setName(editName.getText());
track.setArtist(editArtist.getText());
track.setComposer(editComposer.getText());
track.setAlbum(editAlbum.getText());
track.setGenre(editGenre.getText());
track.setRating(editRating.getRating());
okClicked = true;
dialogStage.close();
}
/**
* Called when the user clicks cancel.
*/
@FXML
private void handleCancel() {
dialogStage.close();
}
public void setTrack(Track track){
this.track=track;
editName.setText(track.getName());
editArtist.setText(track.getArtist());
editComposer.setText(track.getComposer());
editGenre.setText(track.getGenre());
editAlbum.setText(track.getAlbum());
editRating.setRating(track.getRating());
}
/**
* Initializes the controller class.
* @param url
* @param rb
*/
@Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
}
} |
package org.siggd.actor;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import org.siggd.Convert;
import org.siggd.DebugOutput;
import org.siggd.Game;
import org.siggd.Level;
import org.siggd.Timer;
import org.siggd.actor.meta.Prop;
import org.siggd.actor.meta.PropScanner;
import org.siggd.view.CompositeDrawable;
import org.siggd.view.DebugActorLinkDrawable;
import org.siggd.view.Drawable;
import aurelienribon.bodyeditor.BodyEditorLoader;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.audio.Sound;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.BodyDef;
import com.badlogic.gdx.physics.box2d.BodyDef.BodyType;
import com.badlogic.gdx.physics.box2d.Filter;
import com.badlogic.gdx.physics.box2d.Fixture;
import com.badlogic.gdx.physics.box2d.FixtureDef;
/**
* This class represents an object in the world.
*
* @author mysterymath
*
*/
public abstract class Actor {
// The world that contains this actor
protected final Level mLevel;
// The actor's id in the world
private final long mId;
// The way to draw this actor
final protected CompositeDrawable mDrawable;
protected Body mBody;
protected String mName;
protected ArrayList<Body> mSubBodies;
protected boolean mActive;
protected Vector2 mOldVCenter = Vector2.Zero;
protected Timer mSoundTimer;
// members pulled out of property map
private int mLayer;
private int mCollisionGroup;
private int mGrabbableInd;
private int mVisibleInd;
private int mSpawner;
private String mCollisionSound;
private float mCollisionPitch;
public boolean isActive() {
return mActive;
}
public void setActive(boolean active) {
this.mActive = active;
mBody.setActive(active);
}
/**
* The actor's properties These are editable with the editor, and convenient
* for communicating with other actors.
*/
protected HashMap<String, Object> mProps;
/**
* Getter and setter methods for properties.
*/
private PropScanner.Props mPropMethods;
/**
* Constructor. No non-optional parameters may be added to this constructor
* in subclasses. This should contain only properties, and code that MUST
* run before later init,
*
* @param level
* The world that contains this actor
* @param id
* The id
*/
public Actor(Level level, long id) {
mLevel = level;
mId = id;
mActive = true;
mSubBodies = new ArrayList<Body>();
mDrawable = new CompositeDrawable();
// Setup default actor properties
mProps = new HashMap<String, Object>();
// Actor properties:
mLayer = 1;
mCollisionGroup = 0;
mGrabbableInd = 0;
mVisibleInd = 1;
mSpawner = -1;
mCollisionSound = "";
mCollisionPitch = 1.0f;
mSoundTimer = new Timer();
mSoundTimer.setTimer(12);
mSoundTimer.unpause();
if (Game.get().getPropScanner() != null) {
mPropMethods = Game.get().getPropScanner().getProps(getClass());
}
}
/**
* Called to perform actor logic
*/
public void update() {
Vector2 vel;
float threshold = 1f;
vel = new Vector2(mBody.getLinearVelocity());
threshold = 2f;
vel.sub(mOldVCenter);
float velLength = vel.len();
// if(velLength > threshold && mSoundTimer.isTriggered())
// DebugOutput.fine(this, velLength + "");
// else { DebugOutput.fine(this, "Timer at " + mSoundTimer.mCurTime);}
if (velLength > threshold && mSoundTimer.isTriggered()) {
AssetManager man = Game.get().getAssetManager();
Sound sound;
long soundID;
String CollisionSound = "data/sfx/" + mCollisionSound;
if (!man.isLoaded(CollisionSound)) {
if (!CollisionSound.equals("data/sfx/")) {
try {
man.load(CollisionSound, Sound.class);
} catch (Exception e) {
DebugOutput.severe(this, "SOUND FILE NOT FOUND: " + CollisionSound);
}
}
}
else {
sound = man.get(CollisionSound, Sound.class);
soundID = sound.play();
sound.setPitch(soundID, mCollisionPitch + 0.4f);
sound.setVolume(soundID, Math.min(.7f, .4f + velLength * .002f));
mSoundTimer.reset();
}
}
mSoundTimer.update();
mOldVCenter = new Vector2(mBody.getLinearVelocity());
}
/**
* Called to draw the actor. Most actor's won't need this, as LevelView can
* draw simple textures. Use this if you need more complicated drawing (and
* make sure your texture is null)
*/
public void draw() {
}
/**
* Make the Box2d body
*
* @param name
* The name of the body in the JSON body definition file
* @param scale
* The width of the image
* @param Vector2
* origin [out] Object that will receive the image origin
*/
public Body makeBody(String name, float scale, BodyType bdtype, Vector2 origin) {
return makeBody(name, scale, bdtype, origin, false);
}
/**
* Make the Box2d body
*
* @param name
* The name of the body in the JSON body definition file
* @param scale
* The width of the image
* @param Vector2
* origin [out] Object that will receive the image origin
* @param isSensor
* True if should be a sensor
*/
public Body makeBody(String name, float scale, BodyType bdtype, Vector2 origin, boolean isSensor) {
// Correct scale by camera scale factor
float correct = Game.get().getLevelView().getVScale();
scale /= correct;
// Create a BodyDef
BodyDef bd = new BodyDef();
bd.position.set(0, 0);
bd.type = bdtype;
// Create a FixtureDef
FixtureDef fd = new FixtureDef();
fd.density = .1f;
fd.friction = 1f;
fd.restitution = 0.3f;
fd.isSensor = isSensor;
// Create a Body
Body body = mLevel.getWorld().createBody(bd);
// Create the body fixture automatically by using the loader.
BodyEditorLoader loader = Game.get().getBodyEditorLoader();
loader.attachFixture(body, name, fd, scale);
// Give Body a reference to its Actor
body.setUserData(this);
Vector2 tmpOrigin = loader.getOrigin(name, scale);
origin.x = tmpOrigin.x;
origin.y = tmpOrigin.y;
return body;
}
/**
* Load resources needed by the actor
*/
public abstract void loadResources();
/**
* Load body used by the actor
*/
public abstract void loadBodies();
/**
* Called after all actors have been loaded
*/
public abstract void postLoad();
/**
* Dispose of the actor's resources
*/
public void dispose() {
}
/**
* Destroy Actor Body(s)
*/
public void destroy() {
Game.get().getLevel().getWorld().destroyBody(mBody);
}
/**
* Determines if the actor contains a particular property
*
* @param name
* The name of the property
* @return True if the property exists
*/
public boolean hasProp(String name) {
return mProps.containsKey(name);
}
// ACCESSORS & MUTATORS:
/**
* Accessor for the Actor's level (as in stage).
*
* @return Level the Actor is currently in.
*/
public Level getLevel() {
return mLevel;
}
/**
* Accessor for the Actor's name.
*
* @return Actor's name.
*/
public String getName() {
return mName;
}
@Prop(name = "ID")
/**
* Accessor for the Actor's unique ID
*
* @return Unique ID of the Actor
*/
public long getId() {
return mId;
}
/**
* Accessor for the Actor's Box2d body (if any)
*
* @return the body, or null if none
*/
public Body getMainBody() {
return mBody;
}
public int getNumSubBodies() {
return mSubBodies.size();
}
public Body getSubBody(int index) {
return mSubBodies.get(index);
}
/**
* Set a category group to all fixtures of a single body.
*
* @param group
* Id - Negative id does not collide with those with the same
* group id Positive id collides with only those with the same
* group id. Default is 0, which collides with everything;
*/
@Prop(name = "Collision Group")
public void setCollisionGroup(int group) {
// Create a filter
Filter filter;
// Set all fixtures of the body to the same Collision Group.
ArrayList<Fixture> fixtures = mBody.getFixtureList();
for (Fixture f : fixtures) {
// Get the Current Filter data
filter = f.getFilterData();
// Change the group index
filter.groupIndex = (short) group;
// Apply the new filter to the fixture.
f.setFilterData(filter);
}
mCollisionGroup = group;
}
@Prop(name = "Collision Group")
public int getCollisionGroup() {
return mCollisionGroup;
}
/**
* Adds all properties present in h, overwrites duplicates but leaves unique
* keys already present
*
* @param h
* HashMap of properties to add/overwrite
*/
public void setProperties(HashMap<String, Object> h) {
for (Map.Entry<String, Object> entry : h.entrySet()) {
setProp(entry.getKey(), entry.getValue());
}
}
/**
* Accessor for getting all the Actor's properties
*
* @return HashMap of Actor properties
*/
public HashMap<String, Object> getProperties() {
HashMap<String, Object> ret = new HashMap<String, Object>(mProps);
for (String s : mPropMethods.getGetterNames()) {
ret.put(s, mPropMethods.get(this, s));
}
return ret;
}
/**
* Returns a given property, or null if it doesn't exist. Potentially throws
* ClassCastException.
*
* @param name
* The name of the property
* @return Requested property
*/
public <T> T getProp(String name) {
// First attempt to get property using new system
if (mPropMethods != null && mPropMethods.hasGetter(name)) {
return (T) mPropMethods.get(this, name);
}
Object prop = mProps.get(name);
if (prop == null) {
return null;
}
return (T) mProps.get(name);
}
/**
* Sets a given property
*
* @param name
* The name of the property
* @param val
* The value
*/
public void setProp(String name, Object val) {
// Try to set property using new method
if (mPropMethods != null && mPropMethods.hasSetter(name)) {
mPropMethods.set(this, name, val);
return;
}
if (name.equals("ID")) {
return;
}
mProps.put(name, val);
}
public String toString() {
return "Actor ID:" + getProp("ID");
}
/**
* Accessor for the way to draw the Actor
*
* @return The Actor's Drawable
*/
public Drawable getDrawable() {
return mDrawable;
}
// Properties
@Prop(name = "X")
public float getX() {
return mBody.getPosition().x;
}
@Prop(name = "X")
public void setX(float x) {
mBody.setTransform(x, mBody.getPosition().y, mBody.getAngle());
mBody.setLinearVelocity(0, 0);
}
@Prop(name = "Y")
public float getY() {
return mBody.getPosition().y;
}
@Prop(name = "Y")
public void setY(float y) {
mBody.setTransform(mBody.getPosition().x, y, mBody.getAngle());
mBody.setLinearVelocity(0, 0);
}
@Prop(name = "Friction")
public float getFriction() {
return mBody.getFixtureList().get(0).getFriction();
}
@Prop(name = "Friction")
public void setFriction(float friction) {
for (Fixture f : mBody.getFixtureList()) {
f.setFriction(friction);
}
}
@Prop(name = "Density")
public float getDensity() {
return mBody.getFixtureList().get(0).getDensity();
}
@Prop(name = "Density")
public void setDensity(float d) {
for (Fixture f : mBody.getFixtureList()) {
if (!f.isSensor()) {
f.setDensity(Convert.getFloat(d));
}
}
mBody.resetMassData();
}
@Prop(name = "Restitution")
public float getRestitution() {
return mBody.getFixtureList().get(0).getRestitution();
}
@Prop(name = "Restitution")
public void setRestitution(float r) {
for (Fixture f : mBody.getFixtureList()) {
f.setRestitution(Convert.getFloat(r));
}
}
@Prop(name = "Momentum X")
public float getMomentumX() {
return mBody.getLinearVelocity().x * mBody.getMass();
}
@Prop(name = "Momentum X")
public void setMomentumX(float m) {
mBody.setLinearVelocity(m / mBody.getMass(), mBody.getLinearVelocity().y);
}
@Prop(name = "Momentum Y")
public float getMomentumY() {
return mBody.getLinearVelocity().y * mBody.getMass();
}
@Prop(name = "Momentum Y")
public void setMomentumY(float m) {
mBody.setLinearVelocity(mBody.getLinearVelocity().x, m / mBody.getMass());
}
@Prop(name = "Velocity X")
public float getVelocityX() {
return mBody.getLinearVelocity().x;
}
@Prop(name = "Velocity X")
public void setVelocityX(float m) {
mBody.setLinearVelocity(m, mBody.getLinearVelocity().y);
}
@Prop(name = "Velocity Y")
public float getVelocityY() {
return mBody.getLinearVelocity().y;
}
@Prop(name = "Velocity Y")
public void setVelocityY(float m) {
mBody.setLinearVelocity(mBody.getLinearVelocity().x, m);
}
@Prop(name = "Angle")
public float getAngle() {
return Convert.getDegrees(mBody.getAngle());
}
@Prop(name = "Angle")
public void setAngle(float m) {
mBody.setTransform(mBody.getPosition().x, mBody.getPosition().y, Convert.getRadians(m));
}
@Prop(name = "Layer")
public int getLayer() {
return mLayer;
}
@Prop(name = "Layer")
public void setLayer(int layer) {
mLayer = layer;
}
@Prop(name = "BodyType")
public int getBodyType() {
return mBody.getType().ordinal();
}
@Prop(name = "BodyType")
/**
* StaticBody(0), KinematicBody(1), DynamicBody(2)
* @param type integer representation of type
*/
public void setBodyType(int type) {
mBody.setType(BodyType.values()[type]);
}
@Prop(name = "Grabbable")
public int getGrabable() {
return mGrabbableInd;
}
@Prop(name = "Grabbable")
/**
* @param flag 1 or 0
*/
public void setGrabbable(int flag) {
mGrabbableInd = flag;
}
@Prop(name = "Visible")
public int getVisible() {
return mVisibleInd;
}
@Prop(name = "Visible")
/**
* @param flag 1 or 0
*/
public void setVisible(int flag) {
mVisibleInd = flag;
}
@Prop(name = "Spawner")
public int getSpawner() {
return mSpawner;
}
@Prop(name = "Spawner")
public void setSpawner(int id) {
int size = mDrawable.mDrawables.size();
// remove old bodysprite
for (int i = 0; i < size; i++) {
Drawable d = mDrawable.mDrawables.get(i);
if (d instanceof DebugActorLinkDrawable) {
if (((DebugActorLinkDrawable) d).getPropName() != null
&& ((DebugActorLinkDrawable) d).getPropName().equals("Spawner")) {
mDrawable.mDrawables.remove(d);
}
break;
}
}
mDrawable.mDrawables.add(new DebugActorLinkDrawable(this, "Spawner", Color.GREEN));
mSpawner = id;
Actor spawner = mLevel.getActorById(Convert.getInt(id));
if (spawner != null && spawner instanceof Spawner) {
((Spawner) spawner).addToSpawn(this);
}
}
@Prop(name = "Active")
public int getActive() {
return mActive ? 1 : 0;
}
@Prop(name = "Active")
public void setActive(int flag) {
if (flag == 1) {
setActive(true);
} else if (flag == 0) {
setActive(false);
}
}
@Prop(name = "Collision Sound")
public String getCollisionSound() {
return mCollisionSound;
}
@Prop(name = "Collision Sound")
public void setCollisionSound(String sound) {
mCollisionSound = sound;
}
@Prop(name = "colPitch")
public float getCollisionPitch() {
return mCollisionPitch;
}
@Prop(name = "colPitch")
public void setCollisionPitch(float p) {
mCollisionPitch = p;
}
} |
package com.ocrapp.startscreen;
import java.io.File;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Point;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.Spinner;
import android.widget.TextView;
import br.com.thinkti.android.filechooser.FileChooser;
import com.ocrapp.R;
import com.ocrapp.imageui.ImagePreprocessor;
public class StartActivity extends Activity implements OnItemSelectedListener{
private String lang;
Spinner spinner;
Button uploadbtn;
Button camerabtn;
Button helpbtn;
TextView tvOut;
Intent intent;
Point p;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
TextView myTextView=(TextView)findViewById(R.id.textview1);
Typeface typeFace=Typeface.createFromAsset(getAssets(),"fonts/Dosis-Bold.ttf");
myTextView.setTypeface(typeFace);
/** Upload Button ***/
intent = new Intent(this, FileChooser.class);
uploadbtn = (Button) findViewById(R.id.button2);
OnClickListener oclBtnUP = new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
ArrayList<String> extensions = new ArrayList<String>();
extensions.add(".jpg");
extensions.add(".bmp");
extensions.add(".png");
intent.putStringArrayListExtra("filterFileExtension", extensions);
startActivityForResult(intent, 1);
}
};
uploadbtn.setOnClickListener(oclBtnUP);
/* Camera Button*/
camerabtn = (Button) findViewById(R.id.button1);
OnClickListener oclBtnCAM = new OnClickListener() {
@Override
public void onClick(View v) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
Uri uriSavedImage=Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "tesseract/camera/image.png"));
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
if (cameraIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(cameraIntent, 1);
}
}
};
camerabtn.setOnClickListener(oclBtnCAM);
/** Help Button ***/
helpbtn = (Button) findViewById(R.id.button3);
OnClickListener oclBtnHELP = new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (p != null)
showPopup(StartActivity.this, p);
}
};
helpbtn.setOnClickListener(oclBtnHELP);
/** Spinner **/
spinner = (Spinner) findViewById(R.id.spinner);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,R.array.lang_array, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(this);
}
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
// An item was selected. You can retrieve the selected item using
// parent.getItemAtPosition(pos)
spinner.setSelection(pos);
lang = (String) spinner.getSelectedItem();
if(lang.equals("English")){
lang = "eng";
}
else if(lang.equals("Spanish"))
lang = "spa";
else if(lang.equals("French"))
lang = "fra";
else if(lang.equals("Hindi"))
lang = "hin";
else if(lang.equals("Arabic"))
lang = "ara";
else if(lang.equals("Portuguese"))
lang ="por";
else if(lang.equals("Simplified Chinese"))
lang = "chi_sim";
else if(lang.equals("German"))
lang ="deu";
System.out.println(lang);
}
public void onNothingSelected(AdapterView<?> parent) {
// Another interface callback
lang = "en";
System.out.println(lang);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if ((requestCode == 1) && (resultCode == -1)) {
Bitmap bmp = null;
String fileSelected = data.getStringExtra("fileSelected");
System.out.println("SELECTED FILE: " + fileSelected);
Intent imagePreprocessor = new Intent(this, ImagePreprocessor.class);
imagePreprocessor.putExtra("file", fileSelected);
imagePreprocessor.putExtra("lang", lang);
startActivity(imagePreprocessor);
}
}
// Next two methods are for help button popup
@Override
public void onWindowFocusChanged(boolean hasFocus) {
int[] location = new int[2];
Button button = (Button) findViewById(R.id.button3);
// Get the x, y location and store it in the location[] array
// location[0] = x, location[1] = y.
button.getLocationOnScreen(location);
//Initialize the Point with x, and y positions
p = new Point();
p.x = location[0];
p.y = location[1];
}
// The method that displays the popup.
private void showPopup(final Activity context, Point p) {
int popupWidth = 900;
int popupHeight = 650;
// Inflate the popup_layout.xml
LinearLayout viewGroup = (LinearLayout) context.findViewById(R.id.popup);
LayoutInflater layoutInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = layoutInflater.inflate(R.layout.popup_layout, viewGroup);
// Creating the PopupWindow
final PopupWindow popup = new PopupWindow(context);
popup.setContentView(layout);
popup.setWidth(popupWidth);
popup.setHeight(popupHeight);
popup.setFocusable(true);
// Some offset to align the popup a bit to the right, and a bit down, relative to button's position.
int OFFSET_X = 60;
int OFFSET_Y = 70;
// Clear the default translucent background
popup.setBackgroundDrawable(new BitmapDrawable());
// Displaying the popup at the specified location, + offsets.
popup.showAtLocation(layout, Gravity.NO_GRAVITY, p.x + OFFSET_X, p.y + OFFSET_Y);
// Getting a reference to Close button, and close the popup when clicked.
Button close = (Button) layout.findViewById(R.id.close);
close.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
popup.dismiss();
}
});
}
} |
package org.ethereum.vm;
import org.ethereum.config.SystemProperties;
import org.ethereum.core.BlockHeader;
import org.ethereum.db.ContractDetails;
import org.ethereum.vm.MessageCall.MsgType;
import org.ethereum.vm.program.Program;
import org.ethereum.vm.program.Stack;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spongycastle.util.encoders.Hex;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import static org.ethereum.config.SystemProperties.CONFIG;
import static org.ethereum.crypto.HashUtil.sha3;
import static org.ethereum.util.ByteUtil.EMPTY_BYTE_ARRAY;
import static org.ethereum.vm.OpCode.*;
/**
* The Ethereum Virtual Machine (EVM) is responsible for initialization
* and executing a transaction on a contract.
*
* It is a quasi-Turing-complete machine; the quasi qualification
* comes from the fact that the computation is intrinsically bounded
* through a parameter, gas, which limits the total amount of computation done.
*
* The EVM is a simple stack-based architecture. The word size of the machine
* (and thus size of stack item) is 256-bit. This was chosen to facilitate
* the SHA3-256 hash scheme and elliptic-curve computations. The memory model
* is a simple word-addressed byte array. The stack has an unlimited size.
* The machine also has an independent storage model; this is similar in concept
* to the memory but rather than a byte array, it is a word-addressable word array.
*
* Unlike memory, which is volatile, storage is non volatile and is
* maintained as part of the system state. All locations in both storage
* and memory are well-defined initially as zero.
*
* The machine does not follow the standard von Neumann architecture.
* Rather than storing program code in generally-accessible memory or storage,
* it is stored separately in a virtual ROM interactable only though
* a specialised instruction.
*
* The machine can have exceptional execution for several reasons,
* including stack underflows and invalid instructions. These unambiguously
* and validly result in immediate halting of the machine with all state changes
* left intact. The one piece of exceptional execution that does not leave
* state changes intact is the out-of-gas (OOG) exception.
*
* Here, the machine halts immediately and reports the issue to
* the execution agent (either the transaction processor or, recursively,
* the spawning execution environment) and which will deal with it separately.
*
* @author Roman Mandeleil
* @since 01.06.2014
*/
public class VM {
private static final Logger logger = LoggerFactory.getLogger("VM");
private static final Logger dumpLogger = LoggerFactory.getLogger("dump");
private static BigInteger _32_ = BigInteger.valueOf(32);
private static String logString = "{} Op: [{}] Gas: [{}] Deep: [{}] Hint: [{}]";
private static BigInteger MAX_GAS = BigInteger.valueOf(Long.MAX_VALUE);
/* Keeps track of the number of steps performed in this VM */
private int vmCounter = 0;
private static VMHook vmHook;
private final static boolean vmTrace = CONFIG.vmTrace();
private final static long dumpBlock = CONFIG.dumpBlock();
public void step(Program program) {
if (vmTrace) {
program.saveOpTrace();
}
try {
OpCode op = OpCode.code(program.getCurrentOp());
if (op == null) {
throw Program.Exception.invalidOpCode(program.getCurrentOp());
}
if (op == DELEGATECALL) {
// opcode since Homestead release only
if (!SystemProperties.CONFIG.getBlockchainConfig().getConfigForBlock(program.getNumber().longValue()).
getConstants().hasDelegateCallOpcode()) {
throw Program.Exception.invalidOpCode(program.getCurrentOp());
}
}
program.setLastOp(op.val());
program.verifyStackSize(op.require());
program.verifyStackOverflow(op.require(), op.ret()); //Check not exceeding stack limits
long oldMemSize = program.getMemSize();
BigInteger newMemSize = BigInteger.ZERO;
long copySize = 0;
Stack stack = program.getStack();
String hint = "";
long callGas = 0, memWords = 0; // parameters for logging
long gasCost = op.getTier().asInt();
long gasBefore = program.getGas().longValue();
int stepBefore = program.getPC();
/*DEBUG #POC9 if( op.asInt() == 96 || op.asInt() == -128 || op.asInt() == 57 || op.asInt() == 115) {
//byte alphaone = 0x63;
//op = OpCode.code(alphaone);
gasCost = 3;
}
if( op.asInt() == -13 ) {
//byte alphaone = 0x63;
//op = OpCode.code(alphaone);
gasCost = 0;
}*/
// Calculate fees and spend gas
switch (op) {
case STOP:
case SUICIDE:
// The ops that don't charge by step
gasCost = GasCost.STOP;
break;
case SSTORE:
DataWord newValue = stack.get(stack.size() - 2);
DataWord oldValue = program.storageLoad(stack.peek());
if (oldValue == null && !newValue.isZero())
gasCost = GasCost.SET_SSTORE;
else if (oldValue != null && newValue.isZero()) {
// todo: GASREFUND counter policy
// refund step cost policy.
program.futureRefundGas(GasCost.REFUND_SSTORE);
gasCost = GasCost.CLEAR_SSTORE;
} else
gasCost = GasCost.RESET_SSTORE;
break;
case SLOAD:
gasCost = GasCost.SLOAD;
break;
case BALANCE:
gasCost = GasCost.BALANCE;
break;
// These all operate on memory and therefore potentially expand it:
case MSTORE:
newMemSize = memNeeded(stack.peek(), new DataWord(32));
break;
case MSTORE8:
newMemSize = memNeeded(stack.peek(), new DataWord(1));
break;
case MLOAD:
newMemSize = memNeeded(stack.peek(), new DataWord(32));
break;
case RETURN:
gasCost = GasCost.STOP; //rename?
newMemSize = memNeeded(stack.peek(), stack.get(stack.size() - 2));
break;
case SHA3:
gasCost = GasCost.SHA3;
newMemSize = memNeeded(stack.peek(), stack.get(stack.size() - 2));
DataWord size = stack.get(stack.size() - 2);
long chunkUsed = (size.longValue() + 31) / 32;
gasCost += chunkUsed * GasCost.SHA3_WORD;
break;
case CALLDATACOPY:
copySize = stack.get(stack.size() - 3).longValue();
newMemSize = memNeeded(stack.peek(), stack.get(stack.size() - 3));
break;
case CODECOPY:
copySize = stack.get(stack.size() - 3).longValue();
newMemSize = memNeeded(stack.peek(), stack.get(stack.size() - 3));
break;
case EXTCODECOPY:
copySize = stack.get(stack.size() - 4).longValue();
newMemSize = memNeeded(stack.get(stack.size() - 2), stack.get(stack.size() - 4));
break;
case CALL:
case CALLCODE:
case DELEGATECALL:
gasCost = GasCost.CALL;
DataWord callGasWord = stack.get(stack.size() - 1);
if (callGasWord.compareTo(program.getGas()) > 0) {
throw Program.Exception.notEnoughOpGas(op, callGasWord, program.getGas());
}
gasCost += callGasWord.longValue();
DataWord callAddressWord = stack.get(stack.size() - 2);
//check to see if account does not exist and is not a precompiled contract
if (op == CALL && !program.getStorage().isExist(callAddressWord.getLast20Bytes()))
gasCost += GasCost.NEW_ACCT_CALL;
//TODO #POC9 Make sure this is converted to BigInteger (256num support)
if (op != DELEGATECALL && !stack.get(stack.size() - 3).isZero() )
gasCost += GasCost.VT_CALL;
int opOff = op == DELEGATECALL ? 3 : 4;
BigInteger in = memNeeded(stack.get(stack.size() - opOff), stack.get(stack.size() - opOff - 1)); // in offset+size
BigInteger out = memNeeded(stack.get(stack.size() - opOff - 2), stack.get(stack.size() - opOff - 3)); // out offset+size
newMemSize = in.max(out);
break;
case CREATE:
gasCost = GasCost.CREATE;
newMemSize = memNeeded(stack.get(stack.size() - 2), stack.get(stack.size() - 3));
break;
case LOG0:
case LOG1:
case LOG2:
case LOG3:
case LOG4:
int nTopics = op.val() - OpCode.LOG0.val();
newMemSize = memNeeded(stack.peek(), stack.get(stack.size() - 2));
BigInteger dataSize = stack.get(stack.size() - 2).value();
BigInteger dataCost = dataSize.multiply(BigInteger.valueOf(GasCost.LOG_DATA_GAS));
if (program.getGas().value().compareTo(dataCost) < 0) {
throw Program.Exception.notEnoughOpGas(op, dataCost, program.getGas().value());
}
gasCost = GasCost.LOG_GAS +
GasCost.LOG_TOPIC_GAS * nTopics +
GasCost.LOG_DATA_GAS * stack.get(stack.size() - 2).longValue();
break;
case EXP:
DataWord exp = stack.get(stack.size() - 2);
int bytesOccupied = exp.bytesOccupied();
gasCost = GasCost.EXP_GAS + GasCost.EXP_BYTE_GAS * bytesOccupied;
break;
default:
break;
}
//DEBUG System.out.println(" OP IS " + op.name() + " GASCOST IS " + gasCost + " NUM IS " + op.asInt());
program.spendGas(gasCost, op.name());
// Avoid overflows
if (newMemSize.compareTo(MAX_GAS) == 1) {
throw Program.Exception.gasOverflow(newMemSize, MAX_GAS);
}
// memory gas calc
long memoryUsage = (newMemSize.longValue() + 31) / 32 * 32;
if (memoryUsage > oldMemSize) {
memWords = (memoryUsage / 32);
long memWordsOld = (oldMemSize / 32);
//TODO #POC9 c_quadCoeffDiv = 512, this should be a constant, not magic number
long memGas = ( GasCost.MEMORY * memWords + memWords * memWords / 512)
- (GasCost.MEMORY * memWordsOld + memWordsOld * memWordsOld / 512);
program.spendGas(memGas, op.name() + " (memory usage)");
gasCost += memGas;
}
if (copySize > 0) {
long copyGas = GasCost.COPY_GAS * ((copySize + 31) / 32);
gasCost += copyGas;
program.spendGas(copyGas, op.name() + " (copy usage)");
}
// Log debugging line for VM
if (program.getNumber().intValue() == dumpBlock)
this.dumpLine(op, gasBefore, gasCost + callGas, memWords, program);
if (vmHook != null) {
vmHook.step(program, op);
}
// Execute operation
switch (op) {
/**
* Stop and Arithmetic Operations
*/
case STOP: {
program.setHReturn(EMPTY_BYTE_ARRAY);
program.stop();
}
break;
case ADD: {
DataWord word1 = program.stackPop();
DataWord word2 = program.stackPop();
if (logger.isInfoEnabled())
hint = word1.value() + " + " + word2.value();
word1.add(word2);
program.stackPush(word1);
program.step();
}
break;
case MUL: {
DataWord word1 = program.stackPop();
DataWord word2 = program.stackPop();
if (logger.isInfoEnabled())
hint = word1.value() + " * " + word2.value();
word1.mul(word2);
program.stackPush(word1);
program.step();
}
break;
case SUB: {
DataWord word1 = program.stackPop();
DataWord word2 = program.stackPop();
if (logger.isInfoEnabled())
hint = word1.value() + " - " + word2.value();
word1.sub(word2);
program.stackPush(word1);
program.step();
}
break;
case DIV: {
DataWord word1 = program.stackPop();
DataWord word2 = program.stackPop();
if (logger.isInfoEnabled())
hint = word1.value() + " / " + word2.value();
word1.div(word2);
program.stackPush(word1);
program.step();
}
break;
case SDIV: {
DataWord word1 = program.stackPop();
DataWord word2 = program.stackPop();
if (logger.isInfoEnabled())
hint = word1.sValue() + " / " + word2.sValue();
word1.sDiv(word2);
program.stackPush(word1);
program.step();
}
break;
case MOD: {
DataWord word1 = program.stackPop();
DataWord word2 = program.stackPop();
if (logger.isInfoEnabled())
hint = word1.value() + " % " + word2.value();
word1.mod(word2);
program.stackPush(word1);
program.step();
}
break;
case SMOD: {
DataWord word1 = program.stackPop();
DataWord word2 = program.stackPop();
if (logger.isInfoEnabled())
hint = word1.sValue() + " #% " + word2.sValue();
word1.sMod(word2);
program.stackPush(word1);
program.step();
}
break;
case EXP: {
DataWord word1 = program.stackPop();
DataWord word2 = program.stackPop();
if (logger.isInfoEnabled())
hint = word1.value() + " ** " + word2.value();
word1.exp(word2);
program.stackPush(word1);
program.step();
}
break;
case SIGNEXTEND: {
DataWord word1 = program.stackPop();
BigInteger k = word1.value();
if (k.compareTo(_32_) < 0) {
DataWord word2 = program.stackPop();
if (logger.isInfoEnabled())
hint = word1 + " " + word2.value();
word2.signExtend(k.byteValue());
program.stackPush(word2);
}
program.step();
}
break;
case NOT: {
DataWord word1 = program.stackPop();
word1.bnot();
if (logger.isInfoEnabled())
hint = "" + word1.value();
program.stackPush(word1);
program.step();
}
break;
case LT: {
// TODO: can be improved by not using BigInteger
DataWord word1 = program.stackPop();
DataWord word2 = program.stackPop();
if (logger.isInfoEnabled())
hint = word1.value() + " < " + word2.value();
if (word1.value().compareTo(word2.value()) == -1) {
word1.and(DataWord.ZERO);
word1.getData()[31] = 1;
} else {
word1.and(DataWord.ZERO);
}
program.stackPush(word1);
program.step();
}
break;
case SLT: {
// TODO: can be improved by not using BigInteger
DataWord word1 = program.stackPop();
DataWord word2 = program.stackPop();
if (logger.isInfoEnabled())
hint = word1.sValue() + " < " + word2.sValue();
if (word1.sValue().compareTo(word2.sValue()) == -1) {
word1.and(DataWord.ZERO);
word1.getData()[31] = 1;
} else {
word1.and(DataWord.ZERO);
}
program.stackPush(word1);
program.step();
}
break;
case SGT: {
// TODO: can be improved by not using BigInteger
DataWord word1 = program.stackPop();
DataWord word2 = program.stackPop();
if (logger.isInfoEnabled())
hint = word1.sValue() + " > " + word2.sValue();
if (word1.sValue().compareTo(word2.sValue()) == 1) {
word1.and(DataWord.ZERO);
word1.getData()[31] = 1;
} else {
word1.and(DataWord.ZERO);
}
program.stackPush(word1);
program.step();
}
break;
case GT: {
// TODO: can be improved by not using BigInteger
DataWord word1 = program.stackPop();
DataWord word2 = program.stackPop();
if (logger.isInfoEnabled())
hint = word1.value() + " > " + word2.value();
if (word1.value().compareTo(word2.value()) == 1) {
word1.and(DataWord.ZERO);
word1.getData()[31] = 1;
} else {
word1.and(DataWord.ZERO);
}
program.stackPush(word1);
program.step();
}
break;
case EQ: {
DataWord word1 = program.stackPop();
DataWord word2 = program.stackPop();
if (logger.isInfoEnabled())
hint = word1.value() + " == " + word2.value();
if (word1.xor(word2).isZero()) {
word1.and(DataWord.ZERO);
word1.getData()[31] = 1;
} else {
word1.and(DataWord.ZERO);
}
program.stackPush(word1);
program.step();
}
break;
case ISZERO: {
DataWord word1 = program.stackPop();
if (word1.isZero()) {
word1.getData()[31] = 1;
} else {
word1.and(DataWord.ZERO);
}
if (logger.isInfoEnabled())
hint = "" + word1.value();
program.stackPush(word1);
program.step();
}
break;
/**
* Bitwise Logic Operations
*/
case AND: {
DataWord word1 = program.stackPop();
DataWord word2 = program.stackPop();
if (logger.isInfoEnabled())
hint = word1.value() + " && " + word2.value();
word1.and(word2);
program.stackPush(word1);
program.step();
}
break;
case OR: {
DataWord word1 = program.stackPop();
DataWord word2 = program.stackPop();
if (logger.isInfoEnabled())
hint = word1.value() + " || " + word2.value();
word1.or(word2);
program.stackPush(word1);
program.step();
}
break;
case XOR: {
DataWord word1 = program.stackPop();
DataWord word2 = program.stackPop();
if (logger.isInfoEnabled())
hint = word1.value() + " ^ " + word2.value();
word1.xor(word2);
program.stackPush(word1);
program.step();
}
break;
case BYTE: {
DataWord word1 = program.stackPop();
DataWord word2 = program.stackPop();
final DataWord result;
if (word1.value().compareTo(_32_) == -1) {
byte tmp = word2.getData()[word1.intValue()];
word2.and(DataWord.ZERO);
word2.getData()[31] = tmp;
result = word2;
} else {
result = new DataWord();
}
if (logger.isInfoEnabled())
hint = "" + result.value();
program.stackPush(result);
program.step();
}
break;
case ADDMOD: {
DataWord word1 = program.stackPop();
DataWord word2 = program.stackPop();
DataWord word3 = program.stackPop();
word1.addmod(word2, word3);
program.stackPush(word1);
program.step();
}
break;
case MULMOD: {
DataWord word1 = program.stackPop();
DataWord word2 = program.stackPop();
DataWord word3 = program.stackPop();
word1.mulmod(word2, word3);
program.stackPush(word1);
program.step();
}
break;
/**
* SHA3
*/
case SHA3: {
DataWord memOffsetData = program.stackPop();
DataWord lengthData = program.stackPop();
byte[] buffer = program.memoryChunk(memOffsetData.intValue(), lengthData.intValue());
byte[] encoded = sha3(buffer);
DataWord word = new DataWord(encoded);
if (logger.isInfoEnabled())
hint = word.toString();
program.stackPush(word);
program.step();
}
break;
/**
* Environmental Information
*/
case ADDRESS: {
DataWord address = program.getOwnerAddress();
if (logger.isInfoEnabled())
hint = "address: " + Hex.toHexString(address.getLast20Bytes());
program.stackPush(address);
program.step();
}
break;
case BALANCE: {
DataWord address = program.stackPop();
DataWord balance = program.getBalance(address);
if (logger.isInfoEnabled())
hint = "address: "
+ Hex.toHexString(address.getLast20Bytes())
+ " balance: " + balance.toString();
program.stackPush(balance);
program.step();
}
break;
case ORIGIN: {
DataWord originAddress = program.getOriginAddress();
if (logger.isInfoEnabled())
hint = "address: " + Hex.toHexString(originAddress.getLast20Bytes());
program.stackPush(originAddress);
program.step();
}
break;
case CALLER: {
DataWord callerAddress = program.getCallerAddress();
if (logger.isInfoEnabled())
hint = "address: " + Hex.toHexString(callerAddress.getLast20Bytes());
program.stackPush(callerAddress);
program.step();
}
break;
case CALLVALUE: {
DataWord callValue = program.getCallValue();
if (logger.isInfoEnabled())
hint = "value: " + callValue;
program.stackPush(callValue);
program.step();
}
break;
case CALLDATALOAD: {
DataWord dataOffs = program.stackPop();
DataWord value = program.getDataValue(dataOffs);
if (logger.isInfoEnabled())
hint = "data: " + value;
program.stackPush(value);
program.step();
}
break;
case CALLDATASIZE: {
DataWord dataSize = program.getDataSize();
if (logger.isInfoEnabled())
hint = "size: " + dataSize.value();
program.stackPush(dataSize);
program.step();
}
break;
case CALLDATACOPY: {
DataWord memOffsetData = program.stackPop();
DataWord dataOffsetData = program.stackPop();
DataWord lengthData = program.stackPop();
byte[] msgData = program.getDataCopy(dataOffsetData, lengthData);
if (logger.isInfoEnabled())
hint = "data: " + Hex.toHexString(msgData);
program.memorySave(memOffsetData.intValue(), msgData);
program.step();
}
break;
case CODESIZE:
case EXTCODESIZE: {
int length;
if (op == OpCode.CODESIZE)
length = program.getCode().length;
else {
DataWord address = program.stackPop();
length = program.getCodeAt(address).length;
}
DataWord codeLength = new DataWord(length);
if (logger.isInfoEnabled())
hint = "size: " + length;
program.stackPush(codeLength);
program.step();
}
break;
case CODECOPY:
case EXTCODECOPY: {
byte[] fullCode = EMPTY_BYTE_ARRAY;
if (op == OpCode.CODECOPY)
fullCode = program.getCode();
if (op == OpCode.EXTCODECOPY) {
DataWord address = program.stackPop();
fullCode = program.getCodeAt(address);
}
int memOffset = program.stackPop().intValueSafe();
int codeOffset = program.stackPop().intValueSafe();
int lengthData = program.stackPop().intValueSafe();
int sizeToBeCopied =
(long) codeOffset + lengthData > fullCode.length ?
(fullCode.length < codeOffset ? 0 : fullCode.length - codeOffset)
: lengthData;
byte[] codeCopy = new byte[lengthData];
if (codeOffset < fullCode.length)
System.arraycopy(fullCode, codeOffset, codeCopy, 0, sizeToBeCopied);
if (logger.isInfoEnabled())
hint = "code: " + Hex.toHexString(codeCopy);
program.memorySave(memOffset, codeCopy);
program.step();
}
break;
case GASPRICE: {
DataWord gasPrice = program.getGasPrice();
if (logger.isInfoEnabled())
hint = "price: " + gasPrice.toString();
program.stackPush(gasPrice);
program.step();
}
break;
/**
* Block Information
*/
case BLOCKHASH: {
int blockIndex = program.stackPop().intValue();
DataWord blockHash = program.getBlockHash(blockIndex);
if (logger.isInfoEnabled())
hint = "blockHash: " + blockHash;
program.stackPush(blockHash);
program.step();
}
break;
case COINBASE: {
DataWord coinbase = program.getCoinbase();
if (logger.isInfoEnabled())
hint = "coinbase: " + Hex.toHexString(coinbase.getLast20Bytes());
program.stackPush(coinbase);
program.step();
}
break;
case TIMESTAMP: {
DataWord timestamp = program.getTimestamp();
if (logger.isInfoEnabled())
hint = "timestamp: " + timestamp.value();
program.stackPush(timestamp);
program.step();
}
break;
case NUMBER: {
DataWord number = program.getNumber();
if (logger.isInfoEnabled())
hint = "number: " + number.value();
program.stackPush(number);
program.step();
}
break;
case DIFFICULTY: {
DataWord difficulty = program.getDifficulty();
if (logger.isInfoEnabled())
hint = "difficulty: " + difficulty;
program.stackPush(difficulty);
program.step();
}
break;
case GASLIMIT: {
DataWord gaslimit = program.getGasLimit();
if (logger.isInfoEnabled())
hint = "gaslimit: " + gaslimit;
program.stackPush(gaslimit);
program.step();
}
break;
case POP: {
program.stackPop();
program.step();
} break;
case DUP1: case DUP2: case DUP3: case DUP4:
case DUP5: case DUP6: case DUP7: case DUP8:
case DUP9: case DUP10: case DUP11: case DUP12:
case DUP13: case DUP14: case DUP15: case DUP16:{
int n = op.val() - OpCode.DUP1.val() + 1;
DataWord word_1 = stack.get(stack.size() - n);
program.stackPush(word_1.clone());
program.step();
} break;
case SWAP1: case SWAP2: case SWAP3: case SWAP4:
case SWAP5: case SWAP6: case SWAP7: case SWAP8:
case SWAP9: case SWAP10: case SWAP11: case SWAP12:
case SWAP13: case SWAP14: case SWAP15: case SWAP16:{
int n = op.val() - OpCode.SWAP1.val() + 2;
stack.swap(stack.size() - 1, stack.size() - n);
program.step();
}
break;
case LOG0:
case LOG1:
case LOG2:
case LOG3:
case LOG4: {
DataWord address = program.getOwnerAddress();
DataWord memStart = stack.pop();
DataWord memOffset = stack.pop();
int nTopics = op.val() - OpCode.LOG0.val();
List<DataWord> topics = new ArrayList<>();
for (int i = 0; i < nTopics; ++i) {
DataWord topic = stack.pop();
topics.add(topic);
}
byte[] data = program.memoryChunk(memStart.intValue(), memOffset.intValue());
LogInfo logInfo =
new LogInfo(address.getLast20Bytes(), topics, data);
if (logger.isInfoEnabled())
hint = logInfo.toString();
program.getResult().addLogInfo(logInfo);
program.step();
}
break;
case MLOAD: {
DataWord addr = program.stackPop();
DataWord data = program.memoryLoad(addr);
if (logger.isInfoEnabled())
hint = "data: " + data;
program.stackPush(data);
program.step();
}
break;
case MSTORE: {
DataWord addr = program.stackPop();
DataWord value = program.stackPop();
if (logger.isInfoEnabled())
hint = "addr: " + addr + " value: " + value;
program.memorySave(addr, value);
program.step();
}
break;
case MSTORE8: {
DataWord addr = program.stackPop();
DataWord value = program.stackPop();
byte[] byteVal = {value.getData()[31]};
program.memorySave(addr.intValue(), byteVal);
program.step();
}
break;
case SLOAD: {
DataWord key = program.stackPop();
DataWord val = program.storageLoad(key);
if (logger.isInfoEnabled())
hint = "key: " + key + " value: " + val;
if (val == null)
val = key.and(DataWord.ZERO);
program.stackPush(val);
program.step();
}
break;
case SSTORE: {
DataWord addr = program.stackPop();
DataWord value = program.stackPop();
if (logger.isInfoEnabled())
hint = "[" + program.getOwnerAddress().toPrefixString() + "] key: " + addr + " value: " + value;
program.storageSave(addr, value);
program.step();
}
break;
case JUMP: {
DataWord pos = program.stackPop();
int nextPC = program.verifyJumpDest(pos);
if (logger.isInfoEnabled())
hint = "~> " + nextPC;
program.setPC(nextPC);
}
break;
case JUMPI: {
DataWord pos = program.stackPop();
DataWord cond = program.stackPop();
if (!cond.isZero()) {
int nextPC = program.verifyJumpDest(pos);
if (logger.isInfoEnabled())
hint = "~> " + nextPC;
program.setPC(nextPC);
} else {
program.step();
}
}
break;
case PC: {
int pc = program.getPC();
DataWord pcWord = new DataWord(pc);
if (logger.isInfoEnabled())
hint = pcWord.toString();
program.stackPush(pcWord);
program.step();
}
break;
case MSIZE: {
int memSize = program.getMemSize();
DataWord wordMemSize = new DataWord(memSize);
if (logger.isInfoEnabled())
hint = "" + memSize;
program.stackPush(wordMemSize);
program.step();
}
break;
case GAS: {
DataWord gas = program.getGas();
if (logger.isInfoEnabled())
hint = "" + gas;
program.stackPush(gas);
program.step();
}
break;
case PUSH1:
case PUSH2:
case PUSH3:
case PUSH4:
case PUSH5:
case PUSH6:
case PUSH7:
case PUSH8:
case PUSH9:
case PUSH10:
case PUSH11:
case PUSH12:
case PUSH13:
case PUSH14:
case PUSH15:
case PUSH16:
case PUSH17:
case PUSH18:
case PUSH19:
case PUSH20:
case PUSH21:
case PUSH22:
case PUSH23:
case PUSH24:
case PUSH25:
case PUSH26:
case PUSH27:
case PUSH28:
case PUSH29:
case PUSH30:
case PUSH31:
case PUSH32: {
program.step();
int nPush = op.val() - PUSH1.val() + 1;
byte[] data = program.sweep(nPush);
if (logger.isInfoEnabled())
hint = "" + Hex.toHexString(data);
program.stackPush(data);
}
break;
case JUMPDEST: {
program.step();
}
break;
case CREATE: {
DataWord value = program.stackPop();
DataWord inOffset = program.stackPop();
DataWord inSize = program.stackPop();
if (logger.isInfoEnabled())
logger.info(logString, String.format("%5s", "[" + program.getPC() + "]"),
String.format("%-12s", op.name()),
program.getGas().value(),
program.getCallDeep(), hint);
program.createContract(value, inOffset, inSize);
program.step();
}
break;
case CALL:
case CALLCODE:
case DELEGATECALL: {
DataWord gas = program.stackPop();
DataWord codeAddress = program.stackPop();
DataWord value = !op.equals(DELEGATECALL) ?
program.stackPop() : DataWord.ZERO;
if( !value.isZero()) {
gas.add(new DataWord(GasCost.STIPEND_CALL));
}
DataWord inDataOffs = program.stackPop();
DataWord inDataSize = program.stackPop();
DataWord outDataOffs = program.stackPop();
DataWord outDataSize = program.stackPop();
if (logger.isInfoEnabled()) {
hint = "addr: " + Hex.toHexString(codeAddress.getLast20Bytes())
+ " gas: " + gas.shortHex()
+ " inOff: " + inDataOffs.shortHex()
+ " inSize: " + inDataSize.shortHex();
logger.info(logString, String.format("%5s", "[" + program.getPC() + "]"),
String.format("%-12s", op.name()),
program.getGas().value(),
program.getCallDeep(), hint);
}
program.memoryExpand(outDataOffs, outDataSize);
MessageCall msg = new MessageCall(
MsgType.fromOpcode(op),
gas, codeAddress, value, inDataOffs, inDataSize,
outDataOffs, outDataSize);
PrecompiledContracts.PrecompiledContract contract =
PrecompiledContracts.getContractForAddress(codeAddress);
if (contract != null) {
program.callToPrecompiledAddress(msg, contract);
} else {
program.callToAddress(msg);
}
program.step();
}
break;
case RETURN: {
DataWord offset = program.stackPop();
DataWord size = program.stackPop();
byte[] hReturn = program.memoryChunk(offset.intValue(), size.intValue());
program.setHReturn(hReturn);
if (logger.isInfoEnabled())
hint = "data: " + Hex.toHexString(hReturn)
+ " offset: " + offset.value()
+ " size: " + size.value();
program.step();
program.stop();
}
break;
case SUICIDE: {
DataWord address = program.stackPop();
program.suicide(address);
if (logger.isInfoEnabled())
hint = "address: " + Hex.toHexString(program.getOwnerAddress().getLast20Bytes());
program.stop();
}
break;
default:
break;
}
program.setPreviouslyExecutedOp(op.val());
if (logger.isInfoEnabled() && !op.equals(CALL)
&& !op.equals(CALLCODE)
&& !op.equals(CREATE))
logger.info(logString, String.format("%5s", "[" + program.getPC() + "]"),
String.format("%-12s",
op.name()), program.getGas().value(),
program.getCallDeep(), hint);
vmCounter++;
} catch (RuntimeException e) {
logger.warn("VM halted: [{}]", e);
program.spendAllGas();
program.resetFutureRefund();
program.stop();
throw e;
} finally {
program.fullTrace();
}
}
public void play(Program program) {
try {
if (vmHook != null) {
vmHook.startPlay(program);
}
// if (program.byTestingSuite()) return;
while (!program.isStopped()) {
this.step(program);
}
if (vmHook != null) {
vmHook.stopPlay(program);
}
} catch (RuntimeException e) {
program.setRuntimeFailure(e);
} catch (StackOverflowError soe){
logger.error("\n !!! StackOverflowError: update your java run command with -Xss32M !!!\n");
System.exit(-1);
}
}
public static void setVmHook(VMHook vmHook) {
VM.vmHook = vmHook;
}
/**
* Utility to calculate new total memory size needed for an operation.
* <br/> Basically just offset + size, unless size is 0, in which case the result is also 0.
*
* @param offset starting position of the memory
* @param size number of bytes needed
* @return offset + size, unless size is 0. In that case memNeeded is also 0.
*/
private static BigInteger memNeeded(DataWord offset, DataWord size) {
return size.isZero() ? BigInteger.ZERO : offset.value().add(size.value());
}
/*
* Dumping the VM state at the current operation in various styles
* - standard Not Yet Implemented
* - standard+ (owner address, program counter, operation, gas left)
* - pretty (stack, memory, storage, level, contract,
* vmCounter, internalSteps, operation
gasBefore, gasCost, memWords)
*/
private void dumpLine(OpCode op, long gasBefore, long gasCost, long memWords, Program program) {
if (CONFIG.dumpStyle().equals("standard+")) {
switch (op) {
case STOP:
case RETURN:
case SUICIDE:
ContractDetails details = program.getStorage()
.getContractDetails(program.getOwnerAddress().getLast20Bytes());
List<DataWord> storageKeys = new ArrayList<>(details.getStorage().keySet());
Collections.sort(storageKeys);
for (DataWord key : storageKeys) {
dumpLogger.trace("{} {}",
Hex.toHexString(key.getNoLeadZeroesData()),
Hex.toHexString(details.getStorage().get(key).getNoLeadZeroesData()));
}
default:
break;
}
String addressString = Hex.toHexString(program.getOwnerAddress().getLast20Bytes());
String pcString = Hex.toHexString(new DataWord(program.getPC()).getNoLeadZeroesData());
String opString = Hex.toHexString(new byte[]{op.val()});
String gasString = Hex.toHexString(program.getGas().getNoLeadZeroesData());
dumpLogger.trace("{} {} {} {}", addressString, pcString, opString, gasString);
} else if (CONFIG.dumpStyle().equals("pretty")) {
dumpLogger.trace(" STACK");
for (DataWord item : program.getStack()) {
dumpLogger.trace("{}", item);
}
dumpLogger.trace(" MEMORY");
String memoryString = program.memoryToString();
if (!"".equals(memoryString))
dumpLogger.trace("{}", memoryString);
dumpLogger.trace(" STORAGE");
ContractDetails details = program.getStorage()
.getContractDetails(program.getOwnerAddress().getLast20Bytes());
List<DataWord> storageKeys = new ArrayList<>(details.getStorage().keySet());
Collections.sort(storageKeys);
for (DataWord key : storageKeys) {
dumpLogger.trace("{}: {}",
key.shortHex(),
details.getStorage().get(key).shortHex());
}
int level = program.getCallDeep();
String contract = Hex.toHexString(program.getOwnerAddress().getLast20Bytes());
String internalSteps = String.format("%4s", Integer.toHexString(program.getPC())).replace(' ', '0').toUpperCase();
dumpLogger.trace("{} | {} | #{} | {} : {} | {} | -{} | {}x32",
level, contract, vmCounter, internalSteps, op,
gasBefore, gasCost, memWords);
}
}
} |
package org.wings.plaf.css;
import java.io.IOException;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.TreeMap;
import org.wings.io.StringBuilderDevice;
import junit.framework.TestCase;
public class UtilsTest extends TestCase {
private String encodeJSToString(Object o) {
StringBuilderDevice sb = new StringBuilderDevice(10);
try {
Utils.encodeJS(sb, o);
} catch (IOException e) {
}
return sb.toString();
}
public void test_encodeJS_anytype() {
assertEquals("null", encodeJSToString(null));
assertEquals("42", encodeJSToString(new Integer(42)));
assertEquals("\"foo\"", encodeJSToString("foo"));
}
public void test_encodeJS_Stringquoting() {
// Empty.
assertEquals("null", encodeJSToString(null));
assertEquals("\"\"", encodeJSToString(""));
// Generic escapes.
assertEquals("\"\\\\\"", encodeJSToString("\\"));
assertEquals("\"\\b\"", encodeJSToString("\b"));
assertEquals("\"\\f\"", encodeJSToString("\f"));
assertEquals("\"\\n\"", encodeJSToString("\n"));
assertEquals("\"\\r\"", encodeJSToString("\r"));
assertEquals("\"\\t\"", encodeJSToString("\t"));
// Special characters are encoded as utf-8 escape
assertEquals("\"\\u0000\"", encodeJSToString("\u0000"));
assertEquals("\"\\u001f\"", encodeJSToString("\u001F"));
assertEquals("\" \"", encodeJSToString("\u0020")); // first non-special
// Seems, that proper UTF-8 encoding currently requires it to be
// escaped for JS. It seemed to have worked before, but .. mmh.
// If this is changed, back this with selenium browser tests.
assertEquals("\"\\u00e4\"", encodeJSToString("ä"));
// And now: all together ;-)
assertEquals("\"foo\\\\\\\"bar\"", encodeJSToString("foo\\\"bar"));
assertEquals("\"\\nfoo\\\\\\\"bar\"", encodeJSToString("\nfoo\\\"bar"));
assertEquals("\"\\nfoo\\\\\\\"b\\u00e4r\\t\"",
encodeJSToString("\nfoo\\\"bär\t"));
}
public void test_JsonArray_rendering() {
List<Object> list = new ArrayList<Object>();
list.add("foo");
list.add(new Integer(42));
assertEquals("[\"foo\",42]",
encodeJSToString(Utils.listToJsArray(list)));
}
public void test_JsonObject_rendering() {
// Use TreeMap to have a certain sequence
final Map<String, Object> map = new TreeMap<String,Object>();
map.put("bar", new Integer(42));
map.put("baz", "s");
final Map<String, Object> nestedMap = new TreeMap<String,Object>();
nestedMap.put("success", new Boolean(true));
map.put("foo", Utils.mapToJsObject(nestedMap));
final Object json = Utils.mapToJsObject(map);
assertEquals("{\"bar\":42,"
+ "\"baz\":\"s\","
+ "\"foo\":{\"success\":true}}",
encodeJSToString(json));
}
} |
package org.codehaus.httpcache4j.util;
import org.codehaus.httpcache4j.cache.CacheItem;
import org.codehaus.httpcache4j.cache.Key;
import org.codehaus.httpcache4j.cache.MemoryCacheStorage;
import org.codehaus.httpcache4j.cache.Vary;
import java.net.URI;
import java.util.LinkedHashMap;
import java.util.Map;
public class InvalidateOnRemoveLRUHashMap extends LinkedHashMap<URI, Map<Vary, CacheItem>> {
private static final long serialVersionUID = -8600084275381371031L;
private final int capacity;
private transient RemoveListener listener;
public InvalidateOnRemoveLRUHashMap(final int capacity) {
super(capacity);
this.capacity = capacity;
}
public InvalidateOnRemoveLRUHashMap(InvalidateOnRemoveLRUHashMap map) {
super(map);
this.capacity = map.capacity;
this.listener = map.listener;
}
public InvalidateOnRemoveLRUHashMap copy() {
return new InvalidateOnRemoveLRUHashMap(this);
}
@Override
protected boolean removeEldestEntry(Map.Entry<URI, Map<Vary, CacheItem>> eldest) {
return size() > capacity;
}
@Override
@Deprecated
public Map<Vary, CacheItem> remove(Object key) {
throw new IllegalArgumentException("Use remove(Key) instead");
}
public CacheItem remove(Key key) {
Map<Vary, CacheItem> varyCacheItemMap = super.get(key.getURI());
if (varyCacheItemMap != null) {
CacheItem item = varyCacheItemMap.remove(key.getVary());
if (listener != null) {
listener.onRemoveFromMap(key);
}
if (varyCacheItemMap.isEmpty()) {
super.remove(key.getURI());
}
return item;
}
return null;
}
public void remove(URI uri) {
Map<Vary, CacheItem> varyCacheItemMap = super.get(uri);
if (varyCacheItemMap != null) {
for (Vary vary : varyCacheItemMap.keySet()) {
Key key = Key.create(uri, vary);
if (listener != null) {
listener.onRemoveFromMap(key);
}
}
super.remove(uri);
}
}
public void setListener(RemoveListener listener) {
this.listener = listener;
}
public static interface RemoveListener {
public void onRemoveFromMap(Key key);
}
} |
package org.javarosa.service.transport.securehttp.cache;
import java.io.IOException;
import java.io.InputStream;
import java.util.Hashtable;
import java.util.Random;
import org.javarosa.core.util.MD5;
import org.javarosa.core.util.MD5InputStream;
import org.javarosa.core.util.OrderedHashtable;
import org.javarosa.service.transport.securehttp.AuthUtils;
import org.javarosa.service.transport.securehttp.AuthenticatedHttpTransportMessage;
/**
* A digest authorization response object which accepts the
* various parameters associated with digest authentication
* challenges, and creates the appropriate authorization
* header for them.
*
* It is also a cachable response header, capable of creating
* a new response later for additional messages with the same
* credentails.
*
* @author ctsims
*
*/
public class DigestAuthResponse implements AuthCacheRecord {
public static final String QOP_UNSPECIFIED = "unspecified";
public static final String QOP_AUTH = "auth";
public static final String QOP_AUTH_INT = "auth-int";
private String HA1;
private String URL;
private Hashtable<String, String> parameters;
public DigestAuthResponse(String URL, String HA1) {
this(URL, HA1, new OrderedHashtable());
}
public DigestAuthResponse(String URL, String HA1, Hashtable<String, String> parameters) {
this.URL = URL;
this.parameters = parameters;
this.HA1 = HA1;
}
public String getUrl() {
return URL;
}
/*
* (non-Javadoc)
* @see org.javarosa.service.transport.securehttp.cache.AuthCacheRecord#invalidates(org.javarosa.service.transport.securehttp.cache.AuthCacheRecord)
*/
public boolean invalidates(AuthCacheRecord record) {
//this crashes with a null pointer if we try to do more than one digest-auth connection in a
//commcare session -- turning off for now
return true;
/*
if(record.getUrl().equals(this.URL)) { return true; };
//For Digest Auth messages, the _domain_ should also be
//a mechanism of invalidation
if(record instanceof DigestAuthResponse) {
DigestAuthResponse drecord = (DigestAuthResponse)record;
if(this.parameters.get("domain").equals(drecord.parameters.get("domain"))) {
return true;
}
}
return false;
*/
}
public String get(String key) {
return parameters.get(key);
}
public String put(String key, String value) {
return parameters.put(key,value);
}
/**
* Builds an auth response for the provided message based on the
* parameters currently available for authentication
* @param message
* @return An Authenticate HTTP header for the message if one could be
* created, null otherwise.
*/
public String buildResponse(AuthenticatedHttpTransportMessage message) {
String qop = parameters.get("qop");
String nonce= AuthUtils.unquote(parameters.get("nonce"));
String uri = AuthUtils.unquote(parameters.get("uri"));
String method = message.getMethod();
String HA2 = null;
if(qop != DigestAuthResponse.QOP_AUTH_INT) {
HA2 = AuthUtils.MD5(method + ":" + uri);
} else {
InputStream stream = message.getContentStream();
String entityBody;
if(stream == null){
entityBody = MD5.toHex("".getBytes());
} else {
try {
entityBody = new MD5InputStream(stream).getHashCode();
} catch (IOException e) {
//Problem calculating MD5 from content stream
e.printStackTrace();
return null;
}
}
HA2 = AuthUtils.MD5(method + ":" + uri);
}
if(qop == DigestAuthResponse.QOP_UNSPECIFIED) {
//RFC 2069 Auth
parameters.put("response", AuthUtils.quote(AuthUtils.MD5(HA1 + ":" + nonce + ":" + HA2)));
} else {
String nc = getNonceCount();
//Generate client nonce
String cnonce = getClientNonce();
//Calculate response
parameters.put("response", AuthUtils.quote(AuthUtils.MD5(HA1 + ":" + nonce + ":" + nc + ":" + cnonce + ":" + qop + ":" + HA2)));
}
return "Digest " + AuthUtils.encodeQuotedParameters(parameters);
}
private String getClientNonce() {
if(!parameters.contains("cnonce")) {
Random r = new Random();
byte[] b = new byte[8];
for(int i = 0; i < b.length ; ++i) {
b[i] = (byte)r.nextInt(256);
}
String cnonce = MD5.toHex(b);
parameters.put("cnonce",AuthUtils.quote(cnonce));
return cnonce;
} else {
return AuthUtils.unquote(parameters.get("cnonce"));
}
}
private String getNonceCount() {
//The nonce count represents the number of
//times that the nonce has been used for authentication
//and must be incremented for each request. Otherwise
//the nonce data becomes unavailable.
if(!parameters.contains("nc")) {
String nc = "00000001";
parameters.put("nc",nc);
return nc;
} else {
String nc = parameters.get("nc");
int count = Integer.parseInt(nc);
count+=1;
nc = String.valueOf(count);
//Buffer to the left
while(nc.length() < 8) {
nc = "0" + nc;
}
parameters.put("nc",nc);
return nc;
}
}
public boolean validFor(String URI) {
//TODO: Try to guess better probably based on
//domain prefix
if(this.URL.equals(URI)) {
return true;
} else {
return false;
}
}
/*
* (non-Javadoc)
* @see org.javarosa.service.transport.securehttp.cache.AuthCacheRecord#retrieve(org.javarosa.service.transport.securehttp.AuthenticatedHttpTransportMessage)
*/
public String retrieve(AuthenticatedHttpTransportMessage message) {
//TODO: Extract the URI here and replace the one in the current parameter set
//so that we can use the same nonce on multiple URI's.
return buildResponse(message);
}
} |
package org.junit.platform.commons.support;
import static org.apiguardian.api.API.Status.MAINTAINED;
import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Optional;
import org.apiguardian.api.API;
import org.junit.platform.commons.util.AnnotationUtils;
import org.junit.platform.commons.util.ReflectionUtils;
/**
* Common annotation support.
*
* @since 1.0
*/
@API(status = MAINTAINED, since = "5.0")
public final class AnnotationSupport {
///CLOVER:OFF
private AnnotationSupport() {
/* no-op */
}
///CLOVER:ON
/**
* Determine if an annotation of {@code annotationType} is either
* <em>present</em> or <em>meta-present</em> on the supplied
* {@code element}.
*
* @see #findAnnotation(AnnotatedElement, Class)
*/
public static boolean isAnnotated(AnnotatedElement element, Class<? extends Annotation> annotationType) {
return AnnotationUtils.isAnnotated(element, annotationType);
}
/**
* Find the first annotation of {@code annotationType} that is either
* <em>present</em> or <em>meta-present</em> on the supplied optional
* {@code element}.
*
* @see #findAnnotation(AnnotatedElement, Class)
*/
public static <A extends Annotation> Optional<A> findAnnotation(Optional<? extends AnnotatedElement> element,
Class<A> annotationType) {
return AnnotationUtils.findAnnotation(element, annotationType);
}
/**
* Find the first annotation of {@code annotationType} that is either
* <em>directly present</em>, <em>meta-present</em>, or <em>indirectly
* present</em> on the supplied {@code element}.
*
* <p>If the element is a class and the annotation is neither <em>directly
* present</em> nor <em>meta-present</em> on the class, this method will
* additionally search on interfaces implemented by the class before
* finding an annotation that is <em>indirectly present</em> on the class.
*/
public static <A extends Annotation> Optional<A> findAnnotation(AnnotatedElement element, Class<A> annotationType) {
return AnnotationUtils.findAnnotation(element, annotationType);
}
/**
* Find all <em>repeatable</em> {@linkplain Annotation annotations} of
* {@code annotationType} that are either <em>present</em>, <em>indirectly
* present</em>, or <em>meta-present</em> on the supplied {@link AnnotatedElement}.
*
* <p>This method extends the functionality of
* {@link java.lang.reflect.AnnotatedElement#getAnnotationsByType(Class)}
* with additional support for meta-annotations.
*
* <p>In addition, if the element is a class and the repeatable annotation
* is {@link java.lang.annotation.Inherited @Inherited}, this method will
* search on superclasses first in order to support top-down semantics.
* The result is that this algorithm finds repeatable annotations that
* would be <em>shadowed</em> and therefore not visible according to Java's
* standard semantics for inherited, repeatable annotations, but most
* developers will naturally assume that all repeatable annotations in JUnit
* are discovered regardless of whether they are declared stand-alone, in a
* container, or as a meta-annotation (e.g., multiple declarations of
* {@code @ExtendWith} within a test class hierarchy).
*
* <p>If the element is a class and the repeatable annotation is not
* discovered within the class hierarchy, this method will additionally
* search on interfaces implemented by each class in the hierarchy.
*
* <p>If the supplied {@code element} is {@code null}, this method simply
* returns an empty list.
*
* @param element the element to search on, potentially {@code null}
* @param annotationType the repeatable annotation type to search for; never {@code null}
* @return the list of all such annotations found; neither {@code null} nor mutable
* @see java.lang.annotation.Repeatable
* @see java.lang.annotation.Inherited
*/
public static <A extends Annotation> List<A> findRepeatableAnnotations(AnnotatedElement element,
Class<A> annotationType) {
return AnnotationUtils.findRepeatableAnnotations(element, annotationType);
}
/**
* Find all {@code public} {@linkplain Field fields} of the supplied class
* or interface that are of the specified {@code fieldType} and annotated
* or <em>meta-annotated</em> with the specified {@code annotationType}.
*
* <p>Consult the Javadoc for {@link Class#getFields()} for details on
* inheritance and ordering.
*
* @param clazz the class or interface in which to find the fields; never {@code null}
* @param fieldType the type of field to find; never {@code null}
* @param annotationType the annotation type to search for; never {@code null}
* @return the list of all such fields found; neither {@code null} nor mutable
* @see Class#getFields()
*/
public static List<Field> findPublicAnnotatedFields(Class<?> clazz, Class<?> fieldType,
Class<? extends Annotation> annotationType) {
return AnnotationUtils.findPublicAnnotatedFields(clazz, fieldType, annotationType);
}
/**
* Find all {@linkplain Method methods} of the supplied class or interface
* that are annotated or <em>meta-annotated</em> with the specified
* {@code annotationType}.
*
* @param clazz the class or interface in which to find the methods; never {@code null}
* @param annotationType the annotation type to search for; never {@code null}
* @param traversalMode the hierarchy traversal mode; never {@code null}
* @return the list of all such methods found; neither {@code null} nor mutable
*/
public static List<Method> findAnnotatedMethods(Class<?> clazz, Class<? extends Annotation> annotationType,
HierarchyTraversalMode traversalMode) {
return AnnotationUtils.findAnnotatedMethods(clazz, annotationType,
ReflectionUtils.HierarchyTraversalMode.valueOf(traversalMode.name()));
}
} |
package org.languagetool.rules.de;
import org.languagetool.AnalyzedSentence;
import org.languagetool.AnalyzedTokenReadings;
import org.languagetool.rules.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
/**
* A rule that warns on long sentences. Note that this rule is off by default.
*
* @since 3.9
*/
public class LongSentenceRule extends org.languagetool.rules.LongSentenceRule {
private static final int DEFAULT_MAX_WORDS = 40;
private static final boolean DEFAULT_INACTIVE = true;
/**
* @param defaultActive allows default granularity
* @since 3.7
*/
public LongSentenceRule(ResourceBundle messages, int maxSentenceLength, boolean defaultActive) {
super(messages);
super.setCategory(Categories.STYLE.getCategory(messages));
setLocQualityIssueType(ITSIssueType.Style);
addExamplePair(Example.wrong("<marker>Dies ist ein Bandwurmsatz, der immer weiter geht, obwohl das kein guter Stil ist, den man eigentlich berücksichtigen sollte, obwohl es auch andere Meinungen gibt, die aber in der Minderzahl sind, weil die meisten Autoren sich doch an die Stilvorgaben halten, wenn auch nicht alle, was aber letztendlich wiederum eine Sache des Geschmacks ist</marker>."),
Example.fixed("<marker>Dies ist ein kurzer Satz.</marker>"));
if (defaultActive) {
setDefaultOn();
}
maxWords = maxSentenceLength;
}
/**
* @param maxSentenceLength the maximum sentence length that does not yet trigger a match
* @since 2.4
*/
public LongSentenceRule(ResourceBundle messages, int maxSentenceLength) {
this(messages, maxSentenceLength, DEFAULT_INACTIVE);
}
/**
* Creates a rule with the default maximum sentence length (40 words).
*/
public LongSentenceRule(ResourceBundle messages) {
this(messages, DEFAULT_MAX_WORDS, DEFAULT_INACTIVE);
setDefaultOn();
}
@Override
public String getId() {
return "DE_TOO_LONG_SENTENCE_" + maxWords;
}
@Override
public String getDescription() {
return "Sehr langer Satz (mehr als " + maxWords + " Worte)";
}
@Override
public String getMessage() {
return "Dieser Satz ist sehr lang (mehr als " + maxWords + " Worte).";
}
private boolean isWordCount(String tokenText) {
if (tokenText.length() > 0 &&
((tokenText.charAt(0) >= 'A' && tokenText.charAt(0) <= 'Z')
|| (tokenText.charAt(0) >= 'a' && tokenText.charAt(0) <= 'z')
|| tokenText.charAt(0) == 'ä' || tokenText.charAt(0) == 'ö' || tokenText.charAt(0) == 'ü'
|| tokenText.charAt(0) == 'Ä' || tokenText.charAt(0) == 'Ö' || tokenText.charAt(0) == 'Ü')) {
return true;
} else {
return false;
}
}
@Override
public RuleMatch[] match(AnalyzedSentence sentence) throws IOException {
List<RuleMatch> ruleMatches = new ArrayList<>();
AnalyzedTokenReadings[] tokens = sentence.getTokensWithoutWhitespace();
String msg = getMessage();
if (tokens.length < maxWords + 1) { // just a short-circuit
return toRuleMatchArray(ruleMatches);
}
int i = 0;
List<Integer> fromPos = new ArrayList<Integer>();
List<Integer> toPos = new ArrayList<Integer>();
while (i < tokens.length) {
for (; i < tokens.length && !isWordCount(tokens[i].getToken()); i++) ;
if (i < tokens.length) {
fromPos.add(tokens[i].getStartPos());
toPos.add(tokens[i].getEndPos());
}
int numWords = 1;
// Text before and after ':' and ';' is handled as separated sentences
// Direct speech is splitted
while (i < tokens.length && !tokens[i].getToken().equals(":") && !tokens[i].getToken().equals(";")
&& ((i < tokens.length - 1 && !tokens[i + 1].getToken().equals(","))
|| (!tokens[i].getToken().equals("“") && !tokens[i].getToken().equals("»")
&& !tokens[i].getToken().equals("«") && !tokens[i].getToken().equals("\"")))) {
if (isWordCount(tokens[i].getToken())) {
toPos.set(toPos.size() - 1, tokens[i].getEndPos());
numWords++;
} else if (tokens[i].getToken().equals("(") || tokens[i].getToken().equals("{")
|| tokens[i].getToken().equals("[")) { // The Text between brackets is handled as separate sentence
String endChar;
if (tokens[i].getToken().equals("(")) endChar = ")";
else if (tokens[i].getToken().equals("{")) endChar = "}";
else endChar = "]";
int numWordsInt = 0;
int fromPosInt = 0;
int toPosInt = 0;
int k;
for (k = i + 1; k < tokens.length && !tokens[k].getToken().equals(endChar) && !isWordCount(tokens[k].getToken()); k++)
;
if (k < tokens.length) {
fromPosInt = tokens[k].getStartPos();
toPosInt = tokens[k].getEndPos();
}
for (k++; k < tokens.length && !tokens[k].getToken().equals(endChar); k++) {
if (isWordCount(tokens[k].getToken())) {
toPosInt = tokens[k].getEndPos();
numWordsInt++;
}
}
if (k < tokens.length) {
if (numWordsInt > maxWords) {
RuleMatch ruleMatch = new RuleMatch(this, fromPosInt, toPosInt, msg);
ruleMatches.add(ruleMatch);
}
for (i = k; i < tokens.length && !isWordCount(tokens[i].getToken()); i++) ;
if (i < tokens.length) {
fromPos.add(tokens[i].getStartPos());
toPos.add(tokens[i].getEndPos());
numWords++;
}
}
}
i++;
}
if (numWords > maxWords) {
for (int j = 0; j < fromPos.size(); j++) {
RuleMatch ruleMatch = new RuleMatch(this, fromPos.get(j), toPos.get(j), msg);
ruleMatches.add(ruleMatch);
}
} else {
for (int j = fromPos.size() - 1; j >= 0; j
fromPos.remove(j);
toPos.remove(j);
}
}
}
return toRuleMatchArray(ruleMatches);
}
} |
package net.somethingdreadful.MAL.database;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import com.crashlytics.android.Crashlytics;
import net.somethingdreadful.MAL.api.MALModels.RecordStub;
import java.util.ArrayList;
import java.util.List;
public class Query {
String queryString = "";
private static SQLiteDatabase db;
public static Query newQuery(SQLiteDatabase db) {
Query.db = db;
return new Query();
}
public Query selectFrom(String column, String table) {
queryString += " SELECT " + column + " FROM " + table;
return this;
}
public Query innerJoinOn(String table1, String column1, String column2) {
queryString += " INNER JOIN " + table1 + " ON " + column1 + " = " + column2;
return this;
}
public Query where(String column1, String value) {
queryString += " WHERE " + column1 + " = '" + value + "'";
return this;
}
public Query whereEqGr(String column1, String value) {
queryString += " WHERE " + column1 + " >= '" + value + "'";
return this;
}
public Query isNotNull(String column1) {
queryString += " WHERE " + column1 + " IS NOT NULL ";
return this;
}
public Query andIsNotNull(String column1) {
queryString += " AND " + column1 + " IS NOT NULL ";
return this;
}
public Query andEquals(String column1, String value) {
queryString += " AND " + column1 + " = '" + value + "'";
return this;
}
public Query OrderBy(int type, String column) {
switch (type) {
case 1: // Name
queryString += " ORDER BY " + column + " COLLATE NOCASE";
break;
}
return this;
}
public Cursor run() {
try {
Cursor cursor = db.rawQuery(queryString, new String[]{});
queryString = "";
return cursor;
} catch (Exception e) {
log("run", e.getMessage(), true);
}
return null;
}
/**
* Update or insert records.
*
* @param table The table where the record should be updated
* @param cv The ContentValues which should be updated
* @param id The ID of the record
*/
public int updateRecord(String table, ContentValues cv, int id) {
int updateResult = db.update(table, cv, DatabaseTest.COLUMN_ID + " = " + id, new String[]{});
if (updateResult == 0)
return (int) db.insert(table, null, cv);
return updateResult;
}
/**
* Update or insert records.
*
* @param table The table where the record should be updated
* @param cv The ContentValues which should be updated
* @param username The username of the record
*/
public int updateRecord(String table, ContentValues cv, String username) {
int updateResult = db.update(table, cv, "username" + " = '" + username + "'", new String[]{});
if (updateResult == 0)
return (int) db.insert(table, null, cv);
return updateResult;
}
/**
* The query to string.
*
* @return String Query
*/
@Override
public String toString() {
return queryString;
}
/**
* Update relations.
*
* @param table The relation table name
* @param relationType The relation type
* @param id The record id which should be related with
* @param recordStubs The records
*/
public void updateRelation(String table, String relationType, int id, List<RecordStub> recordStubs) {
if (id <= 0)
log("updateRelation", "error saving relation: id <= 0", true);
if (recordStubs == null || recordStubs.size() == 0)
return;
boolean relatedRecordExists;
String recordTable;
try {
for (RecordStub relation : recordStubs) {
recordTable = relation.isAnime() ? DatabaseTest.TABLE_ANIME : DatabaseTest.TABLE_MANGA;
if (!recordExists(DatabaseTest.COLUMN_ID, recordTable, String.valueOf(relation.getId()))) {
ContentValues cv = new ContentValues();
cv.put(DatabaseTest.COLUMN_ID, relation.getId());
cv.put("title", relation.getTitle());
relatedRecordExists = db.insert(recordTable, null, cv) > 0;
} else {
relatedRecordExists = true;
}
if (relatedRecordExists) {
ContentValues cv = new ContentValues();
cv.put(DatabaseTest.COLUMN_ID, id);
cv.put("relationId", relation.getId());
cv.put("relationType", relationType);
db.replace(table, null, cv);
} else {
log("updateRelation", "error saving relation: record does not exist", true);
}
}
} catch (Exception e) {
log("updateRelation", e.getMessage(), true);
e.printStackTrace();
}
}
/**
* Update Links for records.
*
* @param id The anime/manga ID
* @param list Arraylist of strings
* @param refTable The table where the references will be placed
* @param table The table where the records will be placed
* @param column The references column name
* <p/>
* Query.newQuery(db).updateLink(DatabaseTest.TABLE_GENRES, DatabaseTest.TABLE_ANIME_GENRES, anime.getId(), anime.getGenres(), "genre_id");
*/
public void updateLink(String table, String refTable, int id, ArrayList<String> list, String column) {
if (id <= 0)
log("updateLink", "error saving link: id <= 0", true);
if (list == null || list.size() == 0)
return;
String columnID = refTable.contains("anime") ? "anime_id" : "manga_id";
// delete old links
db.delete(refTable, columnID + " = ?", new String[]{String.valueOf(id)});
try {
for (String item : list) {
int linkID = getRecordId(table, item);
if (linkID != -1) {
// get the refID
ContentValues gcv = new ContentValues();
gcv.put(columnID, id);
gcv.put(column, linkID);
db.insert(refTable, null, gcv);
}
}
} catch (Exception e) {
log("updateLink", e.getMessage(), true);
}
}
/**
* Update titles for records.
*
* @param id The anime/manga ID
* @param anime True if the record is an anime type
* @param jp Arraylist of strings
* @param en Arraylist of strings
* @param sy Arraylist of strings
*/
public void updateTitles(int id, boolean anime, ArrayList<String> jp, ArrayList<String> en, ArrayList<String> sy, ArrayList<String> ro) {
String table = anime ? DatabaseTest.TABLE_ANIME_OTHER_TITLES : DatabaseTest.TABLE_MANGA_OTHER_TITLES;
// delete old links
db.delete(table, DatabaseTest.COLUMN_ID + " = ?", new String[]{String.valueOf(id)});
updateTitles(id, table, DatabaseTest.TITLE_TYPE_JAPANESE, jp);
updateTitles(id, table, DatabaseTest.TITLE_TYPE_ENGLISH, en);
updateTitles(id, table, DatabaseTest.TITLE_TYPE_SYNONYM, sy);
updateTitles(id, table, DatabaseTest.TITLE_TYPE_ROMAJI, ro);
}
/**
* Update Links for records.
*
* @param id The anime/manga ID
* @param table The table name where the record should be put
* @param titleType The type of title
* @param list Arraylist of strings
*/
private void updateTitles(int id, String table, int titleType, ArrayList<String> list) {
if (id <= 0)
log("updateTitles", "error saving relation: id <= 0", true);
if (list == null || list.size() == 0)
return;
try {
for (String item : list) {
ContentValues gcv = new ContentValues();
gcv.put(DatabaseTest.COLUMN_ID, id);
gcv.put("titleType", titleType);
gcv.put("title", item);
db.insert(table, null, gcv);
}
} catch (Exception e) {
log("updateTitles", e.getMessage(), true);
e.printStackTrace();
}
}
/**
* Get titles from the database.
*
* @param id The anime or manga ID
* @param anime True if the record is an anime
* @param titleType The title type
* @return
*/
public ArrayList<String> getTitles(int id, boolean anime, int titleType) {
ArrayList<String> result = new ArrayList<>();
Cursor cursor = selectFrom("*", anime ? DatabaseTest.TABLE_ANIME_OTHER_TITLES : DatabaseTest.TABLE_MANGA_OTHER_TITLES)
.where(DatabaseTest.COLUMN_ID, String.valueOf(id)).andEquals("titleType", String.valueOf(titleType))
.run();
if (cursor != null && cursor.moveToFirst()) {
do {
result.add(cursor.getString(2));
} while (cursor.moveToNext());
cursor.close();
}
return result;
}
/**
* Get a record by the ID.
*
* @param table The table where the record should be in
* @param item The title of the record
* @return int Number of record
*/
private int getRecordId(String table, String item) {
Integer result = null;
Cursor cursor = Query.newQuery(db).selectFrom("*", table).where("title", item).run();
if (cursor.moveToFirst())
result = cursor.getInt(0);
cursor.close();
if (result == null) {
ContentValues cv = new ContentValues();
cv.put("title", item);
Long addResult = db.insert(table, null, cv);
if (addResult > -1)
result = addResult.intValue();
}
return result == null ? -1 : result;
}
/**
* Log events.
*
* @param method The method name to find easy crashes
* @param message The thrown message
* @param error True if it is an error else false
*/
@SuppressWarnings("deprecation")
private void log(String method, String message, boolean error) {
Crashlytics.log(error ? Log.ERROR : Log.INFO, "MALX", "Query." + method + "(" + toString() + "): " + message);
}
/**
* Check if a records already exists.
*
* @param column The column where we can find the record
* @param columnValue The ID
* @param table The table where we can find the record
* @return boolean True if it exists
*/
private boolean recordExists(String column, String table, String columnValue) {
Cursor cursor = selectFrom(column, table).where(column, columnValue).run();
boolean result = cursor.moveToFirst();
cursor.close();
return result;
}
/**
* Get relations.
*
* @param Id The record ID
* @param relationTable The table that contains relations
* @param relationType The type of the relation (String with number)
* @param anime True if the RecordStub are anime items
* @return Arraylist of RecordStub
*/
public ArrayList<RecordStub> getRelation(Integer Id, String relationTable, String relationType, boolean anime) {
ArrayList<RecordStub> result = new ArrayList<>();
try {
String name = "mr.title";
String id = "mr." + DatabaseTest.COLUMN_ID;
Cursor cursor = selectFrom(id + ", " + name, (anime ? DatabaseTest.TABLE_ANIME : DatabaseTest.TABLE_MANGA) + " mr")
.innerJoinOn(relationTable + " rr", id, "rr.relationId")
.where("rr." + DatabaseTest.COLUMN_ID, String.valueOf(Id)).andEquals("rr.relationType", relationType).run();
if (cursor != null && cursor.moveToFirst()) {
do {
RecordStub recordStub = new RecordStub();
recordStub.setId(cursor.getInt(0), anime);
recordStub.setTitle(cursor.getString(1));
result.add(recordStub);
} while (cursor.moveToNext());
cursor.close();
}
} catch (Exception e) {
log("getRelation", e.getMessage(), true);
}
return result;
}
/**
* Get ArrayLists that are separated in the DB.
*
* @param id The record ID
* @param relTable The main table
* @param table The table which is separated in anime or manga records
* @param column The column name of the id's
* @param anime If the record is an anime.
* @return
*/
public ArrayList<String> getArrayList(int id, String relTable, String table, String column, boolean anime) {
ArrayList<String> result = new ArrayList<>();
try {
Cursor cursor = selectFrom("*", table)
.innerJoinOn(relTable, table + "." + column, relTable + "." + DatabaseTest.COLUMN_ID)
.where(anime ? "anime_id" : "manga_id", String.valueOf(id))
.run();
if (cursor != null && cursor.moveToFirst()) {
do
result.add(cursor.getString(3));
while (cursor.moveToNext());
cursor.close();
}
} catch (Exception e) {
log("getArrayList", e.getMessage(), true);
}
return result;
}
} |
package polytheque.view;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import org.omg.CORBA.Object;
import com.toedter.calendar.JDateChooser;
@SuppressWarnings("serial")
public class AppliReserverJeu extends JPanel implements ActionListener
{
private TacheDAffichage tacheDAffichageDeLApplication;
private JButton boutonRetourAccueil;
private JButton boutonValider;
private JTextField searchContent;
private JTextField ExtensionContent;
public AppliReserverJeu(TacheDAffichage afficheAppli)
{
this.tacheDAffichageDeLApplication = afficheAppli;
creerPanneauRecherche();
creerPanneauExtension();
creerPanneauDate();
this.boutonRetourAccueil = new JButton();
this.boutonRetourAccueil.setBounds(400, 700, 100, 30);
this.boutonRetourAccueil.addActionListener(this);
this.add(boutonRetourAccueil);
}
private void creerPanneauExtension()
{
JPanel ExtensionPanel = new JPanel();
ExtensionPanel.setPreferredSize(new Dimension(TacheDAffichage.LARGEUR, 50));
JLabel labelSearch = new JLabel("Recherche par nom :");
labelSearch.setBounds(300, 400, 100, 30);
ExtensionPanel.add(labelSearch);
this.ExtensionContent = new JTextField();
this.ExtensionContent.setBounds(450,400, 100, 30);
this.ExtensionContent.setColumns(10);
ExtensionPanel.add(this.searchContent, BorderLayout.NORTH);
this.add(ExtensionPanel);
}
private void creerPanneauRecherche()
{
JPanel searchPanel = new JPanel();
searchPanel.setPreferredSize(new Dimension(TacheDAffichage.LARGEUR, 50));
JLabel labelSearch = new JLabel("Recherche par nom :");
labelSearch.setBounds(400, 0, 100, 30);
searchPanel.add(labelSearch);
this.searchContent = new JTextField();
this.searchContent.setBounds(450, 0, 100, 30);
this.searchContent.setColumns(10);
searchPanel.add(this.searchContent, BorderLayout.NORTH);
this.add(searchPanel);
}
private void creerPanneauDate() {
JPanel DatePanel = new JPanel();
DatePanel.setPreferredSize(new Dimension(TacheDAffichage.LARGEUR, 50));
JLabel labelDate = new JLabel("Cliquez sur la date a laquelle vous voudriez emprunter le jeux :");
labelDate.setBounds(400, 150, 100, 30);
DatePanel.add(labelDate);
JDateChooser dateChooser = new JDateChooser();
dateChooser.setBounds(450, 150, 100, 30);
DatePanel.add(dateChooser);
this.add(DatePanel);
this.boutonValider = new JButton("Valider");
this.boutonValider.setBounds(400, 500, 100, 30);
this.boutonValider.addActionListener(this);
this.add(boutonValider);
}
public void rafraichir(Object object) {
this.removeAll();
this.add(null,object);
this.updateUI();
}
public void creerPanneauDateFin()
{
JPanel DateFinPanel = new JPanel();
DateFinPanel.setPreferredSize(new Dimension(TacheDAffichage.LARGEUR, 50));
JLabel labelDate = new JLabel("Cliquez sur la date a laquelle vous voudriez rendre le jeux :");
labelDate.setBounds(400, 250, 100, 100);
DateFinPanel.add(labelDate);
JDateChooser dateChooser = new JDateChooser();
dateChooser.setBounds(450, 300, 100, 100);
DateFinPanel.add(dateChooser);
this.add(DateFinPanel);
}
public void actionPerformed(ActionEvent e)
{
JButton boutonSelectionne = (JButton) e.getSource();
if (boutonSelectionne == this.boutonValider)
{
this.tacheDAffichageDeLApplication.createReservation(this.tacheDAffichageDeLApplication.getAdherentByNothing().getIdAdherent(),this.tacheDAffichageDeLApplication.getJeu(this.searchContent.getText()).getIdJeu(),20);
this.tacheDAffichageDeLApplication.afficherMessage("Reservation confirmee"," Confirmation", JOptionPane.INFORMATION_MESSAGE);
this.tacheDAffichageDeLApplication.afficherAccueil();
}
else if (boutonSelectionne == this.boutonRetourAccueil)
{
this.tacheDAffichageDeLApplication.afficherAccueil();;
}
}
} |
package org.xbill.DNS;
import java.io.*;
import java.text.*;
import java.util.*;
import org.xbill.DNS.utils.*;
/**
* A representation of a domain name.
*
* @author Brian Wellington
*/
public class Name implements Comparable {
private static final int LABEL_NORMAL = 0;
private static final int LABEL_COMPRESSION = 0xC0;
private static final int LABEL_MASK = 0xC0;
private byte [] name;
private long offsets;
private int hashcode;
private static final byte [] emptyLabel = new byte[] {(byte)0};
private static final byte [] wildLabel = new byte[] {(byte)1, (byte)'*'};
/** The root name */
public static final Name root;
/** The maximum length of a Name */
private static final int MAXNAME = 255;
/** The maximum length of labels a label a Name */
private static final int MAXLABEL = 63;
/** The maximum number of labels in a Name */
private static final int MAXLABELS = 128;
/** The maximum number of cached offsets */
private static final int MAXOFFSETS = 7;
/* Used for printing non-printable characters */
private static final DecimalFormat byteFormat = new DecimalFormat();
/* Used to efficiently convert bytes to lowercase */
private static final byte lowercase[] = new byte[256];
/* Used in wildcard names. */
private static final Name wild;
static {
byteFormat.setMinimumIntegerDigits(3);
for (int i = 0; i < lowercase.length; i++) {
if (i < 'A' || i > 'Z')
lowercase[i] = (byte)i;
else
lowercase[i] = (byte)(i - 'A' + 'a');
}
root = new Name();
wild = new Name();
root.appendSafe(emptyLabel, 0, 1);
wild.appendSafe(wildLabel, 0, 1);
}
private
Name() {
}
private final void
dump(String prefix) {
String s;
try {
s = toString();
} catch (Exception e) {
s = "<unprintable>";
}
System.out.println(prefix + ": " + s);
byte labels = labels();
for (int i = 0; i < labels; i++)
System.out.print(offset(i) + " ");
System.out.println("");
for (int i = 0; name != null && i < name.length; i++)
System.out.print((name[i] & 0xFF) + " ");
System.out.println("");
}
private final void
setoffset(int n, int offset) {
if (n >= MAXOFFSETS)
return;
int shift = 8 * (7 - n);
offsets &= (~(0xFFL << shift));
offsets |= ((long)offset << shift);
}
private final int
offset(int n) {
if (n < 0 || n >= getlabels())
throw new IllegalArgumentException("label out of range");
if (n < MAXOFFSETS) {
int shift = 8 * (7 - n);
return ((int)(offsets >>> shift) & 0xFF);
} else {
int pos = offset(MAXOFFSETS - 1);
for (int i = MAXOFFSETS - 1; i < n; i++)
pos += (name[pos] + 1);
return (pos);
}
}
private final void
setlabels(byte labels) {
offsets &= ~(0xFF);
offsets |= labels;
}
private final byte
getlabels() {
return (byte)(offsets & 0xFF);
}
private static final void
copy(Name src, Name dst) {
dst.name = src.name;
dst.offsets = src.offsets;
}
private final void
append(byte [] array, int start, int n) throws NameTooLongException {
int length = (name == null ? 0 : (name.length - offset(0)));
int alength = 0;
for (int i = 0, pos = start; i < n; i++) {
int len = array[pos];
if (len > MAXLABEL)
throw new IllegalStateException("invalid label");
len++;
pos += len;
alength += len;
}
int newlength = length + alength;
if (newlength > MAXNAME)
throw new NameTooLongException();
byte labels = getlabels();
int newlabels = labels + n;
if (newlabels > MAXLABELS)
throw new IllegalStateException("too many labels");
byte [] newname = new byte[newlength];
if (length != 0)
System.arraycopy(name, offset(0), newname, 0, length);
System.arraycopy(array, start, newname, length, alength);
name = newname;
for (int i = 0, pos = length; i < n; i++) {
setoffset(labels + i, pos);
pos += (newname[pos] + 1);
}
setlabels((byte) newlabels);
}
private final void
appendFromString(byte [] array, int start, int n) throws TextParseException {
try {
append(array, start, n);
}
catch (NameTooLongException e) {
throw new TextParseException("Name too long");
}
}
private final void
appendSafe(byte [] array, int start, int n) {
try {
append(array, start, n);
}
catch (NameTooLongException e) {
}
}
/**
* Create a new name from a string and an origin
* @param s The string to be converted
* @param origin If the name is not absolute, the origin to be appended
* @deprecated As of dnsjava 1.3.0, replaced by <code>Name.fromString</code>.
*/
public
Name(String s, Name origin) {
Name n;
try {
n = Name.fromString(s, origin);
}
catch (TextParseException e) {
StringBuffer sb = new StringBuffer(s);
if (origin != null)
sb.append("." + origin);
sb.append(": "+ e.getMessage());
System.err.println(sb.toString());
return;
}
if (!n.isAbsolute() && !Options.check("pqdn") &&
n.getlabels() > 1 && n.getlabels() < MAXLABELS - 1)
{
/*
* This isn't exactly right, but it's close.
* Partially qualified names are evil.
*/
n.appendSafe(emptyLabel, 0, 1);
}
copy(n, this);
}
/**
* Create a new name from a string
* @param s The string to be converted
* @deprecated as of dnsjava 1.3.0, replaced by <code>Name.fromString</code>.
*/
public
Name(String s) {
this (s, null);
}
/**
* Create a new name from a string and an origin. This does not automatically
* make the name absolute; it will be absolute if it has a trailing dot or an
* absolute origin is appended.
* @param s The string to be converted
* @param origin If the name is not absolute, the origin to be appended.
* @throws TextParseException The name is invalid.
*/
public static Name
fromString(String s, Name origin) throws TextParseException {
Name name = new Name();
if (s.equals(""))
throw new TextParseException("empty name");
else if (s.equals("@")) {
if (origin == null)
return name;
return origin;
} else if (s.equals("."))
return (root);
int labelstart = -1;
int pos = 1;
byte [] label = new byte[MAXLABEL + 1];
boolean escaped = false;
int digits = 0;
int intval = 0;
boolean absolute = false;
for (int i = 0; i < s.length(); i++) {
byte b = (byte) s.charAt(i);
if (escaped) {
if (b >= '0' && b <= '9' && digits < 3) {
digits++;
intval *= 10;
intval += (b - '0');
if (intval > 255)
throw new TextParseException
("bad escape");
if (digits < 3)
continue;
b = (byte) intval;
}
else if (digits > 0 && digits < 3)
throw new TextParseException("bad escape");
if (pos >= MAXLABEL)
throw new TextParseException("label too long");
labelstart = pos;
label[pos++] = b;
escaped = false;
} else if (b == '\\') {
escaped = true;
digits = 0;
intval = 0;
} else if (b == '.') {
if (labelstart == -1)
throw new TextParseException("invalid label");
label[0] = (byte)(pos - 1);
name.appendFromString(label, 0, 1);
labelstart = -1;
pos = 1;
} else {
if (labelstart == -1)
labelstart = i;
if (pos >= MAXLABEL)
throw new TextParseException("label too long");
label[pos++] = b;
}
}
if (labelstart == -1) {
name.appendFromString(emptyLabel, 0, 1);
absolute = true;
} else {
label[0] = (byte)(pos - 1);
name.appendFromString(label, 0, 1);
}
if (origin != null && !absolute)
name.appendFromString(origin.name, 0, origin.getlabels());
return (name);
}
/**
* Create a new name from a string. This does not automatically make the name
* absolute; it will be absolute if it has a trailing dot.
* @param s The string to be converted
* @throws TextParseException The name is invalid.
*/
public static Name
fromString(String s) throws TextParseException {
return fromString(s, null);
}
public static Name
fromConstantString(String s) {
try {
return fromString(s, null);
}
catch (TextParseException e) {
throw new IllegalArgumentException("Invalid name '" + s + "'");
}
}
/**
* Create a new name from DNS wire format
* @param in A stream containing the input data
*/
public
Name(DataByteInputStream in) throws IOException {
int len, pos, currentpos;
Name name2;
boolean done = false;
byte [] label = new byte[MAXLABEL + 1];
int savedpos = -1;
while (!done) {
len = in.readUnsignedByte();
switch (len & LABEL_MASK) {
case LABEL_NORMAL:
if (getlabels() >= MAXLABELS)
throw new WireParseException("too many labels");
if (len == 0) {
append(emptyLabel, 0, 1);
done = true;
} else {
label[0] = (byte)len;
in.readArray(label, 1, len);
append(label, 0, 1);
}
break;
case LABEL_COMPRESSION:
pos = in.readUnsignedByte();
pos += ((len & ~LABEL_MASK) << 8);
if (Options.check("verbosecompression"))
System.err.println("currently " + in.getPos() +
", pointer to " + pos);
currentpos = in.getPos();
if (pos >= currentpos)
throw new WireParseException("bad compression");
if (savedpos == -1)
savedpos = currentpos;
in.setPos(pos);
if (Options.check("verbosecompression"))
System.err.println("current name '" + this +
"', seeking to " + pos);
continue;
}
}
if (savedpos != -1)
in.setPos(savedpos);
}
/**
* Create a new name by removing labels from the beginning of an existing Name
* @param src An existing Name
* @param n The number of labels to remove from the beginning in the copy
*/
public
Name(Name src, int n) {
byte slabels = src.labels();
if (n > slabels)
throw new IllegalArgumentException("attempted to remove too " +
"many labels");
name = src.name;
setlabels((byte)(slabels - n));
for (int i = 0; i < MAXOFFSETS && i < slabels - n; i++)
setoffset(i, src.offset(i + n));
}
/**
* Creates a new name by concatenating two existing names.
* @param prefix The prefix name.
* @param suffix The suffix name.
* @return The concatenated name.
* @throws NameTooLongException The name is too long.
*/
public static Name
concatenate(Name prefix, Name suffix) throws NameTooLongException {
if (prefix.isAbsolute())
return (prefix);
Name newname = new Name();
copy(prefix, newname);
newname.append(suffix.name, suffix.offset(0), suffix.getlabels());
return newname;
}
/**
* Generates a new Name with the first n labels replaced by a wildcard
* @return The wildcard name
*/
public Name
wild(int n) {
if (n < 1)
throw new IllegalArgumentException("must replace 1 or more " +
"labels");
try {
Name newname = new Name();
copy(wild, newname);
newname.append(name, offset(n), getlabels() - n);
return newname;
}
catch (NameTooLongException e) {
throw new IllegalStateException
("Name.wild: concatenate failed");
}
}
/**
* Generates a new Name to be used when following a DNAME.
* @param dname The DNAME record to follow.
* @return The constructed name.
* @throws NameTooLongException The resulting name is too long.
*/
public Name
fromDNAME(DNAMERecord dname) throws NameTooLongException {
Name dnameowner = dname.getName();
Name dnametarget = dname.getTarget();
if (!subdomain(dnameowner))
return null;
int plabels = labels() - dnameowner.labels();
int plength = length() - dnameowner.length();
int pstart = offset(0);
int dlabels = dnametarget.labels();
int dlength = dnametarget.length();
if (plength + dlength > MAXNAME)
throw new NameTooLongException();
Name newname = new Name();
newname.setlabels((byte)(plabels + dlabels));
newname.name = new byte[plength + dlength];
System.arraycopy(name, pstart, newname.name, 0, plength);
System.arraycopy(dnametarget.name, 0, newname.name, plength, dlength);
for (int i = 0, pos = 0; i < MAXOFFSETS && i < plabels + dlabels; i++) {
newname.setoffset(i, pos);
pos += (newname.name[pos] + 1);
}
return newname;
}
/**
* Is this name a wildcard?
*/
public boolean
isWild() {
if (labels() == 0)
return false;
return (name[0] == (byte)1 && name[1] == (byte)'*');
}
/**
* Is this name fully qualified (that is, absolute)?
* @deprecated As of dnsjava 1.3.0, replaced by <code>isAbsolute</code>.
*/
public boolean
isQualified() {
return (isAbsolute());
}
/**
* Is this name absolute?
*/
public boolean
isAbsolute() {
if (labels() == 0)
return false;
return (name[name.length - 1] == 0);
}
/**
* The length of the name.
*/
public short
length() {
return (short)(name.length - offset(0));
}
/**
* The number of labels in the name.
*/
public byte
labels() {
return getlabels();
}
/**
* Is the current Name a subdomain of the specified name?
*/
public boolean
subdomain(Name domain) {
byte labels = labels();
byte dlabels = domain.labels();
if (dlabels > labels)
return false;
if (dlabels == labels)
return equals(domain);
return domain.equals(name, offset(labels - dlabels));
}
private String
byteString(byte [] array, int pos) {
StringBuffer sb = new StringBuffer();
int len = array[pos++];
for (int i = pos; i < pos + len; i++) {
short b = (short)(array[i] & 0xFF);
if (b <= 0x20 || b >= 0x7f) {
sb.append('\\');
sb.append(byteFormat.format(b));
}
else if (b == '"' || b == '(' || b == ')' || b == '.' ||
b == ';' || b == '\\' || b == '@' || b == '$')
{
sb.append('\\');
sb.append((char)b);
}
else
sb.append((char)b);
}
return sb.toString();
}
/**
* Convert Name to a String
*/
public String
toString() {
byte labels = labels();
if (labels == 0)
return "@";
else if (labels == 1 && name[offset(0)] == 0)
return ".";
StringBuffer sb = new StringBuffer();
for (int i = 0, pos = offset(0); i < labels; i++) {
int len = name[pos];
if (len > MAXLABEL)
throw new IllegalStateException("invalid label");
if (len == 0)
break;
sb.append(byteString(name, pos));
sb.append('.');
pos += (1 + len);
}
if (!isAbsolute())
sb.deleteCharAt(sb.length() - 1);
return sb.toString();
}
/**
* Convert the nth label in a Name to a String
* @param n The label to be converted to a String. The first label is 0.
*/
public byte []
getLabel(int n) {
int pos = offset(n);
byte len = (byte)(name[pos] + 1);
byte [] label = new byte[len];
System.arraycopy(name, pos, label, 0, len);
return label;
}
/**
* Convert the nth label in a Name to a String
* @param n The label to be converted to a String. The first label is 0.
*/
public String
getLabelString(int n) {
int pos = offset(n);
return byteString(name, pos);
}
public void
toWire(DataByteOutputStream out, Compression c) throws IOException {
if (!isAbsolute())
throw new IllegalArgumentException("toWire() called on " +
"non-absolute name");
byte labels = labels();
for (int i = 0; i < labels - 1; i++) {
Name tname;
if (i == 0)
tname = this;
else
tname = new Name(this, i);
int pos = -1;
if (c != null)
pos = c.get(tname);
if (pos >= 0) {
pos |= (LABEL_MASK << 8);
out.writeShort(pos);
return;
} else {
if (c != null)
c.add(out.getPos(), tname);
out.writeString(name, offset(i));
}
}
out.writeByte(0);
}
/**
* Convert Name to canonical DNS wire format (all lowercase)
* @param out The output stream to which the message is written.
* @throws IOException An error occurred writing the name.
*/
public void
toWireCanonical(DataByteOutputStream out) throws IOException {
byte [] b = toWireCanonical();
out.write(b);
}
/**
* Convert Name to canonical DNS wire format (all lowercase)
* @throws IOException An error occurred writing the name.
*/
public byte []
toWireCanonical() throws IOException {
byte labels = labels();
if (labels == 0)
return (new byte[0]);
byte [] b = new byte[name.length - offset(0)];
for (int i = 0, pos = offset(0); i < labels; i++) {
int len = name[pos];
if (len > MAXLABEL)
throw new IllegalStateException("invalid label");
b[pos] = name[pos++];
for (int j = 0; j < len; j++)
b[pos] = lowercase[name[pos++]];
}
return b;
}
private final boolean
equals(byte [] b, int bpos) {
byte labels = labels();
for (int i = 0, pos = offset(0); i < labels; i++) {
if (name[pos] != b[bpos])
return false;
int len = name[pos++];
bpos++;
if (len > MAXLABEL)
throw new IllegalStateException("invalid label");
for (int j = 0; j < len; j++)
if (lowercase[name[pos++]] != lowercase[b[bpos++]])
return false;
}
return true;
}
/**
* Are these two Names equivalent?
*/
public boolean
equals(Object arg) {
if (arg == this)
return true;
if (arg == null || !(arg instanceof Name))
return false;
Name d = (Name) arg;
if (d.labels() != labels())
return false;
return equals(d.name, d.offset(0));
}
/**
* Computes a hashcode based on the value
*/
public int
hashCode() {
if (hashcode != 0)
return (hashcode);
int code = 0;
for (int i = offset(0); i < name.length; i++)
code += ((code << 3) + lowercase[name[i]]);
hashcode = code;
return hashcode;
}
/**
* Compares this Name to another Object.
* @param o The Object to be compared.
* @return The value 0 if the argument is a name equivalent to this name;
* a value less than 0 if the argument is less than this name in the canonical
* ordering, and a value greater than 0 if the argument is greater than this
* name in the canonical ordering.
* @throws ClassCastException if the argument is not a Name.
*/
public int
compareTo(Object o) {
Name arg = (Name) o;
if (this == arg)
return (0);
byte labels = labels();
byte alabels = arg.labels();
int compares = labels > alabels ? alabels : labels;
for (int i = 1; i <= compares; i++) {
int start = offset(labels - i);
int astart = arg.offset(alabels - i);
int length = name[start];
int alength = arg.name[astart];
for (int j = 0; j < length && j < alength; j++) {
int n = lowercase[name[j + start]] -
lowercase[arg.name[j + astart]];
if (n != 0)
return (n);
}
if (length != alength)
return (length - alength);
}
return (labels - alabels);
}
} |
package org.xbill.DNS;
import java.io.*;
import java.util.*;
import org.xbill.DNS.utils.*;
/**
* A representation of a domain name.
*
* @author Brian Wellington
*/
public class Name {
private static final int LABEL_NORMAL = 0;
private static final int LABEL_COMPRESSION = 0xC0;
private static final int LABEL_EXTENDED = 0x40;
private static final int LABEL_LOCAL_COMPRESSION = 0x80;
private static final int LABEL_MASK = 0xC0;
private static final int EXT_LABEL_COMPRESSION = 0;
private static final int EXT_LABEL_BITSTRING = 1;
private static final int EXT_LABEL_LOCAL_COMPRESSION = 2;
private Object [] name;
private byte labels;
private boolean qualified;
/** The root name */
public static Name root = new Name("");
/** The maximum number of labels in a Name */
static final int MAXLABELS = 256;
/**
* Create a new name from a string and an origin
* @param s The string to be converted
* @param origin If the name is unqalified, the origin to be appended
*/
public
Name(String s, Name origin) {
labels = 0;
name = new Object[MAXLABELS];
if (s.equals("@") && origin != null) {
append(origin);
qualified = true;
return;
}
try {
MyStringTokenizer st = new MyStringTokenizer(s, ".");
while (st.hasMoreTokens()) {
String token = st.nextToken();
if (token.charAt(0) == '\\')
name[labels++] = new BitString(token);
else
name[labels++] = token;
}
if (st.hasMoreDelimiters())
qualified = true;
else {
if (origin != null) {
append(origin);
qualified = true;
}
else {
/* This isn't exactly right, but it's close.
* Partially qualified names are evil.
*/
if (Options.check("pqdn"))
qualified = false;
else
qualified = (labels > 1);
}
}
}
catch (Exception e) {
StringBuffer sb = new StringBuffer();
sb.append(s);
if (origin != null) {
sb.append(".");
sb.append(origin);
}
if (e instanceof ArrayIndexOutOfBoundsException)
sb.append(" has too many labels");
else if (e instanceof IOException)
sb.append(" contains an invalid binary label");
else
sb.append(" is invalid");
System.err.println(sb.toString());
name = null;
labels = 0;
}
}
/**
* Create a new name from a string
* @param s The string to be converted
*/
public
Name(String s) {
this (s, null);
}
/**
* Create a new name from DNS wire format
* @param in A stream containing the input data
* @param c The compression context. This should be null unless a full
* message is being parsed.
*/
public
Name(DataByteInputStream in, Compression c) throws IOException {
int len, start, pos, count = 0;
Name name2;
labels = 0;
name = new Object[MAXLABELS];
start = in.getPos();
loop:
while ((len = in.readUnsignedByte()) != 0) {
switch(len & LABEL_MASK) {
case LABEL_NORMAL:
byte [] b = new byte[len];
in.read(b);
name[labels++] = new String(b);
count++;
break;
case LABEL_COMPRESSION:
pos = in.readUnsignedByte();
pos += ((len & ~LABEL_MASK) << 8);
name2 = (c == null) ? null : c.get(pos);
if (Options.check("verbosecompression"))
System.err.println("Looking at " + pos +
", found " + name2);
if (name2 == null)
throw new WireParseException("bad compression");
else {
System.arraycopy(name2.name, 0, name, labels,
name2.labels);
labels += name2.labels;
}
break loop;
case LABEL_EXTENDED:
int type = len & ~LABEL_MASK;
switch (type) {
case EXT_LABEL_COMPRESSION:
pos = in.readUnsignedShort();
name2 = (c == null) ? null : c.get(pos);
if (Options.check("verbosecompression"))
System.err.println("Looking at " +
pos + ", found " +
name2);
if (name2 == null)
throw new WireParseException(
"bad compression");
else {
System.arraycopy(name2.name, 0, name,
labels, name2.labels);
labels += name2.labels;
}
break loop;
case EXT_LABEL_BITSTRING:
int bits = in.readUnsignedByte();
if (bits == 0)
bits = 256;
int bytes = (bits + 7) / 8;
byte [] data = new byte[bytes];
in.read(data);
name[labels++] = new BitString(bits, data);
count++;
break;
case EXT_LABEL_LOCAL_COMPRESSION:
throw new WireParseException(
"Long local compression");
default:
throw new WireParseException(
"Unknown name format");
} /* switch */
break;
case LABEL_LOCAL_COMPRESSION:
throw new WireParseException("Local compression");
} /* switch */
}
if (c != null) {
pos = start;
for (int i = 0; i < count; i++) {
Name tname = new Name(this, i);
c.add(pos, tname);
if (Options.check("verbosecompression"))
System.err.println("Adding " + tname +
" at " + pos);
if (name[i] instanceof String)
pos += (((String)name[i]).length() + 1);
else
pos += (((BitString)name[i]).bytes() + 2);
}
}
qualified = true;
}
/**
* Create a new name by removing labels from the beginning of an existing Name
* @param d An existing Name
* @param n The number of labels to remove from the beginning in the copy
*/
/* Skips n labels and creates a new name */
public
Name(Name d, int n) {
name = new Object[MAXLABELS];
labels = (byte) (d.labels - n);
System.arraycopy(d.name, n, name, 0, labels);
qualified = d.qualified;
}
/**
* Generates a new Name with the first label replaced by a wildcard
* @return The wildcard name
*/
public Name
wild() {
Name wild = new Name(this, 0);
wild.name[0] = "*";
return wild;
}
/**
* Is this name a wildcard?
*/
public boolean
isWild() {
return name[0].equals("*");
}
/**
* Is this name fully qualified?
*/
public boolean
isQualified() {
return qualified;
}
/**
* Appends the specified name to the end of the current Name
*/
public void
append(Name d) {
System.arraycopy(d.name, 0, name, labels, d.labels);
labels += d.labels;
}
/**
* The length
*/
public short
length() {
short total = 0;
for (int i = 0; i < labels; i++) {
if (name[i] instanceof String)
total += (((String)name[i]).length() + 1);
else
total += (((BitString)name[i]).bytes() + 2);
}
return ++total;
}
/**
* The number of labels
*/
public byte
labels() {
return labels;
}
/**
* Is the current Name a subdomain of the specified name?
*/
public boolean
subdomain(Name domain) {
if (domain == null || domain.labels > labels)
return false;
int i = labels, j = domain.labels;
while (j > 0)
if (!name[--i].equals(domain.name[--j]))
return false;
return true;
}
/**
* Convert Name to a String
*/
public String
toString() {
StringBuffer sb = new StringBuffer();
if (labels == 0)
sb.append(".");
for (int i = 0; i < labels; i++) {
sb.append(name[i]);
if (qualified || i < labels - 1)
sb.append(".");
}
return sb.toString();
}
/**
* Convert Name to DNS wire format
*/
public void
toWire(DataByteOutputStream out, Compression c) throws IOException {
for (int i = 0; i < labels; i++) {
Name tname = new Name(this, i);
int pos = -1;
if (c != null) {
pos = c.get(tname);
if (Options.check("verbosecompression"))
System.err.println("Looking for " + tname +
", found " + pos);
}
if (pos >= 0) {
pos |= (LABEL_MASK << 8);
out.writeShort(pos);
return;
}
else {
if (c != null) {
c.add(out.getPos(), tname);
if (Options.check("verbosecompression"))
System.err.println("Adding " + tname +
" at " +
out.getPos());
}
if (name[i] instanceof String)
out.writeString((String)name[i]);
else {
out.writeByte(LABEL_EXTENDED |
EXT_LABEL_BITSTRING);
out.writeByte(((BitString)name[i]).wireBits());
out.write(((BitString)name[i]).data);
}
}
}
out.writeByte(0);
}
/**
* Convert Name to canonical DNS wire format (all lowercase)
*/
public void
toWireCanonical(DataByteOutputStream out) throws IOException {
for (int i = 0; i < labels; i++) {
if (name[i] instanceof String)
out.writeStringCanonical((String)name[i]);
else {
out.writeByte(LABEL_EXTENDED | EXT_LABEL_BITSTRING);
out.writeByte(((BitString)name[i]).wireBits());
out.write(((BitString)name[i]).data);
}
}
out.writeByte(0);
}
/**
* Are these two Names equivalent?
*/
public boolean
equals(Object arg) {
if (arg == null || !(arg instanceof Name))
return false;
Name d = (Name) arg;
if (d.labels != labels)
return false;
for (int i = 0; i < labels; i++) {
if (name[i].getClass() != d.name[i].getClass())
return false;
if (name[i] instanceof String) {
String s1 = (String) name[i];
String s2 = (String) d.name[i];
if (!s1.equalsIgnoreCase(s2))
return false;
}
else {
/* BitString */
if (!name[i].equals(d.name[i]))
return false;
}
}
return true;
}
/**
* Computes a hashcode based on the value
*/
public int
hashCode() {
int code = labels;
for (int i = 0; i < labels; i++) {
if (name[i] instanceof String) {
String s = (String) name[i];
for (int j = 0; j < s.length(); j++)
code += Character.toLowerCase(s.charAt(j));
}
else {
BitString b = (BitString) name[i];
for (int j = 0; j < b.bytes(); j++)
code += b.data[i];
}
}
return code;
}
} |
package org.xbill.DNS;
import java.io.*;
import java.util.*;
import org.xbill.DNS.utils.*;
/**
* A representation of a domain name.
*
* @author Brian Wellington
*/
public class Name {
private static final int LABEL_NORMAL = 0;
private static final int LABEL_COMPRESSION = 0xC0;
private static final int LABEL_EXTENDED = 0x40;
private static final int LABEL_MASK = 0xC0;
private static final int EXT_LABEL_BITSTRING = 1;
private Object [] name;
private byte labels;
private boolean qualified;
/** The root name */
public static final Name root = new Name(".");
/** The maximum number of labels in a Name */
static final int MAXLABELS = 128;
/* The number of labels initially allocated. */
private static final int STARTLABELS = 4;
private
Name() {
}
private final void
grow(int n) {
if (n > MAXLABELS)
throw new ArrayIndexOutOfBoundsException("name too long");
Object [] newarray = new Object[n];
System.arraycopy(name, 0, newarray, 0, labels);
name = newarray;
}
private final void
grow() {
grow(labels * 2);
}
/**
* Create a new name from a string and an origin
* @param s The string to be converted
* @param origin If the name is unqalified, the origin to be appended
*/
public
Name(String s, Name origin) {
labels = 0;
name = new Object[STARTLABELS];
if (s.equals("@") && origin != null) {
append(origin);
qualified = true;
return;
}
try {
MyStringTokenizer st = new MyStringTokenizer(s, ".");
while (st.hasMoreTokens()) {
String token = st.nextToken();
if (labels == name.length)
grow();
if (token.charAt(0) == '[')
name[labels++] = new BitString(token);
else
name[labels++] = token.getBytes();
}
if (st.hasMoreDelimiters())
qualified = true;
else {
if (origin != null) {
append(origin);
qualified = true;
}
else {
/* This isn't exactly right, but it's close.
* Partially qualified names are evil.
*/
if (Options.check("pqdn"))
qualified = false;
else
qualified = (labels > 1);
}
}
}
catch (Exception e) {
StringBuffer sb = new StringBuffer();
sb.append(s);
if (origin != null) {
sb.append(".");
sb.append(origin);
}
if (e instanceof ArrayIndexOutOfBoundsException)
sb.append(" has too many labels");
else if (e instanceof IOException)
sb.append(" contains an invalid binary label");
else
sb.append(" is invalid");
System.err.println(sb.toString());
name = null;
labels = 0;
}
}
/**
* Create a new name from a string
* @param s The string to be converted
*/
public
Name(String s) {
this (s, null);
}
/**
* Create a new name from DNS wire format
* @param in A stream containing the input data
* @param c The compression context. This should be null unless a full
* message is being parsed.
*/
public
Name(DataByteInputStream in, Compression c) throws IOException {
int len, start, pos, count = 0;
Name name2;
labels = 0;
name = new Object[STARTLABELS];
start = in.getPos();
loop:
while ((len = in.readUnsignedByte()) != 0) {
switch(len & LABEL_MASK) {
case LABEL_NORMAL:
byte [] b = new byte[len];
in.read(b);
if (labels == name.length)
grow();
name[labels++] = b;
count++;
break;
case LABEL_COMPRESSION:
pos = in.readUnsignedByte();
pos += ((len & ~LABEL_MASK) << 8);
name2 = (c == null) ? null : c.get(pos);
if (Options.check("verbosecompression"))
System.err.println("Looking at " + pos +
", found " + name2);
if (name2 == null)
throw new WireParseException("bad compression");
else {
if (labels + name2.labels > name.length)
grow(labels + name2.labels);
System.arraycopy(name2.name, 0, name, labels,
name2.labels);
labels += name2.labels;
}
break loop;
case LABEL_EXTENDED:
int type = len & ~LABEL_MASK;
switch (type) {
case EXT_LABEL_BITSTRING:
int bits = in.readUnsignedByte();
if (bits == 0)
bits = 256;
int bytes = (bits + 7) / 8;
byte [] data = new byte[bytes];
in.read(data);
if (labels == name.length)
grow();
name[labels++] = new BitString(bits, data);
count++;
break;
default:
throw new WireParseException(
"Unknown name format");
} /* switch */
break;
} /* switch */
}
if (c != null) {
pos = start;
if (Options.check("verbosecompression"))
System.out.println("name = " + this +
", count = " + count);
for (int i = 0; i < count; i++) {
Name tname = new Name(this, i);
c.add(pos, tname);
if (Options.check("verbosecompression"))
System.err.println("Adding " + tname +
" at " + pos);
if (name[i] instanceof BitString)
pos += (((BitString)name[i]).bytes() + 2);
else
pos += (((byte [])name[i]).length + 1);
}
}
qualified = true;
}
/**
* Create a new name by removing labels from the beginning of an existing Name
* @param d An existing Name
* @param n The number of labels to remove from the beginning in the copy
*/
/* Skips n labels and creates a new name */
public
Name(Name d, int n) {
name = new Object[d.labels - n];
labels = (byte) (d.labels - n);
System.arraycopy(d.name, n, name, 0, labels);
qualified = d.qualified;
}
/**
* Generates a new Name with the first n labels replaced by a wildcard
* @return The wildcard name
*/
public Name
wild(int n) {
Name wild = new Name(this, n - 1);
wild.name[0] = new byte[] {(byte)'*'};
return wild;
}
/**
* Generates a new Name to be used when following a DNAME.
* @return The new name, or null if the DNAME is invalid.
*/
public Name
fromDNAME(DNAMERecord dname) {
Name dnameowner = dname.getName();
Name dnametarget = dname.getTarget();
int nlabels;
int saved;
if (!subdomain(dnameowner))
return null;
saved = labels - dnameowner.labels;
nlabels = saved + dnametarget.labels;
if (nlabels > MAXLABELS)
return null;
Name newname = new Name();
newname.labels = (byte)nlabels;
newname.name = new Object[labels];
System.arraycopy(this.name, 0, newname.name, 0, saved);
System.arraycopy(dnametarget.name, 0, newname.name, saved,
dnametarget.labels);
newname.qualified = true;
return newname;
}
/**
* Is this name a wildcard?
*/
public boolean
isWild() {
if (labels == 0 || (name[0] instanceof BitString))
return false;
byte [] b = (byte []) name[0];
return (b.length == 1 && b[0] == '*');
}
/**
* Is this name fully qualified?
*/
public boolean
isQualified() {
return qualified;
}
/**
* Appends the specified name to the end of the current Name
*/
public void
append(Name d) {
if (labels + d.labels > name.length)
grow(labels + d.labels);
System.arraycopy(d.name, 0, name, labels, d.labels);
labels += d.labels;
qualified = d.qualified;
}
/**
* The length
*/
public short
length() {
short total = 0;
for (int i = 0; i < labels; i++) {
if (name[i] instanceof BitString)
total += (((BitString)name[i]).bytes() + 2);
else
total += (((byte [])name[i]).length + 1);
}
return ++total;
}
/**
* The number of labels
*/
public byte
labels() {
return labels;
}
/**
* Is the current Name a subdomain of the specified name?
*/
public boolean
subdomain(Name domain) {
if (domain == null || domain.labels > labels)
return false;
Name tname = new Name(this, labels - domain.labels);
return (tname.equals(domain));
}
/**
* Convert Name to a String
*/
public String
toString() {
StringBuffer sb = new StringBuffer();
if (labels == 0)
sb.append(".");
for (int i = 0; i < labels; i++) {
if (name[i] instanceof BitString)
sb.append(name[i]);
else
sb.append(new String((byte []) name[i]));
if (qualified || i < labels - 1)
sb.append(".");
}
return sb.toString();
}
/**
* Convert Name to DNS wire format
*/
public void
toWire(DataByteOutputStream out, Compression c) throws IOException {
for (int i = 0; i < labels; i++) {
Name tname;
if (i == 0)
tname = this;
else
tname = new Name(this, i);
int pos = -1;
if (c != null) {
pos = c.get(tname);
if (Options.check("verbosecompression"))
System.err.println("Looking for " + tname +
", found " + pos);
}
if (pos >= 0) {
pos |= (LABEL_MASK << 8);
out.writeShort(pos);
return;
}
else {
if (c != null) {
c.add(out.getPos(), tname);
if (Options.check("verbosecompression"))
System.err.println("Adding " + tname +
" at " +
out.getPos());
}
if (name[i] instanceof BitString) {
out.writeByte(LABEL_EXTENDED |
EXT_LABEL_BITSTRING);
out.writeByte(((BitString)name[i]).wireBits());
out.write(((BitString)name[i]).data);
}
else
out.writeString((byte []) name[i]);
}
}
out.writeByte(0);
}
/**
* Convert Name to canonical DNS wire format (all lowercase)
*/
public void
toWireCanonical(DataByteOutputStream out) throws IOException {
for (int i = 0; i < labels; i++) {
if (name[i] instanceof BitString) {
out.writeByte(LABEL_EXTENDED | EXT_LABEL_BITSTRING);
out.writeByte(((BitString)name[i]).wireBits());
out.write(((BitString)name[i]).data);
}
else
out.writeStringCanonical(new String((byte []) name[i]));
}
out.writeByte(0);
}
private static final byte
toLower(byte b) {
if (b < 'A' || b > 'Z')
return b;
else
return (byte)(b - 'A' + 'a');
}
/**
* Are these two Names equivalent?
*/
public boolean
equals(Object arg) {
if (arg == null || !(arg instanceof Name))
return false;
if (arg == this)
return true;
Name d = (Name) arg;
if (d.labels != labels)
return false;
for (int i = 0; i < labels; i++) {
if (name[i].getClass() != d.name[i].getClass())
return false;
if (name[i] instanceof BitString) {
if (!name[i].equals(d.name[i]))
return false;
}
else {
byte [] b1 = (byte []) name[i];
byte [] b2 = (byte []) d.name[i];
if (b1.length != b2.length)
return false;
for (int j = 0; j < b1.length; j++) {
if (toLower(b1[j]) != toLower(b2[j]))
return false;
}
}
}
return true;
}
/**
* Computes a hashcode based on the value
*/
public int
hashCode() {
int code = labels;
for (int i = 0; i < labels; i++) {
if (name[i] instanceof BitString) {
BitString b = (BitString) name[i];
for (int j = 0; j < b.bytes(); j++)
code += ((code << 3) + b.data[i]);
}
else {
byte [] b = (byte []) name[i];
for (int j = 0; j < b.length; j++)
code += ((code << 3) + toLower(b[j]));
}
}
return code;
}
} |
package net.canadensys.harvester.occurrence.view;
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutionException;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;
import net.canadensys.dataportal.occurrence.model.DwcaResourceModel;
import net.canadensys.dataportal.occurrence.model.PublisherModel;
import net.canadensys.harvester.occurrence.controller.StepControllerIF;
import net.canadensys.harvester.occurrence.model.JobStatusModel.JobStatus;
public class ResourcesPanel extends JPanel {
private static final long serialVersionUID = 1093812890375L;
private DwcaResourceModel resourceToImport = null;
private ImageIcon loadingImg = null;
private JButton importBtn = null;
private JButton moveToPublicBtn = null;
private JButton addResourceBtn = null;
private JButton editResourceBtn = null;
private JButton computeUniqueValuesBtn = null;
private JLabel statusLbl = null;
private JTextField bufferSchemaTxt = null;
private JTextArea consoleTxtArea = null;
private JComboBox<String> resourcesCmbBox = null;
private JCheckBox moveChkBox = null;
private JCheckBox uniqueValuesChkBox = null;
// Inherited from OccurrenceHarvesterMainView:
private final StepControllerIF stepController;
private List<DwcaResourceModel> knownResources;
public ResourcesPanel(StepControllerIF stepController) {
this.stepController = stepController;
knownResources = stepController.getResourceModelList();
this.setLayout(new GridBagLayout());
// Load icon image:
loadingImg = new ImageIcon(
OccurrenceHarvesterMainView.class
.getResource("/ajax-loader.gif"));
// Vertical alignment reference index:
int lineIdx = 0;
GridBagConstraints c = new GridBagConstraints();
;
// Resource label:
c.insets = new Insets(5, 5, 5, 5);
c.gridx = 0;
this.add(new JLabel(Messages.getString("view.info.import.dwca")), c);
// Select resource combo box:
initResourceComboBox();
c.gridx = 0;
c.gridy = ++lineIdx;
c.gridwidth = 4;
c.fill = GridBagConstraints.HORIZONTAL;
// c.anchor = GridBagConstraints.NORTH;
this.add(resourcesCmbBox, c);
// Import button:
c.gridx = 1;
c.gridy = ++lineIdx;
c.gridwidth = 1;
c.fill = GridBagConstraints.HORIZONTAL;
c.anchor = GridBagConstraints.NORTHEAST;
importBtn = new JButton(Messages.getString("view.button.import"));
importBtn.setToolTipText(Messages
.getString("view.button.import.tooltip"));
importBtn.setEnabled(false);
importBtn.setVisible(true);
importBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
onImportResource();
}
});
this.add(importBtn, c);
// View/edit resource button:
c.gridx = 2;
editResourceBtn = new JButton(
Messages.getString("view.button.edit.resource"));
editResourceBtn.setToolTipText(Messages
.getString("view.button.edit.resource.tooltip"));
editResourceBtn.setVisible(true);
editResourceBtn.setEnabled(false);
editResourceBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
onEditResource();
}
});
this.add(editResourceBtn, c);
// Add resource button:
// c.gridy = ++lineIdx;
c.gridx = 3;
addResourceBtn = new JButton(
Messages.getString("view.button.add.resource"));
addResourceBtn.setToolTipText(Messages
.getString("view.button.add.resource.tooltip"));
addResourceBtn.setEnabled(true);
addResourceBtn.setVisible(true);
addResourceBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
onAddResource();
}
});
this.add(addResourceBtn, c);
// UI separator
c.gridx = 0;
c.gridy = ++lineIdx;
c.gridwidth = 4;
c.fill = GridBagConstraints.HORIZONTAL;
this.add(new JSeparator(), c);
// DwcA ready to move label:
c.gridy = ++lineIdx;
c.fill = GridBagConstraints.NONE;
c.anchor = GridBagConstraints.NORTHWEST;
this.add(new JLabel(Messages.getString("view.info.move.dwca")), c);
// DwcA text field name display:
bufferSchemaTxt = new JTextField();
bufferSchemaTxt.setEnabled(false);
c.gridwidth = 3;
c.gridx = 0;
c.gridy = ++lineIdx;
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 1.0;
c.anchor = GridBagConstraints.NORTHEAST;
this.add(bufferSchemaTxt, c);
// Move to public schema button:
moveToPublicBtn = new JButton(Messages.getString("view.button.move"));
moveToPublicBtn.setToolTipText(Messages
.getString("view.button.move.tooltip"));
moveToPublicBtn.setEnabled(false);
moveToPublicBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
onMoveToPublic();
}
});
c.gridwidth = 1;
c.gridx = 3;
c.anchor = GridBagConstraints.NORTHEAST;
c.fill = GridBagConstraints.NONE;
this.add(moveToPublicBtn, c);
// Compute unique values to public schema button:
computeUniqueValuesBtn = new JButton(
Messages.getString("view.button.compute.unique.values"));
computeUniqueValuesBtn.setToolTipText(Messages
.getString("view.button.compute.unique.values.tooltip"));
computeUniqueValuesBtn.setEnabled(true);
computeUniqueValuesBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
onComputeUniqueValues();
}
});
c.gridwidth = 1;
c.gridx = 3;
c.gridy = ++lineIdx;
c.anchor = GridBagConstraints.NORTHEAST;
c.fill = GridBagConstraints.NONE;
this.add(computeUniqueValuesBtn, c);
// Auto move checkbox:
moveChkBox = new JCheckBox();
moveChkBox.setText(Messages.getString("view.button.automove"));
moveChkBox.setToolTipText(Messages
.getString("view.button.automove.tip"));
moveChkBox.setEnabled(true);
c.gridwidth = 1;
c.gridy = ++lineIdx;
c.gridx = 0;
c.fill = GridBagConstraints.HORIZONTAL;
this.add(moveChkBox, c);
// Compute unique values checkbox:
uniqueValuesChkBox = new JCheckBox();
uniqueValuesChkBox.setText(Messages
.getString("view.button.unique.values"));
uniqueValuesChkBox.setToolTipText(Messages
.getString("view.button.unique.values.tip"));
uniqueValuesChkBox.setEnabled(true);
c.gridy = ++lineIdx;
this.add(uniqueValuesChkBox, c);
// UI separator
c.gridx = 0;
c.gridy = ++lineIdx;
c.gridwidth = 4;
c.fill = GridBagConstraints.HORIZONTAL;
this.add(new JSeparator(), c);
// UI line break
c.gridy = ++lineIdx;
c.anchor = GridBagConstraints.NORTHWEST;
c.fill = GridBagConstraints.NONE;
this.add(new JLabel(Messages.getString("view.info.status")), c);
// UI line break
c.gridy = ++lineIdx;
c.anchor = GridBagConstraints.WEST;
statusLbl = new JLabel(Messages.getString("view.info.status.waiting"),
null, JLabel.CENTER);
statusLbl.setForeground(Color.RED);
this.add(statusLbl, c);
// UI line break
c.gridy = ++lineIdx;
c.gridwidth = 4;
c.fill = GridBagConstraints.HORIZONTAL;
this.add(new JSeparator(), c);
// UI line break
c.gridy = ++lineIdx;
c.gridwidth = 2;
c.anchor = GridBagConstraints.WEST;
c.fill = GridBagConstraints.NONE;
this.add(new JLabel(Messages.getString("view.info.console")), c);
// UI line break
consoleTxtArea = new JTextArea();
consoleTxtArea.setRows(15);
c.gridy = ++lineIdx;
c.gridwidth = 4;
c.fill = GridBagConstraints.BOTH;
c.weightx = 1.0;
c.weighty = 1.0;
this.add(new JScrollPane(consoleTxtArea), c);
// inner panel
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
c.fill = GridBagConstraints.BOTH;
c.weightx = 1.0;
c.weighty = 1.0;
}
/**
* Safely update the content of the status label.
*
* @param status
*/
public void updateStatusLabel(final String status) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
statusLbl.setText(status);
}
});
}
public void appendConsoleText(final String text) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
consoleTxtArea.append(text);
}
});
}
public void onMoveDone(JobStatus status) {
statusLbl.setIcon(null);
if (JobStatus.DONE == status) {
JOptionPane.showMessageDialog(this,
Messages.getString("view.info.status.moveCompleted"),
Messages.getString("view.info.status.info"),
JOptionPane.INFORMATION_MESSAGE);
bufferSchemaTxt.setText("");
statusLbl.setText(Messages.getString("view.info.status.moveDone"));
statusLbl.setForeground(Color.BLUE);
}
else {
JOptionPane.showMessageDialog(this,
Messages.getString("view.info.status.error.details"),
Messages.getString("view.info.status.error"),
JOptionPane.ERROR_MESSAGE);
statusLbl.setText(Messages
.getString("view.info.status.error.moveError"));
}
}
public void onUpdateDone(JobStatus status) {
statusLbl.setIcon(null);
if (JobStatus.DONE == status) {
JOptionPane.showMessageDialog(this,
Messages.getString("view.info.status.updateDone"),
Messages.getString("view.info.status.info"),
JOptionPane.INFORMATION_MESSAGE);
bufferSchemaTxt.setText("");
statusLbl.setText(Messages.getString("view.info.status.updateDone"));
statusLbl.setForeground(Color.BLUE);
}
else {
JOptionPane.showMessageDialog(this,
Messages.getString("view.info.status.error.details"),
Messages.getString("view.info.status.error"),
JOptionPane.ERROR_MESSAGE);
statusLbl.setText(Messages
.getString("view.info.status.error.updateError"));
}
}
public void onJobStatusChanged(JobStatus newStatus) {
switch (newStatus) {
case DONE:
statusLbl.setIcon(null);
bufferSchemaTxt.setText(resourceToImport.getSourcefileid());
updateStatusLabel(Messages.getString("view.info.status.importDone"));
// If auto move is set, start move:
if (moveChkBox.getSelectedObjects() != null) {
onMoveToPublic();
}
else {
moveToPublicBtn.setEnabled(true);
}
break;
case ERROR:
statusLbl.setIcon(null);
updateStatusLabel(Messages
.getString("view.info.status.error.importError"));
JOptionPane.showMessageDialog(this,
Messages.getString("view.info.status.error.details"),
Messages.getString("view.info.status.error"),
JOptionPane.ERROR_MESSAGE);
break;
case CANCEL:
statusLbl.setIcon(null);
updateStatusLabel(Messages.getString("view.info.status.canceled"));
break;
default:
break;
}
}
/**
* Initializes the resources combo box by creating a JComboBox and filling
* it with resource data from database
*
*/
private void initResourceComboBox() {
resourcesCmbBox = new JComboBox<String>();
resourcesCmbBox.addItem("");
resourcesCmbBox.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String selectedResource = (String) resourcesCmbBox
.getSelectedItem();
if (selectedResource != null) {
if (!selectedResource.equalsIgnoreCase("")) {
editResourceBtn.setEnabled(true);
importBtn.setEnabled(true);
}
else {
editResourceBtn.setEnabled(false);
importBtn.setEnabled(false);
}
}
}
});
// Retrieve available resources list:
List<DwcaResourceModel> resources = stepController
.getResourceModelList();
// Add an item for each resource name:
ArrayList<String> names = new ArrayList<String>();
for (DwcaResourceModel resource : resources) {
names.add(resource.getName());
}
// Reorder alphabetically:
Collections.sort(names);
for (String name : names) {
resourcesCmbBox.addItem(name);
}
}
/**
* Import a resource (asynchronously) using a SwingWorker.
*/
private void onImportResource() {
// Check there is a valid item selected
if (resourcesCmbBox.getSelectedItem() != null) {
// Avoid first entry (void):
if (resourcesCmbBox.getSelectedIndex() > 0) {
String selectedResource = (String) resourcesCmbBox
.getSelectedItem();
// Update resource to be imported based on selected item:
for (DwcaResourceModel resource : stepController.getResourceModelList()) {
if (resource.getName().equalsIgnoreCase(selectedResource))
resourceToImport = resource;
}
importBtn.setEnabled(false);
moveToPublicBtn.setEnabled(false);
addResourceBtn.setEnabled(false);
editResourceBtn.setEnabled(false);
computeUniqueValuesBtn.setEnabled(false);
statusLbl.setIcon(loadingImg);
final SwingWorker<Void, Object> swingWorker = new SwingWorker<Void, Object>() {
@Override
public Void doInBackground() {
try {
if (resourceToImport != null) {
stepController.importDwcA(resourceToImport.getId());
}
else {
stepController
.importDwcAFromLocalFile((String) (resourcesCmbBox
.getSelectedItem()));
}
}
catch (Exception e) {
// should not get there but just in case
e.printStackTrace();
}
// async call, propertyChange(...) will be called once
// done
return null;
}
@Override
protected void done() {
}
};
swingWorker.execute();
}
}
}
/**
* Move the previously importer resource to the public schema using a
* SwingWorker.
*/
private void onMoveToPublic() {
moveToPublicBtn.setEnabled(false);
updateStatusLabel(Messages.getString("view.info.status.moving"));
statusLbl.setIcon(loadingImg);
final SwingWorker<Boolean, Object> swingWorker = new SwingWorker<Boolean, Object>() {
@Override
public Boolean doInBackground() {
String publisherName = "";
// Publisher information:
// Avoid cases when a publisher is not associated to the
// resource:
PublisherModel publisher = resourceToImport.getPublisher();
if (publisher != null) {
publisherName = publisher.getName();
}
// Check if the indexing is supposed to process unique values or
// not:
if (uniqueValuesChkBox.getSelectedObjects() != null) {
stepController.moveToPublicSchema(resourceToImport.getId(), resourceToImport.getName(), publisherName, true);
}
else {
stepController.moveToPublicSchema(resourceToImport.getId(), resourceToImport.getName(), publisherName, false);
}
return true;
}
@Override
protected void done() {
try {
if (get()) {
onMoveDone(JobStatus.DONE);
}
else {
onMoveDone(JobStatus.ERROR);
}
}
catch (InterruptedException e) {
onMoveDone(JobStatus.ERROR);
}
catch (ExecutionException e) {
onMoveDone(JobStatus.ERROR);
}
}
};
swingWorker.execute();
}
/**
* Edit resource button action.
*/
private void onEditResource() {
importBtn.setEnabled(false);
moveToPublicBtn.setEnabled(false);
addResourceBtn.setEnabled(false);
editResourceBtn.setEnabled(false);
computeUniqueValuesBtn.setEnabled(false);
boolean ok = editResourceDialog();
knownResources = stepController.getResourceModelList();
updateResourceComboBox();
// Change back status and buttons display:
addResourceBtn.setEnabled(true);
computeUniqueValuesBtn.setEnabled(true);
// Case the select button was pressed (instead of cancel)
if (ok) {
statusLbl.setIcon(null);
statusLbl.setForeground(Color.BLUE);
updateStatusLabel(Messages.getString("view.info.status.updateDone"));
}
}
private boolean editResourceDialog() {
DwcaResourceModel resourceToEdit = null;
// Check there is a valid item selected
if (resourcesCmbBox.getSelectedItem() != null) {
// Avoid first entry (void):
if (resourcesCmbBox.getSelectedIndex() > 0) {
String selectedResource = (String) resourcesCmbBox
.getSelectedItem();
// Get resource to be edited based on selected item:
for (DwcaResourceModel resource : stepController
.getResourceModelList()) {
if (resource.getName().equalsIgnoreCase(selectedResource))
resourceToEdit = resource;
}
}
// Start resource edition panel
ResourceDialog erd = new ResourceDialog(this,
stepController, resourceToEdit, true);
int resourceId = resourceToEdit.getId();
String resourceName = resourceToEdit.getName();
String publisherName = "";
// Publisher information:
// Avoid cases when a publisher is not associated to the
// resource:
PublisherModel publisher = resourceToEdit.getPublisher();
if (publisher != null) {
publisherName = publisher.getName();
}
if (erd.getExitValue() == JOptionPane.OK_OPTION) {
updateStatusLabel(Messages.getString("view.info.status.updating"));
statusLbl.setIcon(loadingImg);
if (!stepController.updateResourceModel(erd.getResourceModel())) {
JOptionPane
.showMessageDialog(
this,
Messages.getString("resourceView.resource.error.save.msg"),
Messages.getString("resourceView.resource.error.title"),
JOptionPane.ERROR_MESSAGE);
}
else {
// Resource has been changed successfully, update database:
// Update database after move
stepController.updateStep(resourceId, resourceName,
publisherName);
}
return true;
}
}
return false;
}
/**
* Add resource button action
*/
private void onAddResource() {
ResourceDialog rd = new ResourceDialog(this, stepController, null, false);
DwcaResourceModel resourceModel = rd.getResourceModel();
if (rd.getExitValue() == JOptionPane.OK_OPTION) {
if (!stepController.updateResourceModel(resourceModel)) {
JOptionPane
.showMessageDialog(
this,
Messages.getString("resourceView.resource.error.save.msg"),
Messages.getString("resourceView.resource.error.title"),
JOptionPane.ERROR_MESSAGE);
}
// reload data to ensure we have the latest changes
knownResources = stepController.getResourceModelList();
updateResourceComboBox();
}
}
/**
* Update knownCbx if the variable knownResource has changed.
*/
private void updateResourceComboBox() {
resourcesCmbBox.removeAllItems();
resourcesCmbBox.addItem(null);
for (DwcaResourceModel resourceModel : knownResources) {
resourcesCmbBox.addItem(resourceModel.getName());
}
}
public void onComputeUniqueValues() {
final SwingWorker<Boolean, Object> swingWorker = new SwingWorker<Boolean, Object>() {
@Override
public Boolean doInBackground() {
// Update status:
computeUniqueValuesBtn.setEnabled(false);
statusLbl.setIcon(loadingImg);
statusLbl.setForeground(Color.ORANGE);
updateStatusLabel(Messages.getString("view.info.status.compute.unique.values"));
// Call compute unique values task:
stepController.computeUniqueValues(null);
return true;
}
@Override
protected void done() {
// Update status:
statusLbl.setIcon(null);
statusLbl.setForeground(Color.BLUE);
updateStatusLabel(Messages.getString("view.info.status.compute.unique.values.done"));
computeUniqueValuesBtn.setEnabled(true);
}
};
swingWorker.execute();
}
} |
package org.xbill.DNS;
import java.io.*;
import java.text.*;
import java.util.*;
import org.xbill.DNS.utils.*;
/**
* A representation of a domain name.
*
* @author Brian Wellington
*/
public class Name implements Comparable {
private static final int LABEL_NORMAL = 0;
private static final int LABEL_COMPRESSION = 0xC0;
private static final int LABEL_EXTENDED = 0x40;
private static final int LABEL_MASK = 0xC0;
private static final int EXT_LABEL_BITSTRING = 1;
private Object [] name;
private byte offset;
private byte labels;
private boolean qualified;
private boolean hasBitString;
private int hashcode;
/** The root name */
public static final Name root = Name.fromConstantString(".");
/** The maximum number of labels in a Name */
static final int MAXLABELS = 128;
/* The number of labels initially allocated. */
private static final int STARTLABELS = 4;
/* Used for printing non-printable characters */
private static DecimalFormat byteFormat = new DecimalFormat();
/* Used to efficiently convert bytes to lowercase */
private static byte lowercase[] = new byte[256];
/* Used in wildcard names. */
private static byte wildcardLabel[] = new byte[] {(byte)'*'};
static {
byteFormat.setMinimumIntegerDigits(3);
for (int i = 0; i < lowercase.length; i++) {
if (i < 'A' || i > 'Z')
lowercase[i] = (byte)i;
else
lowercase[i] = (byte)(i - 'A' + 'a');
}
}
private
Name() {
}
private final void
grow(int n) {
if (n > MAXLABELS)
throw new ArrayIndexOutOfBoundsException("name too long");
Object [] newarray = new Object[n];
System.arraycopy(name, 0, newarray, 0, labels);
name = newarray;
}
private final void
grow() {
grow(labels * 2);
}
private final void
compact() {
for (int i = labels - 1 + offset; i > offset; i
if (!(name[i] instanceof BitString) ||
!(name[i - 1] instanceof BitString))
continue;
BitString bs = (BitString) name[i];
BitString bs2 = (BitString) name[i - 1];
if (bs.nbits == 256)
continue;
int nbits = bs.nbits + bs2.nbits;
bs.join(bs2);
if (nbits <= 256) {
System.arraycopy(name, i, name, i - 1, labels - i);
labels
}
}
}
/**
* Create a new name from a string and an origin
* @param s The string to be converted
* @param origin If the name is unqualified, the origin to be appended
* @deprecated As of dnsjava 1.3.0, replaced by <code>Name.fromString</code>.
*/
public
Name(String s, Name origin) {
Name n;
try {
n = Name.fromString(s, origin);
}
catch (TextParseException e) {
StringBuffer sb = new StringBuffer();
sb.append(s);
if (origin != null) {
sb.append(".");
sb.append(origin);
}
sb.append(": ");
sb.append(e.getMessage());
System.err.println(sb.toString());
name = null;
labels = 0;
return;
}
labels = n.labels;
name = n.name;
qualified = n.qualified;
if (!qualified) {
/*
* This isn't exactly right, but it's close.
* Partially qualified names are evil.
*/
if (Options.check("pqdn"))
qualified = false;
else
qualified = (labels > 1);
}
}
/**
* Create a new name from a string
* @param s The string to be converted
* @deprecated as of dnsjava 1.3.0, replaced by <code>Name.fromString</code>.
*/
public
Name(String s) {
this (s, null);
}
/**
* Create a new name from a string and an origin. This does not automatically
* make the name absolute; it will be absolute if it has a trailing dot or an
* absolute origin is appended.
* @param s The string to be converted
* @param origin If the name is unqualified, the origin to be appended.
* @throws TextParseException The name is invalid.
*/
public static Name
fromString(String s, Name origin) throws TextParseException {
Name name = new Name();
name.labels = 0;
name.name = new Object[1];
if (s.equals("@")) {
if (origin != null)
return origin;
} else if (s.equals(".")) {
name.qualified = true;
return name;
}
int labelstart = -1;
int pos = 0;
byte [] label = new byte[64];
boolean escaped = false;
int digits = 0;
int intval = 0;
boolean bitstring = false;
for (int i = 0; i < s.length(); i++) {
byte b = (byte) s.charAt(i);
if (escaped) {
if (pos == 0 && b == '[')
bitstring = true;
if (b >= '0' && b <= '9' && digits < 3) {
digits++;
intval *= 10 + (b - '0');
intval += (b - '0');
if (digits < 3)
continue;
b = (byte) intval;
}
else if (digits > 0 && digits < 3)
throw new TextParseException("bad escape");
if (pos >= label.length)
throw new TextParseException("label too long");
label[pos++] = b;
escaped = false;
} else if (b == '\\') {
escaped = true;
digits = 0;
intval = 0;
} else if (b == '.') {
if (labelstart == -1)
throw new TextParseException("invalid label");
byte [] newlabel = new byte[pos];
System.arraycopy(label, 0, newlabel, 0, pos);
if (name.labels == MAXLABELS)
throw new TextParseException("too many labels");
if (name.labels == name.name.length)
name.grow();
if (bitstring) {
bitstring = false;
name.name[name.labels++] =
new BitString(newlabel);
}
else
name.name[name.labels++] = newlabel;
labelstart = -1;
pos = 0;
} else {
if (labelstart == -1)
labelstart = i;
if (pos >= label.length)
throw new TextParseException("label too long");
label[pos++] = b;
}
}
if (labelstart == -1)
name.qualified = true;
else {
byte [] newlabel = new byte[pos];
System.arraycopy(label, 0, newlabel, 0, pos);
if (name.labels == MAXLABELS)
throw new TextParseException("too many labels");
if (name.labels == name.name.length)
name.grow();
if (bitstring) {
bitstring = false;
name.name[name.labels++] = new BitString(newlabel);
name.hasBitString = true;
}
else
name.name[name.labels++] = newlabel;
}
if (!name.qualified && origin != null)
name.append(origin);
if (name.hasBitString)
name.compact();
return (name);
}
/**
* Create a new name from a string. This does not automatically make the name
* absolute; it will be absolute if it has a trailing dot.
* @param s The string to be converted
* @throws TextParseException The name is invalid.
*/
public static Name
fromString(String s) throws TextParseException {
return fromString(s, null);
}
public static Name
fromConstantString(String s) {
try {
return fromString(s, null);
}
catch (TextParseException e) {
throw new IllegalArgumentException("Invalid name '" + s + "'");
}
}
/**
* Create a new name from DNS wire format
* @param in A stream containing the input data
*/
public
Name(DataByteInputStream in) throws IOException {
int len, start, pos, count = 0, savedpos;
Name name2;
labels = 0;
name = new Object[STARTLABELS];
start = in.getPos();
loop:
while ((len = in.readUnsignedByte()) != 0) {
count++;
switch(len & LABEL_MASK) {
case LABEL_NORMAL:
byte [] b = new byte[len];
in.read(b);
if (labels == name.length)
grow();
name[labels++] = b;
break;
case LABEL_COMPRESSION:
pos = in.readUnsignedByte();
pos += ((len & ~LABEL_MASK) << 8);
if (Options.check("verbosecompression"))
System.err.println("currently " + in.getPos() +
", pointer to " + pos);
if (pos >= in.getPos())
throw new WireParseException("bad compression");
savedpos = in.getPos();
in.setPos(pos);
if (Options.check("verbosecompression"))
System.err.println("current name '" + this +
"', seeking to " + pos);
try {
name2 = new Name(in);
}
finally {
in.setPos(savedpos);
}
if (labels + name2.labels > name.length)
grow(labels + name2.labels);
System.arraycopy(name2.name, 0, name, labels,
name2.labels);
labels += name2.labels;
break loop;
case LABEL_EXTENDED:
int type = len & ~LABEL_MASK;
switch (type) {
case EXT_LABEL_BITSTRING:
int bits = in.readUnsignedByte();
if (bits == 0)
bits = 256;
int bytes = (bits + 7) / 8;
byte [] data = new byte[bytes];
in.read(data);
if (labels == name.length)
grow();
name[labels++] = new BitString(bits, data);
hasBitString = true;
break;
default:
throw new WireParseException(
"Unknown name format");
} /* switch */
break;
} /* switch */
}
qualified = true;
if (hasBitString)
compact();
}
/**
* Create a new name by removing labels from the beginning of an existing Name
* @param d An existing Name
* @param n The number of labels to remove from the beginning in the copy
*/
/* Skips n labels and creates a new name */
public
Name(Name d, int n) {
name = d.name;
offset = (byte)(d.offset + n);
labels = (byte)(d.labels - n);
qualified = d.qualified;
}
/**
* Generates a new Name with the first n labels replaced by a wildcard
* @return The wildcard name
*/
public Name
wild(int n) {
Name wild = new Name(this, n - 1);
wild.name[0] = wildcardLabel;
return wild;
}
/**
* Generates a new Name to be used when following a DNAME.
* @return The new name, or null if the DNAME is invalid.
*/
public Name
fromDNAME(DNAMERecord dname) {
Name dnameowner = dname.getName();
Name dnametarget = dname.getTarget();
int nlabels;
int saved;
if (!subdomain(dnameowner))
return null;
saved = labels - dnameowner.labels;
nlabels = saved + dnametarget.labels;
if (nlabels > MAXLABELS)
return null;
Name newname = new Name();
newname.labels = (byte)nlabels;
newname.name = new Object[labels];
System.arraycopy(this.name, 0, newname.name, 0, saved);
System.arraycopy(dnametarget.name, 0, newname.name, saved,
dnametarget.labels);
newname.qualified = true;
for (int i = 0; i < newname.labels; i++)
if (newname.name[i] instanceof BitString)
newname.hasBitString = true;
if (newname.hasBitString)
newname.compact();
return newname;
}
/**
* Is this name a wildcard?
*/
public boolean
isWild() {
if (labels == 0 || (name[0] instanceof BitString))
return false;
if (name[0] == wildcardLabel)
return true;
byte [] b = (byte []) name[0];
return (b.length == 1 && b[0] == '*');
}
/**
* Is this name fully qualified?
*/
public boolean
isQualified() {
return qualified;
}
/**
* Appends the specified name to the end of the current Name
*/
private void
append(Name d) {
if (labels + d.labels > name.length)
grow(labels + d.labels);
System.arraycopy(d.name, 0, name, labels, d.labels);
labels += d.labels;
qualified = d.qualified;
if (hasBitString || d.hasBitString)
compact();
}
/**
* The length of the name.
*/
public short
length() {
short total = 0;
for (int i = offset; i < labels + offset; i++) {
if (name[i] instanceof BitString)
total += (((BitString)name[i]).bytes() + 2);
else
total += (((byte [])name[i]).length + 1);
}
return ++total;
}
/**
* The number of labels in the name.
*/
public byte
labels() {
return labels;
}
/**
* Is the current Name a subdomain of the specified name?
*/
public boolean
subdomain(Name domain) {
if (domain == null || domain.labels > labels)
return false;
Name tname = new Name(this, labels - domain.labels);
return (tname.equals(domain));
}
private String
byteString(byte [] array) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < array.length; i++) {
/* Ick. */
short b = (short)(array[i] & 0xFF);
if (b <= 0x20 || b >= 0x7f) {
sb.append('\\');
sb.append(byteFormat.format(b));
}
else if (b == '"' || b == '(' || b == ')' || b == '.' ||
b == ';' || b == '\\' || b == '@' || b == '$')
{
sb.append('\\');
sb.append((char)b);
}
else
sb.append((char)b);
}
return sb.toString();
}
/**
* Convert Name to a String
*/
public String
toString() {
StringBuffer sb = new StringBuffer();
if (labels == 0)
sb.append(".");
for (int i = offset; i < labels + offset; i++) {
if (name[i] instanceof BitString)
sb.append(name[i]);
else
sb.append(byteString((byte [])name[i]));
if (qualified || i < labels - 1)
sb.append(".");
}
return sb.toString();
}
/**
* Convert the nth label in a Name to a String
* @param n The label to be converted to a String
*/
public String
getLabelString(int n) {
n += offset;
if (name[n] instanceof BitString)
return name[n].toString();
else
return byteString((byte [])name[n]);
}
/**
* Convert Name to DNS wire format
*/
public void
toWire(DataByteOutputStream out, Compression c) throws IOException {
boolean log = (c != null && Options.check("verbosecompression"));
for (int i = offset; i < labels + offset; i++) {
Name tname;
if (i == offset)
tname = this;
else
tname = new Name(this, i);
int pos = -1;
if (c != null) {
pos = c.get(tname);
if (log)
System.err.println("Looking for " + tname +
", found " + pos);
}
if (pos >= 0) {
pos |= (LABEL_MASK << 8);
out.writeShort(pos);
return;
}
else {
if (c != null) {
c.add(out.getPos(), tname);
if (log)
System.err.println("Adding " + tname +
" at " +
out.getPos());
}
if (name[i] instanceof BitString) {
out.writeByte(LABEL_EXTENDED |
EXT_LABEL_BITSTRING);
out.writeByte(((BitString)name[i]).wireBits());
out.write(((BitString)name[i]).data);
}
else
out.writeString((byte []) name[i]);
}
}
out.writeByte(0);
}
/**
* Convert Name to canonical DNS wire format (all lowercase)
*/
public void
toWireCanonical(DataByteOutputStream out) throws IOException {
for (int i = offset; i < labels + offset; i++) {
if (name[i] instanceof BitString) {
out.writeByte(LABEL_EXTENDED | EXT_LABEL_BITSTRING);
out.writeByte(((BitString)name[i]).wireBits());
out.write(((BitString)name[i]).data);
}
else {
byte [] b = (byte []) name[i];
byte [] bc = new byte[b.length];
for (int j = 0; j < b.length; j++)
bc[j] = lowercase[b[j]];
out.writeString(bc);
}
}
out.writeByte(0);
}
/**
* Are these two Names equivalent?
*/
public boolean
equals(Object arg) {
if (arg == this)
return true;
if (arg == null || !(arg instanceof Name))
return false;
Name d = (Name) arg;
if (d.labels != labels)
return false;
for (int i = 0; i < labels; i++) {
Object nobj = name[offset + i];
Object dnobj = d.name[d.offset + i];
if (nobj.getClass() != dnobj.getClass())
return false;
if (nobj instanceof BitString) {
if (!nobj.equals(dnobj))
return false;
} else {
byte [] b1 = (byte []) nobj;
byte [] b2 = (byte []) dnobj;
if (b1.length != b2.length)
return false;
for (int j = 0; j < b1.length; j++) {
if (lowercase[b1[j]] != lowercase[b2[j]])
return false;
}
}
}
return true;
}
/**
* Computes a hashcode based on the value
*/
public int
hashCode() {
if (hashcode != 0)
return (hashcode);
int code = labels;
for (int i = offset; i < labels + offset; i++) {
if (name[i] instanceof BitString) {
BitString b = (BitString) name[i];
for (int j = 0; j < b.bytes(); j++)
code += ((code << 3) + b.data[j]);
}
else {
byte [] b = (byte []) name[i];
for (int j = 0; j < b.length; j++)
code += ((code << 3) + lowercase[b[j]]);
}
}
hashcode = code;
return hashcode;
}
/**
* Compares this Name to another Object.
* @param The Object to be compared.
* @return The value 0 if the argument is a name equivalent to this name;
* a value less than 0 if the argument is less than this name in the canonical
* ordering, and a value greater than 0 if the argument is greater than this
* name in the canonical ordering.
* @throws ClassCastException if the argument is not a Name.
*/
public int
compareTo(Object o) {
Name arg = (Name) o;
int compares = labels > arg.labels ? arg.labels : labels;
for (int i = 1; i <= compares; i++) {
Object label = name[labels - i + offset];
Object alabel = arg.name[arg.labels - i + arg.offset];
if (label.getClass() != alabel.getClass()) {
if (label instanceof BitString)
return (-1);
else
return (1);
}
if (label instanceof BitString) {
BitString bs = (BitString)label;
BitString abs = (BitString)alabel;
int bits = bs.nbits > abs.nbits ? abs.nbits : bs.nbits;
int n = bs.compareBits(abs, bits);
if (n != 0)
return (n);
if (bs.nbits == abs.nbits)
continue;
/*
* If label X has more bits than label Y, then the
* name with X is greater if Y is the first label
* of its name. Otherwise, the name with Y is greater.
*/
if (bs.nbits > abs.nbits)
return (i == arg.labels ? 1 : -1);
else
return (i == labels ? -1 : 1);
}
else {
byte [] b = (byte []) label;
byte [] ab = (byte []) alabel;
for (int j = 0; j < b.length && j < ab.length; j++) {
int n = lowercase[b[j]] - lowercase[ab[j]];
if (n != 0)
return (n);
}
if (b.length != ab.length)
return (b.length - ab.length);
}
}
return (labels - arg.labels);
}
} |
package com.macro.mall.portal.repository;
import com.macro.mall.portal.domain.MemberBrandAttention;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.repository.MongoRepository;
public interface MemberBrandAttentionRepository extends MongoRepository<MemberBrandAttention, String> {
/**
* IDID
*/
MemberBrandAttention findByMemberIdAndBrandId(Long memberId, Long brandId);
/**
* IDID
*/
int deleteByMemberIdAndBrandId(Long memberId, Long brandId);
Page<MemberBrandAttention> findByMemberId(Long memberId, Pageable pageable);
void deleteAllByMemberId(Long memberId);
} |
package org.xbill.DNS;
import java.util.HashMap;
import org.xbill.DNS.utils.*;
/**
* Constants and functions relating to DNS Types
*
* @author Brian Wellington
*/
public final class Type {
/** Address */
public static final short A = 1;
/** Name server */
public static final short NS = 2;
/** Mail destination */
public static final short MD = 3;
/** Mail forwarder */
public static final short MF = 4;
/** Canonical name (alias) */
public static final short CNAME = 5;
/** Start of authority */
public static final short SOA = 6;
/** Mailbox domain name */
public static final short MB = 7;
/** Mail group member */
public static final short MG = 8;
/** Mail rename name */
public static final short MR = 9;
/** Null record */
public static final short NULL = 10;
/** Well known services */
public static final short WKS = 11;
/** Domain name pointer */
public static final short PTR = 12;
/** Host information */
public static final short HINFO = 13;
/** Mailbox information */
public static final short MINFO = 14;
/** Mail routing information */
public static final short MX = 15;
/** Text strings */
public static final short TXT = 16;
/** Responsible person */
public static final short RP = 17;
/** AFS cell database */
public static final short AFSDB = 18;
/** X_25 calling address */
public static final short X25 = 19;
/** ISDN calling address */
public static final short ISDN = 20;
/** Router */
public static final short RT = 21;
/** NSAP address */
public static final short NSAP = 22;
/** Reverse NSAP address (deprecated) */
public static final short NSAP_PTR = 23;
/** Signature */
public static final short SIG = 24;
/** Key */
public static final short KEY = 25;
/** X.400 mail mapping */
public static final short PX = 26;
/** Geographical position (withdrawn) */
public static final short GPOS = 27;
/** IPv6 address (old) */
public static final short AAAA = 28;
/** Location */
public static final short LOC = 29;
/** Next valid name in zone */
public static final short NXT = 30;
/** Endpoint identifier */
public static final short EID = 31;
/** Nimrod locator */
public static final short NIMLOC = 32;
/** Server selection */
public static final short SRV = 33;
/** ATM address */
public static final short ATMA = 34;
/** Naming authority pointer */
public static final short NAPTR = 35;
/** Key exchange */
public static final short KX = 36;
/** Certificate */
public static final short CERT = 37;
/** IPv6 address */
public static final short A6 = 38;
/** Non-terminal name redirection */
public static final short DNAME = 39;
/** Options - contains EDNS metadata */
public static final short OPT = 41;
/** Address Prefix List */
public static final short APL = 42;
/** Delegation Signer */
public static final short DS = 43;
/** Transaction key - used to compute a shared secret or exchange a key */
public static final short TKEY = 249;
/** Transaction signature */
public static final short TSIG = 250;
/** Incremental zone transfer */
public static final short IXFR = 251;
/** Zone transfer */
public static final short AXFR = 252;
/** Transfer mailbox records */
public static final short MAILB = 253;
/** Transfer mail agent records */
public static final short MAILA = 254;
/** Matches any type */
public static final short ANY = 255;
private static class DoubleHashMap {
private HashMap v2s, s2v;
public
DoubleHashMap() {
v2s = new HashMap();
s2v = new HashMap();
}
public void
put(short value, String string) {
Short s = Type.toShort(value);
v2s.put(s, string);
s2v.put(string, s);
}
public Short
getValue(String string) {
return (Short) s2v.get(string);
}
public String
getString(short value) {
return (String) v2s.get(Type.toShort(value));
}
}
private static DoubleHashMap types = new DoubleHashMap();
private static Short [] typecache = new Short [44];
static {
for (short i = 0; i < typecache.length; i++)
typecache[i] = new Short(i);
types.put(A, "A");
types.put(NS, "NS");
types.put(MD, "MD");
types.put(MF, "MF");
types.put(CNAME, "CNAME");
types.put(SOA, "SOA");
types.put(MB, "MB");
types.put(MG, "MG");
types.put(MR, "MR");
types.put(NULL, "NULL");
types.put(WKS, "WKS");
types.put(PTR, "PTR");
types.put(HINFO, "HINFO");
types.put(MINFO, "MINFO");
types.put(MX, "MX");
types.put(TXT, "TXT");
types.put(RP, "RP");
types.put(AFSDB, "AFSDB");
types.put(X25, "X25");
types.put(ISDN, "ISDN");
types.put(RT, "RT");
types.put(NSAP, "NSAP");
types.put(NSAP_PTR, "NSAP_PTR");
types.put(SIG, "SIG");
types.put(KEY, "KEY");
types.put(PX, "PX");
types.put(GPOS, "GPOS");
types.put(AAAA, "AAAA");
types.put(LOC, "LOC");
types.put(NXT, "NXT");
types.put(EID, "EID");
types.put(NIMLOC, "NIMLOC");
types.put(SRV, "SRV");
types.put(ATMA, "ATMA");
types.put(NAPTR, "NAPTR");
types.put(KX, "KX");
types.put(CERT, "CERT");
types.put(A6, "A6");
types.put(DNAME, "DNAME");
types.put(OPT, "OPT");
types.put(APL, "APL");
types.put(DS, "DS");
types.put(TKEY, "TKEY");
types.put(TSIG, "TSIG");
types.put(IXFR, "IXFR");
types.put(AXFR, "AXFR");
types.put(MAILB, "MAILB");
types.put(MAILA, "MAILA");
types.put(ANY, "ANY");
}
private
Type() {
}
/** Converts a numeric Type into a String */
public static String
string(short i) {
String s = types.getString(i);
return (s != null) ? s : ("TYPE" + i);
}
/** Converts a String representation of an Type into its numeric value */
public static short
value(String s) {
Short val = types.getValue(s.toUpperCase());
if (val != null)
return val.shortValue();
try {
if (s.toUpperCase().startsWith("TYPE"))
return (Short.parseShort(s.substring(4)));
else
return Short.parseShort(s);
}
catch (Exception e) {
return (-1);
}
}
/** Is this type valid for a record (a non-meta type)? */
public static boolean
isRR(int type) {
switch (type) {
case OPT:
case TKEY:
case TSIG:
case IXFR:
case AXFR:
case MAILB:
case MAILA:
case ANY:
return false;
default:
return true;
}
}
/* Converts a type into a Short, for use in Hashmaps, etc. */
static Short
toShort(short type) {
if (type < typecache.length)
return (typecache[type]);
return new Short(type);
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.