answer stringlengths 17 10.2M |
|---|
package net.xprova.piccolo;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Scanner;
import java.util.TreeSet;
import jline.TerminalFactory;
import jline.console.ConsoleReader;
public class Console {
private String banner;
private String prompt;
private int exitFlag;
private PrintStream out;
private HashSet<MethodData> availMethods;
private HashMap<String, MethodData> methodAliases;
private HashSet<Object> handlers;
private class MethodData {
public Method method;
public Object object;
public MethodData(Method method, Object object) {
this.method = method;
this.object = object;
}
};
// public functions
/**
* Constructors
*/
public Console() {
methodAliases = new HashMap<String, MethodData>();
availMethods = new HashSet<Console.MethodData>();
handlers = new HashSet<Object>();
out = System.out;
// load banner
String bannerFileContent = "";
Scanner s = null;
try {
final InputStream stream;
stream = Console.class.getClassLoader().getResourceAsStream("piccolo_banner.txt");
s = new Scanner(stream);
bannerFileContent = s.useDelimiter("\\Z").next();
} catch (Exception e) {
bannerFileContent = "<could not load internal banner file>\n";
} finally {
if (s != null)
s.close();
}
setBanner(bannerFileContent).setPrompt(">> ");
}
/**
* Add a handler class to the console
*
* @param handler
* @return same Console object for chaining
*/
public Console addHandler(Object handler) {
handlers.add(handler);
scanForMethods();
return this;
}
/**
* Remove handler class from the console
*
* @param handler
* @return same Console object for chaining
*/
public Console removeHandler(@SuppressWarnings("rawtypes") Class handler) {
handlers.remove(handler);
scanForMethods();
return this;
}
/**
* Set console banner
*
* @param newBanner
* @return same Console object for chaining
*/
public Console setBanner(String newBanner) {
banner = newBanner;
return this;
}
/**
* Set console prompt
*
* @param newPrompt
* @return same Console object for chaining
*/
public Console setPrompt(String newPrompt) {
prompt = newPrompt;
return this;
}
/**
* Start the console
*/
public void run() {
try {
ConsoleReader console = new ConsoleReader();
out.println(banner);
console.setPrompt(prompt);
String line = null;
exitFlag = 0;
while ((line = console.readLine()) != null) {
try {
runCommand(line);
} catch (Exception e) {
prettyPrintStackTrace(e);
}
if (exitFlag != 0)
break;
out.println(""); // new line after each command
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
TerminalFactory.get().restore();
} catch (Exception e) {
e.printStackTrace();
}
}
}
private void prettyPrintStackTrace(Exception e) {
StackTraceElement[] trace;
if (e.getCause() == null)
trace = e.getStackTrace();
else
trace = e.getCause().getStackTrace();
ArrayList<StackTraceElement> stackArr = new ArrayList<StackTraceElement>();
for (StackTraceElement s : trace) {
if (!s.getClassName().contains(".reflect."))
stackArr.add(s);
}
StackTraceElement[] newTrace = new StackTraceElement[stackArr.size()];
stackArr.toArray(newTrace);
if (e.getCause() == null) {
e.setStackTrace(newTrace);
e.printStackTrace();
} else {
e.getCause().setStackTrace(newTrace);
e.getCause().printStackTrace();
}
}
/**
* Run a console command
*
* @param line
* string containing both command name and arguments, separated
* by spaces
* @return true if the command runs successfully and false otherwise
* @throws Exception
* if the command is not found or fails during execution
*/
public void runCommand(String line) throws Exception {
String[] parts = line.split(" ");
String cmd = parts[0];
String[] args = Arrays.copyOfRange(parts, 1, parts.length);
runCommand(cmd, args);
}
/**
* Runs a console command
*
* @param methodAlias
* command (method) name
* @param args
* command arguments
* @throws Exception
* if the command is not found or fails during execution
*/
public void runCommand(String methodAlias, String args[]) throws Exception {
if (methodAlias.isEmpty() || methodAlias.startsWith("
return;
MethodData methodData = methodAliases.get(methodAlias);
if (methodData == null) {
throw new Exception(String.format("Unknown command <%s>", methodAlias));
} else {
smartInvoke(methodAlias, methodData.method, methodData.object, args);
}
}
@Command(aliases = { ":type" }, description = "print type information for a given command")
public boolean getType(String methodAlias) {
MethodData md = methodAliases.get(methodAlias);
if (md == null) {
out.printf("command <%s> does not exist", methodAlias);
return false;
} else {
printParameters(methodAlias, md.method);
return true;
}
}
@Command(aliases = { ":shell", ":!" }, description = "run shell command")
public boolean runShellCmd(String args[]) {
String cmd = String.join(" ", args);
final Runtime rt = Runtime.getRuntime();
try {
Process proc = rt.exec(cmd);
BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
String s = null;
while ((s = stdInput.readLine()) != null)
out.println(s);
while ((s = stdError.readLine()) != null)
out.println(s);
return true;
} catch (IOException e) {
return false;
}
}
@Command(aliases = { ":source", ":s" }, description = "run script file")
public void runScript(String scriptFile) throws Exception {
BufferedReader br = new BufferedReader(new FileReader(scriptFile));
try {
exitFlag = 0;
String line;
while ((line = br.readLine()) != null && exitFlag == 0) {
if (!line.isEmpty()) {
try {
this.runCommand(line);
} catch (Exception e) {
prettyPrintStackTrace(e);
return;
}
}
}
exitFlag = 0;
} finally {
br.close();
}
}
@Command(aliases = { ":quit", ":q" }, description = "exit program")
public boolean exitConsole() {
exitFlag = 1;
return true;
}
@Command(aliases = { ":help", ":h" }, description = "print help text of a command", help = { "Uage:",
" :help <command>" })
public void printHelp(String methodAlias) {
MethodData md = methodAliases.get(methodAlias);
if (md == null) {
System.out.println("Unrecognized command");
} else {
Command anot = getCommandAnnotation(md.method);
System.out.printf("%s : %s\n", methodAlias, anot.description());
if (anot.help().length > 0) {
System.out.println("");
for (String s : anot.help())
System.out.println(s);
}
}
}
@Command(aliases = { ":time", ":t" }, description = "time the execution of a command")
public void timeCommand(String args[]) throws Exception {
long startTime = System.nanoTime();
runCommand(String.join(" ", args));
long endTime = System.nanoTime();
double searchTime = (endTime - startTime) / 1e9;
System.out.printf("Completed execution in %f seconds\n", searchTime);
}
// internal (private) functions
/*
* this function returns true when `method` has 1 parameter and of the type
* String[]
*/
private boolean isMethodGeneric(Method method) {
@SuppressWarnings("rawtypes")
Class[] parameterTypes = method.getParameterTypes();
if (parameterTypes.length == 1) {
return isStringArray(parameterTypes[0]);
} else {
return false;
}
}
private boolean isStringArray(@SuppressWarnings("rawtypes") Class clazz) {
boolean isArr = clazz.isArray();
boolean isCompString = clazz.getComponentType() == String.class;
return isArr && isCompString;
}
/*
* return true if command executes successfully and false otherwise
*/
private boolean smartInvoke(String usedAlias, Method method, Object object, String[] args) throws Exception {
Object[] noargs = new Object[] { new String[] {} };
int nArgs = args.length;
Class<?>[] paramTypes = method.getParameterTypes();
int nMethodArgs = paramTypes.length;
// determine type of invocation
if (nMethodArgs == 0) {
if (nArgs == 0) {
// simple case, invoke with no parameters
method.invoke(object);
return true;
} else {
printParameters(usedAlias, method);
return false;
}
} else if (nMethodArgs == 1 && isMethodGeneric(method)) {
// this method takes one parameter of type String[] that
// contains all user parameters
if (nArgs == 0) {
// user supplied no parameters
method.invoke(object, noargs);
return true;
} else {
// user supplied 1+ parameters
method.invoke(object, new Object[] { args });
return true;
}
} else if (nMethodArgs == nArgs) {
// the method accepts several parameters, attempt to convert
// parameters to the correct types and pass them to the method
ArrayList<Object> objs = new ArrayList<Object>();
try {
for (int i = 0; i < paramTypes.length; i++) {
objs.add(toObject(paramTypes[i], args[i]));
}
} catch (Exception e) {
out.println("Unable to parse parameters");
printParameters(usedAlias, method);
return false;
}
Object[] objsArr = objs.toArray();
method.invoke(object, objsArr);
return true;
} else {
out.printf("command <%s> requires %d parameter(s) (%d supplied)\n", usedAlias, nMethodArgs, nArgs);
return false;
}
}
private static Object toObject(@SuppressWarnings("rawtypes") Class clazz, String value) throws Exception {
if (Boolean.class == clazz || Boolean.TYPE == clazz)
return Boolean.parseBoolean(value);
if (Byte.class == clazz || Byte.TYPE == clazz)
return Byte.parseByte(value);
if (Short.class == clazz || Short.TYPE == clazz)
return Short.parseShort(value);
if (Integer.class == clazz || Integer.TYPE == clazz)
return Integer.parseInt(value);
if (Long.class == clazz || Long.TYPE == clazz)
return Long.parseLong(value);
if (Float.class == clazz || Float.TYPE == clazz)
return Float.parseFloat(value);
if (Double.class == clazz || Double.TYPE == clazz)
return Double.parseDouble(value);
if (String.class == clazz)
return value;
throw new Exception("Attempted to parse non-primitive type");
}
private void printParameters(String usedAlias, Method method) {
Class<?>[] paramTypes = method.getParameterTypes();
if (paramTypes.length == 0) {
out.printf("command <%s> takes no parameters\n", usedAlias);
} else if (paramTypes.length == 1) {
if (isStringArray(paramTypes[0])) {
out.printf("command <%s> takes arbitrary parameters\n", usedAlias);
} else {
out.printf("command <%s> takes <%s> parameter\n", usedAlias, paramTypes[0].getName());
}
} else {
StringBuilder sb = new StringBuilder();
sb.append("command <" + method.getName() + "> takes <");
sb.append(paramTypes[0].getName());
int j = paramTypes.length;
for (int i = 1; i < j - 1; i++) {
sb.append(", " + paramTypes[i].getName());
}
sb.append(", " + paramTypes[j - 1].getName() + "> parameters");
out.println(sb.toString());
}
}
@Command(aliases = { ":list", ":l" }, description = "lists available commands")
private void listMethods() {
TreeSet<String> methodList = new TreeSet<String>();
for (MethodData md : availMethods) {
Command anot = getCommandAnnotation(md.method);
if (anot.visible()) {
String[] aliases = anot.aliases();
String cmd = aliases.length == 0 ? md.method.getName() : aliases[0];
methodList.add(cmd);
}
}
out.println("Available commands:");
for (String cmd : methodList) {
Method m = methodAliases.get(cmd).method;
String desc = getCommandAnnotation(m).description();
out.printf("%-20s : %s\n", cmd, desc);
}
}
@Command(aliases = { ":aliases", ":a" }, description = "list command aliases")
private void listAliases() {
TreeSet<String> methodList = new TreeSet<String>();
for (MethodData md : availMethods) {
Command anot = getCommandAnnotation(md.method);
if (anot.visible()) {
String[] aliases = anot.aliases();
if (aliases.length > 1) {
String cmd = aliases.length == 0 ? md.method.getName() : aliases[0];
methodList.add(cmd);
}
}
}
out.println("Available command aliases:");
for (String cmd : methodList) {
Method m = methodAliases.get(cmd).method;
Command anot = getCommandAnnotation(m);
String aliases = "";
if (anot.aliases().length < 2) {
aliases = "n/a";
} else {
aliases = anot.aliases()[1];
for (int i = 2; i < anot.aliases().length; i++) {
aliases += ", " + anot.aliases()[i];
}
}
out.printf("%-20s : %s\n", cmd, aliases);
}
}
private Command getCommandAnnotation(Method method) {
Command[] anots = method.getDeclaredAnnotationsByType(Command.class);
return anots[0];
}
/**
* Return a list of command aliases for a method annotated with Command
*
* <p>
* If any aliases are defined in the Command annotation then these are
* returned. Otherwise the method name is returned as the only alias.
*
* @param method
* @return
*/
private ArrayList<String> getCommandNames(Method method) {
Command[] anots = method.getDeclaredAnnotationsByType(Command.class);
ArrayList<String> result = new ArrayList<String>();
if (anots.length > 0) {
if (anots[0].aliases().length > 0) {
// this command has aliases
for (String a : anots[0].aliases()) {
result.add(a);
}
} else {
// no defined aliases, use command line as only alias
result.add(method.getName());
}
}
return result;
}
private void scanForMethods() {
HashSet<Object> allHandlers = new HashSet<Object>(handlers);
allHandlers.add(this);
for (Object handler : allHandlers) {
Method[] methods = handler.getClass().getDeclaredMethods();
for (Method method : methods) {
Command[] anots = method.getDeclaredAnnotationsByType(Command.class);
if (anots.length > 0) {
MethodData md = new MethodData(method, handler);
availMethods.add(md);
ArrayList<String> aliases;
aliases = getCommandNames(method);
for (String a : aliases) {
methodAliases.put(a, md);
}
}
}
}
}
@Command(aliases = { ":print", ":p" }, description = "print a text to the console")
private void print(String[] args) {
out.println(String.join(" ", args));
}
} |
package org.gbif.dwc.terms;
import java.util.ArrayList;
import java.util.List;
public enum DwcTerm implements Term, AlternativeNames {
Occurrence(DwcTerm.GROUP_OCCURRENCE, "DarwinCore", "SimpleDarwinCore"),
Organism(DwcTerm.GROUP_ORGANISM),
MaterialSample(DwcTerm.GROUP_MATERIAL_SAMPLE),
Event(DwcTerm.GROUP_EVENT),
GeologicalContext(DwcTerm.GROUP_GEOLOGICALCONTEXT),
Identification(DwcTerm.GROUP_IDENTIFICATION),
Taxon(DwcTerm.GROUP_TAXON),
MeasurementOrFact(DwcTerm.GROUP_MEASUREMENTORFACT),
ResourceRelationship(DwcTerm.GROUP_RESOURCERELATIONSHIP),
institutionID(DwcTerm.GROUP_RECORD),
collectionID(DwcTerm.GROUP_RECORD),
datasetID(DwcTerm.GROUP_RECORD),
institutionCode(DwcTerm.GROUP_RECORD),
collectionCode(DwcTerm.GROUP_RECORD),
datasetName(DwcTerm.GROUP_RECORD),
ownerInstitutionCode(DwcTerm.GROUP_RECORD),
basisOfRecord(DwcTerm.GROUP_RECORD),
informationWithheld(DwcTerm.GROUP_RECORD),
dataGeneralizations(DwcTerm.GROUP_RECORD),
dynamicProperties(DwcTerm.GROUP_RECORD),
occurrenceID(DwcTerm.GROUP_OCCURRENCE),
catalogNumber(DwcTerm.GROUP_OCCURRENCE, "catalogNumberNumeric"),
recordNumber(DwcTerm.GROUP_OCCURRENCE, "collectorNumber"),
recordedBy(DwcTerm.GROUP_OCCURRENCE, "collector"),
individualCount(DwcTerm.GROUP_OCCURRENCE),
sex(DwcTerm.GROUP_OCCURRENCE),
lifeStage(DwcTerm.GROUP_OCCURRENCE),
reproductiveCondition(DwcTerm.GROUP_OCCURRENCE),
behavior(DwcTerm.GROUP_OCCURRENCE),
establishmentMeans(DwcTerm.GROUP_OCCURRENCE),
occurrenceStatus(DwcTerm.GROUP_OCCURRENCE),
preparations(DwcTerm.GROUP_OCCURRENCE),
disposition(DwcTerm.GROUP_OCCURRENCE),
associatedMedia(DwcTerm.GROUP_OCCURRENCE),
associatedReferences(DwcTerm.GROUP_OCCURRENCE),
associatedSequences(DwcTerm.GROUP_OCCURRENCE),
associatedTaxa(DwcTerm.GROUP_OCCURRENCE),
otherCatalogNumbers(DwcTerm.GROUP_OCCURRENCE),
occurrenceRemarks(DwcTerm.GROUP_OCCURRENCE),
organismID(DwcTerm.GROUP_ORGANISM, "individualID"),
organismName(DwcTerm.GROUP_ORGANISM),
organismScope(DwcTerm.GROUP_ORGANISM),
associatedOccurrences(DwcTerm.GROUP_ORGANISM),
associatedOrganisms(DwcTerm.GROUP_ORGANISM),
previousIdentifications(DwcTerm.GROUP_ORGANISM),
organismRemarks(DwcTerm.GROUP_ORGANISM),
materialSampleID(DwcTerm.GROUP_MATERIAL_SAMPLE),
eventID(DwcTerm.GROUP_EVENT),
fieldNumber(DwcTerm.GROUP_EVENT),
eventDate(DwcTerm.GROUP_EVENT, "earliestDateCollected", "latestDateCollected"),
eventTime(DwcTerm.GROUP_EVENT),
startDayOfYear(DwcTerm.GROUP_EVENT),
endDayOfYear(DwcTerm.GROUP_EVENT),
year(DwcTerm.GROUP_EVENT),
month(DwcTerm.GROUP_EVENT),
day(DwcTerm.GROUP_EVENT),
verbatimEventDate(DwcTerm.GROUP_EVENT),
habitat(DwcTerm.GROUP_EVENT),
samplingProtocol(DwcTerm.GROUP_EVENT),
samplingEffort(DwcTerm.GROUP_EVENT),
fieldNotes(DwcTerm.GROUP_EVENT),
eventRemarks(DwcTerm.GROUP_EVENT),
locationID(DwcTerm.GROUP_LOCATION),
higherGeographyID(DwcTerm.GROUP_LOCATION),
higherGeography(DwcTerm.GROUP_LOCATION),
continent(DwcTerm.GROUP_LOCATION),
waterBody(DwcTerm.GROUP_LOCATION),
islandGroup(DwcTerm.GROUP_LOCATION),
island(DwcTerm.GROUP_LOCATION),
country(DwcTerm.GROUP_LOCATION),
countryCode(DwcTerm.GROUP_LOCATION),
stateProvince(DwcTerm.GROUP_LOCATION, "state", "province"),
county(DwcTerm.GROUP_LOCATION),
municipality(DwcTerm.GROUP_LOCATION, "city"),
locality(DwcTerm.GROUP_LOCATION),
verbatimLocality(DwcTerm.GROUP_LOCATION),
minimumElevationInMeters(DwcTerm.GROUP_LOCATION),
maximumElevationInMeters(DwcTerm.GROUP_LOCATION),
verbatimElevation(DwcTerm.GROUP_LOCATION, "elevation"),
minimumDepthInMeters(DwcTerm.GROUP_LOCATION),
maximumDepthInMeters(DwcTerm.GROUP_LOCATION),
verbatimDepth(DwcTerm.GROUP_LOCATION, "depth"),
minimumDistanceAboveSurfaceInMeters(DwcTerm.GROUP_LOCATION),
maximumDistanceAboveSurfaceInMeters(DwcTerm.GROUP_LOCATION),
locationAccordingTo(DwcTerm.GROUP_LOCATION),
locationRemarks(DwcTerm.GROUP_LOCATION),
decimalLatitude(DwcTerm.GROUP_LOCATION, "latitude"),
decimalLongitude(DwcTerm.GROUP_LOCATION, "longitude"),
geodeticDatum(DwcTerm.GROUP_LOCATION, "datum", "horizontaldatum"),
coordinateUncertaintyInMeters(DwcTerm.GROUP_LOCATION),
coordinatePrecision(DwcTerm.GROUP_LOCATION),
pointRadiusSpatialFit(DwcTerm.GROUP_LOCATION),
verbatimCoordinates(DwcTerm.GROUP_LOCATION),
verbatimLatitude(DwcTerm.GROUP_LOCATION),
verbatimLongitude(DwcTerm.GROUP_LOCATION),
verbatimCoordinateSystem(DwcTerm.GROUP_LOCATION),
verbatimSRS(DwcTerm.GROUP_LOCATION),
footprintWKT(DwcTerm.GROUP_LOCATION),
footprintSRS(DwcTerm.GROUP_LOCATION),
footprintSpatialFit(DwcTerm.GROUP_LOCATION),
georeferencedBy(DwcTerm.GROUP_LOCATION),
georeferencedDate(DwcTerm.GROUP_LOCATION),
georeferenceProtocol(DwcTerm.GROUP_LOCATION),
georeferenceSources(DwcTerm.GROUP_LOCATION),
georeferenceVerificationStatus(DwcTerm.GROUP_LOCATION),
georeferenceRemarks(DwcTerm.GROUP_LOCATION),
geologicalContextID(DwcTerm.GROUP_GEOLOGICALCONTEXT),
earliestEonOrLowestEonothem(DwcTerm.GROUP_GEOLOGICALCONTEXT),
latestEonOrHighestEonothem(DwcTerm.GROUP_GEOLOGICALCONTEXT),
earliestEraOrLowestErathem(DwcTerm.GROUP_GEOLOGICALCONTEXT),
latestEraOrHighestErathem(DwcTerm.GROUP_GEOLOGICALCONTEXT),
earliestPeriodOrLowestSystem(DwcTerm.GROUP_GEOLOGICALCONTEXT),
latestPeriodOrHighestSystem(DwcTerm.GROUP_GEOLOGICALCONTEXT),
earliestEpochOrLowestSeries(DwcTerm.GROUP_GEOLOGICALCONTEXT),
latestEpochOrHighestSeries(DwcTerm.GROUP_GEOLOGICALCONTEXT),
earliestAgeOrLowestStage(DwcTerm.GROUP_GEOLOGICALCONTEXT),
latestAgeOrHighestStage(DwcTerm.GROUP_GEOLOGICALCONTEXT),
lowestBiostratigraphicZone(DwcTerm.GROUP_GEOLOGICALCONTEXT),
highestBiostratigraphicZone(DwcTerm.GROUP_GEOLOGICALCONTEXT),
lithostratigraphicTerms(DwcTerm.GROUP_GEOLOGICALCONTEXT),
group(DwcTerm.GROUP_GEOLOGICALCONTEXT),
formation(DwcTerm.GROUP_GEOLOGICALCONTEXT),
member(DwcTerm.GROUP_GEOLOGICALCONTEXT),
bed(DwcTerm.GROUP_GEOLOGICALCONTEXT),
identificationID(DwcTerm.GROUP_IDENTIFICATION),
identificationQualifier(DwcTerm.GROUP_IDENTIFICATION),
typeStatus(DwcTerm.GROUP_IDENTIFICATION),
identifiedBy(DwcTerm.GROUP_IDENTIFICATION),
dateIdentified(DwcTerm.GROUP_IDENTIFICATION),
identificationReferences(DwcTerm.GROUP_IDENTIFICATION),
identificationVerificationStatus(DwcTerm.GROUP_IDENTIFICATION),
identificationRemarks(DwcTerm.GROUP_IDENTIFICATION),
taxonID(DwcTerm.GROUP_TAXON, "nameUsageID"),
scientificNameID(DwcTerm.GROUP_TAXON, "nameID"),
acceptedNameUsageID(DwcTerm.GROUP_TAXON, "acceptedTaxonID"),
parentNameUsageID(DwcTerm.GROUP_TAXON, "parentTaxonID", "higherTaxonID", "higherNameUsageID"),
originalNameUsageID(DwcTerm.GROUP_TAXON, "originalNameID", "originalTaxonID", "basionymID"),
nameAccordingToID(DwcTerm.GROUP_TAXON, "taxonAccordingToID"),
namePublishedInID(DwcTerm.GROUP_TAXON),
taxonConceptID(DwcTerm.GROUP_TAXON),
scientificName(DwcTerm.GROUP_TAXON),
acceptedNameUsage(DwcTerm.GROUP_TAXON, "acceptedTaxon"),
parentNameUsage(DwcTerm.GROUP_TAXON, "parentTaxon", "higherTaxon", "higherNameUsage"),
originalNameUsage(DwcTerm.GROUP_TAXON, "originalName", "originalTaxon", "basionym"),
nameAccordingTo(DwcTerm.GROUP_TAXON, "taxonAccordingTo"),
namePublishedIn(DwcTerm.GROUP_TAXON),
namePublishedInYear(DwcTerm.GROUP_TAXON),
higherClassification(DwcTerm.GROUP_TAXON),
kingdom(DwcTerm.GROUP_TAXON),
phylum(DwcTerm.GROUP_TAXON),
/**
* The taxonomic class.
* The real Darwin Core term is class, but as java does not allow this name we use a variation instead.
*/
class_(DwcTerm.GROUP_TAXON, "class"),
order(DwcTerm.GROUP_TAXON),
family(DwcTerm.GROUP_TAXON),
genus(DwcTerm.GROUP_TAXON),
subgenus(DwcTerm.GROUP_TAXON),
specificEpithet(DwcTerm.GROUP_TAXON),
infraspecificEpithet(DwcTerm.GROUP_TAXON),
taxonRank(DwcTerm.GROUP_TAXON, "rank"),
verbatimTaxonRank(DwcTerm.GROUP_TAXON),
scientificNameAuthorship(DwcTerm.GROUP_TAXON),
vernacularName(DwcTerm.GROUP_TAXON),
nomenclaturalCode(DwcTerm.GROUP_TAXON),
taxonomicStatus(DwcTerm.GROUP_TAXON),
nomenclaturalStatus(DwcTerm.GROUP_TAXON),
taxonRemarks(DwcTerm.GROUP_TAXON, "taxonRemark"),
measurementID(DwcTerm.GROUP_MEASUREMENTORFACT),
measurementType(DwcTerm.GROUP_MEASUREMENTORFACT),
measurementValue(DwcTerm.GROUP_MEASUREMENTORFACT),
measurementAccuracy(DwcTerm.GROUP_MEASUREMENTORFACT),
measurementUnit(DwcTerm.GROUP_MEASUREMENTORFACT),
measurementDeterminedBy(DwcTerm.GROUP_MEASUREMENTORFACT),
measurementDeterminedDate(DwcTerm.GROUP_MEASUREMENTORFACT),
measurementMethod(DwcTerm.GROUP_MEASUREMENTORFACT),
measurementRemarks(DwcTerm.GROUP_MEASUREMENTORFACT),
resourceRelationshipID(DwcTerm.GROUP_RESOURCERELATIONSHIP),
resourceID(DwcTerm.GROUP_RESOURCERELATIONSHIP),
relatedResourceID(DwcTerm.GROUP_RESOURCERELATIONSHIP),
relationshipOfResource(DwcTerm.GROUP_RESOURCERELATIONSHIP),
relationshipAccordingTo(DwcTerm.GROUP_RESOURCERELATIONSHIP),
relationshipEstablishedDate(DwcTerm.GROUP_RESOURCERELATIONSHIP),
relationshipRemarks(DwcTerm.GROUP_RESOURCERELATIONSHIP);
public static final String NS = "http://rs.tdwg.org/dwc/terms/";
public static final String PREFIX = "dwc";
static final String[] PREFIXES = {NS, PREFIX + ":", "darwin:", "darwincore:", "dw:"};
public static final String GROUP_RECORD = "Record";
public static final String GROUP_OCCURRENCE = "Occurrence";
public static final String GROUP_ORGANISM = "Organism";
public static final String GROUP_MATERIAL_SAMPLE = "MaterialSample";
public static final String GROUP_EVENT = "Event";
public static final String GROUP_LOCATION = "Location";
public static final String GROUP_GEOLOGICALCONTEXT = "GeologicalContext";
public static final String GROUP_IDENTIFICATION = "Identification";
public static final String GROUP_TAXON = "Taxon";
public static final String GROUP_MEASUREMENTORFACT = "MeasurementOrFact";
public static final String GROUP_RESOURCERELATIONSHIP = "ResourceRelationship";
public static final String[] GROUPS =
{GROUP_RECORD, GROUP_OCCURRENCE, GROUP_ORGANISM, GROUP_EVENT, GROUP_LOCATION,
GROUP_GEOLOGICALCONTEXT, GROUP_IDENTIFICATION, GROUP_TAXON,
GROUP_MEASUREMENTORFACT, GROUP_RESOURCERELATIONSHIP};
public static final DwcTerm[] TAXONOMIC_TERMS =
{DwcTerm.taxonID, DwcTerm.scientificNameID, DwcTerm.acceptedNameUsageID,
DwcTerm.parentNameUsageID, DwcTerm.originalNameUsageID,
DwcTerm.nameAccordingToID, DwcTerm.namePublishedInID, DwcTerm.taxonConceptID,
DwcTerm.scientificName, DwcTerm.acceptedNameUsage, DwcTerm.parentNameUsage,
DwcTerm.originalNameUsage, DwcTerm.nameAccordingTo, DwcTerm.namePublishedIn,
DwcTerm.namePublishedInYear, DwcTerm.higherClassification, DwcTerm.kingdom,
DwcTerm.phylum, DwcTerm.class_, DwcTerm.order, DwcTerm.family, DwcTerm.genus,
DwcTerm.subgenus, DwcTerm.specificEpithet, DwcTerm.infraspecificEpithet,
DwcTerm.taxonRank, DwcTerm.verbatimTaxonRank, DwcTerm.scientificNameAuthorship,
DwcTerm.vernacularName, DwcTerm.nomenclaturalCode, DwcTerm.taxonomicStatus,
DwcTerm.nomenclaturalStatus, DwcTerm.taxonRemarks};
/**
* List of all higher rank terms in dwc, ordered by rank and starting with kingdom.
*/
public static final DwcTerm[] HIGHER_RANKS =
{DwcTerm.kingdom, DwcTerm.phylum, DwcTerm.class_, DwcTerm.order, DwcTerm.family,
DwcTerm.genus, DwcTerm.subgenus};
/**
* List of all class terms in dwc.
*/
//TODO: create dynamically via method!
// Location is not in this list because it is in the dcterms namespace.
public static final DwcTerm[] CLASS_TERMS =
{DwcTerm.Occurrence, DwcTerm.Organism, DwcTerm.MaterialSample, DwcTerm.Event,
DwcTerm.GeologicalContext, DwcTerm.Identification, DwcTerm.Taxon,
DwcTerm.MeasurementOrFact, DwcTerm.ResourceRelationship};
private final String groupName;
public final String normQName;
public final String[] normAlts;
private DwcTerm(String groupName, String... alternatives) {
normQName = TermFactory.normaliseTerm(qualifiedName());
for (int i = 0; i < alternatives.length; i++) {
alternatives[i] = TermFactory.normaliseTerm(alternatives[i]);
}
normAlts = alternatives;
this.groupName = groupName;
}
@Override
public String qualifiedName() {
return NS + simpleName();
}
/**
* The simple term name without a namespace.
* For example scientificName.
* @return simple term name
*/
@Override
public String simpleName() {
if (this == class_) {
return "class";
}
return name();
}
/**
* Array of alternative simple names in use for the term.
* Often based on older dwc versions.
* @return simple term name
*/
@Override
public String[] alternativeNames() {
return normAlts;
}
/**
* The optional group the term is grouped in.
* For example Taxon, Identification, etc.
*/
public String getGroup() {
return groupName;
}
/**
* @return true if the dwc term is defining a class instead of a property, e.g. Taxon
*/
public boolean isClass() {
return Character.isUpperCase(simpleName().charAt(0));
}
/**
* List all terms that belong to a given group.
*
* @param group the group to list terms for
*
* @return the list of dwc terms in the given group
*/
public static List<DwcTerm> listByGroup(String group) {
List<DwcTerm> terms = new ArrayList<DwcTerm>();
for (DwcTerm t : DwcTerm.values()) {
if (t.getGroup().equalsIgnoreCase(group)) {
terms.add(t);
}
}
return terms;
}
@Override
public String toString() {
return PREFIX + ":" + name();
}
} |
package org.gitlab4j.api;
import java.util.Collections;
import java.util.Map;
import java.util.Optional;
import java.util.WeakHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.gitlab4j.api.Constants.TokenType;
import org.gitlab4j.api.models.OauthTokenResponse;
import org.gitlab4j.api.models.Session;
import org.gitlab4j.api.models.User;
import org.gitlab4j.api.models.Version;
import org.gitlab4j.api.utils.Oauth2LoginStreamingOutput;
import org.gitlab4j.api.utils.SecretString;
/**
* This class is provides a simplified interface to a GitLab API server, and divides the API up into
* a separate API class for each concern.
*/
public class GitLabApi {
private final static Logger LOGGER = Logger.getLogger(GitLabApi.class.getName());
/** GitLab4J default per page. GitLab will ignore anything over 100. */
public static final int DEFAULT_PER_PAGE = 100;
/** Specifies the version of the GitLab API to communicate with. */
public enum ApiVersion {
V3, V4, OAUTH2_CLIENT;
public String getApiNamespace() {
return ("/api/" + name().toLowerCase());
}
}
// Used to keep track of GitLabApiExceptions on calls that return Optional<?>
private static final Map<Optional<?>, GitLabApiException> optionalExceptionMap =
Collections.synchronizedMap(new WeakHashMap<Optional<?>, GitLabApiException>());
GitLabApiClient apiClient;
private ApiVersion apiVersion;
private String gitLabServerUrl;
private Map<String, Object> clientConfigProperties;
private int defaultPerPage = DEFAULT_PER_PAGE;
private Session session;
private AwardEmojiApi awardEmojiApi;
private CommitsApi commitsApi;
private DiscussionsApi discussionsApi;
private DeployKeysApi deployKeysApi;
private EpicsApi epicsApi;
private EventsApi eventsApi;
private GroupApi groupApi;
private HealthCheckApi healthCheckApi;
private IssuesApi issuesApi;
private JobApi jobApi;
private LabelsApi labelsApi;
private LicensesApi licensesApi;
private MarkdownApi markdownApi;
private MergeRequestApi mergeRequestApi;
private MilestonesApi milestonesApi;
private NamespaceApi namespaceApi;
private NotesApi notesApi;
private NotificationSettingsApi notificationSettingsApi;
private PipelineApi pipelineApi;
private ProjectApi projectApi;
private ProtectedBranchesApi protectedBranchesApi;
private RepositoryApi repositoryApi;
private RepositoryFileApi repositoryFileApi;
private RunnersApi runnersApi;
private ServicesApi servicesApi;
private SessionApi sessionApi;
private SnippetsApi snippetsApi;
private SystemHooksApi systemHooksApi;
private TagsApi tagsApi;
private UserApi userApi;
private WikisApi wikisApi;
/**
* Get the GitLab4J shared Logger instance.
*
* @return the GitLab4J shared Logger instance
*/
public static final Logger getLogger() {
return (LOGGER);
}
/**
* Create a new GitLabApi instance that is logically a duplicate of this instance, with the exception off sudo state.
*
* @return a new GitLabApi instance that is logically a duplicate of this instance, with the exception off sudo state.
*/
public final GitLabApi duplicate() {
Integer sudoUserId = this.getSudoAsId();
GitLabApi gitLabApi = new GitLabApi(apiVersion, gitLabServerUrl,
getTokenType(), getAuthToken(), getSecretToken(), clientConfigProperties);
if (sudoUserId != null) {
gitLabApi.apiClient.setSudoAsId(sudoUserId);
}
if (getIgnoreCertificateErrors()) {
gitLabApi.setIgnoreCertificateErrors(true);
}
gitLabApi.defaultPerPage = this.defaultPerPage;
return (gitLabApi);
}
/**
* <p>Logs into GitLab using OAuth2 with the provided {@code username} and {@code password},
* and creates a new {@code GitLabApi} instance using returned access token.</p>
*
* @param url GitLab URL
* @param username user name for which private token should be obtained
* @param password a CharSequence containing the password for a given {@code username}
* @return new {@code GitLabApi} instance configured for a user-specific token
* @throws GitLabApiException GitLabApiException if any exception occurs during execution
*/
public static GitLabApi oauth2Login(String url, String username, CharSequence password) throws GitLabApiException {
return (GitLabApi.oauth2Login(ApiVersion.V4, url, username, password, null, null, false));
}
/**
* <p>Logs into GitLab using OAuth2 with the provided {@code username} and {@code password},
* and creates a new {@code GitLabApi} instance using returned access token.</p>
*
* @param url GitLab URL
* @param username user name for which private token should be obtained
* @param password a char array holding the password for a given {@code username}
* @return new {@code GitLabApi} instance configured for a user-specific token
* @throws GitLabApiException GitLabApiException if any exception occurs during execution
*/
public static GitLabApi oauth2Login(String url, String username, char[] password) throws GitLabApiException {
try (SecretString secretPassword = new SecretString(password)) {
return (GitLabApi.oauth2Login(ApiVersion.V4, url, username, secretPassword, null, null, false));
}
}
/**
* <p>Logs into GitLab using OAuth2 with the provided {@code username} and {@code password},
* and creates a new {@code GitLabApi} instance using returned access token.</p>
*
* @param url GitLab URL
* @param username user name for which private token should be obtained
* @param password a CharSequence containing the password for a given {@code username}
* @param ignoreCertificateErrors if true will set up the Jersey system ignore SSL certificate errors
* @return new {@code GitLabApi} instance configured for a user-specific token
* @throws GitLabApiException GitLabApiException if any exception occurs during execution
*/
public static GitLabApi oauth2Login(String url, String username, CharSequence password, boolean ignoreCertificateErrors) throws GitLabApiException {
return (GitLabApi.oauth2Login(ApiVersion.V4, url, username, password, null, null, ignoreCertificateErrors));
}
/**
* <p>Logs into GitLab using OAuth2 with the provided {@code username} and {@code password},
* and creates a new {@code GitLabApi} instance using returned access token.</p>
*
* @param url GitLab URL
* @param username user name for which private token should be obtained
* @param password a char array holding the password for a given {@code username}
* @param ignoreCertificateErrors if true will set up the Jersey system ignore SSL certificate errors
* @return new {@code GitLabApi} instance configured for a user-specific token
* @throws GitLabApiException GitLabApiException if any exception occurs during execution
*/
public static GitLabApi oauth2Login(String url, String username, char[] password, boolean ignoreCertificateErrors) throws GitLabApiException {
try (SecretString secretPassword = new SecretString(password)) {
return (GitLabApi.oauth2Login(ApiVersion.V4, url, username, secretPassword, null, null, ignoreCertificateErrors));
}
}
/**
* <p>Logs into GitLab using OAuth2 with the provided {@code username} and {@code password},
* and creates a new {@code GitLabApi} instance using returned access token.</p>
*
* @param url GitLab URL
* @param username user name for which private token should be obtained
* @param password a CharSequence containing the password for a given {@code username}
* @param secretToken use this token to validate received payloads
* @param clientConfigProperties Map instance with additional properties for the Jersey client connection
* @param ignoreCertificateErrors if true will set up the Jersey system ignore SSL certificate errors
* @return new {@code GitLabApi} instance configured for a user-specific token
* @throws GitLabApiException GitLabApiException if any exception occurs during execution
*/
public static GitLabApi oauth2Login(String url, String username, CharSequence password, String secretToken,
Map<String, Object> clientConfigProperties, boolean ignoreCertificateErrors) throws GitLabApiException {
return (GitLabApi.oauth2Login(ApiVersion.V4, url, username, password, secretToken, clientConfigProperties, ignoreCertificateErrors));
}
/**
* <p>Logs into GitLab using OAuth2 with the provided {@code username} and {@code password},
* and creates a new {@code GitLabApi} instance using returned access token.</p>
*
* @param url GitLab URL
* @param username user name for which private token should be obtained
* @param password a char array holding the password for a given {@code username}
* @param secretToken use this token to validate received payloads
* @param clientConfigProperties Map instance with additional properties for the Jersey client connection
* @param ignoreCertificateErrors if true will set up the Jersey system ignore SSL certificate errors
* @return new {@code GitLabApi} instance configured for a user-specific token
* @throws GitLabApiException GitLabApiException if any exception occurs during execution
*/
public static GitLabApi oauth2Login(String url, String username, char[] password, String secretToken,
Map<String, Object> clientConfigProperties, boolean ignoreCertificateErrors) throws GitLabApiException {
try (SecretString secretPassword = new SecretString(password)) {
return (GitLabApi.oauth2Login(ApiVersion.V4, url, username, secretPassword,
secretToken, clientConfigProperties, ignoreCertificateErrors));
}
}
/**
* <p>Logs into GitLab using OAuth2 with the provided {@code username} and {@code password},
* and creates a new {@code GitLabApi} instance using returned access token.</p>
*
* @param url GitLab URL
* @param apiVersion the ApiVersion specifying which version of the API to use
* @param username user name for which private token should be obtained
* @param password a char array holding the password for a given {@code username}
* @param secretToken use this token to validate received payloads
* @param clientConfigProperties Map instance with additional properties for the Jersey client connection
* @param ignoreCertificateErrors if true will set up the Jersey system ignore SSL certificate errors
* @return new {@code GitLabApi} instance configured for a user-specific token
* @throws GitLabApiException GitLabApiException if any exception occurs during execution
*/
public static GitLabApi oauth2Login(ApiVersion apiVersion, String url, String username, char[] password, String secretToken,
Map<String, Object> clientConfigProperties, boolean ignoreCertificateErrors) throws GitLabApiException {
try (SecretString secretPassword = new SecretString(password)) {
return (GitLabApi.oauth2Login(apiVersion, url, username, secretPassword,
secretToken, clientConfigProperties, ignoreCertificateErrors));
}
}
/**
* <p>Logs into GitLab using OAuth2 with the provided {@code username} and {@code password},
* and creates a new {@code GitLabApi} instance using returned access token.</p>
*
* @param url GitLab URL
* @param apiVersion the ApiVersion specifying which version of the API to use
* @param username user name for which private token should be obtained
* @param password password for a given {@code username}
* @param secretToken use this token to validate received payloads
* @param clientConfigProperties Map instance with additional properties for the Jersey client connection
* @param ignoreCertificateErrors if true will set up the Jersey system ignore SSL certificate errors
* @return new {@code GitLabApi} instance configured for a user-specific token
* @throws GitLabApiException GitLabApiException if any exception occurs during execution
*/
public static GitLabApi oauth2Login(ApiVersion apiVersion, String url, String username, CharSequence password,
String secretToken, Map<String, Object> clientConfigProperties, boolean ignoreCertificateErrors) throws GitLabApiException {
if (username == null || username.trim().length() == 0) {
throw new IllegalArgumentException("both username and email cannot be empty or null");
}
GitLabApi gitLabApi = new GitLabApi(ApiVersion.OAUTH2_CLIENT, url, (String)null);
if (ignoreCertificateErrors) {
gitLabApi.setIgnoreCertificateErrors(true);
}
class Oauth2Api extends AbstractApi {
Oauth2Api(GitLabApi gitlabApi) {
super(gitlabApi);
}
}
try (Oauth2LoginStreamingOutput stream = new Oauth2LoginStreamingOutput(username, password)) {
Response response = new Oauth2Api(gitLabApi).post(Response.Status.OK, stream, MediaType.APPLICATION_JSON, "oauth", "token");
OauthTokenResponse oauthToken = response.readEntity(OauthTokenResponse.class);
gitLabApi = new GitLabApi(apiVersion, url, TokenType.ACCESS, oauthToken.getAccessToken(), secretToken, clientConfigProperties);
if (ignoreCertificateErrors) {
gitLabApi.setIgnoreCertificateErrors(true);
}
return (gitLabApi);
}
}
/**
* <p>Logs into GitLab using provided {@code username} and {@code password}, and creates a new {@code GitLabApi} instance
* using returned private token and the specified GitLab API version.</p>
*
* <strong>NOTE</strong>: For GitLab servers 10.2 and above this will utilize OAUTH2 for login. For GitLab servers prior to
* 10.2, the Session API login is utilized.
*
* @param apiVersion the ApiVersion specifying which version of the API to use
* @param url GitLab URL
* @param username user name for which private token should be obtained
* @param password password for a given {@code username}
* @return new {@code GitLabApi} instance configured for a user-specific token
* @throws GitLabApiException GitLabApiException if any exception occurs during execution
* @deprecated As of release 4.8.7, will be removed in 4.9.0
*/
@Deprecated
public static GitLabApi login(ApiVersion apiVersion, String url, String username, String password) throws GitLabApiException {
return (GitLabApi.login(apiVersion, url, username, password, false));
}
/**
* <p>Logs into GitLab using provided {@code username} and {@code password}, and creates a new {@code GitLabApi} instance
* using returned private token using GitLab API version 4.</p>
*
* <strong>NOTE</strong>: For GitLab servers 10.2 and above this will utilize OAUTH2 for login. For GitLab servers prior to
* 10.2, the Session API login is utilized.
*
* @param url GitLab URL
* @param username user name for which private token should be obtained
* @param password password for a given {@code username}
* @return new {@code GitLabApi} instance configured for a user-specific token
* @throws GitLabApiException GitLabApiException if any exception occurs during execution
* @deprecated As of release 4.8.7, will be removed in 4.9.0
*/
@Deprecated
public static GitLabApi login(String url, String username, String password) throws GitLabApiException {
return (GitLabApi.login(ApiVersion.V4, url, username, password, false));
}
/**
* <p>Logs into GitLab using provided {@code username} and {@code password}, and creates a new {@code GitLabApi} instance
* using returned private token and the specified GitLab API version.</p>
*
* <strong>NOTE</strong>: For GitLab servers 10.2 and above this will utilize OAUTH2 for login. For GitLab servers prior to
* 10.2, the Session API login is utilized.
*
* @param apiVersion the ApiVersion specifying which version of the API to use
* @param url GitLab URL
* @param username user name for which private token should be obtained
* @param password password for a given {@code username}
* @param ignoreCertificateErrors if true will set up the Jersey system ignore SSL certificate errors
* @return new {@code GitLabApi} instance configured for a user-specific token
* @throws GitLabApiException GitLabApiException if any exception occurs during execution
* @deprecated As of release 4.8.7, will be removed in 4.9.0
*/
@Deprecated
public static GitLabApi login(ApiVersion apiVersion, String url, String username, String password, boolean ignoreCertificateErrors) throws GitLabApiException {
GitLabApi gitLabApi = new GitLabApi(apiVersion, url, (String)null);
if (ignoreCertificateErrors) {
gitLabApi.setIgnoreCertificateErrors(true);
}
try {
SessionApi sessionApi = gitLabApi.getSessionApi();
Session session = sessionApi.login(username, null, password);
gitLabApi = new GitLabApi(apiVersion, url, session);
if (ignoreCertificateErrors) {
gitLabApi.setIgnoreCertificateErrors(true);
}
} catch (GitLabApiException gle) {
if (gle.getHttpStatus() != Response.Status.NOT_FOUND.getStatusCode()) {
throw (gle);
} else {
gitLabApi = GitLabApi.oauth2Login(apiVersion, url, username, password, null, null, ignoreCertificateErrors);
}
}
return (gitLabApi);
}
/**
* <p>Logs into GitLab using provided {@code username} and {@code password}, and creates a new {@code GitLabApi} instance
* using returned private token using GitLab API version 4.</p>
*
* <strong>NOTE</strong>: For GitLab servers 10.2 and above this will utilize OAUTH2 for login. For GitLab servers prior to
* 10.2, the Session API login is utilized.
*
* @param url GitLab URL
* @param username user name for which private token should be obtained
* @param password password for a given {@code username}
* @param ignoreCertificateErrors if true will set up the Jersey system ignore SSL certificate errors
* @return new {@code GitLabApi} instance configured for a user-specific token
* @throws GitLabApiException GitLabApiException if any exception occurs during execution
* @deprecated As of release 4.8.7, will be removed in 4.9.0
*/
@Deprecated
public static GitLabApi login(String url, String username, String password, boolean ignoreCertificateErrors) throws GitLabApiException {
return (GitLabApi.login(ApiVersion.V4, url, username, password, ignoreCertificateErrors));
}
/**
* <p>If this instance was created with {@link #login(String, String, String)} this method will
* return the Session instance returned by the GitLab API on login, otherwise returns null.</p>
*
* <strong>NOTE</strong>: For GitLab servers 10.2 and above this method will always return null.
*
* @return the Session instance
* @deprecated This method will be removed in Release 4.9.0
*/
@Deprecated
public Session getSession() {
return session;
}
/**
* Constructs a GitLabApi instance set up to interact with the GitLab server using the specified GitLab API version.
*
* @param apiVersion the ApiVersion specifying which version of the API to use
* @param hostUrl the URL of the GitLab server
* @param tokenType the type of auth the token is for, PRIVATE or ACCESS
* @param authToken the token to use for access to the API
*/
public GitLabApi(ApiVersion apiVersion, String hostUrl, TokenType tokenType, String authToken) {
this(apiVersion, hostUrl, tokenType, authToken, null);
}
/**
* Constructs a GitLabApi instance set up to interact with the GitLab server using the specified GitLab API version.
*
* @param apiVersion the ApiVersion specifying which version of the API to use
* @param hostUrl the URL of the GitLab server
* @param privateToken to private token to use for access to the API
*/
public GitLabApi(ApiVersion apiVersion, String hostUrl, String privateToken) {
this(apiVersion, hostUrl, privateToken, null);
}
/**
* Constructs a GitLabApi instance set up to interact with the GitLab server using GitLab API version 4.
*
* @param hostUrl the URL of the GitLab server
* @param tokenType the type of auth the token is for, PRIVATE or ACCESS
* @param authToken the token to use for access to the API
*/
public GitLabApi(String hostUrl, TokenType tokenType, String authToken) {
this(ApiVersion.V4, hostUrl, tokenType, authToken, null);
}
/**
* Constructs a GitLabApi instance set up to interact with the GitLab server using GitLab API version 4.
*
* @param hostUrl the URL of the GitLab server
* @param privateToken to private token to use for access to the API
*/
public GitLabApi(String hostUrl, String privateToken) {
this(ApiVersion.V4, hostUrl, privateToken, null);
}
/**
* Constructs a GitLabApi instance set up to interact with the GitLab server using the specified GitLab API version.
*
* @param apiVersion the ApiVersion specifying which version of the API to use
* @param hostUrl the URL of the GitLab server
* @param session the Session instance obtained by logining into the GitLab server
*/
public GitLabApi(ApiVersion apiVersion, String hostUrl, Session session) {
this(apiVersion, hostUrl, TokenType.PRIVATE, session.getPrivateToken(), null);
this.session = session;
}
/**
* Constructs a GitLabApi instance set up to interact with the GitLab server using GitLab API version 4.
*
* @param hostUrl the URL of the GitLab server
* @param session the Session instance obtained by logining into the GitLab server
*/
public GitLabApi(String hostUrl, Session session) {
this(ApiVersion.V4, hostUrl, session);
}
/**
* Constructs a GitLabApi instance set up to interact with the GitLab server using the specified GitLab API version.
*
* @param apiVersion the ApiVersion specifying which version of the API to use
* @param hostUrl the URL of the GitLab server
* @param tokenType the type of auth the token is for, PRIVATE or ACCESS
* @param authToken the token to use for access to the API
* @param secretToken use this token to validate received payloads
*/
public GitLabApi(ApiVersion apiVersion, String hostUrl, TokenType tokenType, String authToken, String secretToken) {
this(apiVersion, hostUrl, tokenType, authToken, secretToken, null);
}
/**
* Constructs a GitLabApi instance set up to interact with the GitLab server using the specified GitLab API version.
*
* @param apiVersion the ApiVersion specifying which version of the API to use
* @param hostUrl the URL of the GitLab server
* @param privateToken to private token to use for access to the API
* @param secretToken use this token to validate received payloads
*/
public GitLabApi(ApiVersion apiVersion, String hostUrl, String privateToken, String secretToken) {
this(apiVersion, hostUrl, privateToken, secretToken, null);
}
/**
* Constructs a GitLabApi instance set up to interact with the GitLab server using GitLab API version 4.
*
* @param hostUrl the URL of the GitLab server
* @param tokenType the type of auth the token is for, PRIVATE or ACCESS
* @param authToken the token to use for access to the API
* @param secretToken use this token to validate received payloads
*/
public GitLabApi(String hostUrl, TokenType tokenType, String authToken, String secretToken) {
this(ApiVersion.V4, hostUrl, tokenType, authToken, secretToken);
}
/**
* Constructs a GitLabApi instance set up to interact with the GitLab server using GitLab API version 4.
*
* @param hostUrl the URL of the GitLab server
* @param privateToken to private token to use for access to the API
* @param secretToken use this token to validate received payloads
*/
public GitLabApi(String hostUrl, String privateToken, String secretToken) {
this(ApiVersion.V4, hostUrl, TokenType.PRIVATE, privateToken, secretToken);
}
/**
* Constructs a GitLabApi instance set up to interact with the GitLab server specified by GitLab API version.
*
* @param apiVersion the ApiVersion specifying which version of the API to use
* @param hostUrl the URL of the GitLab server
* @param privateToken to private token to use for access to the API
* @param secretToken use this token to validate received payloads
* @param clientConfigProperties Map instance with additional properties for the Jersey client connection
*/
public GitLabApi(ApiVersion apiVersion, String hostUrl, String privateToken, String secretToken, Map<String, Object> clientConfigProperties) {
this(apiVersion, hostUrl, TokenType.PRIVATE, privateToken, secretToken, clientConfigProperties);
}
/**
* Constructs a GitLabApi instance set up to interact with the GitLab server using GitLab API version 4.
*
* @param hostUrl the URL of the GitLab server
* @param tokenType the type of auth the token is for, PRIVATE or ACCESS
* @param authToken the token to use for access to the API
* @param secretToken use this token to validate received payloads
* @param clientConfigProperties Map instance with additional properties for the Jersey client connection
*/
public GitLabApi(String hostUrl, TokenType tokenType, String authToken, String secretToken, Map<String, Object> clientConfigProperties) {
this(ApiVersion.V4, hostUrl, tokenType, authToken, secretToken, clientConfigProperties);
}
/**
* Constructs a GitLabApi instance set up to interact with the GitLab server using GitLab API version 4.
*
* @param hostUrl the URL of the GitLab server
* @param privateToken to private token to use for access to the API
* @param secretToken use this token to validate received payloads
* @param clientConfigProperties Map instance with additional properties for the Jersey client connection
*/
public GitLabApi(String hostUrl, String privateToken, String secretToken, Map<String, Object> clientConfigProperties) {
this(ApiVersion.V4, hostUrl, TokenType.PRIVATE, privateToken, secretToken, clientConfigProperties);
}
/**
* Constructs a GitLabApi instance set up to interact with the GitLab server specified by GitLab API version.
*
* @param apiVersion the ApiVersion specifying which version of the API to use
* @param hostUrl the URL of the GitLab server
* @param tokenType the type of auth the token is for, PRIVATE or ACCESS
* @param authToken to token to use for access to the API
* @param secretToken use this token to validate received payloads
* @param clientConfigProperties Map instance with additional properties for the Jersey client connection
*/
public GitLabApi(ApiVersion apiVersion, String hostUrl, TokenType tokenType, String authToken, String secretToken, Map<String, Object> clientConfigProperties) {
this.apiVersion = apiVersion;
this.gitLabServerUrl = hostUrl;
this.clientConfigProperties = clientConfigProperties;
apiClient = new GitLabApiClient(apiVersion, hostUrl, tokenType, authToken, secretToken, clientConfigProperties);
}
/**
* Enable the logging of the requests to and the responses from the GitLab server API
* using the GitLab4J shared Logger instance and Level.FINE as the level.
*
* @return this GitLabApi instance
*/
public GitLabApi withRequestResponseLogging() {
enableRequestResponseLogging();
return (this);
}
/**
* Enable the logging of the requests to and the responses from the GitLab server API
* using the GitLab4J shared Logger instance.
*
* @param level the logging level (SEVERE, WARNING, INFO, CONFIG, FINE, FINER, FINEST)
* @return this GitLabApi instance
*/
public GitLabApi withRequestResponseLogging(Level level) {
enableRequestResponseLogging(level);
return (this);
}
/**
* Enable the logging of the requests to and the responses from the GitLab server API.
*
* @param logger the Logger instance to log to
* @param level the logging level (SEVERE, WARNING, INFO, CONFIG, FINE, FINER, FINEST)
* @return this GitLabApi instance
*/
public GitLabApi withRequestResponseLogging(Logger logger, Level level) {
enableRequestResponseLogging(logger, level);
return (this);
}
/**
* Enable the logging of the requests to and the responses from the GitLab server API
* using the GitLab4J shared Logger instance and Level.FINE as the level.
*/
public void enableRequestResponseLogging() {
enableRequestResponseLogging(LOGGER, Level.FINE);
}
/**
* Enable the logging of the requests to and the responses from the GitLab server API
* using the GitLab4J shared Logger instance.
*
* @param level the logging level (SEVERE, WARNING, INFO, CONFIG, FINE, FINER, FINEST)
*/
public void enableRequestResponseLogging(Level level) {
enableRequestResponseLogging(LOGGER, level);
}
/**
* Enable the logging of the requests to and the responses from the GitLab server API.
*
* @param logger the Logger instance to log to
* @param level the logging level (SEVERE, WARNING, INFO, CONFIG, FINE, FINER, FINEST)
*/
public void enableRequestResponseLogging(Logger logger, Level level) {
this.apiClient.enableRequestResponseLogging(logger, level);
}
/**
* Sets up all future calls to the GitLab API to be done as another user specified by sudoAsUsername.
* To revert back to normal non-sudo operation you must call unsudo(), or pass null as the username.
*
* @param sudoAsUsername the username to sudo as, null will turn off sudo
* @throws GitLabApiException if any exception occurs
*/
public void sudo(String sudoAsUsername) throws GitLabApiException {
if (sudoAsUsername == null || sudoAsUsername.trim().length() == 0) {
apiClient.setSudoAsId(null);
return;
}
// Get the User specified by username, if you are not an admin or the username is not found, this will fail
User user = getUserApi().getUser(sudoAsUsername);
if (user == null || user.getId() == null) {
throw new GitLabApiException("the specified username was not found");
}
Integer sudoAsId = user.getId();
apiClient.setSudoAsId(sudoAsId);
}
/**
* Turns off the currently configured sudo as ID.
*/
public void unsudo() {
apiClient.setSudoAsId(null);
}
/**
* Sets up all future calls to the GitLab API to be done as another user specified by provided user ID.
* To revert back to normal non-sudo operation you must call unsudo(), or pass null as the sudoAsId.
*
* @param sudoAsId the ID of the user to sudo as, null will turn off sudo
* @throws GitLabApiException if any exception occurs
*/
public void setSudoAsId(Integer sudoAsId) throws GitLabApiException {
if (sudoAsId == null) {
apiClient.setSudoAsId(null);
return;
}
// Get the User specified by the sudoAsId, if you are not an admin or the username is not found, this will fail
User user = getUserApi().getUser(sudoAsId);
if (user == null || !user.getId().equals(sudoAsId)) {
throw new GitLabApiException("the specified user ID was not found");
}
apiClient.setSudoAsId(sudoAsId);
}
/**
* Get the current sudo as ID, will return null if not in sudo mode.
*
* @return the current sudo as ID, will return null if not in sudo mode
*/
public Integer getSudoAsId() {
return (apiClient.getSudoAsId());
}
/**
* Get the auth token being used by this client.
*
* @return the auth token being used by this client
*/
public String getAuthToken() {
return (apiClient.getAuthToken());
}
/**
* Get the secret token.
*
* @return the secret token
*/
public String getSecretToken() {
return (apiClient.getSecretToken());
}
/**
* Get the TokenType this client is using.
*
* @return the TokenType this client is using
*/
public TokenType getTokenType() {
return (apiClient.getTokenType());
}
/**
* Return the GitLab API version that this instance is using.
*
* @return the GitLab API version that this instance is using
*/
public ApiVersion getApiVersion() {
return (apiVersion);
}
/**
* Get the URL to the GitLab server.
*
* @return the URL to the GitLab server
*/
public String getGitLabServerUrl() {
return (gitLabServerUrl);
}
/**
* Get the default number per page for calls that return multiple items.
*
* @return the default number per page for calls that return multiple item
*/
public int getDefaultPerPage() {
return (defaultPerPage);
}
/**
* Set the default number per page for calls that return multiple items.
*
* @param defaultPerPage the new default number per page for calls that return multiple item
*/
public void setDefaultPerPage(int defaultPerPage) {
this.defaultPerPage = defaultPerPage;
}
/**
* Return the GitLabApiClient associated with this instance. This is used by all the sub API classes
* to communicate with the GitLab API.
*
* @return the GitLabApiClient associated with this instance
*/
GitLabApiClient getApiClient() {
return (apiClient);
}
/**
* Returns true if the API is setup to ignore SSL certificate errors, otherwise returns false.
*
* @return true if the API is setup to ignore SSL certificate errors, otherwise returns false
*/
public boolean getIgnoreCertificateErrors() {
return (apiClient.getIgnoreCertificateErrors());
}
/**
* Sets up the Jersey system ignore SSL certificate errors or not.
*
* @param ignoreCertificateErrors if true will set up the Jersey system ignore SSL certificate errors
*/
public void setIgnoreCertificateErrors(boolean ignoreCertificateErrors) {
apiClient.setIgnoreCertificateErrors(ignoreCertificateErrors);
}
/**
* Get the version info for the GitLab server using the GitLab Version API.
*
* @return the version info for the GitLab server
* @throws GitLabApiException if any exception occurs
*/
public Version getVersion() throws GitLabApiException {
class VersionApi extends AbstractApi {
VersionApi(GitLabApi gitlabApi) {
super(gitlabApi);
}
}
Response response = new VersionApi(this).get(Response.Status.OK, null, "version");
return (response.readEntity(Version.class));
}
/**
* Gets the AwardEmojiApi instance owned by this GitLabApi instance. The AwardEmojiApi is used
* to perform all award emoji related API calls.
*
* @return the AwardEmojiApi instance owned by this GitLabApi instance
*/
public AwardEmojiApi getAwardEmojiApi() {
if (awardEmojiApi == null) {
synchronized (this) {
if (awardEmojiApi == null) {
awardEmojiApi = new AwardEmojiApi(this);
}
}
}
return (awardEmojiApi);
}
/**
* Gets the CommitsApi instance owned by this GitLabApi instance. The CommitsApi is used
* to perform all commit related API calls.
*
* @return the CommitsApi instance owned by this GitLabApi instance
*/
public CommitsApi getCommitsApi() {
if (commitsApi == null) {
synchronized (this) {
if (commitsApi == null) {
commitsApi = new CommitsApi(this);
}
}
}
return (commitsApi);
}
/**
* Gets the DeployKeysApi instance owned by this GitLabApi instance. The DeployKeysApi is used
* to perform all deploy key related API calls.
*
* @return the DeployKeysApi instance owned by this GitLabApi instance
*/
public DeployKeysApi getDeployKeysApi() {
if (deployKeysApi == null) {
synchronized (this) {
if (deployKeysApi == null) {
deployKeysApi = new DeployKeysApi(this);
}
}
}
return (deployKeysApi);
}
/**
* Gets the DiscussionsApi instance owned by this GitLabApi instance. The DiscussionsApi is used
* to perform all discussion related API calls.
*
* @return the DiscussionsApi instance owned by this GitLabApi instance
*/
public DiscussionsApi getDiscussionsApi() {
if (discussionsApi == null) {
synchronized (this) {
if (discussionsApi == null) {
discussionsApi = new DiscussionsApi(this);
}
}
}
return (discussionsApi);
}
/**
* Gets the EpicsApi instance owned by this GitLabApi instance. The EpicsApi is used
* to perform all Epics and Epic Issues related API calls.
*
* @return the EpicsApi instance owned by this GitLabApi instance
*/
public EpicsApi getEpicsApi() {
if (epicsApi == null) {
synchronized (this) {
if (epicsApi == null) {
epicsApi = new EpicsApi(this);
}
}
}
return (epicsApi);
}
/**
* Gets the EventsApi instance owned by this GitLabApi instance. The EventsApi is used
* to perform all events related API calls.
*
* @return the EventsApi instance owned by this GitLabApi instance
*/
public EventsApi getEventsApi() {
if (eventsApi == null) {
synchronized (this) {
if (eventsApi == null) {
eventsApi = new EventsApi(this);
}
}
}
return (eventsApi);
}
/**
* Gets the GroupApi instance owned by this GitLabApi instance. The GroupApi is used
* to perform all group related API calls.
*
* @return the GroupApi instance owned by this GitLabApi instance
*/
public GroupApi getGroupApi() {
if (groupApi == null) {
synchronized (this) {
if (groupApi == null) {
groupApi = new GroupApi(this);
}
}
}
return (groupApi);
}
/**
* Gets the HealthCheckApi instance owned by this GitLabApi instance. The HealthCheckApi is used
* to perform all admin level gitlab health monitoring.
*
* @return the HealthCheckApi instance owned by this GitLabApi instance
*/
public HealthCheckApi getHealthCheckApi() {
if (healthCheckApi == null) {
synchronized (this) {
if (healthCheckApi == null) {
healthCheckApi = new HealthCheckApi(this);
}
}
}
return (healthCheckApi);
}
/**
* Gets the IssuesApi instance owned by this GitLabApi instance. The IssuesApi is used
* to perform all iossue related API calls.
*
* @return the CommitsApi instance owned by this GitLabApi instance
*/
public IssuesApi getIssuesApi() {
if (issuesApi == null) {
synchronized (this) {
if (issuesApi == null) {
issuesApi = new IssuesApi(this);
}
}
}
return (issuesApi);
}
/**
* Gets the JobApi instance owned by this GitLabApi instance. The JobApi is used
* to perform all jobs related API calls.
*
* @return the JobsApi instance owned by this GitLabApi instance
*/
public JobApi getJobApi() {
if (jobApi == null) {
synchronized (this) {
if (jobApi == null) {
jobApi = new JobApi(this);
}
}
}
return (jobApi);
}
public LabelsApi getLabelsApi() {
if (labelsApi == null) {
synchronized (this) {
if (labelsApi == null) {
labelsApi = new LabelsApi(this);
}
}
}
return (labelsApi);
}
public LicensesApi getLicensesApi() {
if (licensesApi == null) {
synchronized (this) {
if (licensesApi == null) {
licensesApi = new LicensesApi(this);
}
}
}
return (licensesApi);
}
/**
* Gets the MarkdownApi instance owned by this GitLabApi instance. The MarkdownApi is used
* to perform all markdown related API calls.
*
* @return the MarkdownApi instance owned by this GitLabApi instance
*/
public MarkdownApi getMarkdownApi() {
if (markdownApi == null) {
synchronized (this) {
if (markdownApi == null) {
markdownApi = new MarkdownApi(this);
}
}
}
return (markdownApi);
}
/**
* Gets the MergeRequestApi instance owned by this GitLabApi instance. The MergeRequestApi is used
* to perform all merge request related API calls.
*
* @return the MergeRequestApi instance owned by this GitLabApi instance
*/
public MergeRequestApi getMergeRequestApi() {
if (mergeRequestApi == null) {
synchronized (this) {
if (mergeRequestApi == null) {
mergeRequestApi = new MergeRequestApi(this);
}
}
}
return (mergeRequestApi);
}
/**
* Gets the MilsestonesApi instance owned by this GitLabApi instance.
*
* @return the MilsestonesApi instance owned by this GitLabApi instance
*/
public MilestonesApi getMilestonesApi() {
if (milestonesApi == null) {
synchronized (this) {
if (milestonesApi == null) {
milestonesApi = new MilestonesApi(this);
}
}
}
return (milestonesApi);
}
/**
* Gets the NamespaceApi instance owned by this GitLabApi instance. The NamespaceApi is used
* to perform all namespace related API calls.
*
* @return the NamespaceApi instance owned by this GitLabApi instance
*/
public NamespaceApi getNamespaceApi() {
if (namespaceApi == null) {
synchronized (this) {
if (namespaceApi == null) {
namespaceApi = new NamespaceApi(this);
}
}
}
return (namespaceApi);
}
/**
* Gets the NotesApi instance owned by this GitLabApi instance. The NotesApi is used
* to perform all notes related API calls.
*
* @return the NotesApi instance owned by this GitLabApi instance
*/
public NotesApi getNotesApi() {
if (notesApi == null) {
synchronized (this) {
if (notesApi == null) {
notesApi = new NotesApi(this);
}
}
}
return (notesApi);
}
/**
* Gets the NotesApi instance owned by this GitLabApi instance. The NotesApi is used
* to perform all notes related API calls.
*
* @return the NotesApi instance owned by this GitLabApi instance
*/
public NotificationSettingsApi getNotificationSettingsApi() {
if (notificationSettingsApi == null) {
synchronized (this) {
if (notificationSettingsApi == null) {
notificationSettingsApi = new NotificationSettingsApi(this);
}
}
}
return (notificationSettingsApi);
}
/**
* Gets the PipelineApi instance owned by this GitLabApi instance. The PipelineApi is used
* to perform all pipeline related API calls.
*
* @return the PipelineApi instance owned by this GitLabApi instance
*/
public PipelineApi getPipelineApi() {
if (pipelineApi == null) {
synchronized (this) {
if (pipelineApi == null) {
pipelineApi = new PipelineApi(this);
}
}
}
return (pipelineApi);
}
/**
* Gets the ProjectApi instance owned by this GitLabApi instance. The ProjectApi is used
* to perform all project related API calls.
*
* @return the ProjectApi instance owned by this GitLabApi instance
*/
public ProjectApi getProjectApi() {
if (projectApi == null) {
synchronized (this) {
if (projectApi == null) {
projectApi = new ProjectApi(this);
}
}
}
return (projectApi);
}
/**
* Gets the ProtectedBranchesApi instance owned by this GitLabApi instance. The ProtectedBranchesApi is used
* to perform all protection related actions on a branch of a project.
*
* @return the ProtectedBranchesApi instance owned by this GitLabApi instance
*/
public ProtectedBranchesApi getProtectedBranchesApi() {
if (this.protectedBranchesApi == null) {
synchronized (this) {
if (this.protectedBranchesApi == null) {
this.protectedBranchesApi = new ProtectedBranchesApi(this);
}
}
}
return (this.protectedBranchesApi);
}
/**
* Gets the RepositoryApi instance owned by this GitLabApi instance. The RepositoryApi is used
* to perform all repository related API calls.
*
* @return the RepositoryApi instance owned by this GitLabApi instance
*/
public RepositoryApi getRepositoryApi() {
if (repositoryApi == null) {
synchronized (this) {
if (repositoryApi == null) {
repositoryApi = new RepositoryApi(this);
}
}
}
return (repositoryApi);
}
/**
* Gets the RepositoryFileApi instance owned by this GitLabApi instance. The RepositoryFileApi is used
* to perform all repository files related API calls.
*
* @return the RepositoryFileApi instance owned by this GitLabApi instance
*/
public RepositoryFileApi getRepositoryFileApi() {
if (repositoryFileApi == null) {
synchronized (this) {
if (repositoryFileApi == null) {
repositoryFileApi = new RepositoryFileApi(this);
}
}
}
return (repositoryFileApi);
}
/**
* Gets the RunnersApi instance owned by this GitLabApi instance. The RunnersApi is used
* to perform all Runner related API calls.
*
* @return the RunnerApi instance owned by this GitLabApi instance
*/
public RunnersApi getRunnersApi() {
if (runnersApi == null) {
synchronized (this) {
if (runnersApi == null) {
runnersApi = new RunnersApi(this);
}
}
}
return (runnersApi);
}
/**
* Gets the ServicesApi instance owned by this GitLabApi instance. The ServicesApi is used
* to perform all services related API calls.
*
* @return the ServicesApi instance owned by this GitLabApi instance
*/
public ServicesApi getServicesApi() {
if (servicesApi == null) {
synchronized (this) {
if (servicesApi == null) {
servicesApi = new ServicesApi(this);
}
}
}
return (servicesApi);
}
/**
* Gets the SessionApi instance owned by this GitLabApi instance. The SessionApi is used
* to perform a login to the GitLab API.
*
* @return the SessionApi instance owned by this GitLabApi instance
*/
public SessionApi getSessionApi() {
if (sessionApi == null) {
synchronized (this) {
if (sessionApi == null) {
sessionApi = new SessionApi(this);
}
}
}
return (sessionApi);
}
/**
* Gets the SystemHooksApi instance owned by this GitLabApi instance. All methods
* require administrator authorization.
*
* @return the SystemHooksApi instance owned by this GitLabApi instance
*/
public SystemHooksApi getSystemHooksApi() {
if (systemHooksApi == null) {
synchronized (this) {
if (systemHooksApi == null) {
systemHooksApi = new SystemHooksApi(this);
}
}
}
return (systemHooksApi);
}
/**
* Gets the TagsApi instance owned by this GitLabApi instance. The TagsApi is used
* to perform all tag and release related API calls.
*
* @return the TagsApi instance owned by this GitLabApi instance
*/
public TagsApi getTagsApi() {
if (tagsApi == null) {
synchronized (this) {
if (tagsApi == null) {
tagsApi = new TagsApi(this);
}
}
}
return (tagsApi);
}
/**
* Gets the UserApi instance owned by this GitLabApi instance. The UserApi is used
* to perform all user related API calls.
*
* @return the UserApi instance owned by this GitLabApi instance
*/
public UserApi getUserApi() {
if (userApi == null) {
synchronized (this) {
if (userApi == null) {
userApi = new UserApi(this);
}
}
}
return (userApi);
}
/**
* Create and return an Optional instance associated with a GitLabApiException.
*
* @param <T> the type for the Optional parameter
* @param glae the GitLabApiException that was the result of a call to the GitLab API
* @return the created Optional instance
*/
protected static final <T> Optional<T> createOptionalFromException(GitLabApiException glae) {
Optional<T> optional = Optional.empty();
optionalExceptionMap.put(optional, glae);
return (optional);
}
/**
* Get the exception associated with the provided Optional instance, or null if no exception is
* associated with the Optional instance.
*
* @param optional the Optional instance to get the exception for
* @return the exception associated with the provided Optional instance, or null if no exception is
* associated with the Optional instance
*/
public static final GitLabApiException getOptionalException(Optional<?> optional) {
return (optionalExceptionMap.get(optional));
}
/**
* Return the Optional instances contained value, if present, otherwise throw the exception that is
* associated with the Optional instance.
*
* @param <T> the type for the Optional parameter
* @param optional the Optional instance to get the value for
* @return the value of the Optional instance if no exception is associated with it
* @throws GitLabApiException if there was an exception associated with the Optional instance
*/
public static final <T> T orElseThrow(Optional<T> optional) throws GitLabApiException {
GitLabApiException glea = getOptionalException(optional);
if (glea != null) {
throw (glea);
}
return (optional.get());
}
/**
* Gets the SnippetsApi instance owned by this GitLabApi instance. The SnippetsApi is used
* to perform all snippet related API calls.
*
* @return the SnippetsApi instance owned by this GitLabApi instance
*/
public SnippetsApi getSnippetApi() {
if (snippetsApi == null) {
synchronized (this) {
if (snippetsApi == null) {
snippetsApi = new SnippetsApi(this);
}
}
}
return snippetsApi;
}
/**
* Gets the WikisApi instance owned by this GitLabApi instance. The WikisApi is used to perform all wiki related API calls.
*
* @return the WikisApi instance owned by this GitLabApi instance
*/
public WikisApi getWikisApi() {
if (wikisApi == null) {
synchronized (this) {
if (wikisApi == null) {
wikisApi = new WikisApi(this);
}
}
}
return wikisApi;
}
} |
package org.kohsuke.github;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Locale;
import java.util.Map;
/**
* Utility class for creating and retrieving webhooks; removes duplication between GHOrganization and GHRepository
* functionality
*/
class GHHooks {
static abstract class Context {
private final GitHub root;
private Context(GitHub root) {
this.root = root;
}
public List<GHHook> getHooks() throws IOException {
GHHook [] hookArray = root.retrieve().to(collection(),collectionClass()); // jdk/eclipse bug requires this to be on separate line
List<GHHook> list = new ArrayList<GHHook>(Arrays.asList(hookArray));
for (GHHook h : list)
wrap(h);
return list;
}
public GHHook getHook(int id) throws IOException {
GHHook hook = root.retrieve().to(collection() + "/" + id, clazz());
return wrap(hook);
}
public GHHook createHook(String name, Map<String, String> config, Collection<GHEvent> events, boolean active) throws IOException {
List<String> ea = null;
if (events!=null) {
ea = new ArrayList<String>();
for (GHEvent e : events)
ea.add(e.name().toLowerCase(Locale.ENGLISH));
}
GHHook hook = new Requester(root)
.with("name", name)
.with("active", active)
._with("config", config)
._with("events", ea)
.to(collection(), clazz());
return wrap(hook);
}
abstract String collection();
abstract Class<? extends GHHook[]> collectionClass();
abstract Class<? extends GHHook> clazz();
abstract GHHook wrap(GHHook hook);
}
private static class RepoContext extends Context {
private final GHRepository repository;
private final GHUser owner;
private RepoContext(GHRepository repository, GHUser owner) {
super(repository.root);
this.repository = repository;
this.owner = owner;
}
@Override
String collection() {
return String.format("/repos/%s/%s/hooks", owner.getLogin(), repository.getName());
}
@Override
Class<? extends GHHook[]> collectionClass() {
return GHRepoHook[].class;
}
@Override
Class<? extends GHHook> clazz() {
return GHRepoHook.class;
}
@Override
GHHook wrap(GHHook hook) {
return ((GHRepoHook)hook).wrap(repository);
}
}
private static class OrgContext extends Context {
private final GHOrganization organization;
private OrgContext(GHOrganization organization) {
super(organization.root);
this.organization = organization;
}
@Override
String collection() {
return String.format("/orgs/%s/hooks", organization.getLogin());
}
@Override
Class<? extends GHHook[]> collectionClass() {
return GHOrgHook[].class;
}
@Override
Class<? extends GHHook> clazz() {
return GHOrgHook.class;
}
@Override
GHHook wrap(GHHook hook) {
return ((GHOrgHook)hook).wrap(organization);
}
}
static Context repoContext(GHRepository repository, GHUser owner) {
return new RepoContext(repository, owner);
}
static Context orgContext(GHOrganization organization) {
return new OrgContext(organization);
}
} |
package org.spoutcraft.client;
import org.spoutcraft.client.input.Input;
import org.spoutcraft.client.network.Network;
import org.spoutcraft.client.nterface.Interface;
import org.spoutcraft.client.universe.Universe;
/**
* The game class.
*/
public class Game {
private final Object wait = new Object();
private volatile boolean running = false;
private final Universe universe;
private final Interface nterface;
private final Network network;
private final Input input;
static {
try {
Class.forName("org.spoutcraft.client.universe.block.material.Materials");
} catch (Exception ex) {
System.out.println("Couldn't load the default materials");
}
}
public Game() {
universe = new Universe(this);
nterface = new Interface(this);
network = new Network(this);
input = new Input(this);
}
public void start() {
universe.start();
nterface.start();
input.start();
network.start();
running = true;
}
private void stop() {
nterface.stop();
universe.stop();
network.stop();
input.stop();
running = false;
}
public Universe getUniverse() {
return universe;
}
public Interface getInterface() {
return nterface;
}
public Network getNetwork() {
return network;
}
public Input getInput() {
return input;
}
/**
* Stops the game and allows any thread waiting on exit (by having called {@link #waitForExit()}) to resume it's activity.
*/
public void exit() {
stop();
synchronized (wait) {
wait.notifyAll();
}
}
/**
* Returns true if the game is running, false if otherwise.
*
* @return Whether or not the game is running
*/
public boolean isRunning() {
return running;
}
/**
* Causes the current thread to wait until the {@link #exit()} method is called.
*
* @throws InterruptedException If the thread is interrupted while waiting
*/
public void waitForExit() throws InterruptedException {
synchronized (wait) {
while (isRunning()) {
wait.wait();
}
}
}
} |
package org.utplsql.api;
import oracle.jdbc.OracleConnection;
import org.utplsql.api.compatibility.CompatibilityProxy;
import org.utplsql.api.exception.DatabaseNotCompatibleException;
import org.utplsql.api.exception.SomeTestsFailedException;
import org.utplsql.api.exception.UtPLSQLNotInstalledException;
import org.utplsql.api.reporter.DocumentationReporter;
import org.utplsql.api.reporter.Reporter;
import org.utplsql.api.testRunner.TestRunnerStatement;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
public class TestRunner {
private TestRunnerOptions options = new TestRunnerOptions();
public TestRunner addPath(String path) {
options.pathList.add(path);
return this;
}
public TestRunner addPathList(List<String> paths) {
if (options.pathList != null) options.pathList.addAll(paths);
return this;
}
public TestRunner addReporter(Reporter reporter) {
options.reporterList.add(reporter);
return this;
}
public TestRunner colorConsole(boolean colorConsole) {
options.colorConsole = colorConsole;
return this;
}
public TestRunner addReporterList(List<Reporter> reporterList) {
if (options.reporterList != null) options.reporterList.addAll(reporterList);
return this;
}
public TestRunner addCoverageScheme(String coverageScheme) {
options.coverageSchemes.add(coverageScheme);
return this;
}
public TestRunner includeObject(String obj) {
options.includeObjects.add(obj);
return this;
}
public TestRunner excludeObject(String obj) {
options.excludeObjects.add(obj);
return this;
}
public TestRunner includeObjects(List<String> obj) {
options.includeObjects.addAll(obj);
return this;
}
public TestRunner excludeObjects(List<String> obj) {
options.excludeObjects.addAll(obj);
return this;
}
public TestRunner sourceMappingOptions(FileMapperOptions mapperOptions) {
options.sourceMappingOptions = mapperOptions;
return this;
}
public TestRunner testMappingOptions(FileMapperOptions mapperOptions) {
options.testMappingOptions = mapperOptions;
return this;
}
public TestRunner failOnErrors(boolean failOnErrors) {
options.failOnErrors = failOnErrors;
return this;
}
public TestRunner skipCompatibilityCheck( boolean skipCompatibilityCheck )
{
options.skipCompatibilityCheck = skipCompatibilityCheck;
return this;
}
public void run(Connection conn) throws SomeTestsFailedException, SQLException, DatabaseNotCompatibleException, UtPLSQLNotInstalledException {
CompatibilityProxy compatibilityProxy = new CompatibilityProxy(conn, options.skipCompatibilityCheck);
// First of all check version compatibility
compatibilityProxy.failOnNotCompatible();
for (Reporter r : options.reporterList)
validateReporter(conn, r);
if (options.pathList.isEmpty()) {
options.pathList.add(DBHelper.getCurrentSchema(conn));
}
if (options.reporterList.isEmpty()) {
options.reporterList.add(new DocumentationReporter().init(conn));
}
TestRunnerStatement testRunnerStatement = null;
try {
DBHelper.enableDBMSOutput(conn);
testRunnerStatement = compatibilityProxy.getTestRunnerStatement(options, conn);
testRunnerStatement.execute();
} catch (SQLException e) {
if (e.getErrorCode() == SomeTestsFailedException.ERROR_CODE) {
throw new SomeTestsFailedException(e.getMessage(), e);
}
else if (e.getErrorCode() == UtPLSQLNotInstalledException.ERROR_CODE) {
throw new UtPLSQLNotInstalledException(e);
}
else {
// If the execution failed by unexpected reasons finishes all reporters,
// this way the users don't need to care about reporters' sessions hanging.
OracleConnection oraConn = conn.unwrap(OracleConnection.class);
try (CallableStatement closeBufferStmt = conn.prepareCall("BEGIN ut_output_buffer.close(?); END;")) {
closeBufferStmt.setArray(1, oraConn.createOracleArray(CustomTypes.UT_REPORTERS, options.reporterList.toArray()));
closeBufferStmt.execute();
} catch (SQLException ignored) {}
throw e;
}
} finally {
if (testRunnerStatement != null) {
testRunnerStatement.close();
}
DBHelper.disableDBMSOutput(conn);
}
}
/**
* Check if the reporter was initialized, if not call reporter.init.
* @param conn the database connection
* @param reporter the reporter
* @throws SQLException any sql exception
*/
private void validateReporter(Connection conn, Reporter reporter) throws SQLException {
if (reporter.getReporterId() == null || reporter.getReporterId().isEmpty())
reporter.init(conn);
}
} |
package seedu.address.ui;
import java.time.format.DateTimeFormatter;
import javafx.fxml.FXML;
import javafx.scene.Node;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
import seedu.address.model.task.ReadOnlyTask;
import seedu.address.model.task.Time;
public class TitleCard extends UiPart{
private static final String FXML = "TitleListCard.fxml";
public static final String BLANK = " ";
@FXML
private HBox cardPane;
@FXML
private Label name;
@FXML
private Label id;
@FXML
private CheckBox completeStatus;
private ReadOnlyTask task;
private int displayedIndex;
public TitleCard(){
}
public static TitleCard load(ReadOnlyTask task, int displayedIndex){
TitleCard card = new TitleCard();
card.task = task;
card.displayedIndex = displayedIndex;
return UiPartLoader.loadUiPart(card);
}
@FXML
public void initialize() {
name.setText(task.getName().taskName);
id.setText(displayedIndex + ". ");
completeStatus.setSelected(task.getCompleted());
setDesign();
}
@FXML
private void setDesign() {
boolean isCompleted = task.getCompleted();
if (isCompleted) {
completeStatus.setSelected(true);
} else {
completeStatus.setSelected(false);
}
}
public HBox getLayout() {
return cardPane;
}
@Override
public void setNode(Node node) {
cardPane = (HBox)node;
}
@Override
public String getFxmlPath() {
return FXML;
}
} |
package services;
import org.sql2o.Connection;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.sql2o.Sql2oException;
import services.UserService.User;
import services.SessionService.Session;
import services.SessionService.SessionNotFound;
import services.ExerciseService.Exercise;
import services.ExerciseService.ExerciseNotFound;
import static services.ExerciseService.getExerciseById;
import static services.SessionService.getSessionById;
public class SessionTryService {
public static class SessionTryNotFound extends Exception {
public SessionTryNotFound() {
super("Session try not found");
}
}
public static class SessionTryNotCreated extends Exception {
public SessionTryNotCreated() {
super("Session try was not created because of an internal error");
}
}
public static class SessionTriesExceeded extends Exception {
public SessionTriesExceeded() {
super("Too many exercise answer attempts");
}
}
public static class SessionTrySyntaxError extends Exception {
public SessionTrySyntaxError() { super("Syntax error"); }
}
public static class SQLError extends Exception {
public SQLError(String message) {
super(message);
}
}
public static class SessionTry {
public int id;
public int exercise;
public int session;
public String answer;
public boolean correct;
public Date startedAt;
public Date finishedAt;
public SessionTry(
int exercise,
int session,
String answer,
Date startedAt
) {
this.exercise = exercise;
this.session = session;
this.answer = answer;
this.startedAt = startedAt;
}
}
public static SessionTry getSessionTryById(int id) throws SessionTryNotFound {
String sql = "SELECT * FROM session_try where id = :id";
try(Connection con = DatabaseService.getConnection()) {
List<SessionTry> sessions = con
.createQuery(sql)
.addParameter("id", id)
.addColumnMapping("started_at", "startedAt")
.addColumnMapping("finished_at", "finishedAt")
.executeAndFetch(SessionTry.class);
if(sessions.size() == 0) {
throw new SessionTryNotFound();
}
return sessions.get(0);
}
}
public static List<SessionTry> getSessionTriesBySessionAndExercise(int id, int exercise) {
String sql = "SELECT * FROM session_try WHERE session = :id AND exercise = :exercise";
try(Connection con = DatabaseService.getConnection()) {
List<SessionTry> sessionTries = con
.createQuery(sql)
.addParameter("id", id)
.addParameter("exercise", exercise)
.addColumnMapping("started_at", "startedAt")
.addColumnMapping("finished_at", "finishedAt")
.executeAndFetch(SessionTry.class);
return sessionTries;
}
}
public static SessionTry answerExercise(SessionTry sessionTry, User user)
throws SessionTryNotCreated, SessionNotFound, SessionTriesExceeded, ExerciseNotFound,
SessionTrySyntaxError, SQLError {
sessionTry.finishedAt = new Date();
sessionTry.correct = false;
Session session = getSessionById(sessionTry.session);
List<SessionTry> previousTries =
getSessionTriesBySessionAndExercise(sessionTry.session, sessionTry.exercise);
// Has max amount of tries been reached?
if(previousTries.size() == session.maxTries) {
throw new SessionTriesExceeded();
}
// Is answer syntactically correct?
if(sessionTry.answer.charAt((sessionTry.answer.length() -1)) != ';') {
createSessionTry(sessionTry);
throw new SessionTrySyntaxError();
}
if(!isValidSyntax(sessionTry.answer)) {
createSessionTry(sessionTry);
throw new SessionTrySyntaxError();
}
Exercise exercise = getExerciseById(sessionTry.exercise);
try(Connection con = DatabaseService.getConnection()) {
List<Map<String,Object>> correctAnswer = con
.createQuery(exercise.exampleAnswers.get(0))
.executeAndFetchTable()
.asList();
List<Map<String,Object>> userAnswerResult = con
.createQuery(sessionTry.answer)
.executeAndFetchTable()
.asList();
sessionTry.correct = correctAnswer.equals(userAnswerResult);
} catch (Sql2oException err) {
sessionTry.correct = false;
createSessionTry(sessionTry);
throw new SQLError(err.getMessage());
}
sessionTry.correct = true;
return createSessionTry(sessionTry);
}
public static SessionTry createSessionTry(SessionTry sessionTry) throws SessionTryNotCreated {
String sql = "INSERT INTO session_try (exercise, session, answer, started_at, finished_at, correct) " +
"values (:exercise, :session, :answer, :startedAt, :finishedAt, :correct)";
try(Connection con = DatabaseService.getConnection()) {
int id = con
.createQuery(sql, true)
.bind(sessionTry)
.executeUpdate()
.getKey(int.class);
return SessionTryService.getSessionTryById(id);
} catch (SessionTryNotFound err) {
throw new SessionTryNotCreated();
}
}
private static boolean isValidSyntax(String answer) {
if(answer.charAt((answer.length() -1)) != ';') {
return false;
} else {
final char PAR1 = '(';
final char PAR2 = ')';
int parNum1 = 0;
int parNum2 = 0;
for (int i = 0; i < answer.length() - 1; ++i) {
if (answer.charAt(i) == PAR1) {
parNum1++;
}
if (answer.charAt(i) == PAR2) {
parNum2++;
}
}
return parNum1 == parNum2;
}
}
} |
package si.mazi.rescu;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import si.mazi.rescu.utils.AssertUtil;
import java.io.*;
import java.net.*;
import java.util.HashMap;
import java.util.Map;
/**
* Various HTTP utility methods
*/
class HttpTemplate {
public final static String CHARSET_UTF_8 = "UTF-8";
private final Logger log = LoggerFactory.getLogger(HttpTemplate.class);
private ObjectMapper objectMapper;
/**
* Default request header fields
*/
private Map<String, String> defaultHttpHeaders = new HashMap<String, String>();
private final int readTimeout = Config.getHttpReadTimeout();
private final Proxy proxy;
/**
* Constructor
*/
public HttpTemplate() {
objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// Always use UTF8
defaultHttpHeaders.put("Accept-Charset", CHARSET_UTF_8);
// Assume form encoding by default (typically becomes application/json or application/xml)
defaultHttpHeaders.put("Content-Type", "application/x-www-form-urlencoded");
// Accept text/plain by default (typically becomes application/json or application/xml)
defaultHttpHeaders.put("Accept", "text/plain");
// User agent provides statistics for servers, but some use it for content negotiation so fake good agents
defaultHttpHeaders.put("User-Agent", "ResCU JDK/6 AppleWebKit/535.7 Chrome/16.0.912.36 Safari/535.7"); // custom User-Agent
proxy = Config.getProxyPort() == -1 || Config.getProxyHostname().equals("")
? Proxy.NO_PROXY
: new Proxy(Proxy.Type.HTTP, new InetSocketAddress(Config.getProxyHostname(), Config.getProxyPort()));
}
/**
* Requests JSON via an HTTP POST
*
*
* @param urlString A string representation of a URL
* @param returnType The required return type
* @param requestBody The contents of the request body
* @param httpHeaders Any custom header values (application/json is provided automatically)
* @param method Http method (usually GET or POST)
* @param contentType the mime type to be set as the value of the Content-Type header
* @param exceptionType
* @return String - the fetched JSON String
*/
public <T> T executeRequest(String urlString, Class<T> returnType, String requestBody, Map<String, String> httpHeaders, HttpMethod method, String contentType, Class<? extends RuntimeException> exceptionType) {
log.debug("Executing {} request at {}", method, urlString);
log.trace("Request body = {}", requestBody);
log.trace("Request headers = {}", httpHeaders);
AssertUtil.notNull(urlString, "urlString cannot be null");
AssertUtil.notNull(httpHeaders, "httpHeaders should not be null");
httpHeaders.put("Accept", "application/json");
if (contentType != null) {
httpHeaders.put("Content-Type", contentType);
}
try {
int contentLength = requestBody == null ? 0 : requestBody.length();
HttpURLConnection connection = configureURLConnection(method, urlString, httpHeaders, contentLength);
if (contentLength > 0) {
// Write the request body
connection.getOutputStream().write(requestBody.getBytes(CHARSET_UTF_8));
}
String responseEncoding = getResponseEncoding(connection);
int httpStatus = connection.getResponseCode();
log.debug("Request http status = {}", httpStatus);
if (httpStatus != 200) {
String httpBody = readInputStreamAsEncodedString(connection.getErrorStream(), responseEncoding);
log.trace("Http call returned {}; response body:\n{}", httpStatus, httpBody);
if (exceptionType != null) {
throw JSONUtils.getJsonObject(httpBody, exceptionType, objectMapper);
} else {
throw new HttpStatusException("HTTP status code not 200", httpStatus, httpBody);
}
}
InputStream inputStream = connection.getInputStream();
// Get the data
String responseString = readInputStreamAsEncodedString(inputStream, responseEncoding);
log.trace("Response body: {}", responseString);
return JSONUtils.getJsonObject(responseString, returnType, objectMapper);
} catch (MalformedURLException e) {
throw new HttpException("Problem " + method + "ing -- malformed URL: " + urlString, e);
} catch (IOException e) {
throw new HttpException("Problem " + method + "ing (IO)", e);
}
}
/**
* Provides an internal convenience method to allow easy overriding by test classes
*
* @param method The HTTP method (e.g. GET, POST etc)
* @param urlString A string representation of a URL
* @param httpHeaders The HTTP headers (will override the defaults)
* @param contentLength
* @return An HttpURLConnection based on the given parameters
* @throws IOException If something goes wrong
*/
private HttpURLConnection configureURLConnection(HttpMethod method, String urlString, Map<String, String> httpHeaders, int contentLength) throws IOException {
AssertUtil.notNull(method, "method cannot be null");
AssertUtil.notNull(urlString, "urlString cannot be null");
AssertUtil.notNull(httpHeaders, "httpHeaders cannot be null");
HttpURLConnection connection = getHttpURLConnection(urlString);
connection.setRequestMethod(method.name());
// Copy default HTTP headers
Map<String, String> headerKeyValues = new HashMap<String, String>(defaultHttpHeaders);
// Merge defaultHttpHeaders with httpHeaders
headerKeyValues.putAll(httpHeaders);
// Add HTTP headers to the request
for (Map.Entry<String, String> entry : headerKeyValues.entrySet()) {
connection.setRequestProperty(entry.getKey(), entry.getValue());
log.trace("Header request property: key='{}', value='{}'", entry.getKey(), entry.getValue());
}
// Perform additional configuration for POST
if (contentLength > 0) {
connection.setDoOutput(true);
connection.setDoInput(true);
// Add content length to header
connection.setRequestProperty("Content-Length", Integer.toString(contentLength));
}
return connection;
}
/**
* @param urlString
* @return a HttpURLConnection instance
* @throws IOException
*/
protected HttpURLConnection getHttpURLConnection(String urlString) throws IOException {
HttpURLConnection connection = (HttpURLConnection) new URL(urlString).openConnection(proxy);
if (readTimeout > 0) {
connection.setReadTimeout(readTimeout);
}
return connection;
}
/**
* <p>
* Reads an InputStream as a String allowing for different encoding types
* </p>
*
* @param inputStream The input stream
* @param responseEncoding The encoding to use when converting to a String
* @return A String representation of the input stream
* @throws IOException If something goes wrong
*/
String readInputStreamAsEncodedString(InputStream inputStream, String responseEncoding) throws IOException {
if (inputStream == null) {
return null;
}
String responseString;
if (responseEncoding != null) {
// Have an encoding so use it
StringBuilder sb = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, responseEncoding));
for (String line; (line = reader.readLine()) != null; ) {
sb.append(line);
}
responseString = sb.toString();
} else {
// No encoding specified so use a BufferedInputStream
StringBuilder sb = new StringBuilder();
BufferedInputStream bis = new BufferedInputStream(inputStream);
byte[] byteContents = new byte[4096];
int bytesRead;
String strContents;
while ((bytesRead = bis.read(byteContents)) != -1) {
strContents = new String(byteContents, 0, bytesRead);
sb.append(strContents);
}
responseString = sb.toString();
}
// System.out.println("responseString: " + responseString);
return responseString;
}
/**
* Determine the response encoding if specified
*
* @param connection The HTTP connection
* @return The response encoding as a string (taken from "Content-Type")
*/
private String getResponseEncoding(URLConnection connection) {
String charset = null;
String contentType = connection.getHeaderField("Content-Type");
if (contentType != null) {
for (String param : contentType.replace(" ", "").split(";")) {
if (param.startsWith("charset=")) {
charset = param.split("=", 2)[1];
break;
}
}
}
return charset;
}
} |
package ui.components;
import static ui.issuepanel.AbstractPanel.PANEL_WIDTH;
import static ui.issuepanel.AbstractPanel.OCTICON_TICK_MARK;
import static ui.issuepanel.AbstractPanel.OCTICON_UNDO;
import static ui.issuepanel.AbstractPanel.OCTICON_RENAME_PANEL;
import static ui.issuepanel.AbstractPanel.OCTICON_CLOSE_PANEL;
import backend.interfaces.IModel;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.control.Label;
import javafx.scene.control.Tooltip;
import javafx.scene.input.MouseButton;
import javafx.scene.text.Text;
import javafx.application.Platform;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyCode;
import javafx.scene.layout.HBox;
import ui.UI;
import ui.issuepanel.FilterPanel;
import util.events.ShowRenamePanelEvent;
/**
* An HTPanelMenuBar allows for the creation of a high level panel menu bar interface that
* contains logic for renaming the panel menu, handling the button and keyboard events
* and augmenting the children of panel menu bar defined in FilterPanel.java during the
* renaming process. The class is instantiated in FilterPanel.java.
*/
public class PanelMenuBar extends HBox {
private final HBox menuBarUndoButton;
private final HBox menuBarConfirmButton;
private final HBox menuBarRenameButton;
private final HBox menuBarCloseButton;
private TextField renameableTextField;
private final HBox menuBarNameArea;
private HBox nameBox;
private Label renameButton;
private final FilterPanel panel;
private final IModel model;
private Label closeButton;
private final UI ui;
private String panelName = "Panel";
private Text nameText;
public static final int NAME_DISPLAY_WIDTH = PANEL_WIDTH - 80;
public static final int NAME_AREA_WIDTH = PANEL_WIDTH - 65;
public static final int TOOLTIP_WRAP_WIDTH = 220; //prefWidth for longer tooltip
public PanelMenuBar(FilterPanel panel, IModel model, UI ui){
this.model = model;
this.ui = ui;
this.panel = panel;
this.setSpacing(2);
this.setMinWidth(PANEL_WIDTH);
this.setMaxWidth(PANEL_WIDTH);
menuBarNameArea = createNameArea();
menuBarRenameButton = createRenameButton();
menuBarCloseButton = createCloseButton();
menuBarConfirmButton = createOcticonButton(OCTICON_TICK_MARK, "confirmButton");
menuBarUndoButton = createOcticonButton(OCTICON_UNDO, "undoButton");
menuBarRenameButton.setMaxWidth(27);
menuBarRenameButton.setMinWidth(27);
menuBarConfirmButton.setMaxWidth(27);
menuBarConfirmButton.setMinWidth(27);
this.getChildren().addAll(menuBarNameArea, menuBarRenameButton, menuBarCloseButton);
this.setPadding(new Insets(0, 0, 8, 0));
}
private HBox createNameArea() {
HBox nameArea = new HBox();
nameText = new Text(panelName);
nameText.setId(model.getDefaultRepo() + "_col" + panel.panelIndex + "_nameText");
nameText.setWrappingWidth(NAME_DISPLAY_WIDTH);
nameBox = new HBox();
nameBox.getChildren().add(nameText);
nameBox.setMinWidth(NAME_DISPLAY_WIDTH);
nameBox.setMaxWidth(NAME_DISPLAY_WIDTH);
nameBox.setAlignment(Pos.CENTER_LEFT);
nameBox.setOnMouseClicked(mouseEvent -> {
if (mouseEvent.getButton().equals(MouseButton.PRIMARY)
&& mouseEvent.getClickCount() == 2) {
mouseEvent.consume();
activateInplaceRename();
}
});
Tooltip.install(nameArea, new Tooltip("Double click to edit the name of this panel"));
nameArea.getChildren().add(nameBox);
nameArea.setMinWidth(NAME_AREA_WIDTH);
nameArea.setMaxWidth(NAME_AREA_WIDTH);
nameArea.setPadding(new Insets(0, 10, 0, 5));
return nameArea;
}
private void activateInplaceRename() {
ui.triggerEvent(new ShowRenamePanelEvent(panel.panelIndex));
}
private HBox createRenameButton() {
HBox renameBox = new HBox();
renameButton = new Label(OCTICON_RENAME_PANEL);
renameButton.getStyleClass().addAll("octicon", "label-button");
renameButton.setId(model.getDefaultRepo() + "_col" + panel.panelIndex + "_renameButton");
renameButton.setOnMouseClicked((e) -> {
e.consume();
activateInplaceRename();
});
Tooltip.install(renameBox, new Tooltip("Edit the name of this panel"));
renameBox.getChildren().add(renameButton);
return renameBox;
}
private HBox createCloseButton() {
HBox closeArea = new HBox();
closeButton = new Label(OCTICON_CLOSE_PANEL);
closeButton.setId(model.getDefaultRepo() + "_col" + panel.panelIndex + "_closeButton");
closeButton.getStyleClass().addAll("octicon", "label-button");
closeButton.setOnMouseClicked((e) -> {
e.consume();
panel.parentPanelControl.closePanel(panel.panelIndex);
});
Tooltip.install(closeArea, new Tooltip("Close this panel"));
closeArea.getChildren().add(closeButton);
return closeArea;
}
private HBox createOcticonButton(String octString, String cssName) {
HBox buttonArea = new HBox();
Label buttonType = new Label(octString);
buttonType.getStyleClass().addAll("octicon", "label-button");
buttonType.setId(model.getDefaultRepo() + "_col" + panel.panelIndex + "_" + cssName);
buttonArea.getChildren().add(buttonType);
return buttonArea;
}
/** Called in FilterPanel.java when the ShowRenamePanelEventHandler is invoked.
* A renameableTextField is generated in which the user inputs the new panel name.
*/
public void initRenameableTextFieldAndEvents() {
renameableTextField = new TextField();
renameableTextField.setId(model.getDefaultRepo() + "_col" + panel.panelIndex + "_renameTextField");
Platform.runLater(() -> {
renameableTextField.requestFocus();
renameableTextField.selectAll();
});
renameableTextField.setText(panelName);
augmentRenameableTextField();
buttonAndKeyboardEventHandler();
renameableTextField.setPrefColumnCount(30);
}
/** Handles the button and the keyboard events when the panle is in the rename stage
*/
private void buttonAndKeyboardEventHandler() {
// for button events
menuBarUndoButton.setOnMouseClicked((e) -> {
closeRenameableTextField();
e.consume();
});
menuBarConfirmButton.setOnMouseClicked((e) -> {
panelNameValidator();
closeRenameableTextField();
e.consume();
});
// for keyboard events
setOnKeyReleased(e -> {
if (e.getCode() == KeyCode.ESCAPE) {
closeRenameableTextField();
} else if (e.getCode() == KeyCode.ENTER) {
panelNameValidator();
closeRenameableTextField();
}
e.consume();
});
}
/** Augments components of PanelMenuBar when the renaming of the panel happens.
* The confirm button and the undo button are added to the panel.
*/
private void augmentRenameableTextField(){
menuBarNameArea.getChildren().remove(nameBox);
this.getChildren().removeAll(menuBarRenameButton, menuBarCloseButton);
menuBarNameArea.getChildren().addAll(renameableTextField);
Tooltip.install(menuBarConfirmButton, new Tooltip("Confirm this name change"));
Tooltip undoTip = new Tooltip("Abandon this name change and go back to the previous name");
undoTip.setPrefWidth(TOOLTIP_WRAP_WIDTH);
Tooltip.install(menuBarUndoButton, undoTip);
this.getChildren().addAll(menuBarConfirmButton, menuBarUndoButton);
}
/** Closes the renameableTextField. The pencil and the close button are
* added back in.
*/
private void closeRenameableTextField() {
menuBarNameArea.getChildren().remove(renameableTextField);
this.getChildren().removeAll(menuBarConfirmButton, menuBarUndoButton);
menuBarNameArea.getChildren().add(nameBox);
this.getChildren().addAll(menuBarRenameButton, menuBarCloseButton);
panel.requestFocus();
}
private void panelNameValidator(){
String newName = renameableTextField.getText().trim();
if (!newName.equals("")) {
setPanelName(newName);
}
}
public void setNameText(String name){
this.nameText.setText(name);
}
public Text getNameText(){
return this.nameText;
}
public void setPanelName(String panelName){
this.panelName = panelName;
setNameText(panelName);
}
public String getPanelName(){
return this.panelName;
}
public Label getRenameButton(){
return this.renameButton;
}
public Label getCloseButton(){
return this.closeButton;
}
} |
package yanagishima.util;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import java.io.IOException;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.Map;
import static java.nio.charset.StandardCharsets.UTF_8;
public class SparkUtil {
public static String getSparkJdbcApplicationId(String sparkWebUrl) {
OkHttpClient client = new OkHttpClient();
Request okhttpRequest = new Request.Builder().url(sparkWebUrl).build();
try (Response okhttpResponse = client.newCall(okhttpRequest).execute()) {
HttpUrl url = okhttpResponse.request().url();
String sparkJdbcApplicationId = url.pathSegments().get(url.pathSize() - 2);
if (!sparkJdbcApplicationId.startsWith("application_")) {
throw new IllegalArgumentException(sparkJdbcApplicationId + " is illegal");
}
return sparkJdbcApplicationId;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static List<Map> getJobList(String resourceManagerUrl, String sparkJdbcApplicationId) {
try {
String originalJson = org.apache.http.client.fluent.Request.Get(resourceManagerUrl + "/proxy/" + sparkJdbcApplicationId + "/api/v1/applications/" + sparkJdbcApplicationId + "/jobs")
.execute().returnContent().asString(UTF_8);
/*
[ {
"jobId" : 15,
"name" : "run at AccessController.java:0",
"description" : "SELECT * FROM ... LIMIT 100",
"submissionTime" : "2019-02-21T02:23:54.513GMT",
"completionTime" : "2019-02-21T02:24:02.561GMT",
"stageIds" : [ 21 ],
"jobGroup" : "b46b9cee-bb9d-4d10-8b44-5f7328ce5748",
"status" : "SUCCEEDED",
"numTasks" : 1,
"numActiveTasks" : 0,
"numCompletedTasks" : 1,
"numSkippedTasks" : 0,
"numFailedTasks" : 0,
"numActiveStages" : 0,
"numCompletedStages" : 1,
"numSkippedStages" : 0,
"numFailedStages" : 0
}, {
"jobId" : 14,
"name" : "run at AccessController.java:0",
"description" : "SELECT * FROM ... LIMIT 100",
"submissionTime" : "2019-02-21T02:19:38.946GMT",
"completionTime" : "2019-02-21T02:19:50.317GMT",
"stageIds" : [ 20 ],
"jobGroup" : "7040a016-2f3c-47ee-a28e-086dcada02a4",
"status" : "SUCCEEDED",
"numTasks" : 1,
"numActiveTasks" : 0,
"numCompletedTasks" : 1,
"numSkippedTasks" : 0,
"numFailedTasks" : 0,
"numActiveStages" : 0,
"numCompletedStages" : 1,
"numSkippedStages" : 0,
"numFailedStages" : 0
},
*/
ObjectMapper mapper = new ObjectMapper();
List<Map> jobList = mapper.readValue(originalJson, List.class);
for(Map m : jobList) {
if(m.get("status").equals("RUNNING")) {
int numTasks = (int)m.get("numTasks");
int numCompletedTasks = (int)m.get("numCompletedTasks");
double progress = ((double)numCompletedTasks/numTasks)*100;
m.put("progress", progress);
} else {
String submissionTime = (String)m.get("submissionTime");
String completionTime = (String)m.get("completionTime");
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSzzz");
ZonedDateTime submissionTimeZdt = ZonedDateTime.parse(submissionTime, dtf);
ZonedDateTime completionTimeZdt = ZonedDateTime.parse(completionTime, dtf);
long elapsedTimeMillis = ChronoUnit.MILLIS.between(submissionTimeZdt, completionTimeZdt);
m.put("elapsedTime", elapsedTimeMillis);
}
}
return jobList;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
} |
package ibis.constellation;
import ibis.constellation.impl.ActivityIdentifierImpl;
/**
* An <code>ActivityIdentifier</code> uniquely identifies an {@link Activity}
* instance. The only valid ActivityIdentifiers are those returned from the
* constellation system. In other words, it is not possible to create your own
* activity identifiers.
*
* @version 1.0
* @since 1.0
*/
public final class ActivityIdentifier extends ActivityIdentifierImpl {
private static final long serialVersionUID = 1469734868148032028L;
/**
* Returns a human-readable unique string identifying the {@link Activity}
* instance to which this ActivityIdentifier refers. This method can be used
* for debugging prints.
*
* @return a string representation of this ActivityIdentifier.
*/
@Override
public String toString() {
return super.toString();
}
/**
* Returns a hash code for this activity identifier. Note: two activity
* identifiers compare equal if they represent the same activity.
*/
@Override
public int hashCode() {
return super.hashCode();
}
/**
* Returns whether the specified object is equal to the current activity
* identifier. Note: two activity identifiers compare equal if they
* represent the same activity.
*/
@Override
public boolean equals(Object o) {
return super.equals(o);
}
} |
package org.rakam;
import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import org.rakam.analysis.AlreadyExistsException;
import org.rakam.collection.SchemaField;
import org.rakam.collection.event.metastore.Metastore;
import org.rakam.plugin.ContinuousQueryService;
import org.rakam.plugin.MaterializedViewService;
import org.rakam.ui.CustomPageDatabase;
import org.rakam.ui.JDBCCustomReportMetadata;
import org.rakam.ui.JDBCReportMetadata;
import org.rakam.util.RakamException;
import javax.inject.Inject;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import static io.netty.handler.codec.http.HttpResponseStatus.BAD_REQUEST;
public class RecipeHandler {
private final Metastore metastore;
private final ContinuousQueryService continuousQueryService;
private final MaterializedViewService materializedViewService;
private final JDBCReportMetadata reportMetadata;
private final JDBCCustomReportMetadata customReportMetadata;
private final CustomPageDatabase customPageDatabase;
@Inject
public RecipeHandler(Metastore metastore, ContinuousQueryService continuousQueryService,
MaterializedViewService materializedViewService,
JDBCCustomReportMetadata customReportMetadata,
CustomPageDatabase customPageDatabase,
JDBCReportMetadata reportMetadata) {
this.metastore = metastore;
this.materializedViewService = materializedViewService;
this.continuousQueryService = continuousQueryService;
this.customReportMetadata = customReportMetadata;
this.customPageDatabase = customPageDatabase;
this.reportMetadata = reportMetadata;
}
public Recipe export(String project) {
final Map<String, Recipe.Collection> collections = metastore.getCollections(project).entrySet().stream().collect(Collectors.toMap(e -> e.getKey(), e -> {
List<Map<String, Recipe.SchemaFieldInfo>> map = e.getValue().stream()
.map(a -> ImmutableMap.of(a.getName(), new Recipe.SchemaFieldInfo(a.getCategory(), a.getType())))
.collect(Collectors.toList());
return new Recipe.Collection(map);
}));
final List<Recipe.MaterializedViewBuilder> materializedViews = materializedViewService.list(project).stream()
.map(m -> new Recipe.MaterializedViewBuilder(m.name, m.tableName, m.query, m.updateInterval, m.incrementalField))
.collect(Collectors.toList());
final List<Recipe.ContinuousQueryBuilder> continuousQueryBuilders = continuousQueryService.list(project).stream()
.map(m -> new Recipe.ContinuousQueryBuilder(m.name, m.tableName, m.query, m.partitionKeys, m.options))
.collect(Collectors.toList());
final List<Recipe.ReportBuilder> reports = reportMetadata
.getReports(project).stream()
.map(r -> new Recipe.ReportBuilder(r.slug, r.name, r.category, r.query, r.options))
.collect(Collectors.toList());
final List<Recipe.CustomReportBuilder> customReports = customReportMetadata
.list(project).entrySet().stream().flatMap(a -> a.getValue().stream())
.map(r -> new Recipe.CustomReportBuilder(r.reportType, r.name, r.data))
.collect(Collectors.toList());
final List<Recipe.CustomPageBuilder> customPages = customPageDatabase
.list(project).stream()
.map(r -> new Recipe.CustomPageBuilder(r.name, r.slug, r.category, customPageDatabase.get(r.project(), r.slug)))
.collect(Collectors.toList());
return new Recipe(Recipe.Strategy.SPECIFIC, project, collections, materializedViews,
continuousQueryBuilders, customReports, customPages, reports);
}
public void install(Recipe recipe, String project, boolean overrideExisting) {
installInternal(recipe, project, overrideExisting);
}
public void install(Recipe recipe, boolean overrideExisting) {
if(recipe.getProject() != null) {
installInternal(recipe, recipe.getProject(), overrideExisting);
} else {
throw new IllegalArgumentException("project is null");
}
}
public void installInternal(Recipe recipe, String project, boolean overrideExisting) {
recipe.getCollections().forEach((collectionName, collection) -> {
List<SchemaField> build = collection.build();
List<SchemaField> fields = metastore.getOrCreateCollectionFieldList(project, collectionName,
ImmutableSet.copyOf(build));
List<SchemaField> collisions = build.stream()
.filter(f -> fields.stream().anyMatch(field -> field.getName().equals(f.getName()) && !f.getType().equals(field.getType())))
.collect(Collectors.toList());
if(!collisions.isEmpty()) {
String errMessage = collisions.stream().map(f -> {
SchemaField existingField = fields.stream().filter(field -> field.getName().equals(f.getName())).findAny().get();
return String.format("Recipe: [%s : %s], Collection: [%s, %s]", f.getName(), f.getType(),
existingField.getName(), existingField.getType());
}).collect(Collectors.joining(", "));
String message = overrideExisting ? "Overriding collection fields is not possible." : "Collision in collection fields.";
throw new RakamException(message + " " +errMessage, BAD_REQUEST);
}
});
recipe.getContinuousQueryBuilders().stream()
.map(builder -> builder.createContinuousQuery(project))
.forEach(continuousQuery -> continuousQueryService.create(continuousQuery).whenComplete((res, ex) -> {
if(ex != null) {
if(ex instanceof AlreadyExistsException) {
if(overrideExisting) {
continuousQueryService.delete(project, continuousQuery.tableName);
continuousQueryService.create(continuousQuery);
} else {
throw Throwables.propagate(ex);
}
}
throw Throwables.propagate(ex);
}
}));
recipe.getMaterializedViewBuilders().stream()
.map(builder -> builder.createMaterializedView(project))
.forEach(materializedView -> materializedViewService.create(materializedView).whenComplete((res, ex) -> {
if(ex != null) {
if(ex instanceof AlreadyExistsException) {
if(overrideExisting) {
materializedViewService.delete(project, materializedView.tableName);
materializedViewService.create(materializedView);
} else {
throw Throwables.propagate(ex);
}
}
throw Throwables.propagate(ex);
}
}));
recipe.getReports().stream()
.map(reportBuilder -> reportBuilder.createReport(project))
.forEach(report -> {
try {
reportMetadata.save(report);
} catch (AlreadyExistsException e) {
if(overrideExisting) {
reportMetadata.update(report);
} else {
throw Throwables.propagate(e);
}
}
});
recipe.getCustomReports().stream()
.map(reportBuilder -> reportBuilder.createCustomReport(project))
.forEach(customReport -> {
try {
customReportMetadata.save(customReport);
} catch (AlreadyExistsException e) {
if (overrideExisting) {
customReportMetadata.update(customReport);
} else {
throw Throwables.propagate(e);
}
}
});
recipe.getCustomPages().stream()
.map(reportBuilder -> reportBuilder.createCustomPage(project))
.forEach(customReport -> {
try {
customPageDatabase.save(customReport);
} catch (AlreadyExistsException e) {
if (overrideExisting) {
customPageDatabase.delete(customReport.project(), customReport.slug);
customPageDatabase.save(customReport);
} else {
throw Throwables.propagate(e);
}
}
});
}
} |
import com.google.gson.Gson;
import json.set.HikeJson;
import json.set.PersonJson;
import record.RecordGetter;
import record.RecordSetter;
import record.RecordUpdater;
import static spark.SparkBase.port;
import static spark.Spark.*;
public class HikingSpots {
public static void main(String[] args) {
String portNumber = System.getenv("PORT");
port(Integer.parseInt(portNumber));
//TODO: Add authentication for users and app and also way to get ID whether it be through an API or credentials provided by user
//Ignore IDs until we figure out how we want to get them and store them
get("/person/", (req, res) -> {
String userId = "";
String json = RecordGetter.getPerson(userId);
res.status(200);
res.body("{\"msg\":\"Success\"");
return json;
});
get("/hike/", (req, res) -> {
String userId = "";
String json = RecordGetter.getHike(userId);
res.status(200);
res.body("{\"msg\":\"Success\"");
return json;
});
post("/person/", (req, res) -> {
Gson gson = new Gson();
PersonJson json = gson.fromJson(req.body(), PersonJson.class);
RecordSetter.setPerson(json);
res.status(200);
res.body("{\"msg\":\"Success\"");
return "success";
});
post("/hike/", (req, res) -> {
Gson gson = new Gson();
HikeJson json = gson.fromJson(req.body(), HikeJson.class);
RecordSetter.setHike(json);
res.status(200);
res.body("{\"msg\":\"Success\"");
return "success";
});
put("/person/", (req, res) -> {
Gson gson = new Gson();
json.update.PersonJson json = gson.fromJson(req.body(), json.update.PersonJson.class);
RecordUpdater.updatePerson(json);
return "success";
});
put("/hike/", (req, res) -> {
Gson gson = new Gson();
json.update.HikeJson json = gson.fromJson(req.body(), json.update.HikeJson.class);
RecordUpdater.updateHike(json);
return "success";
});
}
} |
package MTR;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fml.common.registry.GameRegistry;
public class Recipes {
public static void addShapelessRecipes() {
// GameRegistry.addShapelessRecipe(new ItemStack(MTRItems.itemtrain), new
// Object[] { Items.compass, Items.MINECART });
GameRegistry.addShapelessRecipe(new ItemStack(MTRBlocks.blocklogo),
new Object[] { new ItemStack(Items.DYE, 1, 1), Blocks.STONE });
GameRegistry.addShapelessRecipe(new ItemStack(MTRItems.itempsd, 8),
new Object[] { Blocks.GLASS, Items.REDSTONE, Items.OAK_DOOR });
GameRegistry.addShapelessRecipe(new ItemStack(MTRItems.itempsd, 8),
new Object[] { Blocks.GLASS, Items.REDSTONE, Items.BIRCH_DOOR });
GameRegistry.addShapelessRecipe(new ItemStack(MTRItems.itempsd, 8),
new Object[] { Blocks.GLASS, Items.REDSTONE, Items.SPRUCE_DOOR });
GameRegistry.addShapelessRecipe(new ItemStack(MTRItems.itempsd, 8),
new Object[] { Blocks.GLASS, Items.REDSTONE, Items.JUNGLE_DOOR });
GameRegistry.addShapelessRecipe(new ItemStack(MTRItems.itempsd, 8),
new Object[] { Blocks.GLASS, Items.REDSTONE, Items.ACACIA_DOOR });
GameRegistry.addShapelessRecipe(new ItemStack(MTRItems.itempsd, 8),
new Object[] { Blocks.GLASS, Items.REDSTONE, Items.DARK_OAK_DOOR });
GameRegistry.addShapelessRecipe(new ItemStack(MTRItems.itempsd, 1, 1),
new Object[] { new ItemStack(MTRItems.itempsd, 1, 0) });
GameRegistry.addShapelessRecipe(new ItemStack(MTRItems.itempsd, 1, 2),
new Object[] { new ItemStack(MTRItems.itempsd, 1, 1) });
GameRegistry.addShapelessRecipe(new ItemStack(MTRItems.itempsd, 1, 0),
new Object[] { new ItemStack(MTRItems.itempsd, 1, 2) });
GameRegistry.addShapelessRecipe(new ItemStack(MTRItems.itemapg, 8),
new Object[] { Blocks.GLASS, Items.REDSTONE, Blocks.OAK_FENCE_GATE });
GameRegistry.addShapelessRecipe(new ItemStack(MTRItems.itemapg, 1, 1),
new Object[] { new ItemStack(MTRItems.itemapg, 1, 0) });
GameRegistry.addShapelessRecipe(new ItemStack(MTRItems.itemapg, 1, 0),
new Object[] { new ItemStack(MTRItems.itemapg, 1, 1) });
GameRegistry.addShapelessRecipe(new ItemStack(MTRItems.itemmtrpane, 1, 1),
new Object[] { new ItemStack(MTRItems.itemmtrpane, 1, 0) });
GameRegistry.addShapelessRecipe(new ItemStack(MTRItems.itemmtrpane, 1, 2),
new Object[] { new ItemStack(MTRItems.itemmtrpane, 1, 1) });
GameRegistry.addShapelessRecipe(new ItemStack(MTRItems.itemmtrpane, 1, 3),
new Object[] { new ItemStack(MTRItems.itemmtrpane, 1, 2) });
GameRegistry.addShapelessRecipe(new ItemStack(MTRItems.itemmtrpane, 1, 4),
new Object[] { new ItemStack(MTRItems.itemmtrpane, 1, 3) });
GameRegistry.addShapelessRecipe(new ItemStack(MTRItems.itemmtrpane, 1, 5),
new Object[] { new ItemStack(MTRItems.itemmtrpane, 1, 4) });
GameRegistry.addShapelessRecipe(new ItemStack(MTRItems.itemmtrpane, 1, 6),
new Object[] { new ItemStack(MTRItems.itemmtrpane, 1, 5) });
GameRegistry.addShapelessRecipe(new ItemStack(MTRItems.itemmtrpane, 1, 7),
new Object[] { new ItemStack(MTRItems.itemmtrpane, 1, 6) });
GameRegistry.addShapelessRecipe(new ItemStack(MTRItems.itemmtrpane, 1, 0),
new Object[] { new ItemStack(MTRItems.itemmtrpane, 1, 7) });
GameRegistry.addShapelessRecipe(new ItemStack(MTRItems.itemminecartspecial),
new Object[] { new ItemStack(Items.MINECART), new ItemStack(Items.IRON_PICKAXE) });
GameRegistry.addShapelessRecipe(new ItemStack(MTRItems.itemlightrail1, 1, 1),
new Object[] { new ItemStack(MTRItems.itemlightrail1, 1, 0) });
GameRegistry.addShapelessRecipe(new ItemStack(MTRItems.itemlightrail1, 1, 0),
new Object[] { new ItemStack(MTRItems.itemlightrail1, 1, 1) });
GameRegistry.addShapelessRecipe(new ItemStack(MTRItems.itemsp1900, 1, 3),
new Object[] { new ItemStack(MTRItems.itemsp1900, 1, 0) });
GameRegistry.addShapelessRecipe(new ItemStack(MTRItems.itemsp1900, 1, 0),
new Object[] { new ItemStack(MTRItems.itemsp1900, 1, 1) });
GameRegistry.addShapelessRecipe(new ItemStack(MTRItems.itemsp1900, 1, 1),
new Object[] { new ItemStack(MTRItems.itemsp1900, 1, 2) });
GameRegistry.addShapelessRecipe(new ItemStack(MTRItems.itemsp1900, 1, 2),
new Object[] { new ItemStack(MTRItems.itemsp1900, 1, 3) });
GameRegistry.addShapelessRecipe(new ItemStack(MTRItems.itemkilltrain),
new Object[] { new ItemStack(Items.MINECART), new ItemStack(Items.LAVA_BUCKET) });
GameRegistry.addShapelessRecipe(new ItemStack(MTRBlocks.blockadside, 4), new Object[] { Items.SIGN });
GameRegistry.addShapelessRecipe(new ItemStack(MTRBlocks.blockpids1, 2),
new Object[] { Items.SIGN, Blocks.REDSTONE_BLOCK, Items.IRON_INGOT });
GameRegistry.addShapelessRecipe(new ItemStack(MTRBlocks.blockplatform), new Object[] { Blocks.STONEBRICK });
GameRegistry.addShapelessRecipe(new ItemStack(MTRBlocks.blockroutechanger, 2),
new Object[] { Blocks.STONE, Blocks.REDSTONE_BLOCK });
GameRegistry.addShapelessRecipe(new ItemStack(MTRBlocks.blockstationnamewall1, 8),
new Object[] { Items.SIGN, Items.SIGN });
GameRegistry.addShapelessRecipe(new ItemStack(MTRBlocks.blockceiling, 2),
new Object[] { Blocks.STONE_SLAB, Blocks.TORCH });
GameRegistry.addShapelessRecipe(new ItemStack(MTRBlocks.blockmtrmap),
new Object[] { new ItemStack(MTRBlocks.blockmtrmapside) });
GameRegistry.addShapelessRecipe(new ItemStack(MTRBlocks.blockmtrmapside),
new Object[] { new ItemStack(MTRBlocks.blockmtrmap) });
GameRegistry.addShapelessRecipe(new ItemStack(MTRBlocks.blockrubbishbin1, 8),
new Object[] { new ItemStack(Items.CAULDRON) });
GameRegistry.addShapelessRecipe(new ItemStack(MTRBlocks.blockgoldenrepeateroff, 8),
new Object[] { new ItemStack(Items.REPEATER), new ItemStack(Items.REPEATER),
new ItemStack(Items.REPEATER), new ItemStack(Items.REPEATER), new ItemStack(Items.REPEATER),
new ItemStack(Items.REPEATER), new ItemStack(Items.REPEATER), new ItemStack(Items.REPEATER),
new ItemStack(Items.GOLD_NUGGET) });
GameRegistry.addShapelessRecipe(new ItemStack(MTRItems.itemspawnplatform),
new Object[] { new ItemStack(MTRItems.itemrail, 1, 0), new ItemStack(MTRItems.itemrail, 1, 1),
new ItemStack(MTRItems.itemrail, 1, 5) });
GameRegistry.addShapelessRecipe(new ItemStack(MTRItems.itemescalator),
new Object[] { Blocks.STONE_STAIRS, Blocks.PISTON, Blocks.REDSTONE_BLOCK });
GameRegistry.addShapelessRecipe(new ItemStack(MTRItems.itemescalator, 1, 1),
new Object[] { new ItemStack(MTRItems.itemescalator, 1, 0) });
GameRegistry.addShapelessRecipe(new ItemStack(MTRItems.itemescalator, 1, 2),
new Object[] { new ItemStack(MTRItems.itemescalator, 1, 1) });
GameRegistry.addShapelessRecipe(new ItemStack(MTRItems.itemescalator, 1, 3),
new Object[] { new ItemStack(MTRItems.itemescalator, 1, 2) });
GameRegistry.addShapelessRecipe(new ItemStack(MTRItems.itemescalator, 1, 4),
new Object[] { new ItemStack(MTRItems.itemescalator, 1, 3) });
GameRegistry.addShapelessRecipe(new ItemStack(MTRItems.itemescalator, 1, 0),
new Object[] { new ItemStack(MTRItems.itemescalator, 1, 4) });
GameRegistry.addShapelessRecipe(new ItemStack(MTRBlocks.blockescalatorlanding, 8),
new Object[] { Blocks.STONE_SLAB, Blocks.IRON_BLOCK, Blocks.REDSTONE_BLOCK });
GameRegistry.addShapelessRecipe(new ItemStack(MTRBlocks.blockmtrsignpost, 16),
new Object[] { Blocks.IRON_BARS, Items.IRON_INGOT });
GameRegistry.addShapelessRecipe(new ItemStack(MTRBlocks.blockrailswitch, 16),
new Object[] { MTRItems.itemrail, Blocks.LEVER });
}
public static void addShapedRecipes() {
GameRegistry.addShapedRecipe(new ItemStack(MTRBlocks.blocklogo, 8), "xxx", "xyx", "xxx", 'x', Blocks.STONE, 'y',
new ItemStack(Items.DYE, 1, 1));
GameRegistry.addShapedRecipe(new ItemStack(MTRBlocks.blockclock, 16), " x ", "xyx", " x ", 'x',
Items.IRON_INGOT, 'y', Items.CLOCK);
GameRegistry.addShapedRecipe(new ItemStack(MTRBlocks.blockmtrmap, 16), " x ", "xyx", " x ", 'x',
Items.IRON_INGOT, 'y', Items.MAP);
GameRegistry.addShapedRecipe(new ItemStack(MTRBlocks.blockticketmachine, 4), "xxx", "xyx", "xxx", 'x',
Items.IRON_INGOT, 'y', Items.MAP);
GameRegistry.addShapedRecipe(new ItemStack(MTRBlocks.blocktraintimer, 2), " ", "zyz", "xxx", 'x',
Blocks.STONE, 'y', Items.COMPASS, 'z', Blocks.REDSTONE_TORCH);
GameRegistry.addShapedRecipe(new ItemStack(MTRItems.itemrail, 1, 0), " x ", " x ", " x ", 'x', Blocks.RAIL);
GameRegistry.addShapedRecipe(new ItemStack(MTRItems.itemrail, 1, 1), " x ", " x ", " x ", 'x',
Blocks.GOLDEN_RAIL);
GameRegistry.addShapedRecipe(new ItemStack(MTRItems.itemrail, 1, 2), " x", " xx", "xxx", 'x', Blocks.RAIL);
GameRegistry.addShapedRecipe(new ItemStack(MTRItems.itemrail, 1, 3), "xxx", "xx ", "x ", 'x', Blocks.RAIL);
GameRegistry.addShapedRecipe(new ItemStack(MTRItems.itemrail, 1, 4), " x ", " x ", " x ", 'x',
Blocks.DETECTOR_RAIL);
GameRegistry.addShapedRecipe(new ItemStack(MTRItems.itemrail, 1, 5), " x ", "yxy", " x ", 'x', Blocks.RAIL, 'y',
Items.REDSTONE);
GameRegistry.addShapedRecipe(new ItemStack(MTRItems.itemrail, 1, 6), " x ", "x x", " x ", 'x', Blocks.RAIL);
GameRegistry.addShapedRecipe(new ItemStack(MTRItems.itemrail, 1, 7), " x ", "xxx", " x ", 'x', Blocks.RAIL);
GameRegistry.addShapedRecipe(new ItemStack(MTRItems.itemlightrail1), "x ", " ", " ", 'x',
new ItemStack(Items.MINECART));
GameRegistry.addShapedRecipe(new ItemStack(MTRItems.itemsp1900), " x ", " ", " ", 'x',
new ItemStack(Items.MINECART));
GameRegistry.addShapedRecipe(new ItemStack(MTRItems.itembrush), "x", "y", 'x', Blocks.WOOL, 'y', Items.STICK);
GameRegistry.addShapedRecipe(new ItemStack(MTRItems.itemmtrpane, 1, 0), "x ", " ", " ", 'x',
new ItemStack(Blocks.GLASS_PANE));
GameRegistry.addShapedRecipe(new ItemStack(MTRItems.itemmtrpane, 1, 1), " x ", " ", " ", 'x',
new ItemStack(Blocks.GLASS_PANE));
GameRegistry.addShapedRecipe(new ItemStack(MTRItems.itemmtrpane, 1, 2), " x", " ", " ", 'x',
new ItemStack(Blocks.GLASS_PANE));
GameRegistry.addShapedRecipe(new ItemStack(MTRItems.itemmtrpane, 1, 3), " ", "x ", " ", 'x',
new ItemStack(Blocks.GLASS_PANE));
GameRegistry.addShapedRecipe(new ItemStack(MTRItems.itemmtrpane, 1, 4), " ", " x ", " ", 'x',
new ItemStack(Blocks.GLASS_PANE));
GameRegistry.addShapedRecipe(new ItemStack(MTRItems.itemmtrpane, 1, 5), " ", " x", " ", 'x',
new ItemStack(Blocks.GLASS_PANE));
GameRegistry.addShapedRecipe(new ItemStack(MTRItems.itemmtrpane, 1, 6), " ", " ", "x ", 'x',
new ItemStack(Blocks.GLASS_PANE));
GameRegistry.addShapedRecipe(new ItemStack(MTRItems.itemmtrpane, 1, 7), " ", " ", " x ", 'x',
new ItemStack(Blocks.GLASS_PANE));
}
} |
package app;
import browserApp.BrowserApp;
import controller.MainAppController;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
import model.DAOFactory;
import model.DAOFileItem;
import model.FileItem;
import util.EntityUtil;
import javax.persistence.EntityManager;
public class MainApp extends Application {
private DAOFileItem dataManager;
private Stage primaryStage;
@Override
public void start(Stage primaryStage) throws Exception {
EntityManager entityManager = EntityUtil.setUp().createEntityManager();
DAOFactory daoFactory = DAOFactory.getInstance(entityManager);
dataManager = daoFactory.getDAOFileItem();
this.primaryStage = primaryStage;
//dataManager = new DAOFileItemImpl(entityManager);
BrowserApp browserApp = new BrowserApp(dataManager, primaryStage);
ObservableList<FileItem> items = browserApp.getItems();
FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass().getResource("../view/main.fxml"));
Parent root = loader.load();
MainAppController mainAppController = loader.getController();
mainAppController.setMainApp(this);
AnchorPane browserContainer = mainAppController.getBrowserContainer();
browserContainer.getChildren().add(browserApp.pane);
browserApp.pane.setFillWidth(true);
primaryStage.setTitle("Hello World");
primaryStage.setScene(new Scene(root, 1000, 700));
primaryStage.show();
dataManager.getContent(dataManager.getRoot());
primaryStage.setOnCloseRequest(event -> {
try {
dataManager.close();
} catch (Exception e) {
e.printStackTrace();
}
});
}
public DAOFileItem getDataManager() {
return dataManager;
}
public Stage getPrimaryStage() {
return primaryStage;
}
public static void main(String[] args) {
launch(args);
}
} |
package applist;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.Properties;
import java.util.logging.Level;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.SystemUtils;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
import common.*;
import javafx.application.Platform;
import logging.FOKLogger;
import mslinks.ShellLink;
import view.MainWindow;
public class App {
private static FOKLogger log = new FOKLogger(App.class.getName());
/**
* Creates a new App with the specified name.
*
* @param name
* The name of the app.
*/
public App(String name) {
this(name, null, null, "", "");
}
/**
* Creates a new App with the specified coordinates.
*
* @param name
* The name of the app
* @param mavenRepoBaseURL
* Base URL of the maven repo where the artifact can be
* downloaded from.
* @param mavenSnapshotRepoBaseURL
* The URL of the maven repo where snapshots of the artifact can
* be downloaded from.
* @param mavenGroupId
* The artifacts group id.
* @param mavenArtifactId
* The artifacts artifact id
*/
public App(String name, URL mavenRepoBaseURL, URL mavenSnapshotRepoBaseURL, String mavenGroupId,
String mavenArtifactId) {
this(name, mavenRepoBaseURL, mavenSnapshotRepoBaseURL, mavenGroupId, mavenArtifactId, "");
}
/**
* Creates a new App with the specified coordinates.
*
* @param name
* The name of the app
* @param mavenRepoBaseURL
* Base URL of the maven repo where the artifact can be
* downloaded from.
* @param mavenSnapshotRepoBaseURL
* The URL of the maven repo where snapshots of the artifact can
* be downloaded from.
* @param mavenGroupId
* The artifacts group id.
* @param mavenArtifactId
* The artifacts artifact id
* @param mavenClassifier
* The artifacts classifier or {@code ""} if the default artifact
* shall be used.
*
*/
public App(String name, URL mavenRepoBaseURL, URL mavenSnapshotRepoBaseURL, String mavenGroupId,
String mavenArtifactId, String mavenClassifier) {
this(name, mavenRepoBaseURL, mavenSnapshotRepoBaseURL, mavenGroupId, mavenArtifactId, mavenClassifier, null);
}
/**
* Creates a new App with the specified coordinates.
*
* @param name
* The name of the app
* @param mavenRepoBaseURL
* Base URL of the maven repo where the artifact can be
* downloaded from.
* @param mavenSnapshotRepoBaseURL
* The URL of the maven repo where snapshots of the artifact can
* be downloaded from.
* @param mavenGroupId
* The artifacts group id.
* @param mavenArtifactId
* The artifacts artifact id
* @param mavenClassifier
* The artifacts classifier or {@code ""} if the default artifact
* shall be used.
* @param additionalInfoURL
* The url to a webpage where the user finds additional info
* about this app.
*/
public App(String name, URL mavenRepoBaseURL, URL mavenSnapshotRepoBaseURL, String mavenGroupId,
String mavenArtifactId, String mavenClassifier, URL additionalInfoURL) {
this.setName(name);
this.setMavenRepoBaseURL(mavenRepoBaseURL);
this.setMavenSnapshotRepoBaseURL(mavenSnapshotRepoBaseURL);
this.setMavenGroupID(mavenGroupId);
this.setMavenArtifactID(mavenArtifactId);
this.setMavenClassifier(mavenClassifier);
this.setAdditionalInfoURL(additionalInfoURL);
}
public App(File fileToImportFrom) throws FileNotFoundException, IOException {
try {
this.importInfo(fileToImportFrom);
} catch (IOException e) {
log.getLogger().log(Level.SEVERE,
"The app that should be imported from " + fileToImportFrom.getAbsolutePath()
+ " is automatically deleted from the imported apps list because something went wrong during the import. We probably didn't find the file to import.",
e);
this.removeFromImportedAppList();
// Propagate the Exception
throw e;
}
}
/**
* Specifies if the info of this app was imported from a file or gatheerd
* from the remote server.
*/
private boolean imported;
/**
* Specifies the file from which this app was imported from (if it was
* imported)
*/
private File importFile;
/**
* The name of the app
*/
private String name;
/**
* The latest version of the app that is available online
*/
Version latestOnlineVersion;
/**
* A {@link List} of all available online Versions
*/
VersionList onlineVersionList;
/**
* The latest snapshot version of the app that is available online
*/
Version latestOnlineSnapshotVersion;
/**
* {@code true} if the user requested to cancel the current action.
*/
private boolean cancelDownloadAndLaunch;
/**
* Base URL of the maven repo where the artifact can be downloaded from.
*/
private URL mavenRepoBaseURL;
/**
* The URL of the maven repo where snapshots of the artifact can be
* downloaded from.
*/
private URL mavenSnapshotRepoBaseURL;
/**
* The artifacts group id.
*/
private String mavenGroupID;
/**
* The artifacts artifact id
*/
private String mavenArtifactID;
/**
* The artifacts classifier or {@code ""} if the default artifact shall be
* used.
*/
private String mavenClassifier;
/**
* A webpage where the user finds additional info for this app.
*/
private URL additionalInfoURL;
private boolean specificVersionListLoaded = false;
private boolean deletableVersionListLoaded = false;
/**
* A list of event handlers that handle the event that this app was launched
* and exited then
*/
private List<Runnable> eventHandlersWhenLaunchedAppExits = new ArrayList<Runnable>();
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name
* the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* Returns a list that contains all versions of the artifact available
* online
*
* @return A list that contains all versions of the artifact available
* online
* @throws IOException
* If the maven metadata file can't be read or downloaded
* @throws JDOMException
* If the maven metadata file is malformed
* @throws MalformedURLException
* If the repo base url is malformed
*/
public VersionList getAllOnlineVersions() throws MalformedURLException, JDOMException, IOException {
if (onlineVersionList != null) {
return onlineVersionList.clone();
} else {
Document mavenMetadata = getMavenMetadata(false);
VersionList res = new VersionList();
List<Element> versions = mavenMetadata.getRootElement().getChild("versioning").getChild("versions")
.getChildren("version");
for (Element versionElement : versions) {
Version version = new Version(versionElement.getValue());
if (!version.isSnapshot()) {
// Version is not a snapshot so add it to the list
res.add(version);
}
}
onlineVersionList = res.clone();
return res;
}
}
/**
* @return the latestOnlineVersion
* @throws IOException
* If the maven metadata file can't be read or downloaded
* @throws JDOMException
* If the maven metadata file is malformed
* @throws MalformedURLException
* If the repo base url is malformed
*/
public Version getLatestOnlineVersion() throws MalformedURLException, JDOMException, IOException {
if (latestOnlineVersion != null) {
return latestOnlineVersion.clone();
} else {
Document mavenMetadata = getMavenMetadata(false);
Version res = new Version(
mavenMetadata.getRootElement().getChild("versioning").getChild("latest").getValue());
if (res.isSnapshot()) {
throw new IllegalStateException(
"Latest version in this repository is a snapshot and not a release. This might happen if you host snapshots and releases in the same repository (which is not recommended). If you still need this case to be covered, please submit an issue at https://github.com/vatbub/fokLauncher/issues");
}
latestOnlineVersion = res.clone();
return res;
}
}
/**
* @return the latestOnlineSnapshotVersion
* @throws IOException
* If the maven metadata file can't be read or downloaded
* @throws JDOMException
* If the maven metadata file is malformed
* @throws MalformedURLException
* If the repo base url is malformed
*/
public Version getLatestOnlineSnapshotVersion() throws MalformedURLException, JDOMException, IOException {
if (latestOnlineSnapshotVersion != null) {
return latestOnlineSnapshotVersion.clone();
} else {
Document mavenMetadata = getMavenMetadata(true);
Version res = new Version(
mavenMetadata.getRootElement().getChild("versioning").getChild("latest").getValue());
Document snapshotMetadata = new SAXBuilder()
.build(new URL(this.getMavenSnapshotRepoBaseURL().toString() + "/" + mavenGroupID.replace('.', '/')
+ "/" + mavenArtifactID + "/" + res.getVersion() + "/maven-metadata.xml"));
if (!res.isSnapshot()) {
throw new IllegalStateException(
"Latest version in this repository is a release and not a snapshot. This might happen if you host snapshots and releases in the same repository (which is not recommended). If you still need this case to be covered, please submit an issue at https://github.com/vatbub/fokLauncher/issues");
}
// get the buildnumber
res.setBuildNumber(snapshotMetadata.getRootElement().getChild("versioning").getChild("snapshot")
.getChild("buildNumber").getValue());
// get the build timestamp
res.setTimestamp(snapshotMetadata.getRootElement().getChild("versioning").getChild("snapshot")
.getChild("timestamp").getValue());
latestOnlineSnapshotVersion = res.clone();
return res;
}
}
/**
* Returns the currently installed version of the app or {@code null} if the
* app is not yet installed locally. Takes snapshots into account.
*
* @return the currentlyInstalledVersion
* @see #isPresentOnHarddrive()
*/
public Version getCurrentlyInstalledVersion() {
return getCurrentlyInstalledVersion(true);
}
/**
* Returns the currently installed version of the app or {@code null} if the
* app is not yet installed locally.
*
* @param snapshotsEnabled
* If {@code false}, snapshots will be removed from this list.
* @return the currentlyInstalledVersion
* @see #isPresentOnHarddrive()
*/
public Version getCurrentlyInstalledVersion(boolean snapshotsEnabled) {
try {
VersionList vers = getCurrentlyInstalledVersions();
if (!snapshotsEnabled) {
vers.removeSnapshots();
}
return Collections.max(vers);
} catch (Exception e) {
return null;
}
}
/**
* Returns a list of currently installed versions
*
* @return A list of currently installed versions
*/
public VersionList getCurrentlyInstalledVersions() {
VersionList res = new VersionList();
// Load the metadata.xml file
String destFolder = Common.getAndCreateAppDataPath() + AppConfig.subfolderToSaveApps
.replace("{groupId}", this.getMavenGroupID()).replace("{artifactId}", this.getMavenArtifactID());
String fileName = destFolder + File.separator + AppConfig.appMetadataFileName;
Document versionDoc;
try {
versionDoc = new SAXBuilder().build(fileName);
} catch (JDOMException | IOException e) {
System.err.println("Cannot retreive currently installed version of app " + this.getName()
+ ", probably because it is not installed.");
// only info level as exceptions can happen if the app was never
// installed on this machine before
log.getLogger().log(Level.INFO, "An error occured!", e);
return null;
}
for (Element versionEl : versionDoc.getRootElement().getChild("versions").getChildren()) {
Version tempVer = new Version(versionEl.getChild("version").getValue(),
versionEl.getChild("buildNumber").getValue(), versionEl.getChild("timestamp").getValue());
res.add(tempVer);
}
return res;
}
/**
* @return the mavenRepoBaseURL
*/
public URL getMavenRepoBaseURL() {
return mavenRepoBaseURL;
}
/**
* @param mavenRepoBaseURL
* the mavenRepoBaseURL to set
*/
public void setMavenRepoBaseURL(URL mavenRepoBaseURL) {
this.mavenRepoBaseURL = mavenRepoBaseURL;
}
/**
* @return the mavenSnapshotRepoBaseURL
*/
public URL getMavenSnapshotRepoBaseURL() {
return mavenSnapshotRepoBaseURL;
}
/**
* @param mavenSnapshotRepoBaseURL
* the mavenSnapshotRepoBaseURL to set
*/
public void setMavenSnapshotRepoBaseURL(URL mavenSnapshotRepoBaseURL) {
this.mavenSnapshotRepoBaseURL = mavenSnapshotRepoBaseURL;
}
/**
* @return the mavenGroupID
*/
public String getMavenGroupID() {
return mavenGroupID;
}
/**
* @param mavenGroupID
* the mavenGroupID to set
*/
public void setMavenGroupID(String mavenGroupID) {
this.mavenGroupID = mavenGroupID;
}
/**
* @return the mavenArtifactID
*/
public String getMavenArtifactID() {
return mavenArtifactID;
}
/**
* @param mavenArtifactID
* the mavenArtifactID to set
*/
public void setMavenArtifactID(String mavenArtifactID) {
this.mavenArtifactID = mavenArtifactID;
}
/**
* @return the mavenClassifier
*/
public String getMavenClassifier() {
return mavenClassifier;
}
/**
* @param mavenClassifier
* the mavenClassifier to set
*/
public void setMavenClassifier(String mavenClassifier) {
this.mavenClassifier = mavenClassifier;
}
/**
* @return the imported
*/
public boolean isImported() {
return imported;
}
/**
* @return the importFile
*/
public File getImportFile() {
return importFile;
}
/**
* @return the specificVersionListLoaded
*/
public boolean isSpecificVersionListLoaded() {
return specificVersionListLoaded;
}
/**
* @param specificVersionListLoaded
* the specificVersionListLoaded to set
*/
public void setSpecificVersionListLoaded(boolean specificVersionListLoaded) {
this.specificVersionListLoaded = specificVersionListLoaded;
}
/**
* @return the deletableVersionListLoaded
*/
public boolean isDeletableVersionListLoaded() {
return deletableVersionListLoaded;
}
/**
* @param deletableVersionListLoaded
* the deletableVersionListLoaded to set
*/
public void setDeletableVersionListLoaded(boolean deletableVersionListLoaded) {
this.deletableVersionListLoaded = deletableVersionListLoaded;
}
/**
* @return the additionalInfoURL
*/
public URL getAdditionalInfoURL() {
return additionalInfoURL;
}
/**
* @param additionalInfoURL
* the additionalInfoURL to set
*/
public void setAdditionalInfoURL(URL additionalInfoURL) {
this.additionalInfoURL = additionalInfoURL;
}
/**
* Checks if any version of this app is already downloaded
*
* @return {@code true} if any version of this app is already downloaded,
* {@code false} otherwise.
*/
public boolean isPresentOnHarddrive() {
// Check if metadata file is present
return this.getCurrentlyInstalledVersion() != null;
}
/**
* Checks if the specified version of this app is already downloaded
*
* @param ver
* The version to check
* @return {@code true} if the specified version of this app is already
* downloaded, {@code false} otherwise.
*/
public boolean isPresentOnHarddrive(Version ver) {
String destFolder = Common.getAndCreateAppDataPath() + AppConfig.subfolderToSaveApps
.replace("{groupId}", this.getMavenGroupID()).replace("{artifactId}", this.getMavenArtifactID());
String fileName = destFolder + File.separator + AppConfig.appMetadataFileName;
Element root;
Document versionDoc;
Element artifactId;
Element groupId;
Element versions;
try {
versionDoc = new SAXBuilder().build(fileName);
root = versionDoc.getRootElement();
artifactId = root.getChild("artifactId");
groupId = root.getChild("groupId");
versions = root.getChild("versions");
// Check if one of those elements is not defined
if (artifactId == null) {
throw new NullPointerException("artifactId is null");
} else if (groupId == null) {
throw new NullPointerException("groupId is null");
} else if (versions == null) {
throw new NullPointerException("versions is null");
}
// Go through all versions
for (Element version : versions.getChildren()) {
if (ver.equals(new Version(version.getChild("version").getValue(),
version.getChild("buildNumber").getValue(), version.getChild("timestamp").getValue()))) {
// Match found
return true;
}
}
// No match found, return false
return false;
} catch (JDOMException | IOException e) {
log.getLogger().log(Level.SEVERE, "An error occured!", e);
return false;
}
}
/**
* Downloads the version info and saves it as a xml file in the app folder.
*
* @param versionToGet
* The version to get the info for
* @param destFolder
* The folder where apps should be saved into
* @throws MalformedURLException
* If the repo base url is malformed
* @throws JDOMException
* If the maven metadata file is malformed
* @throws IOException
* If the maven metadata file cannot be downloaded
*/
private void downloadVersionInfo(Version versionToGet, String destFolder)
throws MalformedURLException, JDOMException, IOException {
String fileName = destFolder + File.separator + AppConfig.appMetadataFileName;
Element root;
Document versionDoc;
Element artifactId;
Element groupId;
Element versions;
try {
versionDoc = new SAXBuilder().build(fileName);
root = versionDoc.getRootElement();
artifactId = root.getChild("artifactId");
groupId = root.getChild("groupId");
versions = root.getChild("versions");
// Check if one of those elements is not defined
if (artifactId == null) {
throw new NullPointerException("artifactId is null");
} else if (groupId == null) {
throw new NullPointerException("groupId is null");
} else if (versions == null) {
throw new NullPointerException("versions is null");
}
} catch (JDOMException | IOException | NullPointerException e) {
// Could not read document for some reason so generate a new one
root = new Element("artifactInfo");
versionDoc = new Document(root);
artifactId = new Element("artifactId");
groupId = new Element("groupId");
versions = new Element("versions");
root.addContent(artifactId);
root.addContent(groupId);
root.addContent(versions);
}
artifactId.setText(this.getMavenArtifactID());
groupId.setText(this.getMavenGroupID());
boolean versionFound = false;
for (Element el : versions.getChildren()) {
Version ver = new Version(el.getChild("version").getValue(), el.getChild("buildNumber").getValue(),
el.getChild("timestamp").getValue());
if (ver.equals(versionToGet)) {
versionFound = true;
}
}
// Check if the specified version is already present
if (!versionFound) {
Element version = new Element("version");
Element versionNumber = new Element("version");
Element buildNumber = new Element("buildNumber");
Element timestamp = new Element("timestamp");
versionNumber.setText(versionToGet.getVersion());
if (versionToGet.isSnapshot()) {
buildNumber.setText(versionToGet.getBuildNumber());
timestamp.setText(versionToGet.getTimestamp());
}
version.addContent(versionNumber);
version.addContent(buildNumber);
version.addContent(timestamp);
versions.addContent(version);
}
// Write xml-File
// Create directories if necessary
File f = new File(fileName);
f.getParentFile().mkdirs();
// Create empty file on disk if necessary
(new XMLOutputter(Format.getPrettyFormat())).output(versionDoc, new FileOutputStream(fileName));
}
/**
* Gets the Maven Metadata file and converts it into a
* {@code JDOM-}{@link Document}
*
* @param snapshotsEnabled
* {@code true} if snapshots shall be taken into account.
* @return A {@link Document} representation of the maven Metadata file
* @throws MalformedURLException
* If the repo base url is malformed
* @throws JDOMException
* If the maven metadata file is malformed
* @throws IOException
* If the maven metadata file cannot be downloaded
*/
private Document getMavenMetadata(boolean snapshotsEnabled)
throws MalformedURLException, JDOMException, IOException {
Document mavenMetadata;
if (snapshotsEnabled) {
// Snapshots enabled
mavenMetadata = new SAXBuilder().build(new URL(
this.getMavenSnapshotRepoBaseURL().toString() + "/" + this.getMavenGroupID().replace('.', '/') + "/"
+ this.getMavenArtifactID() + "/maven-metadata.xml"));
} else {
// Snapshots disabled
mavenMetadata = new SAXBuilder().build(new URL(this.getMavenRepoBaseURL().toString() + "/"
+ this.getMavenGroupID().replace('.', '/') + "/" + mavenArtifactID + "/maven-metadata.xml"));
}
return mavenMetadata;
}
/**
* Checks if this artifact needs to be downloaded proir to launching it.
*
* @param snapshotsEnabled
* {@code true} if snapshots shall be taken into account.
* @return {@code true} if this artifact needs to be downloaded prior to
* launching it, {@code false} otherwise
* @throws MalformedURLException
* If the repo base url is malformed
* @throws JDOMException
* If the maven metadata file is malformed
* @throws IOException
* If the maven metadata file cannot be downloaded
*/
public boolean downloadRequired(boolean snapshotsEnabled) throws MalformedURLException, JDOMException, IOException {
if (this.isPresentOnHarddrive() && (!snapshotsEnabled)
&& !this.getCurrentlyInstalledVersions().containsRelease()) {
// App is downloaded, most current version on harddrive is a
// snapshot but snapshots are disabled, so download is required
return true;
} else if (this.isPresentOnHarddrive() && (!snapshotsEnabled)) {
// App is downloaded, most current version on harddrive is not a
// snapshot and snapshots are disabled, so no download is required
return false;
} else if (this.isPresentOnHarddrive() && snapshotsEnabled) {
// A version is available on the harddrive and snapshots are
// enabled, so we don't matter if the downloaded version is a
// snapshot or not.
return false;
} else {
// App not downloaded at all
return true;
}
}
/**
* Checks if an update is available for this artifact.
*
* @param snapshotsEnabled
* {@code true} if snapshots shall be taken into account.
* @return {@code true} if an update is available, {@code false} otherwise
* @throws MalformedURLException
* If the repo base url is malformed
* @throws JDOMException
* If the maven metadata file is malformed
* @throws IOException
* If the maven metadata file cannot be downloaded
*/
public boolean updateAvailable(boolean snapshotsEnabled) throws MalformedURLException, JDOMException, IOException {
Version onlineVersion;
if (snapshotsEnabled) {
onlineVersion = this.getLatestOnlineSnapshotVersion();
} else {
onlineVersion = this.getLatestOnlineVersion();
}
return onlineVersion.compareTo(this.getCurrentlyInstalledVersion(snapshotsEnabled)) == 1;
}
/**
* Checks if an update is available for the specified artifact version.
*
* @param versionToCheck
* The version to be checked.
* @return {@code true} if an update is available, {@code false} otherwise
* @throws MalformedURLException
* If the repo base url is malformed
* @throws JDOMException
* If the maven metadata file is malformed
* @throws IOException
* If the maven metadata file cannot be downloaded
*/
public boolean updateAvailable(Version versionToCheck) throws MalformedURLException, JDOMException, IOException {
return versionToCheck.compareTo(this.getCurrentlyInstalledVersion()) == 1;
}
/**
* Downloads the artifact if necessary and launches it afterwards. Does not
* take snapshots into account
*
* @throws IOException
* If the maven metadata cannot be downloaded
* @throws JDOMException
* If the maven metadata fale is malformed
*/
public void downloadIfNecessaryAndLaunch() throws IOException, JDOMException {
downloadIfNecessaryAndLaunch(null);
}
/**
* Downloads the artifact if necessary and launches it afterwards. Does not
* take snapshots into account
*
* @param gui
* A reference to a gui that shows the update and launch
* progress.
* @throws IOException
* If the maven metadata cannot be downloaded
* @throws JDOMException
* If the maven metadata fale is malformed
*/
public void downloadIfNecessaryAndLaunch(HidableUpdateProgressDialog gui) throws IOException, JDOMException {
downloadIfNecessaryAndLaunch(false, gui);
}
/**
* Downloads the artifact if necessary and launches it afterwards. Only
* takes snapshots into account
*
* @throws IOException
* If the maven metadata cannot be downloaded
* @throws JDOMException
* If the maven metadata fale is malformed
*/
public void downloadSnapshotIfNecessaryAndLaunch() throws IOException, JDOMException {
downloadSnapshotIfNecessaryAndLaunch(null);
}
/**
* Downloads the artifact if necessary and launches it afterwards. Only
* takes snapshots into account
*
* @param gui
* A reference to a gui that shows the update and launch
* progress.
* @throws IOException
* If the maven metadata cannot be downloaded
* @throws JDOMException
* If the maven metadata fale is malformed
*/
public void downloadSnapshotIfNecessaryAndLaunch(HidableUpdateProgressDialog gui)
throws IOException, JDOMException {
downloadIfNecessaryAndLaunch(true, gui);
}
/**
* Downloads the artifact if necessary and launches it afterwards
*
* @param snapshotsEnabled
* {@code true} if snapshots shall be taken into account.
* @param gui
* A reference to a gui that shows the update and launch
* progress.
* @throws IOException
* If the maven metadata cannot be downloaded
* @throws JDOMException
* If the maven metadata fale is malformed
*/
public void downloadIfNecessaryAndLaunch(boolean snapshotsEnabled, HidableUpdateProgressDialog gui)
throws IOException, JDOMException {
downloadIfNecessaryAndLaunch(snapshotsEnabled, gui, false);
}
public void launchWithoutDownload() throws IOException, JDOMException, IllegalStateException {
launchWithoutDownload(false);
}
public void launchSnapshotWithoutDownload() throws IOException, JDOMException, IllegalStateException {
launchWithoutDownload(true);
}
public void launchWithoutDownload(boolean snapshotsEnabled)
throws IOException, JDOMException, IllegalStateException {
launchWithoutDownload(snapshotsEnabled, null);
}
public void launchWithoutDownload(boolean snapshotsEnabled, HidableUpdateProgressDialog gui)
throws IOException, JDOMException, IllegalStateException {
downloadIfNecessaryAndLaunch(snapshotsEnabled, gui, true);
}
public void downloadIfNecessaryAndLaunch(boolean snapshotsEnabled, HidableUpdateProgressDialog gui,
boolean disableDownload) throws IOException, JDOMException, IllegalStateException {
Version versionToLaunch;
if (!disableDownload) {
if (snapshotsEnabled) {
versionToLaunch = this.getLatestOnlineSnapshotVersion();
} else {
versionToLaunch = this.getLatestOnlineVersion();
}
} else {
versionToLaunch = this.getCurrentlyInstalledVersion();
}
downloadIfNecessaryAndLaunch(gui, versionToLaunch, disableDownload);
}
public void downloadIfNecessaryAndLaunch(HidableUpdateProgressDialog gui, Version versionToLaunch,
boolean disableDownload) throws IOException, JDOMException, IllegalStateException {
cancelDownloadAndLaunch = false;
String destFolder = Common.getAndCreateAppDataPath() + AppConfig.subfolderToSaveApps
.replace("{groupId}", this.getMavenGroupID()).replace("{artifactId}", this.getMavenArtifactID());
String destFilename;
if (!disableDownload) {
// Continue by default, only cancel, when user cancelled
boolean downloadPerformed = true;
// download if necessary
if (!this.isPresentOnHarddrive(versionToLaunch)) {
// app not downloaded at all or needs to be updated
if (!this.isPresentOnHarddrive()) {
// App was never downloaded
log.getLogger().info("Downloading package because it was never downloaded before...");
} else {
// App needs an update
log.getLogger().info("Downloading package because an update is available...");
}
downloadPerformed = this.download(versionToLaunch, gui);
}
if (!downloadPerformed) {
// Download was cancelled by the user so return
return;
}
} else if (!this.isPresentOnHarddrive(versionToLaunch)) {
// Download is disabled and app needs to be downloaded
throw new IllegalStateException(
"The artifact needs to be downloaded prior to launch but download is disabled.");
}
// Perform Cancel if requested
if (cancelDownloadAndLaunch) {
if (gui != null) {
gui.operationCanceled();
}
return;
}
if (this.getMavenClassifier().equals("")) {
// No classifier
destFilename = this.getMavenArtifactID() + "-" + versionToLaunch.toString() + ".jar";
} else {
destFilename = this.getMavenArtifactID() + "-" + versionToLaunch.toString() + "-"
+ this.getMavenClassifier() + ".jar";
}
if (gui != null) {
gui.launchStarted();
}
String jarFileName = destFolder + File.separator + destFilename;
// throw exception if the jar can't be found for some unlikely reason
if (!(new File(jarFileName)).exists()) {
throw new FileNotFoundException(jarFileName);
}
// Set implicit exit = false if handlers are defined when the app exits
Platform.setImplicitExit(!this.eventHandlersWhenLaunchedAppExitsAttached());
log.getLogger().info("Launching app using the command: java -jar " + jarFileName + " disableUpdateChecks");
ProcessBuilder pb = new ProcessBuilder("java", "-jar", jarFileName, "disableUpdateChecks",
"locale=" + Locale.getDefault().getLanguage()).inheritIO();
Process process;
if (gui != null) {
gui.hide();
log.getLogger().info("Launching application " + destFilename);
System.out.println("
System.out.println("The following output is coming from " + destFilename);
System.out.println("
process = pb.start();
} else {
process = pb.start();
}
try {
process.waitFor();
} catch (InterruptedException e) {
log.getLogger().log(Level.SEVERE, "An error occurred", e);
}
// Check the status code of the process
if (process.exitValue() != 0) {
// Something went wrong
log.getLogger().log(Level.SEVERE, "The java process returned with exit code " + process.exitValue());
if (gui != null) {
gui.showErrorMessage(
"Something happened while launching the selected app. Try to launch it again and if this error occurs again, try to delete the app and download it again.");
}
}
fireLaunchedAppExits();
}
/**
* Downloads this artifact to the location specified in the
* {@link AdditionalConfig}. Does not take snapshots into account.
*
* @return {@code true} if the download finished successfully, {@code false}
* if the download was cancelled using
* {@link #cancelDownloadAndLaunch()}
* @throws IOException
* If the version info cannot be read
* @throws JDOMException
* If the version xml is malformed
*
*/
public boolean download() throws IOException, JDOMException {
HidableUpdateProgressDialog gui = null;
return download(gui);
}
/**
* Downloads this artifact to the location specified in the
* {@link AdditionalConfig}. Does not take snapshots into account.
*
* @param gui
* The {@link HidableUpdateProgressDialog} that represents the
* gui to inform the user about the progress.
* @return {@code true} if the download finished successfully, {@code false}
* if the download was cancelled using
* {@link #cancelDownloadAndLaunch()}
* @throws IOException
* If the version info cannot be read
* @throws JDOMException
* If the version xml is malformed
*
*/
public boolean download(HidableUpdateProgressDialog gui) throws IOException, JDOMException {
return download(this.getLatestOnlineVersion(), gui);
}
/**
* Downloads this artifact to the location specified in the
* {@link AdditionalConfig}. Only takes snapshots into account.
*
* @return {@code true} if the download finished successfully, {@code false}
* if the download was cancelled using
* {@link #cancelDownloadAndLaunch()}
* @throws IOException
* If the version info cannot be read
* @throws JDOMException
* If the version xml is malformed
*
*/
public boolean downloadSnapshot() throws IOException, JDOMException {
HidableUpdateProgressDialog gui = null;
return downloadSnapshot(gui);
}
/**
* Downloads this artifact to the location specified in the
* {@link AdditionalConfig}. Only takes snapshots into account.
*
* @param gui
* The {@link HidableUpdateProgressDialog} that represents the
* gui to inform the user about the progress.
* @return {@code true} if the download finished successfully, {@code false}
* if the download was cancelled using
* {@link #cancelDownloadAndLaunch()}
* @throws IOException
* If the version info cannot be read
* @throws JDOMException
* If the version xml is malformed
*
*/
public boolean downloadSnapshot(HidableUpdateProgressDialog gui) throws IOException, JDOMException {
return download(this.getLatestOnlineSnapshotVersion(), gui);
}
/**
* Downloads this artifact to the location specified in the
* {@link AdditionalConfig}.
*
* @param versionToDownload
* The {@link Version} to be downloaded.
* @param gui
* The {@link HidableUpdateProgressDialog} that represents the
* gui to inform the user about the progress.
* @return {@code true} if the download finished successfully, {@code false}
* if the download was cancelled using
* {@link #cancelDownloadAndLaunch()}
* @throws MalformedURLException
* If the specified repository {@link URL} is malformed
* @throws IOException
* If the version info cannot be read
* @throws JDOMException
* If the version xml is malformed
*
*/
public boolean download(Version versionToDownload, HidableUpdateProgressDialog gui)
throws MalformedURLException, IOException, JDOMException {
if (gui != null) {
gui.preparePhaseStarted();
}
String destFolder = Common.getAndCreateAppDataPath() + AppConfig.subfolderToSaveApps
.replace("{groupId}", this.getMavenGroupID()).replace("{artifactId}", this.getMavenArtifactID());
String destFilename;
URL repoBaseURL;
URL artifactURL;
// Perform Cancel if requested
if (cancelDownloadAndLaunch) {
if (gui != null) {
gui.operationCanceled();
}
return false;
}
if (versionToDownload.isSnapshot()) {
// Snapshot
repoBaseURL = this.getMavenSnapshotRepoBaseURL();
} else {
// Not a snapshot
repoBaseURL = this.getMavenRepoBaseURL();
}
// Construct the download url
if (this.getMavenClassifier().equals("")) {
artifactURL = new URL(repoBaseURL.toString() + "/" + this.mavenGroupID.replace('.', '/') + "/"
+ this.getMavenArtifactID() + "/" + versionToDownload.getVersion() + "/" + this.getMavenArtifactID()
+ "-" + versionToDownload.toString() + ".jar");
} else {
artifactURL = new URL(repoBaseURL.toString() + "/" + this.getMavenGroupID().replace('.', '/') + "/"
+ this.getMavenArtifactID() + "/" + versionToDownload.getVersion() + "/" + this.getMavenArtifactID()
+ "-" + versionToDownload.toString() + "-" + this.getMavenClassifier() + ".jar");
}
// Construct file name of output file
if (this.getMavenClassifier().equals("")) {
// No classifier
destFilename = this.getMavenArtifactID() + "-" + versionToDownload.toString() + ".jar";
} else {
destFilename = this.getMavenArtifactID() + "-" + versionToDownload.toString() + "-"
+ this.getMavenClassifier() + ".jar";
}
// Perform Cancel if requested
if (cancelDownloadAndLaunch) {
if (gui != null) {
gui.operationCanceled();
}
return false;
}
// Create empty file
File outputFile = new File(destFolder + File.separator + destFilename);
// Perform Cancel if requested
if (cancelDownloadAndLaunch) {
if (gui != null) {
gui.operationCanceled();
}
return false;
}
// Download
if (gui != null) {
gui.downloadStarted();
}
log.getLogger().info("Downloading artifact from " + artifactURL.toString() + "...");
log.getLogger().info("Downloading to: " + outputFile.getAbsolutePath());
// FileUtils.copyURLToFile(artifactURL, outputFile);
HttpURLConnection httpConnection = (HttpURLConnection) (artifactURL.openConnection());
long completeFileSize = httpConnection.getContentLength();
java.io.BufferedInputStream in = new java.io.BufferedInputStream(httpConnection.getInputStream());
outputFile.getParentFile().mkdirs();
java.io.FileOutputStream fos = new java.io.FileOutputStream(outputFile);
java.io.BufferedOutputStream bout = new BufferedOutputStream(fos, 1024);
byte[] data = new byte[1024];
long downloadedFileSize = 0;
int x = 0;
while ((x = in.read(data, 0, 1024)) >= 0) {
downloadedFileSize += x;
// update progress bar
if (gui != null) {
gui.downloadProgressChanged((double) (downloadedFileSize / 1024.0),
(double) (completeFileSize / 1024.0));
}
bout.write(data, 0, x);
// Perform Cancel if requested
if (cancelDownloadAndLaunch) {
bout.close();
in.close();
outputFile.delete();
if (gui != null) {
gui.operationCanceled();
}
return false;
}
}
bout.close();
in.close();
// download version info
downloadVersionInfo(versionToDownload, destFolder);
// Perform Cancel if requested
if (cancelDownloadAndLaunch) {
if (gui != null) {
gui.operationCanceled();
}
return false;
}
// Perform install steps (none at the moment)
if (gui != null) {
gui.installStarted();
}
return true;
}
/**
* Cancels the download and launch process.
*/
public void cancelDownloadAndLaunch() {
cancelDownloadAndLaunch(null);
}
/**
* Cancels the download and launch process.
*
* @param gui
* The {@link HidableUpdateProgressDialog} that represents the
* gui to inform the user about the progress.
*/
public void cancelDownloadAndLaunch(HidableUpdateProgressDialog gui) {
cancelDownloadAndLaunch = true;
if (gui != null) {
gui.cancelRequested();
}
}
/**
* Returns a combined list of imported apps and apps from the server.
*
* @return A combined list of imported apps and apps from the server.
* @throws MalformedURLException
* If the maven repo base url of an app is malformed. The base
* urls are downloaded from the server.
* @throws JDOMException
* If the xml-app list on the server or the xml file containing
* info about the imported apps is malformed
* @throws IOException
* If the app list or metadata of some apps cannot be downloaded
* or if the xml file containing the info about the imported
* apps cannot be read.
* @see App#getOnlineAppList()
* @see App#getImportedAppList()
*/
public static AppList getAppList() throws MalformedURLException, JDOMException, IOException {
AppList res = getOnlineAppList();
try {
res.addAll(getImportedAppList());
} catch (JDOMException | IOException e) {
log.getLogger().log(Level.SEVERE, "An error occurred", e);
}
return res;
}
/**
* Get a {@link List} of available apps from the server.
*
* @return A {@link List} of available apps from the server.
* @throws MalformedURLException
* If the maven repo base url of an app is malformed or if an
* app specifies a malformed additionalInfoURL. The base urls
* are downloaded from the server.
*
* @throws JDOMException
* If the xml-app list on the server is malformed
* @throws IOException
* If the app list or metadata of some apps cannot be
* downloaded.
*/
public static AppList getOnlineAppList() throws MalformedURLException, JDOMException, IOException {
Document doc = null;
String fileName = Common.getAndCreateAppDataPath() + File.separator + AppConfig.appListCacheFileName;
try {
doc = new SAXBuilder().build(AppConfig.getAppListXMLURL());
(new XMLOutputter(Format.getPrettyFormat())).output(doc, new FileOutputStream(fileName));
} catch (UnknownHostException e) {
try {
doc = new SAXBuilder().build(new File(fileName));
} catch (FileNotFoundException e1) {
throw new UnknownHostException("Could not connect to " + AppConfig.getAppListXMLURL().toString()
+ " and app list cache not found. \nPlease ensure a stable internet connection.");
}
}
Element fokLauncherEl = doc.getRootElement();
String modelVersion = fokLauncherEl.getChild("modelVersion").getValue();
// Check for unsupported modelVersion
if (!AppConfig.getSupportedFOKConfigModelVersion().contains(modelVersion)) {
throw new IllegalStateException(
"The modelVersion of the fokprojectsOnLauncher.xml file is not supported! (modelVersion is "
+ modelVersion + ")");
}
AppList res = new AppList();
for (Element app : fokLauncherEl.getChild("apps").getChildren("app")) {
App newApp = new App(app.getChild("name").getValue(), new URL(app.getChild("repoBaseURL").getValue()),
new URL(app.getChild("snapshotRepoBaseURL").getValue()), app.getChild("groupId").getValue(),
app.getChild("artifactId").getValue());
// Add classifier only if one is defined
if (app.getChild("classifier") != null) {
newApp.setMavenClassifier(app.getChild("classifier").getValue());
}
if (app.getChild("additionalInfoURL") != null) {
newApp.setAdditionalInfoURL(new URL(app.getChild("additionalInfoURL").getValue()));
}
res.add(newApp);
}
return res;
}
/**
* Returns the list of apps that were imported by the user. If any app
* cannot be imported, it will be removed from the list permanently
*
* @return The list of apps that were imported by the user.
* @throws IOException
* If the xml list cannot be read
* @throws JDOMException
* If the xml list is malformed
*/
public static AppList getImportedAppList() throws JDOMException, IOException {
String fileName = Common.getAndCreateAppDataPath() + AppConfig.importedAppListFileName;
try {
AppList res = new AppList();
Document appsDoc = new SAXBuilder().build(fileName);
Element root = appsDoc.getRootElement();
@SuppressWarnings("unused")
Element modelVersion = root.getChild("modelVersion");
Element appsElement = root.getChild("importedApps");
for (Element app : appsElement.getChildren()) {
// import the info of every app
try {
App a = new App(new File(app.getChild("fileName").getValue()));
res.add(a);
} catch (IOException e) {
// Exception is already logged by the constructor
}
}
return res;
} catch (FileNotFoundException e) {
return new AppList();
}
}
/**
* Deletes the specified artifact version.
*
* @param versionToDelete
* The version to be deleted.
* @return {@code true} if the artifact was successfully deleted,
* {@code false} otherwise
*/
public boolean delete(Version versionToDelete) {
// Delete from metadata
String destFolder = Common.getAndCreateAppDataPath() + AppConfig.subfolderToSaveApps
.replace("{groupId}", this.getMavenGroupID()).replace("{artifactId}", this.getMavenArtifactID());
String fileName = destFolder + File.separator + AppConfig.appMetadataFileName;
Document versionDoc;
Element versions;
try {
versionDoc = new SAXBuilder().build(fileName);
versions = versionDoc.getRootElement().getChild("versions");
} catch (JDOMException | IOException e) {
System.err.println("Cannot retreive currently installed version of app " + this.getName()
+ ", probably because it is not installed.");
log.getLogger().log(Level.SEVERE, "An error occured!", e);
return false;
}
Element elementToDelete = null;
// Find the version node to be deleted
for (Element el : versions.getChildren()) {
Version ver = new Version(el.getChild("version").getValue(), el.getChild("buildNumber").getValue(),
el.getChild("timestamp").getValue());
if (ver.equals(versionToDelete)) {
elementToDelete = el;
}
}
// Delete the node
if (elementToDelete != null) {
elementToDelete.detach();
try {
(new XMLOutputter(Format.getPrettyFormat())).output(versionDoc, new FileOutputStream(fileName));
} catch (IOException e) {
log.getLogger().log(Level.SEVERE, "An error occured!", e);
}
}
// Delete the file
String appFileName;
if (this.getMavenClassifier().equals("")) {
// No classifier
appFileName = this.getMavenArtifactID() + "-" + versionToDelete.toString() + ".jar";
} else {
appFileName = this.getMavenArtifactID() + "-" + versionToDelete.toString() + "-" + this.getMavenClassifier()
+ ".jar";
}
File appFile = new File(destFolder + File.separator + appFileName);
return appFile.delete();
}
/**
* Adds a handler for the event that the launched app exits again.
*
* @param handler
* The handler to add.
*/
public void addEventHandlerWhenLaunchedAppExits(Runnable handler) {
// Only add handler if it was not already added
if (!this.isEventHandlerWhenLaunchedAppExitsAttached(handler)) {
eventHandlersWhenLaunchedAppExits.add(handler);
}
}
/**
* Removes a handler for the event that the launched app exits again.
*
* @param handler
* The handler to remove.
*/
public void removeEventHandlerWhenLaunchedAppExits(Runnable handler) {
// Only remove handler if it was already added
if (this.isEventHandlerWhenLaunchedAppExitsAttached(handler)) {
eventHandlersWhenLaunchedAppExits.remove(handler);
}
}
/**
* checks if the specified handler is already attached to the event that the
* launched app exits again.
*
* @param handler
* The handler to be checked.
* @return {@code true} if the handler is already attached, {@code false}
* otherwise
*/
public boolean isEventHandlerWhenLaunchedAppExitsAttached(Runnable handler) {
return eventHandlersWhenLaunchedAppExits.contains(handler);
}
/**
* Checks if any handler is attached to the event that the launched app
* exits again.
*
* @return {@code true} if any event handler is attached, {@code false}, if
* no event handler is attached.
*/
public boolean eventHandlersWhenLaunchedAppExitsAttached() {
return eventHandlersWhenLaunchedAppExits.size() > 0;
}
/**
* Fires all handlers registered for the launchedAppExits event.
*/
private void fireLaunchedAppExits() {
log.getLogger().info("The launched app exited and the LaunchedAppExits event is now fired.");
for (Runnable handler : eventHandlersWhenLaunchedAppExits) {
Platform.runLater(handler);
}
}
/**
* Exports the info of this app to a *.foklauncher file
*
* @param fileToWrite
* The {@link File} to be written to. If the file already exists
* on the disk, it will be overwritten.
* @throws IOException
* If something happens while saving the file
*/
public void exportInfo(File fileToWrite) throws IOException {
if (!fileToWrite.exists()) {
// Create a new file
fileToWrite.createNewFile();
}
// We either have an empty file or a file that needs to be overwritten
Properties props = new Properties();
props.setProperty("name", this.getName());
props.setProperty("repoBaseURL", this.getMavenRepoBaseURL().toString());
props.setProperty("snapshotRepoBaseURL", this.getMavenSnapshotRepoBaseURL().toString());
props.setProperty("groupId", this.getMavenGroupID());
props.setProperty("artifactId", this.getMavenArtifactID());
props.setProperty("classifier", this.getMavenClassifier());
if (this.getAdditionalInfoURL() != null) {
props.setProperty("additionalInfoURL", this.getAdditionalInfoURL().toString());
}
FileOutputStream out = new FileOutputStream(fileToWrite);
props.store(out, "This file stores info about a java app. To open this file, get the foklauncher");
out.close();
}
private void importInfo(File fileToImport) throws IOException {
this.imported = true;
this.importFile = fileToImport;
FileReader fileReader = null;
if (!fileToImport.isFile()) {
// Not a file
throw new IOException("The specified file is not a file");
} else if (!fileToImport.canRead()) {
// Cannot write to file
throw new IOException("The specified file is read-only");
}
Properties props = new Properties();
if (fileToImport.exists()) {
// Load the properties
fileReader = new FileReader(fileToImport);
props.load(fileReader);
}
this.setName(props.getProperty("name"));
this.setMavenRepoBaseURL(new URL(props.getProperty("repoBaseURL")));
this.setMavenSnapshotRepoBaseURL(new URL(props.getProperty("snapshotRepoBaseURL")));
this.setMavenGroupID(props.getProperty("groupId"));
this.setMavenArtifactID(props.getProperty("artifactId"));
this.setMavenClassifier(props.getProperty("classifier"));
if (!props.getProperty("additionalInfoURL", "").equals("")) {
this.setAdditionalInfoURL(new URL(props.getProperty("additionalInfoURL")));
}
fileReader.close();
}
public static void addImportedApp(File infoFile) throws FileNotFoundException, IOException {
String fileName = Common.getAndCreateAppDataPath() + AppConfig.importedAppListFileName;
Element root;
Document appsDoc;
Element modelVersion;
Element appsElement;
try {
appsDoc = new SAXBuilder().build(fileName);
root = appsDoc.getRootElement();
modelVersion = root.getChild("modelVersion");
appsElement = root.getChild("importedApps");
// Check if one of those elements is not defined
if (modelVersion == null) {
throw new NullPointerException("modelVersion is null");
} else if (appsElement == null) {
throw new NullPointerException("appsElement is null");
}
} catch (JDOMException | IOException | NullPointerException e) {
// Could not read document for some reason so generate a new one
root = new Element("fokLauncher");
appsDoc = new Document(root);
modelVersion = new Element("modelVersion");
appsElement = new Element("importedApps");
root.addContent(modelVersion);
root.addContent(appsElement);
}
modelVersion.setText("0.0.1");
boolean fileFound = false;
for (Element app : appsElement.getChildren()) {
if (app.getChild("fileName").getValue().equals(infoFile.getAbsolutePath())) {
fileFound = true;
}
}
// Check if the specified version is already present
if (!fileFound) {
Element app = new Element("app");
Element fileNameElement = new Element("fileName");
fileNameElement.setText(infoFile.getAbsolutePath());
app.addContent(fileNameElement);
appsElement.addContent(app);
}
// Write xml-File
// Create directories if necessary
File f = new File(fileName);
f.getParentFile().mkdirs();
// Create empty file on disk if necessary
(new XMLOutputter(Format.getPrettyFormat())).output(appsDoc, new FileOutputStream(fileName));
}
public void removeFromImportedAppList() throws FileNotFoundException, IOException {
String fileName = Common.getAndCreateAppDataPath() + AppConfig.importedAppListFileName;
Element root;
Document appsDoc;
Element modelVersion;
Element appsElement;
try {
appsDoc = new SAXBuilder().build(fileName);
root = appsDoc.getRootElement();
modelVersion = root.getChild("modelVersion");
appsElement = root.getChild("importedApps");
// Check if one of those elements is not defined
if (modelVersion == null) {
throw new NullPointerException("modelVersion is null");
} else if (appsElement == null) {
throw new NullPointerException("appsElement is null");
}
} catch (JDOMException | IOException | NullPointerException e) {
// Could not read document for some reason so generate a new one
root = new Element("fokLauncher");
appsDoc = new Document(root);
modelVersion = new Element("modelVersion");
appsElement = new Element("importedApps");
root.addContent(modelVersion);
root.addContent(appsElement);
}
modelVersion.setText("0.0.1");
List<Element> appsToDetach = new ArrayList<Element>();
for (Element app : appsElement.getChildren()) {
if (app.getChild("fileName").getValue().equals(this.getImportFile().getAbsolutePath())) {
// Collect elements to be detached
appsToDetach.add(app);
}
}
// Detach them
for (Element app : appsToDetach) {
app.detach();
}
// Write xml-File
// Create directories if necessary
File f = new File(fileName);
f.getParentFile().mkdirs();
// Create empty file on disk if necessary
(new XMLOutputter(Format.getPrettyFormat())).output(appsDoc, new FileOutputStream(fileName));
}
public void createShortCut(File shortcutFile, String quickInfoText) throws IOException {
System.out.println(new File(Common.getPathAndNameOfCurrentJar()).toPath().toString());
if (SystemUtils.IS_OS_WINDOWS) {
ShellLink sl = ShellLink.createLink(new File(Common.getPathAndNameOfCurrentJar()).toPath().toString());
if (this.getMavenClassifier().equals("")) {
// no classifier set
sl.setCMDArgs("launch autolaunchrepourl=" + this.getMavenRepoBaseURL().toString()
+ " autolaunchsnapshotrepourl=" + this.getMavenSnapshotRepoBaseURL().toString()
+ " autolaunchgroupid=" + this.getMavenGroupID() + " autolaunchartifactid="
+ this.getMavenArtifactID());
} else {
sl.setCMDArgs("launch autolaunchrepourl=" + this.getMavenRepoBaseURL().toString()
+ " autolaunchsnapshotrepourl=" + this.getMavenSnapshotRepoBaseURL().toString()
+ " autolaunchgroupid=" + this.getMavenGroupID() + " autolaunchartifactid="
+ this.getMavenArtifactID() + " autolaunchclassifier=" + this.getMavenClassifier());
}
sl.setName(quickInfoText.replace("%s", this.getName()));
if (common.Common.getPackaging().equals("exe")) {
sl.setIconLocation(new File(Common.getPathAndNameOfCurrentJar()).toPath().toString());
} else {
URL inputUrl = MainWindow.class.getResource("icon.ico");
File dest = new File(Common.getAndCreateAppDataPath() + "icon.ico");
FileUtils.copyURLToFile(inputUrl, dest);
sl.setIconLocation(dest.getAbsolutePath());
}
sl.saveTo(shortcutFile.toPath().toString());
} else {
// Actually does not create a shortcut but a bash script
System.out.println(Common.getPathAndNameOfCurrentJar());
}
// Files.createLink(shortcutFile.toPath(), new
// File(Common.getPathAndNameOfCurrentJar()).toPath());
}
@Override
public String toString() {
if (this.getName() != null) {
return this.getName();
} else {
return "";
}
}
} |
package ay;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.RemovalListener;
import com.google.common.cache.RemovalNotification;
import rx.Observable;
import rx.Scheduler;
import rx.Subscription;
import rx.functions.Action1;
import rx.subjects.*;
import java.lang.annotation.*;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;
import java.util.HashSet;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* <h3>Yet another EventBus based on RxJava's {@link Subject} and Guava's {@link Cache}.</h3>
*
* <p>It's thread-safe, memory-friendly, with the simplest API in the world.</p>
*
* <h5>1. define an event, by extending the {@link Watcher} interface</h5>
* <pre>
* public interface PushWatcher extends Watcher {
* void notify(PushMessage msg);
* }
* </pre>
*
* <h5>2. listener to an event, by implementing the methods. </h5>
* <pre>
* PushWatcher watcher = new PushWatcher() {
* public void notify(PushMessage msg) {
* Log.d("watcher", "receive msg");
* }
* };
* </pre>
*
* <h5>3. bind or unbind an event. </h5>
* <pre>
* Watchers.bind(watcher);
* Watchers.unbind(watcher);
* </pre>
*
* <h5>3. trigger an event. </h5>
* <pre>
* Watchers.of(PushWatcher.class).notify(new PushMessage());
* </pre>
*
* <h5>Event more..</h5>
* <pre>
* public class MyFragment extends Fragment implement PushWatcher, NetworkChangedWatcher {
* public void notify(PushMessage msg) {
* Log.d("watcher", "receive msg: " + msg);
* }
* public void onNetworkChanged(boolean isConnected) {
* Log.d("watcher", "network connected: " + isConnected);
* }
* protected void onStart() {
* Watchers.bind(this);
* }
* protected void onStop() {
* Watchers.unbind(this);
* }
* }
* </pre>
*/
public class Watchers {
/** base interface for identify this is a watcher. */
@Config
public interface Watcher {
}
/** all kinds of subjects. */
public enum Subjects {
/** {@link PublishSubject} */
PUBLISH {
@Override
Subject<Context, Context> create() {
return PublishSubject.create();
}
},
/** {@link BehaviorSubject} */
BEHAVIOR {
@Override
Subject<Context, Context> create() {
return BehaviorSubject.create();
}
},
/** {@link ReplaySubject} */
REPLAY {
@Override
Subject<Context, Context> create() {
return ReplaySubject.create();
}
};
abstract Subject<Context, Context> create();
}
static class Context {
final AtomicBoolean consumed = new AtomicBoolean(false);
final Method method;
final Object[] args;
Context(Method method, Object[] args) {
this.method = method;
this.args = args;
}
}
/** Configuration for watcher. */
@Documented
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Config {
/** choose a subject, or use {@link PublishSubject} by default. */
Subjects subject() default Subjects.PUBLISH;
/** delegate for {@link Observable#sample(long, TimeUnit)} */
long sample() default 0;
/** delegate for {@link Observable#sample(long, TimeUnit)} */
TimeUnit timeunit() default TimeUnit.MILLISECONDS;
/** delegate for {@link Observable#onBackpressureDrop()} */
boolean backpressureDrop() default false;
/** delegate for {@link Observable#onBackpressureBuffer(long)} */
int backpressureBuffer() default 0;
/** consume the arguments just once, for the listeners whom first bind to this watcher. */
boolean once() default false;
}
static final Watchers instance = new Watchers();
final ConcurrentMap<Class<? extends Watcher>, Cache<Watcher, Subscription>>
consumers = new ConcurrentHashMap<>();
final ConcurrentMap<Class<? extends Watcher>, Subject<Context, Context>>
producers = new ConcurrentHashMap<>();
final ConcurrentMap<Class<? extends Watcher>, Watcher> watchers =
new ConcurrentHashMap<>();
private Watchers() { }
/** obtain a watcher adapter for trigger. */
public static <T extends Watcher> T of(Class<T> clz) {
return instance.getWatcher(clz);
}
/** bind the watcher into its adapters. with specific callback Scheduler. */
public static void bind(Watcher watcher, Scheduler observeOn) {
instance.bindWatcher(watcher, observeOn);
}
/** bind the watcher into its adapters. with same Scheduler as the adapter triggers. */
public static void bind(Watcher watcher) {
instance.bindWatcher(watcher);
}
/** unbind the watcher from its adapters. */
public static void unbind(Watcher watcher) {
instance.unbindWatcher(watcher);
}
public static void unbindAll(Class<? extends Watcher> clazz) {
instance.unbindAllWatchers(clazz);
}
<T extends Watcher> T getWatcher(Class<T> clz) {
if (!watchers.containsKey(clz)) {
watchers.putIfAbsent(clz, create(clz));
}
return clz.cast(watchers.get(clz));
}
static <T extends Watcher> T create(Class<T> clazz) {
if (!clazz.isInterface()) {
throw new IllegalArgumentException(
"Only interface endpoint definitions are supported.");
}
if (!(clazz.getInterfaces().length == 1 &&
Watcher.class.equals(clazz.getInterfaces()[0]))) {
throw new IllegalArgumentException(
"Interface definitions must extend Watcher interface.");
}
return clazz.cast(Proxy.newProxyInstance(
clazz.getClassLoader(), new Class[]{clazz}, new WatcherHandler(clazz)));
}
static class WatcherHandler implements InvocationHandler {
private final Class<? extends Watcher> clazz;
WatcherHandler(Class<? extends Watcher> clazz) {
this.clazz = clazz;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (method.getDeclaringClass() == Object.class) {
return method.invoke(this, args);
}
instance.trigger(clazz, method, args);
return null;
}
}
private void bindWatcher(Watcher watcher) {
bindWatcher(watcher, null);
}
private void bindWatcher(final Watcher watcher, Scheduler observeOn) {
HashSet<Class<? extends Watcher>> classes = findWatchers(watcher);
for (Class<? extends Watcher> clazz : classes) {
bindWatcher(watcher, observeOn, clazz);
}
}
private void bindWatcher(final Watcher watcher, Scheduler observeOnScheduler,
Class<? extends Watcher> clazz) {
prepare(clazz);
Cache<Watcher, Subscription> watchers = consumers.get(clazz);
if (watchers.getIfPresent(watcher) == null) {
Observable<Context> obs = producers.get(clazz);
final Config config = getWatcherConfig(clazz);
if (config.sample() > 0 && config.timeunit() != null) {
obs = obs.sample(config.sample(), config.timeunit());
}
if (config.backpressureDrop()) {
obs = obs.onBackpressureDrop();
}
if (config.backpressureBuffer() > 0) {
obs = obs.onBackpressureBuffer(config.backpressureBuffer());
}
if (observeOnScheduler != null) {
obs = obs.observeOn(observeOnScheduler);
}
watchers.put(watcher, obs.subscribe(new Action1<Context>() {
@Override
public void call(Context context) {
if (config.once() && context.consumed.getAndSet(true)) return;
try {
Class<?> clazz = watcher.getClass();
Method method = clazz.getMethod(
context.method.getName(),
context.method.getParameterTypes());
method.invoke(watcher, context.args);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}));
}
}
/** find all watchers from this object. */
private HashSet<Class<? extends Watcher>> findWatchers(Watcher watcher) {
Class<?> clazz = watcher.getClass();
HashSet<Class<?>> interfaces = getAllInterfaces(clazz);
interfaces.remove(Watcher.class);
HashSet<Class<? extends Watcher>> watchers = new HashSet<>();
for (Class<?> interfaze : interfaces) {
if (isExtendsFrom(Watcher.class, interfaze)) {
//noinspection unchecked
watchers.add((Class<? extends Watcher>) interfaze);
}
}
return watchers;
}
private HashSet<Class<?>> getAllInterfaces(Class<?> clazz) {
HashSet<Class<?>> ret = new HashSet<>();
do {
Class<?>[] interfaces = clazz.getInterfaces();
if (interfaces.length > 0) {
for (Class<?> interfaze : interfaces) {
if (!ret.contains(interfaze)) {
ret.addAll(getAllInterfaces(interfaze));
}
}
ret.addAll(Arrays.asList(interfaces));
}
Class<?> superClass = clazz.getSuperclass();
if (superClass == null) break;
clazz = superClass;
} while (clazz != Object.class);
return ret;
}
private boolean isExtendsFrom(Class<?> from, Class<?> target) {
if (from == target) return true;
Class<?>[] interfaces = target.getInterfaces();
for (Class<?> interfaze : interfaces) {
if (isExtendsFrom(from, interfaze)) return true;
}
return false;
}
private void prepare(Class<? extends Watcher> clazz) {
Subject<Context, Context> cache = producers.get(clazz);
if (cache == null) {
cache = createSubject(clazz);
producers.putIfAbsent(clazz, cache);
}
Cache<Watcher, Subscription> watchers = consumers.get(clazz);
if (watchers == null) {
watchers =
CacheBuilder.newBuilder().weakKeys().weakValues()
.removalListener(new RemovalListener<Watcher, Subscription>() {
@Override
public void onRemoval(
RemovalNotification<Watcher, Subscription> notification) {
Subscription sub = notification.getValue();
if (sub != null && !sub.isUnsubscribed()) {
sub.unsubscribe();
}
}
}).build();
consumers.putIfAbsent(clazz, watchers);
}
}
private void unbindWatcher(Watcher watcher) {
HashSet<Class<? extends Watcher>> classes = findWatchers(watcher);
for (Class<? extends Watcher> clazz : classes) {
unbindWatcher(watcher, clazz);
}
}
private void unbindWatcher(Watcher watcher, Class<? extends Watcher> clazz) {
prepare(clazz);
Cache<Watcher, Subscription> cache = consumers.get(clazz);
if (cache != null) {
cache.invalidate(watcher);
}
}
/** for test */
void unbindAllWatchers(Class<? extends Watcher> clazz) {
prepare(clazz);
consumers.get(clazz).invalidateAll();
}
private void trigger(Class<? extends Watcher> clazz, Method baseMethod, Object...args) {
prepare(clazz);
Subject<Context, Context> cache = producers.get(clazz);
cache.onNext(new Context(baseMethod, args));
}
private Subject<Context, Context> createSubject(Class<? extends Watcher> clazz) {
return getWatcherConfig(clazz).subject().create();
}
private Config getWatcherConfig(Class<? extends Watcher> clazz) {
Config config = clazz.getAnnotation(Config.class);
return config != null ? config : Watcher.class.getAnnotation(Config.class);
}
} |
package csci599;
public class App {
public static void main(String[] args) throws Exception {
String usage = "Pass bfa to perform byte frequency analysis, bfc to perform byte frequency correlation, or fht to perform file/header trailer analysis.";
if (args.length < 1) {
System.out.println(usage);
return;
}
switch (args[0]) {
case "bfa":
System.out.println("TODO: bfa");
break;
case "bfc":
System.out.println("TODO: bfc");
break;
case "fht":
System.out.println("TODO: fht");
break;
default:
System.out.println(usage);
}
}
} |
package test1;
public class Hello {
Breaking build
public static void main(String[] args) {
System.out.println("Hello GitHub World.");
}
} |
package hudson;
import hudson.model.Action;
import hudson.model.Computer;
import hudson.model.Item;
import hudson.model.ItemGroup;
import hudson.model.TopLevelItem;
import hudson.model.View;
import hudson.model.ViewGroup;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import hudson.util.VersionNumber;
import jenkins.model.Jenkins;
import org.apache.commons.io.IOUtils;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.jvnet.hudson.test.Issue;
import org.kohsuke.stapler.Ancestor;
import org.kohsuke.stapler.Stapler;
import org.kohsuke.stapler.StaplerRequest;
import static org.powermock.api.mockito.PowerMockito.mock;
import static org.powermock.api.mockito.PowerMockito.mockStatic;
import static org.powermock.api.mockito.PowerMockito.when;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
@RunWith(PowerMockRunner.class)
@PowerMockIgnore({"com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*"})
public class FunctionsTest {
@Test
public void testGetActionUrl_absoluteUriWithAuthority(){
String[] uris = {
"http://example.com/foo/bar",
"https://example.com/foo/bar",
"ftp://example.com/foo/bar",
"svn+ssh://nobody@example.com/foo/bar",
};
for(String uri : uris) {
String result = Functions.getActionUrl(null, createMockAction(uri));
assertEquals(uri, result);
}
}
@Test
@Issue("JENKINS-7725")
public void testGetActionUrl_absoluteUriWithoutAuthority(){
String[] uris = {
"mailto:nobody@example.com",
"mailto:nobody@example.com?subject=hello",
"javascript:alert('hello')",
};
for(String uri : uris) {
String result = Functions.getActionUrl(null, createMockAction(uri));
assertEquals(uri, result);
}
}
@Test
@PrepareForTest(Stapler.class)
public void testGetActionUrl_absolutePath() throws Exception{
String contextPath = "/jenkins";
StaplerRequest req = createMockRequest(contextPath);
String[] paths = {
"/",
"/foo/bar",
};
mockStatic(Stapler.class);
when(Stapler.getCurrentRequest()).thenReturn(req);
for(String path : paths) {
String result = Functions.getActionUrl(null, createMockAction(path));
assertEquals(contextPath + path, result);
}
}
@Test
@PrepareForTest(Stapler.class)
public void testGetActionUrl_relativePath() throws Exception{
String contextPath = "/jenkins";
String itUrl = "iturl/";
StaplerRequest req = createMockRequest(contextPath);
String[] paths = {
"foo/bar",
"./foo/bar",
"../foo/bar",
};
mockStatic(Stapler.class);
when(Stapler.getCurrentRequest()).thenReturn(req);
for(String path : paths) {
String result = Functions.getActionUrl(itUrl, createMockAction(path));
assertEquals(contextPath + "/" + itUrl + path, result);
}
}
@Test
@PrepareForTest({Stapler.class, Jenkins.class})
public void testGetRelativeLinkTo_JobContainedInView() throws Exception{
Jenkins j = createMockJenkins();
ItemGroup parent = j;
String contextPath = "/jenkins";
StaplerRequest req = createMockRequest(contextPath);
mockStatic(Stapler.class);
when(Stapler.getCurrentRequest()).thenReturn(req);
View view = mock(View.class);
when(view.getOwner()).thenReturn(j);
when(j.getItemGroup()).thenReturn(j);
createMockAncestors(req, createAncestor(view, "."), createAncestor(j, "../.."));
TopLevelItem i = createMockItem(parent, "job/i/");
when(view.getItems()).thenReturn(Arrays.asList(i));
String result = Functions.getRelativeLinkTo(i);
assertEquals("job/i/", result);
}
@Test
@PrepareForTest({Stapler.class, Jenkins.class})
public void testGetRelativeLinkTo_JobFromComputer() throws Exception{
Jenkins j = createMockJenkins();
ItemGroup parent = j;
String contextPath = "/jenkins";
StaplerRequest req = createMockRequest(contextPath);
mockStatic(Stapler.class);
when(Stapler.getCurrentRequest()).thenReturn(req);
Computer computer = mock(Computer.class);
createMockAncestors(req, createAncestor(computer, "."), createAncestor(j, "../.."));
TopLevelItem i = createMockItem(parent, "job/i/");
String result = Functions.getRelativeLinkTo(i);
assertEquals("/jenkins/job/i/", result);
}
@Ignore("too expensive to make it correct")
@Test
@PrepareForTest({Stapler.class, Jenkins.class})
public void testGetRelativeLinkTo_JobNotContainedInView() throws Exception{
Jenkins j = createMockJenkins();
ItemGroup parent = j;
String contextPath = "/jenkins";
StaplerRequest req = createMockRequest(contextPath);
mockStatic(Stapler.class);
when(Stapler.getCurrentRequest()).thenReturn(req);
View view = mock(View.class);
when(view.getOwner().getItemGroup()).thenReturn(parent);
createMockAncestors(req, createAncestor(j, "../.."), createAncestor(view, "."));
TopLevelItem i = createMockItem(parent, "job/i/");
when(view.getItems()).thenReturn(Collections.<TopLevelItem>emptyList());
String result = Functions.getRelativeLinkTo(i);
assertEquals("/jenkins/job/i/", result);
}
private interface TopLevelItemAndItemGroup <T extends TopLevelItem> extends TopLevelItem, ItemGroup<T>, ViewGroup {}
@Test
@PrepareForTest({Stapler.class,Jenkins.class})
public void testGetRelativeLinkTo_JobContainedInViewWithinItemGroup() throws Exception{
Jenkins j = createMockJenkins();
TopLevelItemAndItemGroup parent = mock(TopLevelItemAndItemGroup.class);
when(parent.getShortUrl()).thenReturn("parent/");
String contextPath = "/jenkins";
StaplerRequest req = createMockRequest(contextPath);
mockStatic(Stapler.class);
when(Stapler.getCurrentRequest()).thenReturn(req);
View view = mock(View.class);
when(view.getOwner()).thenReturn(parent);
when(parent.getItemGroup()).thenReturn(parent);
createMockAncestors(req, createAncestor(j, "../../.."), createAncestor(parent, "../.."), createAncestor(view, "."));
TopLevelItem i = createMockItem(parent, "job/i/", "parent/job/i/");
when(view.getItems()).thenReturn(Arrays.asList(i));
String result = Functions.getRelativeLinkTo(i);
assertEquals("job/i/", result);
}
@Issue("JENKINS-17713")
@PrepareForTest({Stapler.class, Jenkins.class})
@Test public void getRelativeLinkTo_MavenModules() throws Exception {
Jenkins j = createMockJenkins();
StaplerRequest req = createMockRequest("/jenkins");
mockStatic(Stapler.class);
when(Stapler.getCurrentRequest()).thenReturn(req);
TopLevelItemAndItemGroup ms = mock(TopLevelItemAndItemGroup.class);
when(ms.getShortUrl()).thenReturn("job/ms/");
// TODO "." (in second ancestor) is what Stapler currently fails to do. Could edit test to use ".." but set a different request path?
createMockAncestors(req, createAncestor(j, "../.."), createAncestor(ms, "."));
Item m = mock(Item.class);
when(m.getParent()).thenReturn(ms);
when(m.getShortUrl()).thenReturn("grp$art/");
assertEquals("grp$art/", Functions.getRelativeLinkTo(m));
}
@Test
public void testGetRelativeDisplayName() {
Item i = mock(Item.class);
when(i.getName()).thenReturn("jobName");
when(i.getFullDisplayName()).thenReturn("displayName");
assertEquals("displayName",Functions.getRelativeDisplayNameFrom(i, null));
}
@Test
public void testGetRelativeDisplayNameInsideItemGroup() {
Item i = mock(Item.class);
when(i.getName()).thenReturn("jobName");
when(i.getDisplayName()).thenReturn("displayName");
TopLevelItemAndItemGroup ig = mock(TopLevelItemAndItemGroup.class);
ItemGroup j = mock(Jenkins.class);
when(ig.getName()).thenReturn("parent");
when(ig.getDisplayName()).thenReturn("parentDisplay");
when(ig.getParent()).thenReturn(j);
when(i.getParent()).thenReturn(ig);
Item i2 = mock(Item.class);
when(i2.getDisplayName()).thenReturn("top");
when(i2.getParent()).thenReturn(j);
assertEquals("displayName", Functions.getRelativeDisplayNameFrom(i, ig));
assertEquals("parentDisplay » displayName", Functions.getRelativeDisplayNameFrom(i, j));
assertEquals(".. » top", Functions.getRelativeDisplayNameFrom(i2, ig));
}
private void createMockAncestors(StaplerRequest req, Ancestor... ancestors) {
List<Ancestor> ancestorsList = Arrays.asList(ancestors);
when(req.getAncestors()).thenReturn(ancestorsList);
}
private TopLevelItem createMockItem(ItemGroup p, String shortUrl) {
return createMockItem(p, shortUrl, shortUrl);
}
private TopLevelItem createMockItem(ItemGroup p, String shortUrl, String url) {
TopLevelItem i = mock(TopLevelItem.class);
when(i.getShortUrl()).thenReturn(shortUrl);
when(i.getUrl()).thenReturn(url);
when(i.getParent()).thenReturn(p);
return i;
}
private Jenkins createMockJenkins() {
mockStatic(Jenkins.class);
Jenkins j = mock(Jenkins.class);
when(Jenkins.get()).thenReturn(j);
return j;
}
private static Ancestor createAncestor(Object o, String relativePath) {
Ancestor a = mock(Ancestor.class);
when(a.getObject()).thenReturn(o);
when(a.getRelativePath()).thenReturn(relativePath);
return a;
}
@Test
@PrepareForTest(Stapler.class)
public void testGetActionUrl_unparseable() throws Exception{
assertNull(Functions.getActionUrl(null, createMockAction("http://example.net/stuff?something=^woohoo")));
}
private static Action createMockAction(String uri) {
Action action = mock(Action.class);
when(action.getUrlName()).thenReturn(uri);
return action;
}
private static StaplerRequest createMockRequest(String contextPath) {
StaplerRequest req = mock(StaplerRequest.class);
when(req.getContextPath()).thenReturn(contextPath);
return req;
}
@Test
@Issue("JENKINS-16630")
public void testHumanReadableFileSize(){
Locale defaultLocale = Locale.getDefault();
try{
Locale.setDefault(Locale.ENGLISH);
assertEquals("0 B", Functions.humanReadableByteSize(0));
assertEquals("1023 B", Functions.humanReadableByteSize(1023));
assertEquals("1.00 KB", Functions.humanReadableByteSize(1024));
assertEquals("1.50 KB", Functions.humanReadableByteSize(1536));
assertEquals("20.00 KB", Functions.humanReadableByteSize(20480));
assertEquals("1023.00 KB", Functions.humanReadableByteSize(1047552));
assertEquals("1.00 MB", Functions.humanReadableByteSize(1048576));
assertEquals("1.50 GB", Functions.humanReadableByteSize(1610612700));
}finally{
Locale.setDefault(defaultLocale);
}
}
@Issue("JENKINS-17030")
@Test
public void testBreakableString() {
assertBrokenAs("Hello world!", "Hello world!");
assertBrokenAs("Hello-world!", "Hello", "-world!");
assertBrokenAs("ALongStringThatCanNotBeBrokenByDefaultAndNeedsToUseTheBreakableElement",
"ALongStringThatCanNo", "tBeBrokenByDefaultAn", "dNeedsToUseTheBreaka", "bleElement");
assertBrokenAs("DontBreakShortStringBefore-Hyphen", "DontBreakShortStringBefore", "-Hyphen");
assertBrokenAs("jenkins_main_trunk", "jenkins", "_main", "_trunk");
assertBrokenAs("<<<<<", "", "<", "<", "<", "<", "<");
assertBrokenAs("&&&&&", "", "&", "&", "&", "&", "&");
assertBrokenAs("ϑϑϑ", "", "ϑ", "ϑ", "ϑ");
assertBrokenAs("Crazy <ha ha>", "Crazy ", "<ha ha", ">");
assertBrokenAs("A;String>Full]Of)Weird}Punctuation", "A;String", ">Full", "]Of", ")Weird", "}Punctuation");
assertBrokenAs("<<a<bc<def<ghi<", "", "<", "<a", "<bc", "<def", "<ghi", "<");
assertBrokenAs("H,e.l/l:o=w_o+|d", "H", ",e", ".l", "/l", ":o", "=w", "_o", "+|d");
assertBrokenAs("a¶‱a¶‱a¶‱a¶‱a¶‱a¶‱a¶‱a¶‱", "a¶‱a¶‱a¶‱a¶‱a¶‱", "a¶‱a¶‱a¶‱");
assertNull(Functions.breakableString(null));
}
private void assertBrokenAs(String plain, String... chunks) {
assertEquals(
Util.join(Arrays.asList(chunks), "<wbr>"),
Functions.breakableString(plain)
);
}
@Issue("JENKINS-20800")
@Test public void printLogRecordHtml() throws Exception {
LogRecord lr = new LogRecord(Level.INFO, "Bad input <xml/>");
lr.setLoggerName("test");
assertEquals("Bad input <xml/>\n", Functions.printLogRecordHtml(lr, null)[3]);
}
@Issue("JDK-6507809")
@Test public void printThrowable() throws Exception {
// Basics: a single exception. No change.
assertPrintThrowable(new Stack("java.lang.NullPointerException: oops", "p.C.method1:17", "m.Main.main:1"),
"java.lang.NullPointerException: oops\n" +
"\tat p.C.method1(C.java:17)\n" +
"\tat m.Main.main(Main.java:1)\n",
"java.lang.NullPointerException: oops\n" +
"\tat p.C.method1(C.java:17)\n" +
"\tat m.Main.main(Main.java:1)\n");
assertPrintThrowable(new Stack("java.lang.IllegalStateException: java.lang.NullPointerException: oops", "p.C.method1:19", "m.Main.main:1").
cause(new Stack("java.lang.NullPointerException: oops", "p.C.method2:23", "p.C.method1:17", "m.Main.main:1")),
"java.lang.IllegalStateException: java.lang.NullPointerException: oops\n" +
"\tat p.C.method1(C.java:19)\n" +
"\tat m.Main.main(Main.java:1)\n" +
"Caused by: java.lang.NullPointerException: oops\n" +
"\tat p.C.method2(C.java:23)\n" +
"\tat p.C.method1(C.java:17)\n" +
"\t... 1 more\n",
"java.lang.NullPointerException: oops\n" +
"\tat p.C.method2(C.java:23)\n" +
"\tat p.C.method1(C.java:17)\n" +
"Caused: java.lang.IllegalStateException\n" +
"\tat p.C.method1(C.java:19)\n" +
"\tat m.Main.main(Main.java:1)\n");
assertPrintThrowable(new Stack("java.lang.IllegalStateException: more info", "p.C.method1:19", "m.Main.main:1").
cause(new Stack("java.lang.NullPointerException: oops", "p.C.method2:23", "p.C.method1:17", "m.Main.main:1")),
"java.lang.IllegalStateException: more info\n" +
"\tat p.C.method1(C.java:19)\n" +
"\tat m.Main.main(Main.java:1)\n" +
"Caused by: java.lang.NullPointerException: oops\n" +
"\tat p.C.method2(C.java:23)\n" +
"\tat p.C.method1(C.java:17)\n" +
"\t... 1 more\n",
"java.lang.NullPointerException: oops\n" +
"\tat p.C.method2(C.java:23)\n" +
"\tat p.C.method1(C.java:17)\n" +
"Caused: java.lang.IllegalStateException: more info\n" +
"\tat p.C.method1(C.java:19)\n" +
"\tat m.Main.main(Main.java:1)\n");
assertPrintThrowable(new Stack("java.lang.IllegalStateException: more info: java.lang.NullPointerException: oops", "p.C.method1:19", "m.Main.main:1").
cause(new Stack("java.lang.NullPointerException: oops", "p.C.method2:23", "p.C.method1:17", "m.Main.main:1")),
"java.lang.IllegalStateException: more info: java.lang.NullPointerException: oops\n" +
"\tat p.C.method1(C.java:19)\n" +
"\tat m.Main.main(Main.java:1)\n" +
"Caused by: java.lang.NullPointerException: oops\n" +
"\tat p.C.method2(C.java:23)\n" +
"\tat p.C.method1(C.java:17)\n" +
"\t... 1 more\n",
"java.lang.NullPointerException: oops\n" +
"\tat p.C.method2(C.java:23)\n" +
"\tat p.C.method1(C.java:17)\n" +
"Caused: java.lang.IllegalStateException: more info\n" +
"\tat p.C.method1(C.java:19)\n" +
"\tat m.Main.main(Main.java:1)\n");
// Synthetic stack showing an exception made elsewhere, such as happens with hudson.remoting.Channel.attachCallSiteStackTrace.
Throwable t = new Stack("remote.Exception: oops", "remote.Place.method:17", "remote.Service.run:9");
StackTraceElement[] callSite = new Stack("wrapped.Exception", "local.Side.call:11", "local.Main.main:1").getStackTrace();
StackTraceElement[] original = t.getStackTrace();
StackTraceElement[] combined = new StackTraceElement[original.length + 1 + callSite.length];
System.arraycopy(original, 0, combined, 0, original.length);
combined[original.length] = new StackTraceElement(".....", "remote call", null, -2);
System.arraycopy(callSite,0,combined,original.length+1,callSite.length);
t.setStackTrace(combined);
assertPrintThrowable(t,
"remote.Exception: oops\n" +
"\tat remote.Place.method(Place.java:17)\n" +
"\tat remote.Service.run(Service.java:9)\n" +
"\tat ......remote call(Native Method)\n" +
"\tat local.Side.call(Side.java:11)\n" +
"\tat local.Main.main(Main.java:1)\n",
"remote.Exception: oops\n" +
"\tat remote.Place.method(Place.java:17)\n" +
"\tat remote.Service.run(Service.java:9)\n" +
"\tat ......remote call(Native Method)\n" +
"\tat local.Side.call(Side.java:11)\n" +
"\tat local.Main.main(Main.java:1)\n");
// Same but now using a cause on the remote side.
t = new Stack("remote.Wrapper: remote.Exception: oops", "remote.Place.method2:19", "remote.Service.run:9").cause(new Stack("remote.Exception: oops", "remote.Place.method1:11", "remote.Place.method2:17", "remote.Service.run:9"));
callSite = new Stack("wrapped.Exception", "local.Side.call:11", "local.Main.main:1").getStackTrace();
original = t.getStackTrace();
combined = new StackTraceElement[original.length + 1 + callSite.length];
System.arraycopy(original, 0, combined, 0, original.length);
combined[original.length] = new StackTraceElement(".....", "remote call", null, -2);
System.arraycopy(callSite,0,combined,original.length+1,callSite.length);
t.setStackTrace(combined);
assertPrintThrowable(t,
"remote.Wrapper: remote.Exception: oops\n" +
"\tat remote.Place.method2(Place.java:19)\n" +
"\tat remote.Service.run(Service.java:9)\n" +
"\tat ......remote call(Native Method)\n" +
"\tat local.Side.call(Side.java:11)\n" +
"\tat local.Main.main(Main.java:1)\n" +
"Caused by: remote.Exception: oops\n" +
"\tat remote.Place.method1(Place.java:11)\n" +
"\tat remote.Place.method2(Place.java:17)\n" +
"\tat remote.Service.run(Service.java:9)\n",
"remote.Exception: oops\n" +
"\tat remote.Place.method1(Place.java:11)\n" +
"\tat remote.Place.method2(Place.java:17)\n" +
"\tat remote.Service.run(Service.java:9)\n" + // we do not know how to elide the common part in this case
"Caused: remote.Wrapper\n" +
"\tat remote.Place.method2(Place.java:19)\n" +
"\tat remote.Service.run(Service.java:9)\n" +
"\tat ......remote call(Native Method)\n" +
"\tat local.Side.call(Side.java:11)\n" +
"\tat local.Main.main(Main.java:1)\n");
// Suppressed exceptions:
assertPrintThrowable(new Stack("java.lang.IllegalStateException: java.lang.NullPointerException: oops", "p.C.method1:19", "m.Main.main:1").
cause(new Stack("java.lang.NullPointerException: oops", "p.C.method2:23", "p.C.method1:17", "m.Main.main:1")).
suppressed(new Stack("java.io.IOException: could not close", "p.C.close:99", "p.C.method1:18", "m.Main.main:1"),
new Stack("java.io.IOException: java.lang.NullPointerException", "p.C.flush:77", "p.C.method1:18", "m.Main.main:1").
cause(new Stack("java.lang.NullPointerException", "p.C.findFlushee:70", "p.C.flush:75", "p.C.method1:18", "m.Main.main:1"))),
"java.lang.IllegalStateException: java.lang.NullPointerException: oops\n" +
"\tat p.C.method1(C.java:19)\n" +
"\tat m.Main.main(Main.java:1)\n" +
"\tSuppressed: java.io.IOException: could not close\n" +
"\t\tat p.C.close(C.java:99)\n" +
"\t\tat p.C.method1(C.java:18)\n" +
"\t\t... 1 more\n" +
"\tSuppressed: java.io.IOException: java.lang.NullPointerException\n" +
"\t\tat p.C.flush(C.java:77)\n" +
"\t\tat p.C.method1(C.java:18)\n" +
"\t\t... 1 more\n" +
"\tCaused by: java.lang.NullPointerException\n" +
"\t\tat p.C.findFlushee(C.java:70)\n" +
"\t\tat p.C.flush(C.java:75)\n" +
"\t\t... 2 more\n" +
"Caused by: java.lang.NullPointerException: oops\n" +
"\tat p.C.method2(C.java:23)\n" +
"\tat p.C.method1(C.java:17)\n" +
"\t... 1 more\n",
"java.lang.NullPointerException: oops\n" +
"\tat p.C.method2(C.java:23)\n" +
"\tat p.C.method1(C.java:17)\n" +
"Also: java.io.IOException: could not close\n" +
"\t\tat p.C.close(C.java:99)\n" +
"\t\tat p.C.method1(C.java:18)\n" +
"Also: java.lang.NullPointerException\n" +
"\t\tat p.C.findFlushee(C.java:70)\n" +
"\t\tat p.C.flush(C.java:75)\n" +
"\tCaused: java.io.IOException\n" +
"\t\tat p.C.flush(C.java:77)\n" +
"\t\tat p.C.method1(C.java:18)\n" +
"Caused: java.lang.IllegalStateException\n" +
"\tat p.C.method1(C.java:19)\n" +
"\tat m.Main.main(Main.java:1)\n");
// Custom printStackTrace implementations:
assertPrintThrowable(new Throwable() {
@Override
public void printStackTrace(PrintWriter s) {
s.println("Some custom exception");
}
}, "Some custom exception\n", "Some custom exception\n");
// Circular references:
Stack stack1 = new Stack("p.Exc1", "p.C.method1:17");
Stack stack2 = new Stack("p.Exc2", "p.C.method2:27");
stack1.cause(stack2);
stack2.cause(stack1);
//Format changed in 11.0.9 / 8.0.272 (JDK-8226809 / JDK-8252444 / JDK-8252489)
if ((getVersion().getDigitAt(0) == 11 && getVersion().isNewerThanOrEqualTo(new VersionNumber("11.0.9"))) ||
(getVersion().getDigitAt(0) == 8 && getVersion().isNewerThanOrEqualTo(new VersionNumber("8.0.272")))) {
assertPrintThrowable(stack1,
"p.Exc1\n" +
"\tat p.C.method1(C.java:17)\n" +
"Caused by: p.Exc2\n" +
"\tat p.C.method2(C.java:27)\n" +
"Caused by: [CIRCULAR REFERENCE: p.Exc1]\n",
"<cycle to p.Exc1>\n" +
"Caused: p.Exc2\n" +
"\tat p.C.method2(C.java:27)\n" +
"Caused: p.Exc1\n" +
"\tat p.C.method1(C.java:17)\n");
} else {
assertPrintThrowable(stack1,
"p.Exc1\n" +
"\tat p.C.method1(C.java:17)\n" +
"Caused by: p.Exc2\n" +
"\tat p.C.method2(C.java:27)\n" +
"\t[CIRCULAR REFERENCE:p.Exc1]\n",
"<cycle to p.Exc1>\n" +
"Caused: p.Exc2\n" +
"\tat p.C.method2(C.java:27)\n" +
"Caused: p.Exc1\n" +
"\tat p.C.method1(C.java:17)\n");
}
}
private static VersionNumber getVersion() {
String version = System.getProperty("java.version");
if(version.startsWith("1.")) {
version = version.substring(2).replace("_", ".");
}
return new VersionNumber(version);
}
private static void assertPrintThrowable(Throwable t, String traditional, String custom) {
StringWriter sw = new StringWriter();
t.printStackTrace(new PrintWriter(sw));
assertEquals(sw.toString().replace(IOUtils.LINE_SEPARATOR, "\n"), traditional);
String actual = Functions.printThrowable(t);
System.out.println(actual);
assertEquals(actual.replace(IOUtils.LINE_SEPARATOR, "\n"), custom);
}
private static final class Stack extends Throwable {
private static final Pattern LINE = Pattern.compile("(.+)[.](.+)[.](.+):(\\d+)");
private final String toString;
Stack(String toString, String... stack) {
this.toString = toString;
StackTraceElement[] lines = new StackTraceElement[stack.length];
for (int i = 0; i < stack.length; i++) {
Matcher m = LINE.matcher(stack[i]);
assertTrue(m.matches());
lines[i] = new StackTraceElement(m.group(1) + "." + m.group(2), m.group(3), m.group(2) + ".java", Integer.parseInt(m.group(4)));
}
setStackTrace(lines);
}
@Override
public String toString() {
return toString;
}
synchronized Stack cause(Throwable cause) {
return (Stack) initCause(cause);
}
synchronized Stack suppressed(Throwable... suppressed) {
for (Throwable t : suppressed) {
addSuppressed(t);
}
return this;
}
}
} |
package com.threerings.gwt.util;
import java.util.Date;
import com.google.gwt.core.client.GWT;
import com.google.gwt.i18n.client.DateTimeFormat;
/**
* Time and date utility methods.
*/
public class DateUtil
{
/**
* Creates a label of the form "9:15am". TODO: support 24 hour time for people who go for that
* sort of thing. If date is null the empty string is returned.
*/
public static String formatTime (Date date)
{
return (date == null) ? "" : _tfmt.format(date).toLowerCase();
}
/**
* Formats the supplied date relative to the current time: Today, Yesterday, MMM dd, and
* finally MMM dd, YYYY. If date is null the empty string is returned.
*/
public static String formatDate (Date date)
{
return formatDate(date, true);
}
/**
* Formats the supplied date relative to the current time: Today, Yesterday, MMM dd, and
* finally MMM dd, YYYY. If date is null the empty string is returned.
*
* @param useShorthand if false, "Today" and "Yesterday" will not be used, only the month/day
* and month/day/year formats.
*/
public static String formatDate (Date date, boolean useShorthand)
{
if (date == null) {
return "";
}
Date now = new Date();
if (getYear(date) != getYear(now)) {
return _yfmt.format(date);
} else if (getMonth(date) != getMonth(now)) {
return _mfmt.format(date);
} else if (useShorthand && getDayOfMonth(date) == getDayOfMonth(now)) {
return _msgs.today();
// this will break for one hour on daylight savings time and we'll instead report the date
// in MMM dd format or we'll call two days ago yesterday for that witching hour; we don't
// have excellent date services in the browser, so we're just going to be OK with that
} else if (useShorthand && getDayOfMonth(date) ==
getDayOfMonth(new Date(now.getTime()-24*60*60*1000))) {
return _msgs.yesterday();
} else {
return _mfmt.format(date);
}
}
/**
* Creates a label of the form "{@link #formatDate} at {@link #formatTime}". If date is null
* the empty string is returned.
*/
public static String formatDateTime (Date date)
{
return (date == null) ? "" : _msgs.dateTime(formatDate(date), formatTime(date));
}
@SuppressWarnings("deprecation")
public static Date toDate (int[] datevec)
{
return new Date(datevec[0] - 1900, datevec[1], datevec[2]);
}
@SuppressWarnings("deprecation")
public static int[] toDateVec (Date date)
{
return new int[]{date.getYear() + 1900, date.getMonth(), date.getDate()};
}
@SuppressWarnings("deprecation")
public static Date newDate (String dateStr)
{
return new Date(dateStr);
}
@SuppressWarnings("deprecation")
public static int getDayOfMonth (Date date)
{
return date.getDate();
}
@SuppressWarnings("deprecation")
public static int getMonth (Date date)
{
return date.getMonth();
}
@SuppressWarnings("deprecation")
public static int getYear (Date date)
{
return date.getYear();
}
@SuppressWarnings("deprecation")
public static void zeroTime (Date date)
{
date.setHours(0);
date.setMinutes(0);
date.setSeconds(0);
}
protected static final DateTimeFormat _tfmt = DateTimeFormat.getFormat("h:mmaa");
protected static final DateTimeFormat _mfmt = DateTimeFormat.getFormat("MMM dd");
protected static final DateTimeFormat _yfmt = DateTimeFormat.getFormat("MMM dd, yyyy");
protected static final UtilMessages _msgs = GWT.create(UtilMessages.class);
} |
package org.apache.lucene.document;
import java.io.Reader;
import java.util.Date;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.search.Similarity;
import org.apache.lucene.search.Hits;
/**
A field is a section of a Document. Each field has two parts, a name and a
value. Values may be free text, provided as a String or as a Reader, or they
may be atomic keywords, which are not further processed. Such keywords may
be used to represent dates, urls, etc. Fields are optionally stored in the
index, so that they may be returned with hits on the document.
*/
public final class Field implements java.io.Serializable {
private String name = "body";
private String stringValue = null;
private Reader readerValue = null;
private boolean isStored = false;
private boolean isIndexed = true;
private boolean isTokenized = true;
private float boost = 1.0f;
/** Sets the boost factor hits on this field. This value will be
* multiplied into the score of all hits on this this field of this
* document.
*
* <p>The boost is multiplied by {@link Document#getBoost()} of the document
* containing this field. If a document has multiple fields with the same
* name, all such values are multiplied together. This product is then
* multipled by the value {@link Similarity#lengthNorm(String,int)}, and
* rounded by {@link Similarity#encodeNorm(float)} before it is stored in the
* index. One should attempt to ensure that this product does not overflow
* the range of that encoding.
*
* @see Document#setBoost(float)
* @see Similarity#lengthNorm(String, int)
* @see Similarity#encodeNorm(float)
*/
public void setBoost(float boost) {
this.boost = boost;
}
/** Returns the boost factor for hits on any field of this document.
*
* <p>The default value is 1.0.
*
* <p>Note: this value is not stored directly with the document in the index.
* Documents returned from {@link IndexReader#document(int)} and {@link
* Hits#doc(int)} may thus not have the same value present as when this field
* was indexed.
*
* @see #setBoost(float)
*/
public float getBoost() {
return boost;
}
/** Constructs a String-valued Field that is not tokenized, but is indexed
and stored. Useful for non-text fields, e.g. date or url. */
public static final Field Keyword(String name, String value) {
return new Field(name, value, true, true, false);
}
/** Constructs a String-valued Field that is not tokenized nor indexed,
but is stored in the index, for return with hits. */
public static final Field UnIndexed(String name, String value) {
return new Field(name, value, true, false, false);
}
/** Constructs a String-valued Field that is tokenized and indexed,
and is stored in the index, for return with hits. Useful for short text
fields, like "title" or "subject". */
public static final Field Text(String name, String value) {
return new Field(name, value, true, true, true);
}
/** Constructs a Date-valued Field that is not tokenized and is indexed,
and stored in the index, for return with hits. */
public static final Field Keyword(String name, Date value) {
return new Field(name, DateField.dateToString(value), true, true, false);
}
/** Constructs a String-valued Field that is tokenized and indexed,
but that is not stored in the index. */
public static final Field UnStored(String name, String value) {
return new Field(name, value, false, true, true);
}
/** Constructs a Reader-valued Field that is tokenized and indexed, but is
not stored in the index verbatim. Useful for longer text fields, like
"body". */
public static final Field Text(String name, Reader value) {
return new Field(name, value);
}
/** The name of the field (e.g., "date", "subject", "title", or "body")
as an interned string. */
public String name() { return name; }
/** The value of the field as a String, or null. If null, the Reader value
is used. Exactly one of stringValue() and readerValue() must be set. */
public String stringValue() { return stringValue; }
/** The value of the field as a Reader, or null. If null, the String value
is used. Exactly one of stringValue() and readerValue() must be set. */
public Reader readerValue() { return readerValue; }
public Field(String name, String string,
boolean store, boolean index, boolean token) {
if (name == null)
throw new IllegalArgumentException("name cannot be null");
if (string == null)
throw new IllegalArgumentException("value cannot be null");
this.name = name.intern(); // field names are interned
this.stringValue = string;
this.isStored = store;
this.isIndexed = index;
this.isTokenized = token;
}
Field(String name, Reader reader) {
if (name == null)
throw new IllegalArgumentException("name cannot be null");
if (reader == null)
throw new IllegalArgumentException("value cannot be null");
this.name = name.intern(); // field names are interned
this.readerValue = reader;
}
/** True iff the value of the field is to be stored in the index for return
with search hits. It is an error for this to be true if a field is
Reader-valued. */
public final boolean isStored() { return isStored; }
/** True iff the value of the field is to be indexed, so that it may be
searched on. */
public final boolean isIndexed() { return isIndexed; }
/** True iff the value of the field should be tokenized as text prior to
indexing. Un-tokenized fields are indexed as a single word and may not be
Reader-valued. */
public final boolean isTokenized() { return isTokenized; }
/** Prints a Field for human consumption. */
public final String toString() {
if (isStored && isIndexed && !isTokenized)
return "Keyword<" + name + ":" + stringValue + ">";
else if (isStored && !isIndexed && !isTokenized)
return "Unindexed<" + name + ":" + stringValue + ">";
else if (isStored && isIndexed && isTokenized && stringValue!=null)
return "Text<" + name + ":" + stringValue + ">";
else if (!isStored && isIndexed && isTokenized && readerValue!=null)
return "Text<" + name + ":" + readerValue + ">";
else
return super.toString();
}
} |
package org.jdesktop.swingx;
import java.awt.Color;
import java.awt.ComponentOrientation;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyVetoException;
import java.text.DateFormat;
import java.text.MessageFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.EventListener;
import java.util.TimeZone;
import javax.swing.AbstractAction;
import javax.swing.JComponent;
import javax.swing.JFormattedTextField;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.UIManager;
import javax.swing.JFormattedTextField.AbstractFormatter;
import javax.swing.JFormattedTextField.AbstractFormatterFactory;
import javax.swing.text.DefaultFormatterFactory;
import org.jdesktop.swingx.calendar.DateSpan;
import org.jdesktop.swingx.calendar.JXMonthView;
import org.jdesktop.swingx.event.EventListenerMap;
import org.jdesktop.swingx.painter.MattePainter;
import org.jdesktop.swingx.plaf.DatePickerUI;
import org.jdesktop.swingx.plaf.JXDatePickerAddon;
import org.jdesktop.swingx.plaf.LookAndFeelAddons;
import org.jdesktop.swingx.util.Contract;
/**
* A component that combines a button, an editable field and a JXMonthView
* component. The user can select a date from the calendar component, which
* appears when the button is pressed. The selection from the calendar
* component will be displayed in editable field. Values may also be modified
* manually by entering a date into the editable field using one of the
* supported date formats.
*
* @author Joshua Outwater
*/
public class JXDatePicker extends JComponent {
static {
LookAndFeelAddons.contribute(new JXDatePickerAddon());
}
/**
* UI Class ID
*/
public static final String uiClassID = "DatePickerUI";
public static final String EDITOR = "editor";
public static final String MONTH_VIEW = "monthView";
public static final String DATE_IN_MILLIS = "dateInMillis";
public static final String LINK_PANEL = "linkPanel";
/**
* The editable date field that displays the date
*/
private JFormattedTextField _dateField;
/**
* Popup that displays the month view with controls for
* traversing/selecting dates.
*/
private JPanel _linkPanel;
private long _linkDate;
private MessageFormat _linkFormat;
private JXMonthView _monthView;
private String _actionCommand = "selectionChanged";
private boolean editable = true;
private EventListenerMap listenerMap;
protected boolean lightWeightPopupEnabled = JPopupMenu.getDefaultLightWeightPopupEnabled();
private Date date;
/**
* Create a new date picker using the current date as the initial
* selection and the default abstract formatter
* <code>JXDatePickerFormatter</code>.
* <p/>
* The date picker is configured with the default time zone and locale
*
* @see #setTimeZone
* @see #getTimeZone
*/
public JXDatePicker() {
this(System.currentTimeMillis());
}
/**
* Create a new date picker using the specified time as the initial
* selection and the default abstract formatter
* <code>JXDatePickerFormatter</code>.
* <p/>
* The date picker is configured with the default time zone and locale
*
* @param millis initial time in milliseconds
* @see #setTimeZone
* @see #getTimeZone
*/
public JXDatePicker(long millis) {
init();
// install the controller before setting the date
updateUI();
setDate(new Date(millis));
}
/**
* Sets the date property. <p>
*
* Does nothing if the ui vetos the new date - as might happen if
* the code tries to set a date which is unselectable in the
* monthView's context. The actual value of the new Date might
* be changed by the ui, the default implementation cleans
* the Date by zeroing all time components. <p>
*
* At all "stable" (= not editing in date input field nor
* in the monthView) times the date is the same in the
* JXMonthView, this JXDatePicker and the editor. If a new Date
* is set, this invariant is enforce by the DatePickerUI.<p>
*
* A not null default value is set on instantiation.
*
* This is a bound property.
*
*
* @param date the new date to set.
* @see #getDate();
*/
public void setDate(Date date) {
/*
* JW:
* this is a poor woman's constraint property.
* Introduces explicit coupling to the ui.
* Which is unusual at this place in code.
*
* If needed the date can be made a formal
* constraint property and let the ui add a
* VetoablePropertyListener.
*/
try {
date = getUI().getSelectableDate(date);
} catch (PropertyVetoException e) {
return;
}
Date old = getDate();
this.date = date;
firePropertyChange("date", old, getDate());
}
/**
* Set the currently selected date.
*
* @param millis milliseconds
*/
public void setDateInMillis(long millis) {
setDate(new Date(millis));
}
/**
* Returns the currently selected date.
*
* @return Date
*/
public Date getDate() {
return date;
}
/**
* Returns the currently selected date in milliseconds.
*
* @return the date in milliseconds, -1 if there is no selection.
*/
public long getDateInMillis() {
long result = -1;
Date selection = getDate();
if (selection != null) {
result = selection.getTime();
}
return result;
}
private void init() {
listenerMap = new EventListenerMap();
_monthView = new JXMonthView();
_monthView.setTraversable(true);
_linkFormat = new MessageFormat(UIManager.getString("JXDatePicker.linkFormat"));
_linkDate = System.currentTimeMillis();
_linkPanel = new TodayPanel();
}
/**
* @inheritDoc
*/
public DatePickerUI getUI() {
return (DatePickerUI) ui;
}
/**
* Sets the L&F object that renders this component.
*
* @param ui UI to use for this {@code JXDatePicker}
*/
public void setUI(DatePickerUI ui) {
super.setUI(ui);
}
/**
* Resets the UI property with the value from the current look and feel.
*
* @see UIManager#getUI
*/
@Override
public void updateUI() {
setUI((DatePickerUI) LookAndFeelAddons.getUI(this, DatePickerUI.class));
invalidate();
}
/**
* @inheritDoc
*/
@Override
public String getUIClassID() {
return uiClassID;
}
/**
* Replaces the currently installed formatter and factory used by the
* editor. These string formats are defined by the
* <code>java.text.SimpleDateFormat</code> class.
*
* @param formats The string formats to use.
* @see java.text.SimpleDateFormat
*/
public void setFormats(String... formats) {
DateFormat[] dateFormats = new DateFormat[formats.length];
for (int counter = formats.length - 1; counter >= 0; counter
dateFormats[counter] = new SimpleDateFormat(formats[counter]);
}
setFormats(dateFormats);
}
/**
* Replaces the currently installed formatter and factory used by the
* editor.
*
* @param formats The date formats to use.
*/
public void setFormats(DateFormat... formats) {
DateFormat[] old = getFormats();
_dateField.setFormatterFactory(new DefaultFormatterFactory(
new JXDatePickerFormatter(formats)));
firePropertyChange("formats", old, getFormats());
}
/**
* Returns an array of the formats used by the installed formatter
* if it is a subclass of <code>JXDatePickerFormatter<code>.
* <code>javax.swing.JFormattedTextField.AbstractFormatter</code>
* and <code>javax.swing.text.DefaultFormatter</code> do not have
* support for accessing the formats used.
*
* @return array of formats or null if unavailable.
*/
public DateFormat[] getFormats() {
// Dig this out from the factory, if possible, otherwise return null.
AbstractFormatterFactory factory = _dateField.getFormatterFactory();
if (factory != null) {
AbstractFormatter formatter = factory.getFormatter(_dateField);
if (formatter instanceof JXDatePickerFormatter) {
return ((JXDatePickerFormatter) formatter).getFormats();
}
}
return null;
}
/**
* Return the <code>JXMonthView</code> used in the popup to
* select dates from.
*
* @return the month view component
*/
public JXMonthView getMonthView() {
return _monthView;
}
/**
* Set the component to use the specified JXMonthView. If the new JXMonthView
* is configured to a different time zone it will affect the time zone of this
* component.
*
* @param monthView month view comopnent.
* @throws NullPointerException if view component is null
*
* @see #setTimeZone
* @see #getTimeZone
*/
public void setMonthView(JXMonthView monthView) {
Contract.asNotNull(monthView, "monthView must not be null");
JXMonthView oldMonthView = _monthView;
_monthView = monthView;
firePropertyChange(MONTH_VIEW, oldMonthView, _monthView);
}
/**
* Gets the time zone. This is a convenience method which returns the time zone
* of the JXMonthView being used.
*
* @return The <code>TimeZone</code> used by the <code>JXMonthView</code>.
*/
public TimeZone getTimeZone() {
return _monthView.getTimeZone();
}
/**
* Sets the time zone with the given time zone value. This is a convenience
* method which returns the time zone of the JXMonthView being used.
*
* @param tz The <code>TimeZone</code>.
*/
public void setTimeZone(TimeZone tz) {
_monthView.setTimeZone(tz);
}
public long getLinkDate() {
return _linkDate;
}
/**
* Set the date the link will use and the string defining a MessageFormat
* to format the link. If no valid date is in the editor when the popup
* is displayed the popup will focus on the month the linkDate is in. Calling
* this method will replace the currently installed linkPanel and install
* a new one with the requested date and format.
*
* @param linkDate Date in milliseconds
* @param linkFormatString String used to format the link
* @see java.text.MessageFormat
*/
public void setLinkDate(long linkDate, String linkFormatString) {
_linkDate = linkDate;
_linkFormat = new MessageFormat(linkFormatString);
setLinkPanel(new TodayPanel());
}
/**
* Return the panel that is used at the bottom of the popup. The default
* implementation shows a link that displays the current month.
*
* @return The currently installed link panel
*/
public JPanel getLinkPanel() {
return _linkPanel;
}
/**
* Set the panel that will be used at the bottom of the popup.
*
* @param linkPanel The new panel to install in the popup
*/
public void setLinkPanel(JPanel linkPanel) {
JPanel oldLinkPanel = _linkPanel;
_linkPanel = linkPanel;
firePropertyChange(LINK_PANEL, oldLinkPanel, _linkPanel);
}
/**
* Returns the formatted text field used to edit the date selection.
*
* @return the formatted text field
*/
public JFormattedTextField getEditor() {
return _dateField;
}
/**
* Sets the editor. <p>
*
* The default is created and set by the UI delegate.
*
* @param editor the formatted input.
* @throws NullPointerException if editor is null.
*
* @see #getEditor
*/
public void setEditor(JFormattedTextField editor) {
Contract.asNotNull(editor, "editor must not be null");
JFormattedTextField oldEditor = _dateField;
_dateField = editor;
firePropertyChange(EDITOR, oldEditor, _dateField);
}
@Override
public void setComponentOrientation(ComponentOrientation orientation) {
super.setComponentOrientation(orientation);
_monthView.setComponentOrientation(orientation);
}
/**
* Returns true if the current value being edited is valid.
*
* @return true if the current value being edited is valid.
*/
public boolean isEditValid() {
return _dateField.isEditValid();
}
/**
* Forces the current value to be taken from the AbstractFormatter and
* set as the current value. This has no effect if there is no current
* AbstractFormatter installed.
*
* @throws java.text.ParseException Throws parse exception if the date
* can not be parsed.
*/
public void commitEdit() throws ParseException {
_dateField.commitEdit();
}
public void setEditable(boolean value) {
boolean oldEditable = isEditable();
editable = value;
firePropertyChange("editable", oldEditable, editable);
if (editable != oldEditable) {
repaint();
}
}
public boolean isEditable() {
return editable;
}
/**
* Returns the font that is associated with the editor of this date picker.
*/
@Override
public Font getFont() {
return getEditor().getFont();
}
/**
* Set the font for the editor associated with this date picker.
*/
@Override
public void setFont(final Font font) {
getEditor().setFont(font);
}
public void setLightWeightPopupEnabled(boolean aFlag) {
boolean oldFlag = lightWeightPopupEnabled;
lightWeightPopupEnabled = aFlag;
firePropertyChange("lightWeightPopupEnabled", oldFlag, lightWeightPopupEnabled);
}
/**
* Gets the value of the <code>lightWeightPopupEnabled</code>
* property.
*
* @return the value of the <code>lightWeightPopupEnabled</code>
* property
* @see #setLightWeightPopupEnabled
*/
public boolean isLightWeightPopupEnabled() {
return lightWeightPopupEnabled;
}
/**
* Get the baseline for the specified component, or a value less
* than 0 if the baseline can not be determined. The baseline is measured
* from the top of the component.
*
* @param width Width of the component to determine baseline for.
* @param height Height of the component to determine baseline for.
* @return baseline for the specified component
*/
public int getBaseline(int width, int height) {
return ((DatePickerUI) ui).getBaseline(width, height);
}
/**
* Returns the string currently used to identiy fired ActionEvents.
*
* @return String The string used for identifying ActionEvents.
*/
public String getActionCommand() {
return _actionCommand;
}
/**
* Sets the string used to identify fired ActionEvents.
*
* @param actionCommand The string used for identifying ActionEvents.
*/
public void setActionCommand(String actionCommand) {
_actionCommand = actionCommand;
}
/**
* Adds an ActionListener.
* <p/>
* The ActionListener will receive an ActionEvent when a selection has
* been made.
*
* @param l The ActionListener that is to be notified
*/
public void addActionListener(ActionListener l) {
listenerMap.add(ActionListener.class, l);
}
/**
* Removes an ActionListener.
*
* @param l The action listener to remove.
*/
public void removeActionListener(ActionListener l) {
listenerMap.remove(ActionListener.class, l);
}
@Override
public <T extends EventListener> T[] getListeners(Class<T> listenerType) {
java.util.List<T> listeners = listenerMap.getListeners(listenerType);
T[] result;
if (!listeners.isEmpty()) {
//noinspection unchecked
result = (T[]) java.lang.reflect.Array.newInstance(listenerType, listeners.size());
result = listeners.toArray(result);
} else {
result = super.getListeners(listenerType);
}
return result;
}
/**
* Fires an ActionEvent to all listeners.
*/
protected void fireActionPerformed() {
ActionListener[] listeners = getListeners(ActionListener.class);
ActionEvent e = null;
for (ActionListener listener : listeners) {
if (e == null) {
e = new ActionEvent(JXDatePicker.this,
ActionEvent.ACTION_PERFORMED,
_actionCommand);
}
listener.actionPerformed(e);
}
}
public void postActionEvent() {
fireActionPerformed();
}
private final class TodayPanel extends JXPanel {
TodayPanel() {
super(new FlowLayout());
setBackgroundPainter(new MattePainter(new GradientPaint(0, 0, new Color(238, 238, 238), 0, 1, Color.WHITE)));
JXHyperlink todayLink = new JXHyperlink(new TodayAction());
Color textColor = new Color(16, 66, 104);
todayLink.setUnclickedColor(textColor);
todayLink.setClickedColor(textColor);
add(todayLink);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(new Color(187, 187, 187));
g.drawLine(0, 0, getWidth(), 0);
g.setColor(new Color(221, 221, 221));
g.drawLine(0, 1, getWidth(), 1);
}
private final class TodayAction extends AbstractAction {
TodayAction() {
super(_linkFormat.format(new Object[]{new Date(_linkDate)}));
}
public void actionPerformed(ActionEvent ae) {
DateSpan span = new DateSpan(_linkDate, _linkDate);
_monthView.ensureDateVisible(span.getStart());
}
}
}
} |
package jsaf.intf.windows.registry;
/**
* Interface to a Windows registry REG_NONE value.
*
* @author David A. Solin
* @version %I% %G%
* @since 1.0
*/
public interface INoneValue extends IValue {
/**
* Get the data.
*
* @since 1.3.9
*/
byte[] getData();
} |
package bisq.core.app;
import bisq.common.util.Utilities;
import java.io.IOException;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class OSXStandbyModeDisabler {
public void doIt() {
if (!Utilities.isOSX()) {
return;
}
long pid = ProcessHandle.current().pid();
try {
String[] params = {"/usr/bin/caffeinate", "-w", "" + pid};
// we only start the process. caffeinate blocks until we exit.
new ProcessBuilder(params).start();
log.info("disabled power management via " + String.join(" ", params));
} catch (IOException e) {
log.error("could not disable standby mode on osx", e);
}
}
} |
package bisq.core.btc;
import bisq.core.btc.wallet.BtcWalletService;
import bisq.core.provider.fee.FeeService;
import bisq.core.user.Preferences;
import bisq.common.util.Tuple2;
import org.bitcoinj.core.Coin;
import org.bitcoinj.core.InsufficientMoneyException;
import javax.inject.Inject;
import com.google.common.annotations.VisibleForTesting;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import static com.google.common.base.Preconditions.checkArgument;
/**
* Util class for getting the estimated tx fee for maker or taker fee tx.
*/
@Slf4j
public class TxFeeEstimationService {
// Size/vsize of typical trade txs
// Real txs size/vsize may vary in 1 or 2 bytes from the estimated values.
// legacy fee tx with 1 input, maker/taker fee paid in btc size/vsize = 258
// legacy deposit tx without change size/vsize = 381
// legacy deposit tx with change size/vsize = 414
// legacy payout tx size/vsize = 337
// legacy delayed payout tx size/vsize = 302
// segwit fee tx with 1 input, maker/taker fee paid in btc vsize = 173
// segwit deposit tx without change vsize = 232
// segwit deposit tx with change vsize = 263
// segwit payout tx vsize = 169
// segwit delayed payout tx vsize = 139
public static int TYPICAL_TX_WITH_1_INPUT_SIZE = 175;
private static int DEPOSIT_TX_SIZE = 233;
private static int BSQ_INPUT_INCREASE = 150;
private static int MAX_ITERATIONS = 10;
private final FeeService feeService;
private final BtcWalletService btcWalletService;
private final Preferences preferences;
@Inject
public TxFeeEstimationService(FeeService feeService,
BtcWalletService btcWalletService,
Preferences preferences) {
this.feeService = feeService;
this.btcWalletService = btcWalletService;
this.preferences = preferences;
}
public Tuple2<Coin, Integer> getEstimatedFeeAndTxSizeForTaker(Coin fundsNeededForTrade, Coin tradeFee) {
return getEstimatedFeeAndTxSize(true,
fundsNeededForTrade,
tradeFee,
feeService,
btcWalletService,
preferences);
}
public Tuple2<Coin, Integer> getEstimatedFeeAndTxSizeForMaker(Coin reservedFundsForOffer,
Coin tradeFee) {
return getEstimatedFeeAndTxSize(false,
reservedFundsForOffer,
tradeFee,
feeService,
btcWalletService,
preferences);
}
private Tuple2<Coin, Integer> getEstimatedFeeAndTxSize(boolean isTaker,
Coin amount,
Coin tradeFee,
FeeService feeService,
BtcWalletService btcWalletService,
Preferences preferences) {
Coin txFeePerByte = feeService.getTxFeePerByte();
// We start with min taker fee size of 175
int estimatedTxSize = TYPICAL_TX_WITH_1_INPUT_SIZE;
try {
estimatedTxSize = getEstimatedTxSize(List.of(tradeFee, amount), estimatedTxSize, txFeePerByte, btcWalletService);
} catch (InsufficientMoneyException e) {
if (isTaker) {
// If we cannot do the estimation, we use the size o the largest of our txs which is the deposit tx.
estimatedTxSize = DEPOSIT_TX_SIZE;
}
log.info("We cannot do the fee estimation because there are not enough funds in the wallet. This is expected " +
"if the user pays from an external wallet. In that case we use an estimated tx size of {} bytes.", estimatedTxSize);
}
if (!preferences.isPayFeeInBtc()) {
// If we pay the fee in BSQ we have one input more which adds about 150 bytes
// TODO: Clarify if there is always just one additional input or if there can be more.
estimatedTxSize += BSQ_INPUT_INCREASE;
}
Coin txFee;
int size;
if (isTaker) {
int averageSize = (estimatedTxSize + DEPOSIT_TX_SIZE) / 2; // deposit tx has about 233 bytes
// We use at least the size of the deposit tx to not underpay it.
size = Math.max(DEPOSIT_TX_SIZE, averageSize);
txFee = txFeePerByte.multiply(size);
log.info("Fee estimation resulted in a tx size of {} bytes.\n" +
"We use an average between the taker fee tx and the deposit tx (233 bytes) which results in {} bytes.\n" +
"The deposit tx has 233 bytes, we use that as our min value. Size for fee calculation is {} bytes.\n" +
"The tx fee of {} Sat", estimatedTxSize, averageSize, size, txFee.value);
} else {
size = estimatedTxSize;
txFee = txFeePerByte.multiply(size);
log.info("Fee estimation resulted in a tx size of {} bytes and a tx fee of {} Sat.", size, txFee.value);
}
return new Tuple2<>(txFee, size);
}
public Tuple2<Coin, Integer> getEstimatedFeeAndTxSize(Coin amount,
FeeService feeService,
BtcWalletService btcWalletService) {
Coin txFeePerByte = feeService.getTxFeePerByte();
// We start with min taker fee size of 175
int estimatedTxSize = TYPICAL_TX_WITH_1_INPUT_SIZE;
try {
estimatedTxSize = getEstimatedTxSize(List.of(amount), estimatedTxSize, txFeePerByte, btcWalletService);
} catch (InsufficientMoneyException e) {
log.info("We cannot do the fee estimation because there are not enough funds in the wallet. This is expected " +
"if the user pays from an external wallet. In that case we use an estimated tx size of {} bytes.", estimatedTxSize);
}
Coin txFee = txFeePerByte.multiply(estimatedTxSize);
log.info("Fee estimation resulted in a tx size of {} bytes and a tx fee of {} Sat.", estimatedTxSize, txFee.value);
return new Tuple2<>(txFee, estimatedTxSize);
}
// We start with the initialEstimatedTxSize for a tx with 1 input (175) bytes and get from BitcoinJ a tx back which
// contains the required inputs to fund that tx (outputs + miner fee). The miner fee in that case is based on
// the assumption that we only need 1 input. Once we receive back the real tx size from the tx BitcoinJ has created
// with the required inputs we compare if the size is not more then 20% different to our assumed tx size. If we are inside
// that tolerance we use that tx size for our fee estimation, if not (if there has been more then 1 inputs) we
// apply the new fee based on the reported tx size and request again from BitcoinJ to fill that tx with the inputs
// to be sufficiently funded. The algorithm how BitcoinJ selects utxos is complex and contains several aspects
// (minimize fee, don't create too many tiny utxos,...). We treat that algorithm as an unknown and it is not
// guaranteed that there are more inputs required if we increase the fee (it could be that there is a better
// selection of inputs chosen if we have increased the fee and therefore less inputs and smaller tx size). As the increased fee might
// change the number of inputs we need to repeat that process until we are inside of a certain tolerance. To avoid
// potential endless loops we add a counter (we use 10, usually it takes just very few iterations).
// Worst case would be that the last size we got reported is > 20% off to
// the real tx size but as fee estimation is anyway a educated guess in the best case we don't worry too much.
// If we have underpaid the tx might take longer to get confirmed.
@VisibleForTesting
static int getEstimatedTxSize(List<Coin> outputValues,
int initialEstimatedTxSize,
Coin txFeePerByte,
BtcWalletService btcWalletService)
throws InsufficientMoneyException {
boolean isInTolerance;
int estimatedTxSize = initialEstimatedTxSize;
int realTxSize;
int counter = 0;
do {
Coin txFee = txFeePerByte.multiply(estimatedTxSize);
realTxSize = btcWalletService.getEstimatedFeeTxSize(outputValues, txFee);
isInTolerance = isInTolerance(estimatedTxSize, realTxSize, 0.2);
if (!isInTolerance) {
estimatedTxSize = realTxSize;
}
counter++;
}
while (!isInTolerance && counter < MAX_ITERATIONS);
if (!isInTolerance) {
log.warn("We could not find a tx which satisfies our tolerance requirement of 20%. " +
"realTxSize={}, estimatedTxSize={}",
realTxSize, estimatedTxSize);
}
return estimatedTxSize;
}
@VisibleForTesting
static boolean isInTolerance(int estimatedSize, int txSize, double tolerance) {
checkArgument(estimatedSize > 0, "estimatedSize must be positive");
checkArgument(txSize > 0, "txSize must be positive");
checkArgument(tolerance > 0, "tolerance must be positive");
double deviation = Math.abs(1 - ((double) estimatedSize / (double) txSize));
return deviation <= tolerance;
}
} |
package forklift.producers;
import forklift.connectors.ForkliftMessage;
import forklift.message.Header;
import java.io.Closeable;
import java.util.Map;
public interface ForkliftProducerI extends Closeable {
String send(String message) throws ProducerException;
String send(ForkliftMessage message) throws ProducerException;
String send(Object message) throws ProducerException;
String send(Map<String, String> message) throws ProducerException;
String send(Map<String, String> properties,
ForkliftMessage message) throws ProducerException;
String send(Map<Header, Object> headers,
Map<String, String> properties,
ForkliftMessage message) throws ProducerException;
Map<Header, Object> getHeaders() throws ProducerException;
void setHeaders(Map<Header, Object> headers) throws ProducerException;
Map<String, String> getProperties() throws ProducerException;
void setProperties(Map<String, String> properties) throws ProducerException;
} |
package io.bisq.core.btc.wallet;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableList;
import com.google.common.util.concurrent.Service;
import com.google.inject.Inject;
import com.runjva.sourceforge.jsocks.protocol.Socks5Proxy;
import io.bisq.common.Timer;
import io.bisq.common.UserThread;
import io.bisq.common.app.Log;
import io.bisq.common.handlers.ExceptionHandler;
import io.bisq.common.handlers.ResultHandler;
import io.bisq.common.storage.FileUtil;
import io.bisq.core.app.BisqEnvironment;
import io.bisq.core.btc.*;
import io.bisq.core.user.Preferences;
import io.bisq.network.DnsLookupTor;
import io.bisq.network.Socks5MultiDiscovery;
import io.bisq.network.Socks5ProxyProvider;
import javafx.beans.property.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.bitcoinj.core.*;
import org.bitcoinj.core.listeners.DownloadProgressTracker;
import org.bitcoinj.net.OnionCat;
import org.bitcoinj.params.MainNetParams;
import org.bitcoinj.params.RegTestParams;
import org.bitcoinj.utils.Threading;
import org.bitcoinj.wallet.DeterministicSeed;
import org.bitcoinj.wallet.Wallet;
import org.jetbrains.annotations.NotNull;
import javax.annotation.Nullable;
import javax.inject.Named;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.stream.Collectors;
import static com.google.common.base.Preconditions.checkNotNull;
// Setup wallets and use WalletConfig for BitcoinJ wiring.
// Other like WalletConfig we are here always on the user thread. That is one reason why we do not
// merge WalletsSetup with WalletConfig to one class.
@Slf4j
public class WalletsSetup {
// We reduce defaultConnections from 12 (PeerGroup.DEFAULT_CONNECTIONS) to 9 nodes
private static final int DEFAULT_CONNECTIONS = 9;
private static final long STARTUP_TIMEOUT = 180;
private final String btcWalletFileName;
private static final String BSQ_WALLET_FILE_NAME = "bisq_BSQ.wallet";
private static final String SPV_CHAIN_FILE_NAME = "bisq.spvchain";
private final RegTestHost regTestHost;
private final AddressEntryList addressEntryList;
private final Preferences preferences;
private final Socks5ProxyProvider socks5ProxyProvider;
private final BisqEnvironment bisqEnvironment;
private final BitcoinNodes bitcoinNodes;
private final int numConnectionForBtc;
private final boolean useAllProvidedNodes;
private final String userAgent;
private final NetworkParameters params;
private final File walletDir;
private final int socks5DiscoverMode;
private final IntegerProperty numPeers = new SimpleIntegerProperty(0);
private final ObjectProperty<List<Peer>> connectedPeers = new SimpleObjectProperty<>();
private final DownloadListener downloadListener = new DownloadListener();
private final List<Runnable> setupCompletedHandlers = new ArrayList<>();
public final BooleanProperty shutDownComplete = new SimpleBooleanProperty();
private WalletConfig walletConfig;
// Constructor
@Inject
public WalletsSetup(RegTestHost regTestHost,
AddressEntryList addressEntryList,
Preferences preferences,
Socks5ProxyProvider socks5ProxyProvider,
BisqEnvironment bisqEnvironment,
BitcoinNodes bitcoinNodes,
@Named(BtcOptionKeys.USER_AGENT) String userAgent,
@Named(BtcOptionKeys.WALLET_DIR) File appDir,
@Named(BtcOptionKeys.USE_ALL_PROVIDED_NODES) String useAllProvidedNodes,
@Named(BtcOptionKeys.NUM_CONNECTIONS_FOR_BTC) String numConnectionForBtc,
@Named(BtcOptionKeys.SOCKS5_DISCOVER_MODE) String socks5DiscoverModeString) {
this.regTestHost = regTestHost;
this.addressEntryList = addressEntryList;
this.preferences = preferences;
this.socks5ProxyProvider = socks5ProxyProvider;
this.bisqEnvironment = bisqEnvironment;
this.bitcoinNodes = bitcoinNodes;
this.numConnectionForBtc = numConnectionForBtc != null ? Integer.parseInt(numConnectionForBtc) : DEFAULT_CONNECTIONS;
this.useAllProvidedNodes = "true".equals(useAllProvidedNodes);
this.userAgent = userAgent;
this.socks5DiscoverMode = evaluateMode(socks5DiscoverModeString);
btcWalletFileName = "bisq_" + BisqEnvironment.getBaseCurrencyNetwork().getCurrencyCode() + ".wallet";
params = BisqEnvironment.getParameters();
walletDir = new File(appDir, "wallet");
PeerGroup.setIgnoreHttpSeeds(true);
}
// Lifecycle
public void initialize(@Nullable DeterministicSeed seed, ResultHandler resultHandler, ExceptionHandler exceptionHandler) {
Log.traceCall();
// Tell bitcoinj to execute event handlers on the JavaFX UI thread. This keeps things simple and means
// we cannot forget to switch threads when adding event handlers. Unfortunately, the DownloadListener
// we give to the app kit is currently an exception and runs on a library thread. It'll get fixed in
// a future version.
Threading.USER_THREAD = UserThread.getExecutor();
Timer timeoutTimer = UserThread.runAfter(() ->
exceptionHandler.handleException(new TimeoutException("Wallet did not initialize in " +
STARTUP_TIMEOUT + " seconds.")), STARTUP_TIMEOUT);
backupWallets();
final Socks5Proxy socks5Proxy = preferences.getUseTorForBitcoinJ() ? socks5ProxyProvider.getSocks5Proxy() : null;
log.info("Socks5Proxy for bitcoinj: socks5Proxy=" + socks5Proxy);
walletConfig = new WalletConfig(params,
socks5Proxy,
walletDir,
bisqEnvironment,
userAgent,
numConnectionForBtc,
btcWalletFileName,
BSQ_WALLET_FILE_NAME,
SPV_CHAIN_FILE_NAME) {
@Override
protected void onSetupCompleted() {
//We are here in the btcj thread Thread[ STARTING,5,main]
super.onSetupCompleted();
final PeerGroup peerGroup = walletConfig.peerGroup();
// We don't want to get our node white list polluted with nodes from AddressMessage calls.
if (preferences.getBitcoinNodes() != null && !preferences.getBitcoinNodes().isEmpty())
peerGroup.setAddPeersFromAddressMessage(false);
peerGroup.addConnectedEventListener((peer, peerCount) -> {
// We get called here on our user thread
numPeers.set(peerCount);
connectedPeers.set(peerGroup.getConnectedPeers());
});
peerGroup.addDisconnectedEventListener((peer, peerCount) -> {
// We get called here on our user thread
numPeers.set(peerCount);
connectedPeers.set(peerGroup.getConnectedPeers());
});
// Map to user thread
UserThread.execute(() -> {
addressEntryList.onWalletReady(walletConfig.getBtcWallet());
timeoutTimer.stop();
setupCompletedHandlers.stream().forEach(Runnable::run);
});
// onSetupCompleted in walletAppKit is not the called on the last invocations, so we add a bit of delay
UserThread.runAfter(resultHandler::handleResult, 100, TimeUnit.MILLISECONDS);
}
};
configPeerNodes(socks5Proxy);
walletConfig.setDownloadListener(downloadListener)
.setBlockingStartup(false);
// If seed is non-null it means we are restoring from backup.
walletConfig.setSeed(seed);
walletConfig.addListener(new Service.Listener() {
@Override
public void failed(@NotNull Service.State from, @NotNull Throwable failure) {
walletConfig = null;
log.error("Service failure from state: {}; failure={}", from, failure);
timeoutTimer.stop();
UserThread.execute(() -> exceptionHandler.handleException(failure));
}
}, Threading.USER_THREAD);
walletConfig.startAsync();
}
public void shutDown() {
if (walletConfig != null) {
try {
walletConfig.stopAsync();
walletConfig.awaitTerminated(5, TimeUnit.SECONDS);
} catch (Throwable ignore) {
}
shutDownComplete.set(true);
} else {
shutDownComplete.set(true);
}
}
public boolean reSyncSPVChain() {
try {
return new File(walletDir, SPV_CHAIN_FILE_NAME).delete();
} catch (Throwable t) {
log.error(t.toString());
t.printStackTrace();
return false;
}
}
// Initialize methods
@VisibleForTesting
private int evaluateMode(String socks5DiscoverModeString) {
String[] socks5DiscoverModes = StringUtils.deleteWhitespace(socks5DiscoverModeString).split(",");
int mode = 0;
for (String socks5DiscoverMode : socks5DiscoverModes) {
switch (socks5DiscoverMode) {
case "ADDR":
mode |= Socks5MultiDiscovery.SOCKS5_DISCOVER_ADDR;
break;
case "DNS":
mode |= Socks5MultiDiscovery.SOCKS5_DISCOVER_DNS;
break;
case "ONION":
mode |= Socks5MultiDiscovery.SOCKS5_DISCOVER_ONION;
break;
case "ALL":
default:
mode |= Socks5MultiDiscovery.SOCKS5_DISCOVER_ALL;
break;
}
}
return mode;
}
private void configPeerNodes(Socks5Proxy socks5Proxy) {
if (params == RegTestParams.get()) {
walletConfig.setMinBroadcastConnections(1);
if (regTestHost == RegTestHost.REG_TEST_SERVER) {
try {
walletConfig.setPeerNodes(new PeerAddress(InetAddress.getByName(RegTestHost.SERVER_IP), params.getPort()));
} catch (UnknownHostException e) {
log.error(e.toString());
e.printStackTrace();
throw new RuntimeException(e);
}
} else if (regTestHost == RegTestHost.LOCALHOST) {
walletConfig.connectToLocalHost();
}
} else {
List<BitcoinNodes.BtcNode> btcNodeList = new ArrayList<>();
walletConfig.setMinBroadcastConnections((int) Math.floor(DEFAULT_CONNECTIONS * 0.8));
switch (BitcoinNodes.BitcoinNodesOption.values()[preferences.getBitcoinNodesOptionOrdinal()]) {
case CUSTOM:
String bitcoinNodesString = preferences.getBitcoinNodes();
if (bitcoinNodesString != null) {
btcNodeList = Splitter.on(",")
.splitToList(StringUtils.deleteWhitespace(bitcoinNodesString))
.stream()
.filter(e -> !e.isEmpty())
.map(BitcoinNodes.BtcNode::fromFullAddress)
.collect(Collectors.toList());
}
break;
case PUBLIC:
// we keep the empty list
break;
default:
case PROVIDED:
btcNodeList = bitcoinNodes.getProvidedBtcNodes();
// We require only 4 nodes instead of 7 (for 9 max connections) because our provided nodes
// are more reliable than random public nodes.
walletConfig.setMinBroadcastConnections(4);
break;
}
final boolean useTorForBitcoinJ = socks5Proxy != null;
List<PeerAddress> peerAddressList = new ArrayList<>();
// We connect to onion nodes only in case we use Tor for BitcoinJ (default) to avoid privacy leaks at
// exit nodes with bloom filters.
if (useTorForBitcoinJ) {
btcNodeList.stream()
.filter(BitcoinNodes.BtcNode::hasOnionAddress)
.forEach(btcNode -> {
// no DNS lookup for onion addresses
log.info("We add a onion node. btcNode={}", btcNode);
final String onionAddress = checkNotNull(btcNode.getOnionAddress());
try {
// OnionCat.onionHostToInetAddress converts onion to ipv6 representation
// inetAddress is not used but required for wallet persistence. Throws nullPointer if not set.
final InetAddress inetAddress = OnionCat.onionHostToInetAddress(onionAddress);
final PeerAddress peerAddress = new PeerAddress(onionAddress, btcNode.getPort());
peerAddress.setAddr(inetAddress);
peerAddressList.add(peerAddress);
} catch (UnknownHostException e) {
log.error("OnionCat.onionHostToInetAddress() failed with btcNode={}, error={}", btcNode.toString(), e.toString());
e.printStackTrace();
}
});
if (useAllProvidedNodes) {
// We also use the clear net nodes (used for monitor)
btcNodeList.stream()
.filter(BitcoinNodes.BtcNode::hasClearNetAddress)
.forEach(btcNode -> {
try {
// We use DnsLookupTor to not leak with DNS lookup
// Blocking call. takes about 600 ms ;-(
InetSocketAddress address = new InetSocketAddress(DnsLookupTor.lookup(socks5Proxy, btcNode.getHostNameOrAddress()), btcNode.getPort());
log.info("We add a clear net node (tor is used) with InetAddress={}, btcNode={}", address.getAddress(), btcNode);
peerAddressList.add(new PeerAddress(address.getAddress(), address.getPort()));
} catch (Exception e) {
if (btcNode.getAddress() != null) {
log.warn("Dns lookup failed. We try with provided IP address. BtcNode: {}", btcNode);
try {
InetSocketAddress address = new InetSocketAddress(DnsLookupTor.lookup(socks5Proxy, btcNode.getAddress()), btcNode.getPort());
log.info("We add a clear net node (tor is used) with InetAddress={}, BtcNode={}", address.getAddress(), btcNode);
peerAddressList.add(new PeerAddress(address.getAddress(), address.getPort()));
} catch (Exception e2) {
log.warn("Dns lookup failed for BtcNode: {}", btcNode);
}
} else {
log.warn("Dns lookup failed. No IP address is provided. BtcNode: {}", btcNode);
}
}
});
}
} else {
btcNodeList.stream()
.filter(BitcoinNodes.BtcNode::hasClearNetAddress)
.forEach(btcNode -> {
try {
InetSocketAddress address = new InetSocketAddress(btcNode.getHostNameOrAddress(), btcNode.getPort());
log.info("We add a clear net node (no tor is used) with host={}, btcNode.getPort()={}", btcNode.getHostNameOrAddress(), btcNode.getPort());
peerAddressList.add(new PeerAddress(address.getAddress(), address.getPort()));
} catch (Throwable t) {
if (btcNode.getAddress() != null) {
log.warn("Dns lookup failed. We try with provided IP address. BtcNode: {}", btcNode);
try {
InetSocketAddress address = new InetSocketAddress(btcNode.getAddress(), btcNode.getPort());
log.info("We add a clear net node (no tor is used) with host={}, btcNode.getPort()={}", btcNode.getHostNameOrAddress(), btcNode.getPort());
peerAddressList.add(new PeerAddress(address.getAddress(), address.getPort()));
} catch (Throwable t2) {
log.warn("Failed to create InetSocketAddress from btcNode {}", btcNode);
}
} else {
log.warn("Dns lookup failed. No IP address is provided. BtcNode: {}", btcNode);
}
}
});
}
if (!peerAddressList.isEmpty()) {
final PeerAddress[] peerAddresses = peerAddressList.toArray(new PeerAddress[peerAddressList.size()]);
log.info("You connect with peerAddresses: " + peerAddressList.toString());
walletConfig.setPeerNodes(peerAddresses);
} else if (useTorForBitcoinJ) {
if (params == MainNetParams.get())
log.warn("You use the public Bitcoin network and are exposed to privacy issues caused by the broken bloom filters." +
"See https://bisq.network/blog/privacy-in-bitsquare/ for more info. It is recommended to use the provided nodes.");
// SeedPeers uses hard coded stable addresses (from MainNetParams). It should be updated from time to time.
walletConfig.setDiscovery(new Socks5MultiDiscovery(socks5Proxy, params, socks5DiscoverMode));
} else {
log.warn("You don't use gtor and use the public Bitcoin network and are exposed to privacy issues caused by the broken bloom filters." +
"See https://bisq.network/blog/privacy-in-bitsquare/ for more info. It is recommended to use Tor and the provided nodes.");
}
}
}
// Backup
void backupWallets() {
FileUtil.rollingBackup(walletDir, btcWalletFileName, 20);
FileUtil.rollingBackup(walletDir, BSQ_WALLET_FILE_NAME, 20);
}
void clearBackups() {
try {
FileUtil.deleteDirectory(new File(Paths.get(walletDir.getAbsolutePath(), "backup").toString()));
} catch (IOException e) {
log.error("Could not delete directory " + e.getMessage());
e.printStackTrace();
}
}
// Restore
public void restoreSeedWords(@Nullable DeterministicSeed seed, ResultHandler resultHandler, ExceptionHandler exceptionHandler) {
checkNotNull(seed, "Seed must be not be null.");
backupWallets();
Context ctx = Context.get();
new Thread(() -> {
try {
Context.propagate(ctx);
walletConfig.stopAsync();
walletConfig.awaitTerminated();
initialize(seed, resultHandler, exceptionHandler);
} catch (Throwable t) {
t.printStackTrace();
log.error("Executing task failed. " + t.getMessage());
}
}, "RestoreBTCWallet-%d").start();
}
// Handlers
public void addSetupCompletedHandler(Runnable handler) {
setupCompletedHandlers.add(handler);
}
// Getters
public Wallet getBtcWallet() {
return walletConfig.getBtcWallet();
}
@Nullable
public Wallet getBsqWallet() {
return walletConfig.getBsqWallet();
}
public NetworkParameters getParams() {
return params;
}
public BlockChain getChain() {
return walletConfig.chain();
}
public PeerGroup getPeerGroup() {
return walletConfig.peerGroup();
}
public WalletConfig getWalletConfig() {
return walletConfig;
}
public ReadOnlyIntegerProperty numPeersProperty() {
return numPeers;
}
public ReadOnlyObjectProperty<List<Peer>> connectedPeersProperty() {
return connectedPeers;
}
public ReadOnlyDoubleProperty downloadPercentageProperty() {
return downloadListener.percentageProperty();
}
public Set<Address> getAddressesByContext(@SuppressWarnings("SameParameterValue") AddressEntry.Context context) {
return ImmutableList.copyOf(addressEntryList.getList()).stream()
.filter(addressEntry -> addressEntry.getContext() == context)
.map(AddressEntry::getAddress)
.collect(Collectors.toSet());
}
public Set<Address> getAddressesFromAddressEntries(Set<AddressEntry> addressEntries) {
return addressEntries.stream()
.map(AddressEntry::getAddress)
.collect(Collectors.toSet());
}
public boolean hasSufficientPeersForBroadcast() {
return bisqEnvironment.isBitcoinLocalhostNodeRunning() || numPeers.get() >= walletConfig.getMinBroadcastConnections();
}
// Inner classes
private static class DownloadListener extends DownloadProgressTracker {
private final DoubleProperty percentage = new SimpleDoubleProperty(-1);
@Override
protected void progress(double percentage, int blocksLeft, Date date) {
super.progress(percentage, blocksLeft, date);
UserThread.execute(() -> this.percentage.set(percentage / 100d));
}
@Override
protected void doneDownload() {
super.doneDownload();
UserThread.execute(() -> this.percentage.set(1d));
}
public ReadOnlyDoubleProperty percentageProperty() {
return percentage;
}
}
} |
package jenkins.triggers;
import hudson.Extension;
import hudson.ExtensionList;
import hudson.Util;
import hudson.console.ModelHyperlinkNote;
import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;
import hudson.model.Action;
import hudson.model.AutoCompletionCandidates;
import hudson.model.Cause;
import hudson.model.CauseAction;
import hudson.model.DependencyGraph;
import hudson.model.Item;
import hudson.model.ItemGroup;
import hudson.model.Items;
import hudson.model.Job;
import hudson.model.Queue;
import hudson.model.Result;
import hudson.model.Run;
import hudson.model.TaskListener;
import hudson.model.listeners.ItemListener;
import hudson.model.listeners.RunListener;
import hudson.model.queue.Tasks;
import hudson.security.ACL;
import hudson.tasks.BuildTrigger;
import hudson.triggers.Trigger;
import hudson.triggers.TriggerDescriptor;
import hudson.util.FormValidation;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.WeakHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import jenkins.model.DependencyDeclarer;
import jenkins.model.Jenkins;
import jenkins.model.ParameterizedJobMixIn;
import jenkins.security.QueueItemAuthenticatorConfiguration;
import org.acegisecurity.Authentication;
import org.acegisecurity.context.SecurityContext;
import org.acegisecurity.context.SecurityContextHolder;
import org.apache.commons.lang.StringUtils;
import org.kohsuke.stapler.AncestorInPath;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.QueryParameter;
import javax.annotation.Nonnull;
/**
* Like {@link BuildTrigger} but defined on the downstream project.
* Operates via {@link BuildTrigger#execute} and {@link DependencyGraph},
* so run implicitly at the end of the upstream build,
* when used on a pair of {@link AbstractProject}s.
* Otherwise directly listens for the upstream build to complete.
* @since 1.560
*/
@SuppressWarnings("rawtypes")
public final class ReverseBuildTrigger extends Trigger<Job> implements DependencyDeclarer {
private static final Logger LOGGER = Logger.getLogger(ReverseBuildTrigger.class.getName());
private String upstreamProjects;
private final Result threshold;
@DataBoundConstructor
public ReverseBuildTrigger(String upstreamProjects, Result threshold) {
this.upstreamProjects = upstreamProjects;
this.threshold = threshold;
}
public String getUpstreamProjects() {
return upstreamProjects;
}
public Result getThreshold() {
return threshold;
}
private boolean shouldTrigger(Run upstreamBuild, TaskListener listener) {
Jenkins jenkins = Jenkins.getInstance();
if (job == null) {
return false;
}
// This checks Item.READ also on parent folders; note we are checking as the upstream auth currently:
boolean downstreamVisible = jenkins.getItemByFullName(job.getFullName()) == job;
Authentication originalAuth = Jenkins.getAuthentication();
Job upstream = upstreamBuild.getParent();
Authentication auth = Tasks.getAuthenticationOf((Queue.Task) job);
if (auth.equals(ACL.SYSTEM) && !QueueItemAuthenticatorConfiguration.get().getAuthenticators().isEmpty()) {
auth = Jenkins.ANONYMOUS; // cf. BuildTrigger
}
SecurityContext orig = ACL.impersonate(auth);
try {
if (jenkins.getItemByFullName(upstream.getFullName()) != upstream) {
if (downstreamVisible) {
// TODO ModelHyperlink
listener.getLogger().println(Messages.ReverseBuildTrigger_running_as_cannot_even_see_for_trigger_f(auth.getName(), upstream.getFullName(), job.getFullName()));
} else {
LOGGER.log(Level.WARNING, "Running as {0} cannot even see {1} for trigger from {2} (but cannot tell {3} that)", new Object[] {auth.getName(), upstream, job, originalAuth.getName()});
}
return false;
}
} finally {
SecurityContextHolder.setContext(orig);
}
Result result = upstreamBuild.getResult();
return result != null && result.isBetterOrEqualTo(threshold);
}
@Override public void buildDependencyGraph(final AbstractProject downstream, DependencyGraph graph) {
for (AbstractProject upstream : Items.fromNameList(downstream.getParent(), upstreamProjects, AbstractProject.class)) {
graph.addDependency(new DependencyGraph.Dependency(upstream, downstream) {
@Override public boolean shouldTriggerBuild(AbstractBuild upstreamBuild, TaskListener listener, List<Action> actions) {
return shouldTrigger(upstreamBuild, listener);
}
});
}
}
@Override public void start(@Nonnull Job project, boolean newInstance) {
super.start(project, newInstance);
RunListenerImpl.get().invalidateCache();
}
@Override public void stop() {
super.stop();
RunListenerImpl.get().invalidateCache();
}
@Extension public static final class DescriptorImpl extends TriggerDescriptor {
@Override public String getDisplayName() {
return Messages.ReverseBuildTrigger_build_after_other_projects_are_built();
}
@Override public boolean isApplicable(Item item) {
return item instanceof Job && item instanceof ParameterizedJobMixIn.ParameterizedJob;
}
public AutoCompletionCandidates doAutoCompleteUpstreamProjects(@QueryParameter String value, @AncestorInPath Item self, @AncestorInPath ItemGroup container) {
return AutoCompletionCandidates.ofJobNames(Job.class, value, self, container);
}
public FormValidation doCheckUpstreamProjects(@AncestorInPath Job project, @QueryParameter String value) {
if (!project.hasPermission(Item.CONFIGURE)) {
return FormValidation.ok();
}
StringTokenizer tokens = new StringTokenizer(Util.fixNull(value),",");
boolean hasProjects = false;
while(tokens.hasMoreTokens()) {
String projectName = tokens.nextToken().trim();
if (StringUtils.isNotBlank(projectName)) {
Job item = Jenkins.getInstance().getItem(projectName, project, Job.class);
if (item == null) {
Job nearest = Items.findNearest(Job.class, projectName, project.getParent());
String alternative = nearest != null ? nearest.getRelativeNameFrom(project) : "?";
return FormValidation.error(hudson.tasks.Messages.BuildTrigger_NoSuchProject(projectName, alternative));
}
hasProjects = true;
}
}
if (!hasProjects) {
return FormValidation.error(hudson.tasks.Messages.BuildTrigger_NoProjectSpecified());
}
return FormValidation.ok();
}
}
@Extension public static final class RunListenerImpl extends RunListener<Run> {
static RunListenerImpl get() {
return ExtensionList.lookup(RunListener.class).get(RunListenerImpl.class);
}
private Map<Job,Collection<ReverseBuildTrigger>> upstream2Trigger;
synchronized void invalidateCache() {
upstream2Trigger = null;
}
private Map<Job,Collection<ReverseBuildTrigger>> calculateCache() {
Map<Job,Collection<ReverseBuildTrigger>> result = new WeakHashMap<>();
SecurityContext orig = ACL.impersonate(ACL.SYSTEM);
try {
for (Job<?, ?> downstream : Jenkins.getInstance().getAllItems(Job.class)) {
ReverseBuildTrigger trigger = ParameterizedJobMixIn.getTrigger(downstream, ReverseBuildTrigger.class);
if (trigger == null) {
continue;
}
List<Job> upstreams = Items.fromNameList(downstream.getParent(), trigger.upstreamProjects, Job.class);
LOGGER.log(Level.FINE, "from {0} see upstreams {1}", new Object[] {downstream, upstreams});
for (Job upstream : upstreams) {
if (upstream instanceof AbstractProject && downstream instanceof AbstractProject) {
continue; // handled specially
}
Collection<ReverseBuildTrigger> triggers = result.get(upstream);
if (triggers == null) {
triggers = new LinkedList<>();
result.put(upstream, triggers);
}
triggers.remove(trigger);
triggers.add(trigger);
}
}
} finally {
SecurityContextHolder.setContext(orig);
}
return result;
}
@Override public void onCompleted(@Nonnull Run r, @Nonnull TaskListener listener) {
Collection<ReverseBuildTrigger> triggers;
synchronized (this) {
if (upstream2Trigger == null) {
upstream2Trigger = calculateCache();
}
Collection<ReverseBuildTrigger> _triggers = upstream2Trigger.get(r.getParent());
if (_triggers == null || _triggers.isEmpty()) {
return;
}
triggers = new ArrayList<>(_triggers);
}
for (final ReverseBuildTrigger trigger : triggers) {
if (trigger.shouldTrigger(r, listener)) {
if (!trigger.job.isBuildable()) {
listener.getLogger().println(hudson.tasks.Messages.BuildTrigger_Disabled(ModelHyperlinkNote.encodeTo(trigger.job)));
continue;
}
String name = ModelHyperlinkNote.encodeTo(trigger.job) + " #" + trigger.job.getNextBuildNumber();
if (ParameterizedJobMixIn.scheduleBuild2(trigger.job, -1, new CauseAction(new Cause.UpstreamCause(r))) != null) {
listener.getLogger().println(hudson.tasks.Messages.BuildTrigger_Triggering(name));
} else {
listener.getLogger().println(hudson.tasks.Messages.BuildTrigger_InQueue(name));
}
}
}
}
}
@Extension public static class ItemListenerImpl extends ItemListener {
@Override public void onLocationChanged(Item item, String oldFullName, String newFullName) {
for (Job<?,?> p : Jenkins.getInstance().getAllItems(Job.class)) {
ReverseBuildTrigger t = ParameterizedJobMixIn.getTrigger(p, ReverseBuildTrigger.class);
if (t != null) {
String revised = Items.computeRelativeNamesAfterRenaming(oldFullName, newFullName, t.upstreamProjects, p.getParent());
if (!revised.equals(t.upstreamProjects)) {
t.upstreamProjects = revised;
try {
p.save();
} catch (IOException e) {
LOGGER.log(Level.WARNING, "Failed to persist project setting during rename from " + oldFullName + " to " + newFullName, e);
}
}
}
}
}
}
} |
// leaderboard server with rest api, supporting json or jsonp
// rest server
import static spark.Spark.*;
import spark.*;
// mysql
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
//import java.sql.PreparedStatement;
// logging
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;
// json
//import com.google.gson.Gson;
//import com.google.gson.JsonArray;
//import com.google.gson.JsonParser;
//import java.util.ArrayList;
//import java.util.Collection;
// json-minimal
import com.eclipsesource.json.JsonArray;
import com.eclipsesource.json.JsonObject;
import com.eclipsesource.json.JsonValue;
import com.eclipsesource.json.ParseException;
// configuration file
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
public class LeaderboardREST {
static String configFileName = "config.properties";
static Logger logger;
public static int toIntDef(String v, int defaultValue) {
int result = defaultValue;
try {
result = Integer.parseInt(v);
} catch (Exception e) {
}
return result;
}
public static String toSafeString(String s, int maxLength) { // this should return a string that is safe to use in sql inputs, preventing sql injection
if (s == null) return null;
try {
s = java.net.URLDecoder.decode(s, "UTF-8"); // to enable spaces
} catch (Exception e) {return null;};
int len = s.length();
if (len > maxLength) len = maxLength;
StringBuilder res = new StringBuilder(len);
for (int i=0; i<len; i++) {
char ch = s.charAt(i);
if ( ((ch >= 'a') && (ch <= 'z')) // be very careful when changing this! besides ',\,; there are also comment charaters etc.
|| ((ch >= 'A') && (ch <= 'Z'))
|| ((ch >= '0') && (ch <= '9'))
|| (ch == '.') || (ch == ' ') )
res.append(ch);
}
return res.toString();
}
public static void main(String[] args) {
Properties prop = new Properties();
//load a properties file
try {
prop.load(new FileInputStream(configFileName));
} catch (IOException ex) {
System.out.println("error reading config file: " + configFileName);
return;
}
//get the property values and print them
final String url = prop.getProperty("url"); // jdbc:mysql://localhost:3306/mygame";
final String user = prop.getProperty("user");
final String password = prop.getProperty("password");
final String logfile = prop.getProperty("logfile");
System.out.println("read these config values:");
System.out.println("url: " + url);
System.out.println("user: " + user);
System.out.println("password: " + password);
System.out.println("logfile: " + logfile);
// init logger (to file)
logger = Logger.getLogger("MyLog");
FileHandler fh;
if (logfile != null) try {
// This block configure the logger with handler and formatter
fh = new FileHandler(logfile, 100000, 1, true);
logger.addHandler(fh);
SimpleFormatter formatter = new SimpleFormatter();
fh.setFormatter(formatter);
// the following statement is used to log any messages
logger.info("My first log");
} catch (SecurityException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
logger.info("//////////// LeaderboardREST server started /////////////");
// for browser (FireFox) cross origin resource sharing (CORS) to confirm that PUT and DELETE work, too
options(new Route("/lb/:gameID") {
@Override
public Object handle(Request request, Response response) {
System.out.println("OPTIONS");
response.header("Access-Control-Allow-Origin", "*");
response.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
response.header("Access-Control-Allow-Headers", "X-Requested-With");
response.header("Access-Control-Max-Age", "100");
response.status(204);
return ("");
}
});
/*
put(new Route("/lb/:gameID") {
@Override
public Object handle(Request request, Response response) {
System.out.println("12345");
return ("");
}
});
*/
post(new Route("/lb/:gameID/:playerID/score") {
@Override
public Object handle(Request request, Response response) {
String callback = request.queryParams("callback");
String gameID = toSafeString(request.params(":gameID"), 30);
String playerID = toSafeString(request.params(":playerID"), 30);
System.out.println(gameID);
System.out.println(playerID);
System.out.println("queryparams:");
System.out.println(request.queryParams());
System.out.println("body:");
System.out.println(request.body());
// read other parameters
String content = request.body();
//String content = request.queryParams().toString(); // this wraps the content in an additional array '[...]'
String names = "";
String values = "";
try {
JsonObject requestObj = JsonObject.readFrom(content);
//JsonObject requestObj = JsonArray.readFrom(content).get(0).asObject(); // strip the additional '[...]' introduced above
JsonArray scoresArr = requestObj.get("scoreEntries").asArray();
for (int i=0; i<scoresArr.size(); i++) {
JsonObject scoreEntryObj = scoresArr.get(i).asObject();
if (i>0) {
names += ',';
values += ',';
}
names += toSafeString(scoreEntryObj.get("name").asString(), 30);
//values += scoreEntryObj.get("value").asInt(); // convert to int as safe method to prevent injection
values += Integer.parseInt(scoreEntryObj.get("value").asString()); // convert to int as safe method to prevent injection
}
//JsonObject authObj = requestObj.get("authentication").asObject();
//JsonObject userDataObj = requestObj.get("userData").asObject();
} catch (ParseException ex) {
System.out.println("JSON parse exception: " + ex.getMessage());
System.out.println(content);
response.status(400); // 400 bad request
return "Cannot parse JSON payload. " + ex.getMessage();
} catch (Exception ex) {
response.status(500); // 500 internal server error
System.out.println("submitscore: exception " + ex.getMessage());
ex.printStackTrace();
return "Cannot read input. " + ex.getMessage();
}
System.out.println(names);
System.out.println(values);
Connection con = null;
Statement st = null;
response.type("application/json");
StringBuilder result = new StringBuilder(40);
if (callback != null) {
result.append(callback);
result.append("(");
}
try {
con = DriverManager.getConnection(url, user, password);
st = con.createStatement();
String updstr = "INSERT INTO mygame." + gameID + " (playerID," + names + ") VALUES (\'" + playerID + "\'," + values + ");";
System.out.println(updstr);
System.out.println();
st.executeUpdate(updstr);
response.status(200); // 200 ok
} catch (SQLException ex) {
response.status(503); // 503 Service Unavailable
logger.log(Level.SEVERE, ex.getMessage(), ex);
// } catch (Exception e) {
// response.status(503); // 503 Service Unavailable
} finally {
try {
if (st != null) {
st.close();
}
if (con != null) {
con.close();
}
} catch (SQLException ex) {
logger.log(Level.WARNING, ex.getMessage(), ex);
}
}
return "";
}
});
get(new Route("/lb/:gameID/:playerID/rankingposition") {
@Override
public Object handle(Request request, Response response) {
String callback = request.queryParams("callback");
String gameID = toSafeString(request.params(":gameID"), 30);
String playerID = toSafeString(request.params(":playerID"), 30);
// read other parameters
String orderBy = toSafeString(request.queryParams("orderBy"), 30);
if (orderBy == null) orderBy = "highscore";
String higherIsBetterStr = request.queryParams("higherIsBetter");
boolean higherIsBetter = (higherIsBetterStr==null) || (!higherIsBetterStr.equals("false")); // set to true (default) if not param set to false
Connection con = null;
Statement st = null;
ResultSet rs = null;
response.type("application/json");
StringBuilder result = new StringBuilder(40);
if (callback != null) {
result.append(callback);
result.append("(");
}
try {
con = DriverManager.getConnection(url, user, password);
st = con.createStatement();
String qustr = "SELECT x.position FROM (SELECT mygame." + gameID + ".highscore,mygame." + gameID + ".playerID,@rownum:=@rownum+1 AS POSITION from mygame." + gameID + " JOIN (select @rownum:=0) r ORDER by mygame." + gameID + "." + orderBy + (higherIsBetter?" DESC":"") +") x WHERE x.playerID=\'" + playerID + "\' order by position limit 1;";
System.out.println(qustr);
System.out.println();
rs = st.executeQuery(qustr);
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
if (rs.next()) { // only first position
String pos = rs.getString(1);
if (pos != null) {
response.status(200); // 200 ok
result.append("{position:");
result.append(pos);
result.append('}');
} else {
// no such player id in database
response.status(404); // 404 Not Found
}
}
if (callback != null) {
result.append(");");
}
System.out.println(result.toString());
System.out.println();
} catch (SQLException ex) {
response.status(503); // 503 Service Unavailable
logger.log(Level.SEVERE, ex.getMessage(), ex);
// } catch (Exception e) {
// response.status(503); // 503 Service Unavailable
} finally {
try {
if (rs != null) {
rs.close();
}
if (st != null) {
st.close();
}
if (con != null) {
con.close();
}
} catch (SQLException ex) {
logger.log(Level.WARNING, ex.getMessage(), ex);
}
}
return result.toString();
}
});
// static class getRankedListParams {
get(new Route("/lb/:gameID/rankedlist") {
@Override
public Object handle(Request request, Response response) {
String callback = request.queryParams("callback");
String gameID = toSafeString(request.params(":gameID"), 30);
// read other parameters
int rankStart = toIntDef(request.queryParams("rankStart"), 0); // todo: check if 0 is ok as default?
int rankEnd = toIntDef(request.queryParams("rankEnd"), 0); // todo: check if 0 is ok as default?
String orderBy = toSafeString(request.queryParams("orderBy"), 30);
if (orderBy == null) orderBy = "highscore";
Connection con = null;
Statement st = null;
//PreparedStatement st = null;
ResultSet rs = null;
//response.type("text/xml");
response.type("application/json");
StringBuilder result = new StringBuilder(400);
if (callback != null) {
result.append(callback);
result.append("(");
}
try {
con = DriverManager.getConnection(url, user, password);
String qustr = "SELECT * FROM mygame." + gameID + " ORDER BY " + orderBy + " DESC" + ((rankStart+rankEnd > 0) ? (" LIMIT " + rankStart + "," + rankEnd) : "") + ";";
System.out.println(qustr);
System.out.println();
st = con.createStatement();
rs = st.executeQuery(qustr);
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
result.append('[');
boolean firstRow = true;
while (rs.next()) {
if (!firstRow) result.append(',');
result.append('{');
boolean firstOutpCol = true;
for (int i=1; i<=columnCount; i++) {
if (rs.getObject(i) != null) {
if (!firstOutpCol) result.append(',');
String column = rsmd.getColumnName(i);
Object value = rs.getString(i);
result.append('\"');
result.append(column);
result.append("\":\"");
result.append(value);
result.append('\"');
firstOutpCol = false;
}
}
result.append('}');
firstRow = false;
}
result.append(']');
if (callback != null) {
result.append(");");
}
response.status(200); // 200 ok
System.out.println(result.toString());
System.out.println();
/*
JSON example output:
[
{"playerID":"2", "score":"300"},
{"playerID":"3", "score":"800"},
{"playerID":"4", "score":"600"}
]
*/
} catch (SQLException ex) {
response.status(503); // 503 Service Unavailable
logger.log(Level.SEVERE, ex.getMessage(), ex);
// } catch (Exception e) {
// response.status(503); // 503 Service Unavailable
} finally {
try {
if (rs != null) {
rs.close();
}
if (st != null) {
st.close();
}
if (con != null) {
con.close();
}
} catch (SQLException ex) {
logger.log(Level.WARNING, ex.getMessage(), ex);
}
}
return result.toString();
}
});
put(new Route("/lb/:gameID") {
@Override
public Object handle(Request request, Response response) {
String callback = request.queryParams("callback");
String gameID = toSafeString(request.params(":gameID"), 30);
System.out.println(gameID);
Connection con = null;
Statement st = null;
response.type("application/json");
StringBuilder result = new StringBuilder(40);
if (callback != null) {
result.append(callback);
result.append("(");
}
try {
con = DriverManager.getConnection(url, user, password);
st = con.createStatement();
String updstr = "CREATE TABLE mygame." + gameID + " (playerID varchar(20) DEFAULT NULL, highscore int(11) DEFAULT NULL, userData blob);";
System.out.println(updstr);
System.out.println();
st.executeUpdate(updstr);
response.status(200); // 200 ok
} catch (SQLException ex) {
response.status(503); // 503 Service Unavailable
logger.log(Level.SEVERE, ex.getMessage(), ex);
// } catch (Exception e) {
// response.status(503); // 503 Service Unavailable
} finally {
try {
if (st != null) {
st.close();
}
if (con != null) {
con.close();
}
} catch (SQLException ex) {
logger.log(Level.WARNING, ex.getMessage(), ex);
}
}
return "";
}
});
delete(new Route("/lb/:gameID") {
@Override
public Object handle(Request request, Response response) {
String callback = request.queryParams("callback");
String gameID = toSafeString(request.params(":gameID"), 30);
System.out.println(gameID);
Connection con = null;
Statement st = null;
response.type("application/json");
StringBuilder result = new StringBuilder(40);
if (callback != null) {
result.append(callback);
result.append("(");
}
try {
con = DriverManager.getConnection(url, user, password);
st = con.createStatement();
String updstr = "DROP TABLE mygame." + gameID;
System.out.println(updstr);
System.out.println();
st.executeUpdate(updstr);
response.status(200); // 200 ok
} catch (SQLException ex) {
response.status(503); // 503 Service Unavailable
logger.log(Level.SEVERE, ex.getMessage(), ex);
// } catch (Exception e) {
// response.status(503); // 503 Service Unavailable
} finally {
try {
if (st != null) {
st.close();
}
if (con != null) {
con.close();
}
} catch (SQLException ex) {
logger.log(Level.WARNING, ex.getMessage(), ex);
}
}
return "";
}
});
} // main
} |
package com.doubleleft.api;
import android.util.Log;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Vector;
public class Collection {
protected Client client;
protected String name;
protected String segments;
protected CollectionOptions _options;
protected Vector<CollectionWhere> _wheres;
protected Vector<CollectionOrdering> _ordering;
protected Vector<String> _group;
protected Integer _limit;
protected Integer _offset;
public Collection(Client client, String name)
{
if(!name.matches("^[a-z_
throw new Error("Invalid name"+ name);
}
this.client = client;
this.name = name;
this.segments = "collection/" + this.name;
this.reset();
}
public void create(JSONObject data, Responder responder)
{
JSONObject dataToPost = new JSONObject();
try{
dataToPost.put("data", data);
}catch (JSONException exception){
}
client.post(this.segments, dataToPost, responder);
}
public void get(Responder responder)
{
client.get(this.segments, this.buildQuery(), responder);
}
public void first(Responder responder)
{
_options.first = true;
this.get(responder);
}
public void firstOrCreate(Responder responder)
{
//TODO: implement firstOrCreate method
throw new Error("Not implemented");
}
public void count(Responder responder)
{
_options.aggregation = new CollectionOptionItem("count", null, null);
this.get(responder);
}
public void max(String field, Responder responder)
{
_options.aggregation = new CollectionOptionItem("max", field, null);
this.get(responder);
}
public void min(String field, Responder responder)
{
_options.aggregation = new CollectionOptionItem("min", field, null);
this.get(responder);
}
public void avg(String field, Responder responder)
{
_options.aggregation = new CollectionOptionItem("avg", field, null);
this.get(responder);
}
public void sum(String field, Responder responder)
{
_options.aggregation = new CollectionOptionItem("sum", field, null);
this.get(responder);
}
public void update(int id, JSONObject data, Responder responder)
{
JSONObject dataToPost = new JSONObject();
try{
dataToPost.put("data", data);
}catch (JSONException exception){
}
client.post(this.segments + "/" + id, dataToPost, responder);
}
public void updateAll(JSONObject data, Responder responder)
{
_options.data = data;
client.put(this.segments, this.buildQuery(), responder);
}
public void increment(String field, Object value, Responder responder)
{
_options.operation = new CollectionOptionItem("increment", field, value);
client.put(this.segments, this.buildQuery(), responder);
}
public void decrement(String field, Object value, Responder responder)
{
_options.operation = new CollectionOptionItem("decrement", field, value);
client.put(this.segments, this.buildQuery(), responder);
}
public void remove(int id, Responder responder)
{
client.remove(this.segments + "/" + id, responder);
}
public void drop(Responder responder)
{
client.remove(this.segments, responder);
}
public Collection where(String field, Object value)
{
return this.where(field, "=", value);
}
public Collection where(String field, String operation, Object value)
{
CollectionWhere obj = new CollectionWhere(field, operation, value);
_wheres.add(obj);
return this;
}
public Collection group(String field)
{
_group.add(field);
return this;
}
public Collection group(String[] fields)
{
for(int i = 0; i<fields.length; i++){
_group.add(fields[i]);
}
return this;
}
public Collection sort(String field, Integer direction)
{
return this.sort(field, direction == -1 ? "desc" : "asc");
}
public Collection sort(String field, String direction)
{
CollectionOrdering obj = new CollectionOrdering(field, direction);
_ordering.add(obj);
return this;
}
public Collection limit(Integer num)
{
_limit = num;
return this;
}
public Collection offset(Integer num)
{
_offset = num;
return this;
}
protected JSONObject buildQuery()
{
JSONObject query = new JSONObject();
try{
if(_limit != null){
query.putOpt("limit", _limit);
}
if(_offset != null){
query.putOpt("offset", _offset);
}
if(_wheres != null){
query.putOpt("q", _wheres);
}
if(_ordering != null){
query.putOpt("s", _ordering);
}
if(_group != null){
query.putOpt("g", _group);
}
if(_options != null){
if(_options.data != null){
query.putOpt("d", _options.data);
}
if(_options.first){
query.putOpt("first", 1);
}
if(_options.aggregation != null){
query.putOpt("aggr", _options.aggregation);
}
if(_options.operation != null){
query.putOpt("op", _options.operation);
}
}
}catch (JSONException e){
Log.d("dl-api", "error building query " + e.toString());
}
this.reset(); //clear for future calls
return query;
}
protected void reset()
{
this._options = new CollectionOptions();
this._wheres = new Vector<CollectionWhere>();
this._ordering = new Vector<CollectionOrdering>();
this._group = new Vector<String>();
this._limit = null;
this._offset = null;
}
class CollectionOptions
{
public boolean first;
public JSONObject data;
public CollectionOptionItem aggregation;
public CollectionOptionItem operation;
public CollectionOptions()
{
first = false;
data = null;
aggregation = null;
operation = null;
}
}
class CollectionOptionItem
{
public String method;
public String field;
public Object value;
public CollectionOptionItem(String method, String field, Object value)
{
this.method = method;
this.field = field;
this.value = value;
}
}
class CollectionWhere
{
public String field;
public String operation;
public Object value;
public CollectionWhere(String field, String operation, Object value)
{
this.field = field;
this.operation = operation;
this.value = value;
}
}
class CollectionOrdering
{
public String field;
public String direction;
public CollectionOrdering(String field, String direction)
{
this.field = field;
this.direction = direction;
}
}
} |
package bspkrs.mmv;
import immibis.bon.IProgressListener;
import java.io.File;
import java.io.IOException;
import java.security.DigestException;
import java.security.NoSuchAlgorithmException;
import java.util.Collection;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableModel;
import bspkrs.mmv.McpBotCommand.MemberType;
import bspkrs.mmv.gui.MappingGui;
public class McpMappingLoader
{
public static class CantLoadMCPMappingException extends Exception
{
private static final long serialVersionUID = 1;
public CantLoadMCPMappingException(String reason)
{
super(reason);
}
}
private final File baseDir = new File(new File(System.getProperty("user.home")), ".cache/MCPMappingViewer");
private final String baseSrgDir = "{mc_ver}";
private final String baseMappingDir = "{mc_ver}/{channel}_{map_ver}";
private final String baseMappingUrl = "https://maven.minecraftforge.net/de/oceanlabs/mcp/mcp_{channel}/{map_ver}-{mc_ver}/mcp_{channel}-{map_ver}-{mc_ver}.zip";
private final String newBaseSrgUrl = "https://maven.minecraftforge.net/de/oceanlabs/mcp/mcp_config/{mc_ver}/mcp_config-{mc_ver}.zip";
private final String oldBaseSrgUrl = "https://maven.minecraftforge.net/de/oceanlabs/mcp/mcp/{mc_ver}/mcp-{mc_ver}-srg.zip";
private final File srgDir;
private final File mappingDir;
private final File srgFile;
private final File excFile;
private final File staticMethodsFile;
private SrgFile srgFileData;
private ExcFile excFileData;
private StaticMethodsFile staticMethods;
private CsvFile csvFieldData, csvMethodData;
private ParamCsvFile csvParamData;
private final MappingGui parentGui;
private final Map<String, McpBotCommand> commandMap = new TreeMap<String, McpBotCommand>(); // srgName -> McpBotCommand
public final Map<MethodSrgData, CsvData> srgMethodData2CsvData = new TreeMap<MethodSrgData, CsvData>();
public final Map<FieldSrgData, CsvData> srgFieldData2CsvData = new TreeMap<FieldSrgData, CsvData>();
public final Map<ExcData, Map<String, ParamCsvData>> excData2MapParamCsvData = new TreeMap<ExcData, Map<String, ParamCsvData>>();
public McpMappingLoader(MappingGui parentGui, String mappingString, IProgressListener progress) throws IOException, CantLoadMCPMappingException, NoSuchAlgorithmException, DigestException
{
progress.setMax(6);
progress.set(0);
this.parentGui = parentGui;
// mappingString: <mc>_<channel>_<ver>, eg, 1.8_snapshot_20151118
String[] tokens = mappingString.split("_");
if (tokens.length < 3)
throw new CantLoadMCPMappingException("Invalid mapping string specified.");
boolean isNew = tokens[0].compareTo("1.13") >= 0;
if (tokens[0].contains("1.9") || tokens[0].contains("1.8") || tokens[0].contains("1.7"))
isNew = false;
String baseSrgUrl = isNew ? newBaseSrgUrl : oldBaseSrgUrl;
String srgFileName = isNew ? "config/joined.tsrg" : "joined.srg";
String excFileName = isNew ? "config/exceptions.txt" : "joined.exc";
String staticMethodsFileName = isNew ? "config/static_methods.txt" : "static_methods.txt";
progress.set(0, "Fetching SRG data");
srgDir = getSubDirForZip(tokens, baseSrgUrl, baseSrgDir);
progress.set(1, "Fetching CSV data");
mappingDir = getSubDirForZip(tokens, baseMappingUrl, baseMappingDir);
srgFile = new File(srgDir, srgFileName);
excFile = new File(srgDir, excFileName);
staticMethodsFile = new File(srgDir, staticMethodsFileName);
if (!srgFile.exists())
throw new CantLoadMCPMappingException("Unable to find joined.srg. Your MCP conf folder may be corrupt.");
if (!excFile.exists())
throw new CantLoadMCPMappingException("Unable to find joined.exc. Your MCP conf folder may be corrupt.");
if (!staticMethodsFile.exists())
throw new CantLoadMCPMappingException("Unable to find static_methods.txt. Your MCP conf folder may be corrupt.");
progress.set(2, "Loading CSV data");
loadCsvMapping();
progress.set(3, "Loading SRG data");
loadSrgMapping(isNew);
progress.set(4, "Linking SRG data with CSV data");
linkSrgDataToCsvData();
progress.set(5, "Linking EXC data with CSV data");
linkExcDataToSetParamCsvData();
}
private File getSubDirForZip(String[] tokens, String baseZipUrl, String baseSubDir) throws CantLoadMCPMappingException, NoSuchAlgorithmException, DigestException, IOException
{
if (!baseDir.exists() && !baseDir.mkdirs())
throw new CantLoadMCPMappingException("Application data folder does not exist and cannot be created.");
File subDir = new File(baseDir, replaceTokens(baseSubDir, tokens));
if (!subDir.exists() && !subDir.mkdirs())
throw new CantLoadMCPMappingException("Data folder does not exist and cannot be created.");
RemoteZipHandler rzh = new RemoteZipHandler(replaceTokens(baseZipUrl, tokens), subDir, "SHA1");
rzh.checkRemoteZip();
return subDir;
}
private String replaceTokens(String s, String[] tokens)
{
return s.replace("{mc_ver}", tokens[0]).replace("{channel}", tokens[1]).replace("{map_ver}", tokens[2]);
}
private void loadSrgMapping(boolean newFormat) throws IOException
{
staticMethods = new StaticMethodsFile(staticMethodsFile);
excFileData = new ExcFile(excFile);
srgFileData = newFormat
? new TSrgFile(srgFile, excFileData, staticMethods)
: new SrgFile(srgFile, excFileData, staticMethods);
}
private void loadCsvMapping() throws IOException
{
csvFieldData = new CsvFile(new File(mappingDir, "fields.csv"));
csvMethodData = new CsvFile(new File(mappingDir, "methods.csv"));
csvParamData = new ParamCsvFile(new File(mappingDir, "params.csv"));
}
private void linkSrgDataToCsvData()
{
for (Entry<String, MethodSrgData> methodData : srgFileData.srgMethodName2MethodData.entrySet())
{
if (!srgMethodData2CsvData.containsKey(methodData.getValue()) && csvMethodData.hasCsvDataForKey(methodData.getKey()))
{
srgMethodData2CsvData.put(methodData.getValue(), csvMethodData.getCsvDataForKey(methodData.getKey()));
}
else if (srgMethodData2CsvData.containsKey(methodData.getValue()))
System.out.println("SRG method " + methodData.getKey() + " has multiple entries in CSV file!");
}
for (Entry<String, FieldSrgData> fieldData : srgFileData.srgFieldName2FieldData.entrySet())
{
if (!srgFieldData2CsvData.containsKey(fieldData.getValue()) && csvFieldData.hasCsvDataForKey(fieldData.getKey()))
{
srgFieldData2CsvData.put(fieldData.getValue(), csvFieldData.getCsvDataForKey(fieldData.getKey()));
}
else if (srgFieldData2CsvData.containsKey(fieldData.getValue()))
System.out.println("SRG field " + fieldData.getKey() + " has multiple entries in CSV file!");
}
}
private void linkExcDataToSetParamCsvData()
{
for (Entry<String, ExcData> excData : excFileData.srgMethodName2ExcData.entrySet())
{
if (!excData2MapParamCsvData.containsKey(excData.getValue()) && excData.getValue().getParameters().length > 0)
{
TreeMap<String, ParamCsvData> params = new TreeMap<String, ParamCsvData>();
for (String srgName : excData.getValue().getParameters())
if (csvParamData.hasCsvDataForKey(srgName))
params.put(srgName, csvParamData.getCsvDataForKey(srgName));
excData2MapParamCsvData.put(excData.getValue(), params);
}
else if (excData2MapParamCsvData.containsKey(excData.getValue()))
System.out.println("EXC method param " + excData.getKey() + " has multiple entries in CSV file!");
}
}
private CsvData processMemberDataEdit(MemberType type, Map<String, ? extends MemberSrgData> srg2MemberData,
Map<? extends MemberSrgData, CsvData> memberData2CsvData,
String srgName, String mcpName, String comment)
{
MemberSrgData memberData = srg2MemberData.get(srgName);
CsvData csvData = null;
if (memberData != null)
{
boolean isForced = memberData2CsvData.containsKey(memberData);
if (isForced)
{
csvData = memberData2CsvData.get(memberData);
if (!mcpName.trim().equals(csvData.getMcpName()) || !comment.trim().equals(csvData.getComment()))
{
csvData.setMcpName(mcpName.trim());
csvData.setComment(comment.trim());
}
else
return null;
}
else
{
csvData = new CsvData(srgName, mcpName.trim(), 2, comment.trim());
}
commandMap.put(srgName, McpBotCommand.getMcpBotCommand(type, isForced, csvData.getSrgName(), csvData.getMcpName(), csvData.getComment()));
}
return csvData;
}
public String getBotCommands(boolean clear)
{
String r = "";
for (McpBotCommand command : commandMap.values())
r += command.toString() + "\n";
if (clear)
commandMap.clear();
return r;
}
public boolean hasPendingCommands()
{
return !commandMap.isEmpty();
}
public TableModel getSearchResults(String input, IProgressListener progress)
{
if (input == null || input.trim().isEmpty())
return getClassModel();
if (progress != null)
{
progress.setMax(3);
progress.set(0);
}
Set<ClassSrgData> results = new TreeSet<ClassSrgData>();
// Search Class objects
for (ClassSrgData classData : srgFileData.srgClassName2ClassData.values())
if (classData.contains(input))
results.add(classData);
if (progress != null)
progress.set(1);
// Search Methods
for (Entry<ClassSrgData, Set<MethodSrgData>> entry : srgFileData.class2MethodDataSet.entrySet())
{
if (!results.contains(entry.getKey()))
{
for (MethodSrgData methodData : entry.getValue())
{
CsvData csv = srgMethodData2CsvData.get(methodData);
if (methodData.contains(input) || csv != null && csv.contains(input))
{
results.add(entry.getKey());
break;
}
}
}
}
if (progress != null)
progress.set(2);
// Search Fields
for (Entry<ClassSrgData, Set<FieldSrgData>> entry : srgFileData.class2FieldDataSet.entrySet())
{
if (!results.contains(entry.getKey()))
{
for (FieldSrgData fieldData : entry.getValue())
{
CsvData csv = srgFieldData2CsvData.get(fieldData);
if (fieldData.contains(input) || csv != null && csv.contains(input))
{
results.add(entry.getKey());
break;
}
}
}
}
return new ClassModel(results);
}
public TableModel getClassModel()
{
return new ClassModel(srgFileData.srgClassName2ClassData.values());
}
public TableModel getMethodModel(String srgPkgAndOwner)
{
ClassSrgData classData = srgFileData.srgClassName2ClassData.get(srgPkgAndOwner);
return new MethodModel(srgFileData.class2MethodDataSet.get(classData));
}
public TableModel getParamModel(String srgMethodName)
{
if (excFileData.srgMethodName2ExcData.containsKey(srgMethodName))
return new ParamModel(excFileData.srgMethodName2ExcData.get(srgMethodName));
else
return MappingGui.paramsDefaultModel;
}
public TableModel getFieldModel(String srgPkgAndOwner)
{
ClassSrgData classData = srgFileData.srgClassName2ClassData.get(srgPkgAndOwner);
return new FieldModel(srgFileData.class2FieldDataSet.get(classData));
}
@SuppressWarnings("rawtypes")
public class ClassModel extends AbstractTableModel
{
private static final long serialVersionUID = 1L;
public final String[] columnNames = { "Pkg name", "SRG name", "Obf name" };
private final Class[] columnTypes = { String.class, String.class, String.class };
private final boolean[] isColumnEditable = { false, false, false };
private final Object[][] data;
private final Collection<ClassSrgData> collectionRef;
public ClassModel(Collection<ClassSrgData> map)
{
collectionRef = map;
data = new Object[collectionRef.size()][columnNames.length];
int i = 0;
for (ClassSrgData classData : collectionRef)
{
data[i][0] = classData.getSrgPkgName();
data[i][1] = classData.getSrgName();
data[i][2] = classData.getObfName();
i++;
}
}
@Override
public int getRowCount()
{
return data.length;
}
@Override
public int getColumnCount()
{
return columnNames.length;
}
@Override
public String getColumnName(int columnIndex)
{
if (columnIndex < columnNames.length && columnIndex >= 0)
return columnNames[columnIndex];
return "";
}
@Override
public Class<?> getColumnClass(int columnIndex)
{
if (columnIndex < columnTypes.length && columnIndex >= 0)
return columnTypes[columnIndex];
return String.class;
}
@Override
public boolean isCellEditable(int rowIndex, int columnIndex)
{
if (columnIndex < isColumnEditable.length && columnIndex >= 0)
return isColumnEditable[columnIndex];
return false;
}
@Override
public Object getValueAt(int rowIndex, int columnIndex)
{
return data[rowIndex][Math.min(columnIndex, data[rowIndex].length - 1)];
}
}
@SuppressWarnings("rawtypes")
public class MethodModel extends AbstractTableModel
{
private static final long serialVersionUID = 1L;
private final String[] columnNames = { "MCP Name", "SRG Name", "Obf Name", "SRG Descriptor", "Comment" };
private final Class[] columnTypes = { String.class, String.class, String.class, String.class, String.class };
private final boolean[] isColumnEditable = { true, false, false, false, true };
private final Object[][] data;
private final Set<MethodSrgData> setRef;
public MethodModel(Set<MethodSrgData> srgMethodSet)
{
setRef = srgMethodSet;
data = new Object[setRef.size()][columnNames.length];
int i = 0;
for (MethodSrgData methodData : setRef)
{
CsvData csvData = srgMethodData2CsvData.get(methodData);
if (csvData != null)
{
data[i][0] = csvData.getMcpName();
data[i][4] = csvData.getComment();
}
else
{
data[i][0] = "";
data[i][4] = "";
}
data[i][1] = methodData.getSrgName();
data[i][2] = methodData.getObfName();
data[i][3] = methodData.getSrgDescriptor();
i++;
}
}
@Override
public int getRowCount()
{
return data.length;
}
@Override
public int getColumnCount()
{
return columnNames.length;
}
@Override
public String getColumnName(int columnIndex)
{
if (columnIndex < columnNames.length && columnIndex >= 0)
return columnNames[columnIndex];
return "";
}
@Override
public Class<?> getColumnClass(int columnIndex)
{
if (columnIndex < columnTypes.length && columnIndex >= 0)
return columnTypes[columnIndex];
return String.class;
}
@Override
public boolean isCellEditable(int rowIndex, int columnIndex)
{
if (columnIndex < isColumnEditable.length && columnIndex >= 0)
return isColumnEditable[columnIndex];
return false;
}
@Override
public Object getValueAt(int rowIndex, int columnIndex)
{
return data[rowIndex][Math.min(columnIndex, data[rowIndex].length - 1)];
}
@Override
public void setValueAt(Object aValue, int rowIndex, int columnIndex)
{
data[rowIndex][columnIndex] = aValue;
if (columnIndex == 4 && aValue != null && (data[rowIndex][0] == null || data[rowIndex][0].toString().trim().isEmpty()))
return; // if only the comment has been set, don't bother adding a command
String srgName = (String) data[rowIndex][1];
String mcpName = (String) data[rowIndex][0];
String comment = (String) data[rowIndex][4];
if (mcpName.trim().isEmpty())
return;
CsvData result = processMemberDataEdit(MemberType.METHOD, srgFileData.srgMethodName2MethodData, srgMethodData2CsvData, srgName, mcpName, comment);
if (result != null)
{
csvMethodData.updateCsvDataForKey(srgName, result);
srgMethodData2CsvData.put(srgFileData.srgMethodName2MethodData.get(srgName), result);
parentGui.setCsvFileEdited(true);
}
}
}
@SuppressWarnings("rawtypes")
public class ParamModel extends AbstractTableModel
{
private static final long serialVersionUID = 1L;
private final String[] columnNames = { "MCP Name", "SRG Name", "Type" };
private final Class[] columnTypes = { String.class, String.class, String.class };
private final boolean[] isColumnEditable = { true, false, false };
private final Object[][] data;
public ParamModel(ExcData excData)
{
data = new Object[excData.getParameters().length][columnNames.length];
for (int i = 0; i < excData.getParameters().length; i++)
{
if (excData2MapParamCsvData.containsKey(excData) && excData2MapParamCsvData.get(excData).containsKey(excData.getParameters()[i]))
data[i][0] = excData2MapParamCsvData.get(excData).get(excData.getParameters()[i]).getMcpName();
else
data[i][0] = "";
data[i][1] = excData.getParameters()[i];
data[i][2] = excData.getParamTypes()[i];
}
}
@Override
public int getRowCount()
{
return data.length;
}
@Override
public int getColumnCount()
{
return columnNames.length;
}
@Override
public String getColumnName(int columnIndex)
{
if (columnIndex < columnNames.length && columnIndex >= 0)
return columnNames[columnIndex];
return "";
}
@Override
public Class<?> getColumnClass(int columnIndex)
{
if (columnIndex < columnTypes.length && columnIndex >= 0)
return columnTypes[columnIndex];
return String.class;
}
@Override
public boolean isCellEditable(int rowIndex, int columnIndex)
{
if (columnIndex < isColumnEditable.length && columnIndex >= 0)
return isColumnEditable[columnIndex];
return false;
}
@Override
public Object getValueAt(int rowIndex, int columnIndex)
{
return data[rowIndex][Math.min(columnIndex, data[rowIndex].length - 1)];
}
@Override
public void setValueAt(Object aValue, int rowIndex, int columnIndex)
{
data[rowIndex][columnIndex] = aValue;
String srgName = (String) data[rowIndex][1];
String mcpName = (String) data[rowIndex][0];
if (mcpName.trim().isEmpty())
return;
ExcData excData = excFileData.srgParamName2ExcData.get(srgName);
ParamCsvData csvData = null;
boolean isForced = csvParamData.hasCsvDataForKey(srgName);
if (isForced)
{
csvData = csvParamData.getCsvDataForKey(srgName);
if (!mcpName.trim().equals(csvData.getMcpName()))
csvData.setMcpName(mcpName.trim());
else
return;
}
else
{
csvData = new ParamCsvData(srgName, mcpName, 2);
excData2MapParamCsvData.get(excData).put(srgName, csvData);
}
commandMap.put(srgName, McpBotCommand.getMcpBotCommand(MemberType.PARAM, isForced, csvData.getSrgName(), csvData.getMcpName(), ""));
csvParamData.updateCsvDataForKey(srgName, csvData);
parentGui.setCsvFileEdited(true);
}
}
@SuppressWarnings("rawtypes")
public class FieldModel extends AbstractTableModel
{
private static final long serialVersionUID = 1L;
private final String[] columnNames = { "MCP Name", "SRG Name", "Obf Name", "Comment" };
private final Class[] columnTypes = { String.class, String.class, String.class, String.class };
private final boolean[] isColumnEditable = { true, false, false, true };
private final Object[][] data;
private final Set<FieldSrgData> setRef;
public FieldModel(Set<FieldSrgData> srgFieldSet)
{
setRef = srgFieldSet;
data = new Object[setRef.size()][columnNames.length];
int i = 0;
for (FieldSrgData fieldData : setRef)
{
CsvData csvData = srgFieldData2CsvData.get(fieldData);
if (csvData != null)
{
data[i][0] = csvData.getMcpName();
data[i][3] = csvData.getComment();
}
else
{
data[i][0] = "";
data[i][3] = "";
}
data[i][1] = fieldData.getSrgName();
data[i][2] = fieldData.getObfName();
i++;
}
}
@Override
public int getRowCount()
{
return data.length;
}
@Override
public int getColumnCount()
{
return columnNames.length;
}
@Override
public String getColumnName(int columnIndex)
{
if (columnIndex < columnNames.length && columnIndex >= 0)
return columnNames[columnIndex];
return "";
}
@Override
public Class<?> getColumnClass(int columnIndex)
{
if (columnIndex < columnTypes.length && columnIndex >= 0)
return columnTypes[columnIndex];
return String.class;
}
@Override
public boolean isCellEditable(int rowIndex, int columnIndex)
{
if (columnIndex < isColumnEditable.length && columnIndex >= 0)
return isColumnEditable[columnIndex];
return false;
}
@Override
public Object getValueAt(int rowIndex, int columnIndex)
{
return data[rowIndex][Math.min(columnIndex, data[rowIndex].length - 1)];
}
@Override
public void setValueAt(Object aValue, int rowIndex, int columnIndex)
{
data[rowIndex][columnIndex] = aValue;
if (columnIndex == 3 && aValue != null && (data[rowIndex][0] == null || data[rowIndex][0].toString().trim().isEmpty()))
return; // if only the comment has been set, don't bother adding a command
String srgName = (String) data[rowIndex][1];
String mcpName = (String) data[rowIndex][0];
String comment = (String) data[rowIndex][3];
if (mcpName.trim().isEmpty())
return;
CsvData result = processMemberDataEdit(MemberType.FIELD, srgFileData.srgFieldName2FieldData, srgFieldData2CsvData, srgName, mcpName, comment);
if (result != null)
{
csvFieldData.updateCsvDataForKey(srgName, result);
srgFieldData2CsvData.put(srgFileData.srgFieldName2FieldData.get(srgName), result);
parentGui.setCsvFileEdited(true);
}
}
}
} |
package com.areen.jlib.util;
import com.areen.jlib.model.SimpleObject;
import com.areen.jlib.tuple.Pair;
import java.awt.event.KeyEvent;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.net.URLConnection;
import java.util.Date;
import java.util.Iterator;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Various utility functions.
*
* @author dejan
*/
public class Utility {
/**
* A helper constructor to prevents calls from asubclass.
*/
protected Utility() {
throw new UnsupportedOperationException();
} // Utility constructor
/**
* A convenience function which should be used when we need a line number where the exception has been
* thrown.
*
* @return String File name, plus the line number where the exception has been thrown.
*/
public static String getLineInfo() {
StackTraceElement ste = new Throwable().getStackTrace()[1];
return ste.getFileName() + ": Line " + ste.getLineNumber();
} // getLineInfo() method
/**
* Function to export csv file.
*
* TODO: (Dejan) we should remove Iterator(s), and use foreach loops instead.
*
* @param file A String containing the file-name information (with path).
* @param h1 A String object with the first header line.
* @param h2 A String object with the second header line.
* @param headings A Vector with column headings as String objects.
* @param data A Vector of vectors to be exported to the CSV file.
*/
public static void exportToCSV(final String file, final String h1, final String h2,
final Vector<String> headings, final Vector<Vector<String>> data) {
try {
FileOutputStream out = new FileOutputStream(file);
PrintStream ps = new PrintStream(out);
ps.println(h1);
ps.println(h2);
ps.println();
//print headings
Iterator<String> hi = headings.iterator();
int i = 0;
while (hi.hasNext()) {
ps.print(hi.next());
if (i < headings.size() - 1) {
ps.print(",");
} else {
ps.println();
} // else
i++;
} // while
// print the data
Iterator<Vector<String>> di = data.iterator();
Iterator<String> si = null;
while (di.hasNext()) {
// get iterator
si = di.next().iterator();
i = 0;
while (si.hasNext()) {
ps.print(si.next());
if (i < headings.size() - 1) {
ps.print(",");
} else {
ps.println();
} // else
i++;
} // while
} // while
ps.close();
} catch (IOException e) {
e.printStackTrace();
} // catch
} // exportToCSV() method
/**
* Utility function which should be used when developer has a value as a String, and has to assign
* the value to a field of a SimpleObject argSo. As you know all SimpleObject members are statically
* typed, so argValue has to be converted to appropriate type.
*
* @param argSo SimpleObject which field we have to set.
* @param argValue The value as a String.
* @param argIndex Index of the SO field to which we assign the value argValue.
*/
public static void set(final SimpleObject argSo, final String argValue, final int argIndex) {
try {
if (argSo.getFieldClass(argIndex) == Double.class) {
argSo.set(argIndex, Double.parseDouble(argValue));
} else if (argSo.getFieldClass(argIndex) == String.class) {
argSo.set(argIndex, argValue.toString());
} else if (argSo.getFieldClass(argIndex) == Integer.class) {
argSo.set(argIndex, Integer.parseInt(argValue));
} else if (argSo.getFieldClass(argIndex) == Float.class) {
argSo.set(argIndex, Float.parseFloat(argValue));
} //end of try
} catch (NumberFormatException numberFormat) {
System.out.println("DEBUG: NumberFormat Error");
if (argSo.getFieldClass(argIndex) == Double.class) {
argSo.set(argIndex, 0.0);
} else if (argSo.getFieldClass(argIndex) == Float.class) {
argSo.set(argIndex, 0.0f);
} else if (argSo.getFieldClass(argIndex) == Integer.class) {
argSo.set(argIndex, 0);
} // else if
} // end catch
} // set() method
/**
* A utility method to compare two objects, both of type argClass and see if they have equal content
* or not.
*
* @param argFirst First Object.
* @param argSecond Second Object.
* @param argClass The type.
* @return 0 if they are equal, some other value otherwise.
*/
public static int compare(Object argFirst, Object argSecond, Class argClass) {
// NULL cases
if (argFirst == null && argSecond == null) {
return 0;
}
if (argFirst == null && argSecond != null) {
return -1;
}
if (argFirst != null && argSecond == null) {
return 1;
}
// if argFirst and argSecond references refer to the same object, return 0
if (argFirst == argSecond) {
return 0;
}
// else, make comparison for each type...
if (argClass == Byte.class) {
Byte a = (Byte) argFirst;
Byte b = (Byte) argSecond;
return a.compareTo(b);
}
if (argClass == Short.class) {
Short a = (Short) argFirst;
Short b = (Short) argSecond;
return a.compareTo(b);
}
if (argClass == Integer.class) {
Integer a = (Integer) argFirst;
Integer b = (Integer) argSecond;
return a.compareTo(b);
}
if (argClass == Long.class) {
Long a = (Long) argFirst;
Long b = (Long) argSecond;
return a.compareTo(b);
}
if (argClass == Float.class) {
Float a = (Float) argFirst;
Float b = (Float) argSecond;
return a.compareTo(b);
}
if (argClass == Double.class) {
Double a = (Double) argFirst;
Double b = (Double) argSecond;
return a.compareTo(b);
}
if (argClass == Date.class) {
Date a = (Date) argFirst;
Date b = (Date) argSecond;
return a.compareTo(b);
}
// What if one of the objects is null?
if (argSecond == null) {
return 1;
}
if (argFirst == null) {
return -1;
}
// fall back to using Strings...
return argFirst.toString().compareTo(argSecond.toString());
} // compare() method
/**
* Use this method whenever you have to convert an array of Objects to a String.
*/
public static String oa2string(Object[] argObjectArray, String argSeparator) {
if (argObjectArray == null) {
return "";
}
if (argObjectArray.length == 0) {
return "";
}
if (argObjectArray.length == 1) {
return argObjectArray[0].toString();
}
String ret = "";
if (argObjectArray[0] != null) {
ret = argObjectArray[0].toString();
}
for (int i = 1; i < argObjectArray.length; i++) {
if (argObjectArray[i] != null) {
ret += argSeparator + argObjectArray[i].toString();
}
} // for
return ret;
} // oa2string() method
public static boolean isPrintableChar(char argCharacter) {
Character.UnicodeBlock block = Character.UnicodeBlock.of(argCharacter);
return (!Character.isISOControl(argCharacter))
&& argCharacter != KeyEvent.CHAR_UNDEFINED
&& block != null
&& block != Character.UnicodeBlock.SPECIALS;
} // isPrintableChar() method
/**
* Use this method to convert any Number object to a double.
*
* NOTE: This method may become deprecated because user can simply do:
*
* Number num = (Number) object; // object is an instance of any Number subtype.
* double value = num.doubleValue();
*
* @param argSource
* @return
*/
public static double toDouble(Object argSource) {
double ret = Double.NaN;
Class argClass = argSource.getClass();
if (argClass == Byte.class) {
Byte val = (Byte) argSource;
ret = val.doubleValue();
}
if (argClass == Short.class) {
Short val = (Short) argSource;
ret = val.doubleValue();
}
if (argClass == Integer.class) {
Integer val = (Integer) argSource;
ret = val.doubleValue();
}
if (argClass == Long.class) {
Long val = (Long) argSource;
ret = val.doubleValue();
}
if (argClass == Float.class) {
Float val = (Float) argSource;
ret = val.doubleValue();
}
if (argClass == Double.class) {
ret = (Double) argSource;
}
return ret;
} // toDouble() method
/**
* This method is useful when you want to convert an array of Objects into a Pair. argColumns array
* contains indexes of those elements we want concatenated in the pair's second element.
* @param argArray
* @param argColumns
* @param argDelim String delimiter.
* @return
*/
public static Pair<String, String> pairOfStrings(Object[] argArray, int[] argColumns, String argDelim) {
Pair<String, String> pair = new Pair<String, String>(argArray[argColumns[0]].toString(),
argArray[argColumns[1]].toString());
StringBuilder sb = new StringBuilder(argArray[argColumns[1]].toString());
for (int i = 2; i < argColumns.length; i++) {
sb.append(argDelim);
sb.append(argArray[argColumns[i]]);
} // foreach
pair.setSecond(sb.toString());
return pair;
} // pairOfString() method
/**
* Java 7 has Files.propeContentType(path) . However we can't use it yet, so we have to do a workaround.
* guessContentTypeFromStream() "understands" only few MIME types thought...
*
* @param argFileName
* @return
*/
public static String getMimeType(String argFileName) {
String ret = "application/octet-stream";
try {
InputStream is = new BufferedInputStream(new FileInputStream(argFileName));
ret = URLConnection.guessContentTypeFromStream(is);
} catch (FileNotFoundException ex) {
Logger.getLogger(Utility.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Utility.class.getName()).log(Level.SEVERE, null, ex);
} // catch
return ret;
} // getMimeType() method
} // Utility class |
package step.rtm;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.jetty.webapp.WebAppContext;
import org.rtm.commons.Configuration;
import org.rtm.commons.MeasurementAccessor;
import step.artefacts.reports.CallFunctionReportNode;
import step.core.GlobalContext;
import step.core.accessors.AbstractAccessor;
import step.core.artefacts.reports.ReportNode;
import step.core.plugins.AbstractPlugin;
import step.core.plugins.Plugin;
import step.grid.io.Measure;
import step.rtm.RtmPluginServices;
@Plugin
public class RtmPlugin extends AbstractPlugin {
MeasurementAccessor accessor;
boolean measureReportNodes;
@Override
public void executionControllerStart(GlobalContext context) throws Exception {
context.getServiceRegistrationCallback().registerService(RtmPluginServices.class);
Properties rtmProperties = Configuration.getInstance().getUnderlyingPropertyObject();
step.commons.conf.Configuration stepProperties = step.commons.conf.Configuration.getInstance();
if(stepProperties.getPropertyAsBoolean("plugins.rtm.useLocalDB", true) == true){
cloneProperty(rtmProperties, stepProperties, "db.host");
cloneProperty(rtmProperties, stepProperties, "db.port");
cloneProperty(rtmProperties, stepProperties, "db.database");
cloneProperty(rtmProperties, stepProperties, "db.username");
cloneProperty(rtmProperties, stepProperties, "db.password");
}
measureReportNodes = stepProperties.getPropertyAsBoolean("plugins.rtm.measurereportnodes", true);
AbstractAccessor.createOrUpdateCompoundIndex(context.getMongoDatabase().getCollection("measurements"),"eId", "begin");
WebAppContext webappCtx = new WebAppContext();
webappCtx.setContextPath("/rtm");
String war = step.commons.conf.Configuration.getInstance().getProperty("plugins.rtm.war");
if(war==null) {
throw new RuntimeException("Property 'plugins.rtm.war' is null. Unable to start RTM.");
} else {
File warFile = new File(war);
if(!warFile.exists()||!warFile.canRead()) {
throw new RuntimeException("The file '"+war+"' set by the property 'plugins.rtm.war' doesn't exist or cannot be read. Unable to start RTM.");
}
}
webappCtx.setWar(war);
webappCtx.setParentLoaderPriority(true);
context.getServiceRegistrationCallback().registerHandler(webappCtx);
accessor = MeasurementAccessor.getInstance();
}
private void cloneProperty(Properties rtmProperties, step.commons.conf.Configuration stepProperties, String property) {
if(stepProperties.getProperty(property)!=null) {
rtmProperties.put(property, stepProperties.getProperty(property));
}
}
@Override
public void afterReportNodeExecution(ReportNode node) {
if(node instanceof CallFunctionReportNode) {
CallFunctionReportNode stepReport = (CallFunctionReportNode) node;
List<Object> measurements = new ArrayList<>();
Map<String, Object> measurement;
if(measureReportNodes) {
measurement = new HashMap<>();
measurement.put("eId", stepReport.getExecutionID());
measurement.put("name", stepReport.getName());
measurement.put("value", (long)stepReport.getDuration());
measurement.put("begin", stepReport.getExecutionTime());
measurement.put("rnId", stepReport.getId().toString());
measurement.put("rnStatus", stepReport.getStatus().toString());
measurements.add(measurement);
}
if(stepReport.getMeasures()!=null) {
for(Measure measure:stepReport.getMeasures()) {
measurement = new HashMap<>();
measurement.put("eId", stepReport.getExecutionID());
measurement.put("name", measure.getName());
measurement.put("value", measure.getDuration());
measurement.put("begin", measure.getBegin());
measurement.put("rnId", stepReport.getId().toString());
measurement.put("rnStatus", stepReport.getStatus().toString());
measurement.put("type", "custom");
if(measure.getData() != null){
for(Map.Entry<String,Object> entry : measure.getData().entrySet()){
String key = entry.getKey();
Object val = entry.getValue();
if((key != null) && (val != null)){
if( (val instanceof Long) || (val instanceof String)){
measurement.put(key, val);
}else{
if( (val instanceof Number)){
measurement.put(key, ((Integer) val).longValue());
}else{
// ignore improper types
}
}
}
}
}
measurements.add(measurement);
}
}
accessor.saveManyMeasurements(measurements);;
}
}
} |
package com.badlogic.dcpu;
import java.util.HashMap;
import java.util.Map;
import com.badlogic.dcpu.Cpu.Opcode;
import com.badlogic.dcpu.Cpu.Register;
public class Assembler {
ShortArray mem = new ShortArray();
Map<String, Label> labels = new HashMap<String, Label>();
/**
* @return the binary data for the opcodes assembled so far.
*/
public short[] getDump() {
patchLabels();
short[] dump = new short[mem.size];
System.arraycopy(mem.elements, 0, dump, 0, mem.size());
return dump;
}
private void patchLabels() {
for(Label label: labels.values()) {
for(int i = 0; i < label.addresses.size; i++) {
mem.set(label.addresses.get(i), (short)label.targetAddress);
}
}
}
/**
* Writes the opcode plus its arguments. Extended
* opcodes should be written with {@link #eop(Opcode, Arg)}.
*
* @param op the {@link Opcode}
* @param a argument a
* @param b argument b
*/
public void op(Opcode op, Arg a, Arg b) {
if(op.code != 0) {
int v = (b.bits << 10) | (a.bits << 4) | op.code;
mem.add((short)v);
a.writeNextWord(mem);
b.writeNextWord(mem);
} else {
throw new RuntimeException("Use Assembler#eop() for extended Opcodes " + op);
}
}
/**
* Writes the extended opcode plus its arguments. Non-extended
* opcodes should be written with {@link #op(Opcode, Arg, Arg)}.
*
* @param op the {@link Opcode}
* @param a argument a
*/
public void eop(Opcode eop, Arg a) {
if(eop.code == 0) {
int v = (a.bits << 10) | (eop.extended << 4);
mem.add((short)v);
a.writeNextWord(mem);
} else {
throw new RuntimeException("Use Assembler#op() for non-extended Opcodes like " + eop);
}
}
/**
* Writes the given value to the next memory location-
* @param val
*/
public void val(short val) {
mem.add(val);
}
/**
* Creates a label to be used with {@link #op(Opcode, Arg, Arg)} which
* is pack patched in {@link #getDump()}.
* @param name
* @return
*/
public Label label(String name) {
Label label = labels.get(name);
if(label == null) {
label = new Label(0x1f, name, this);
labels.put(name, label);
}
return label;
}
/**
* Creates a label to be used with {@link #op(Opcode, Arg, Arg)} which
* is pack patched in {@link #getDump()}.
* @param name
* @return
*/
public Arg label( Register reg, String name) {
Label label = labels.get(name);
if(label == null) {
label = new Label(0x1f, name, this);
labels.put(name, label);
}
return new ExLabel(0x10+reg.index, label);
}
/**
* Marks the location of a label.
* @param name the name of the label.
*/
public Label markLabel(String name) {
Label label = labels.get(name);
if(label == null) {
label = new Label(0x1f, name, this);
labels.put(name, label);
}
label.targetAddress = mem.size;
return label;
}
public static class ExLabel extends Arg {
final Label parent;
ExLabel (int bits, Label parent) {
super(bits);
this.parent = parent;
}
@Override
void writeNextWord (ShortArray array) {
parent.writeNextWord(array);
}
}
public static class Label extends Arg {
final Assembler assembler;
final ShortArray addresses = new ShortArray();
int targetAddress = 0;
final String name;
Label (int bits, String name, Assembler assembler) {
super(bits);
this.name = name;
this.assembler = assembler;
}
@Override
void writeNextWord (ShortArray array) {
addresses.add((short)(array.size));
array.add((short)0xdead);
}
}
public static class Arg {
protected int bits = 0;
protected int nextWord = 0;
protected boolean hasNextWord;
Arg(int bits) {
this.bits = bits;
}
Arg(int bits, int nextWord) {
this.bits = bits;
this.nextWord = nextWord & 0xffff;
this.hasNextWord = true;
}
int getBits() {
return bits;
}
void writeNextWord(ShortArray array) {
if(hasNextWord) array.add((short)nextWord);
}
/** register **/
public static Arg reg(Cpu.Register reg) {
return new Arg(reg.index);
}
/** pop **/
public static Arg pop() {
return new Arg(0x18);
}
/** peek **/
public static Arg peek() {
return new Arg(0x19);
}
/** push **/
public static Arg push() {
return new Arg(0x1a);
}
public static Arg sp() {
return new Arg(0x1b);
}
public static Arg pc() {
return new Arg(0x1c);
}
public static Arg o() {
return new Arg(0x1d);
}
/** [register] **/
public static Arg mem(Cpu.Register reg) {
return new Arg(0x8 + reg.index);
}
/** [next word + register] **/
public static Arg mem(Cpu.Register reg, int nextWord) {
return new Arg(0x10 + reg.index, nextWord);
}
/** [address] **/
public static Arg mem(int address) {
return new Arg(0x1e, address);
}
/** literal (if > 0x1f then its stored in the next word) **/
public static Arg lit(int literal) {
if(literal >= 0 && literal <= 0x1f) return new Arg(0x20 + literal);
else return new Arg(0x1f, literal);
}
}
public static void main (String[] args) {
Assembler asm = new Assembler();
asm.op(Opcode.SET, Arg.reg(Register.A), Arg.lit(0x30));
asm.op(Opcode.SET, Arg.mem(0x1000), Arg.lit(0x20));
asm.op(Opcode.SUB, Arg.reg(Register.A), Arg.mem(0x1000));
asm.op(Opcode.IFN, Arg.reg(Register.A), Arg.lit(0x10));
asm.op(Opcode.SET, Arg.pc(), asm.label("crash"));
asm.markLabel("loop");
asm.op(Opcode.SET, Arg.reg(Register.I), Arg.lit(10));
asm.op(Opcode.SET, Arg.reg(Register.A), Arg.lit(0x2000));
asm.op(Opcode.SET, Arg.mem(Register.I, 0x2000), Arg.mem(Register.A));
asm.op(Opcode.SUB, Arg.reg(Register.I), Arg.lit(1));
asm.op(Opcode.IFN, Arg.reg(Register.I), Arg.lit(0));
asm.op(Opcode.SET, Arg.pc(), asm.label("loop"));
asm.op(Opcode.SET, Arg.reg(Register.X), Arg.lit(0x4));
asm.eop(Opcode.JSR, asm.label("testsub"));
asm.op(Opcode.SET, Arg.pc(), asm.label("crash"));
asm.markLabel("testsub");
asm.op(Opcode.SHL, Arg.reg(Register.X), Arg.lit(0x4));
asm.op(Opcode.SET, Arg.pc(), Arg.pop());
asm.markLabel("crash");
asm.op(Opcode.SET, Arg.pc(), asm.label("crash"));
short[] dump = asm.getDump();
System.out.println(Disassembler.disassemble(dump, 0, dump.length));
}
} |
package com.conveyal.gtfs;
import com.conveyal.file.FileStorage;
import com.conveyal.file.FileStorageKey;
import com.conveyal.file.FileUtils;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.LoadingCache;
import com.github.benmanes.caffeine.cache.RemovalListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nonnull;
import java.io.File;
import java.util.concurrent.TimeUnit;
import java.util.zip.ZipFile;
/**
* Cache for GTFSFeed objects, a disk-backed (MapDB) representation of data from one GTFS feed. The source GTFS
* feeds and backing MapDB files are themselves cached in the file store for reuse by later deployments and worker
* machines. GTFSFeeds may be evicted from the in-memory cache, at which time they will be closed. Any code continuing
* to hold a reference to the evicted GTFSFeed will then fail if it tries to access the closed MapDB. The exact eviction
* policy is discussed in Javadoc on the class fields and methods.
*/
public class GTFSCache {
private static final Logger LOG = LoggerFactory.getLogger(GTFSCache.class);
private final LoadingCache<String, GTFSFeed> cache;
private final String bucket;
private final FileStorage fileStore;
public interface Config {
String bundleBucket ();
}
public static String cleanId(String id) {
return id.replaceAll("[^A-Za-z0-9_]", "-");
}
public GTFSCache(FileStorage fileStore, Config config) {
LOG.info("Initializing the GTFS cache...");
this.fileStore = fileStore;
this.bucket = config.bundleBucket();
this.cache = makeCaffeineCache();
}
private LoadingCache<String, GTFSFeed> makeCaffeineCache () {
RemovalListener<String, GTFSFeed> removalListener = (uniqueId, feed, cause) -> {
LOG.info("Evicting feed {} from GTFSCache and closing MapDB file. Reason: {}", uniqueId, cause);
// Close DB to avoid leaking (off-heap allocated) memory for MapDB object cache, and MapDB corruption.
feed.close();
};
return Caffeine.newBuilder()
.maximumSize(20L)
.expireAfterAccess(60L, TimeUnit.MINUTES)
.removalListener(removalListener)
.build(this::retrieveAndProcessFeed);
}
public FileStorageKey getFileKey (String id, String extension) {
return new FileStorageKey(this.bucket, String.join(".", cleanId(id), extension));
}
/**
* Retrieve the feed with the given id, lazily creating it if it's not yet loaded or built. This is expected to
* always return a non-null GTFSFeed. If it can't it will always throw an exception with a cause. The returned feed
* must be closed manually to avoid corruption, so it's preferable to have a single synchronized component managing
* when files shared between threads are opened and closed.
*/
public @Nonnull GTFSFeed get(String id) {
GTFSFeed feed = cache.get(id);
// The cache can in principle return null, but only if its loader method returns null.
// This should never happen in normal use - the loader should be revised to throw a clear exception.
if (feed == null) throw new IllegalStateException("Cache should always return a feed or throw an exception.");
// The feedId of the GTFSFeed objects may not be unique - we can have multiple versions of the same feed
// covering different time periods, uploaded by different users. Therefore we record another ID here that is
// known to be unique across the whole application - the ID used to fetch the feed.
feed.uniqueId = id;
return feed;
}
/** This method should only ever be called by the cache loader. */
private @Nonnull GTFSFeed retrieveAndProcessFeed(String id) throws GtfsLibException {
FileStorageKey dbKey = getFileKey(id, "db");
FileStorageKey dbpKey = getFileKey(id, "db.p");
if (fileStore.exists(dbKey) && fileStore.exists(dbpKey)) {
// Ensure both MapDB files are local, pulling them down from remote storage as needed.
fileStore.getFile(dbKey);
fileStore.getFile(dbpKey);
return new GTFSFeed(fileStore.getFile(dbKey));
}
FileStorageKey zipKey = getFileKey(id, "zip");
if (!fileStore.exists(zipKey)) {
throw new GtfsLibException("Original GTFS zip file could not be found: " + zipKey);
}
LOG.debug("Building or rebuilding MapDB from original GTFS ZIP file at {}...", zipKey);
try {
File tempDbFile = FileUtils.createScratchFile("db");
File tempDbpFile = new File(tempDbFile.getAbsolutePath() + ".p");
ZipFile zipFile = new ZipFile(fileStore.getFile(zipKey));
GTFSFeed feed = new GTFSFeed(tempDbFile);
feed.loadFromFile(zipFile);
feed.findPatterns();
// Close the DB and flush to disk before we start moving and copying files around.
feed.close();
// Ensure the DB and DB.p files have been fully stored.
fileStore.moveIntoStorage(dbKey, tempDbFile);
fileStore.moveIntoStorage(dbpKey, tempDbpFile);
return new GTFSFeed(fileStore.getFile(dbKey));
} catch (Exception e) {
throw new GtfsLibException("Error loading zip file for GTFS feed: " + zipKey, e);
}
}
} |
package com.elevenpaths.latch;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.TimeZone;
import java.util.TreeMap;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.ning.http.util.Base64;
public class Latch {
protected static final String API_VERSION = "0.6";
public static String API_HOST = "https://latch.elevenpaths.com";
public static final String API_CHECK_STATUS_URL = "/api/"+API_VERSION+"/status";
public static final String API_PAIR_URL = "/api/"+API_VERSION+"/pair";
public static final String API_PAIR_WITH_ID_URL = "/api/"+API_VERSION+"/pairWithId";
public static final String API_UNPAIR_URL = "/api/"+API_VERSION+"/unpair";
public static final String API_LOCK_URL = "/api/"+API_VERSION+"/lock";
public static final String API_UNLOCK_URL = "/api/"+API_VERSION+"/unlock";
public static final String API_HISTORY_URL = "/api/"+API_VERSION+"/history";
public static final String API_OPERATION = "/api/"+API_VERSION+"/operation";
public static final String X_11PATHS_HEADER_PREFIX = "X-11paths-";
private static final String X_11PATHS_HEADER_SEPARATOR = ":";
public static final String AUTHORIZATION_HEADER_NAME = "Authorization";
public static final String DATE_HEADER_NAME = X_11PATHS_HEADER_PREFIX + "Date";
public static final String AUTHORIZATION_METHOD = "11PATHS";
private static final String AUTHORIZATION_HEADER_FIELD_SEPARATOR = " ";
public static final String UTC_STRING_FORMAT = "yyyy-MM-dd HH:mm:ss";
private static final String HMAC_ALGORITHM = "HmacSHA1";
private static final String CHARSET_ISO_8859_1 = "ISO-8859-1";
private static final String CHARSET_UTF_8 = "UTF-8";
private static final String PARAM_SEPARATOR = "&";
private static final String PARAM_VALUE_SEPARATOR = "=";
public static void setHost(String host) {
API_HOST = host;
}
/**
* The custom header consists of three parts, the method, the appId and the signature
* This method returns the specified part if it exists.
* @param part The zero indexed part to be returned
* @param header The HTTP header value from which to extract the part
* @return the specified part from the header or an empty string if not existent
*/
private static final String getPartFromHeader(int part, String header) {
if (header != null) {
String[] parts = header.split(AUTHORIZATION_HEADER_FIELD_SEPARATOR);
if(parts.length > part) {
return parts[part];
}
}
return "";
}
/**
*
* @param authorizationHeader Authorization HTTP Header
* @return the Authorization method. Typical values are "Basic", "Digest" or "11PATHS"
*/
public static final String getAuthMethodFromHeader(String authorizationHeader) {
return getPartFromHeader(0, authorizationHeader);
}
/**
*
* @param authorizationHeader Authorization HTTP Header
* @return the requesting application Id. Identifies the application using the API
*/
public static final String getAppIdFromHeader(String authorizationHeader) {
return getPartFromHeader(1, authorizationHeader);
}
/**
*
* @param authorizationHeader Authorization HTTP Header
* @return the signature of the current request. Verifies the identity of the application using the API
*/
public static final String getSignatureFromHeader(String authorizationHeader) {
return getPartFromHeader(2, authorizationHeader);
}
private String appId;
private String secretKey;
/**
* Create an instance of the class with the Application ID and secret obtained from Eleven Paths
* @param appId
* @param secretKey
*/
public Latch (String appId, String secretKey){
this.appId = appId;
this.secretKey = secretKey;
}
public JsonElement HTTP_GET(String URL, Map<String, String> headers) {
return HTTP(URL, "GET", headers, null);
}
public JsonElement HTTP_POST(String URL, Map<String, String> headers, Map<String, String> data) {
return HTTP(URL, "POST", headers, data);
}
public JsonElement HTTP_DELETE(String URL, Map<String, String> headers) {
return HTTP(URL, "DELETE", headers, null);
}
public JsonElement HTTP_PUT(String URL, Map<String, String> headers, Map<String, String> data) {
return HTTP(URL, "PUT", headers, data);
}
protected LatchResponse HTTP_GET_proxy(String url) {
try {
return new LatchResponse(HTTP_GET(API_HOST + url, authenticationHeaders("GET", url, null, null)));
} catch (UnsupportedEncodingException e) {
return null;
}
}
protected LatchResponse HTTP_POST_proxy(String url, Map<String, String> data) {
try {
return new LatchResponse(HTTP_POST(API_HOST + url, authenticationHeaders("POST", url, null, data), data));
} catch (UnsupportedEncodingException e) {
return null;
}
}
protected LatchResponse HTTP_DELETE_proxy(String url) {
try {
return new LatchResponse(HTTP_DELETE(API_HOST + url, authenticationHeaders("DELETE", url, null, null)));
} catch (UnsupportedEncodingException e) {
return null;
}
}
protected LatchResponse HTTP_PUT_proxy(String url, Map<String, String> data) {
try {
return new LatchResponse(HTTP_PUT(API_HOST + url, authenticationHeaders("PUT", url, null, data), data));
} catch (UnsupportedEncodingException e) {
return null;
}
}
public LatchResponse pairWithId(String id) {
return HTTP_GET_proxy(new StringBuilder(API_PAIR_WITH_ID_URL).append("/").append(id).toString());
}
public LatchResponse pair(String token) {
return HTTP_GET_proxy(new StringBuilder(API_PAIR_URL).append("/").append(token).toString());
}
public LatchResponse status(String accountId) {
return HTTP_GET_proxy(new StringBuilder(API_CHECK_STATUS_URL).append("/").append(accountId).toString());
}
public LatchResponse operationStatus(String accountId, String operationId) {
return HTTP_GET_proxy(new StringBuilder(API_CHECK_STATUS_URL).append("/").append(accountId).append("/op/").append(operationId).toString());
}
public LatchResponse unpair(String id) {
return HTTP_GET_proxy(new StringBuilder(API_UNPAIR_URL).append("/").append(id).toString());
}
public LatchResponse lock(String accountId) {
return HTTP_GET_proxy(new StringBuilder(API_LOCK_URL).append("/").append(accountId).toString());
}
public LatchResponse lock(String accountId, String operationId) {
return HTTP_GET_proxy(new StringBuilder(API_LOCK_URL).append("/").append(accountId).append("/op/").append(operationId).toString());
}
public LatchResponse unlock(String accountId) {
return HTTP_GET_proxy(new StringBuilder(API_UNLOCK_URL).append("/").append(accountId).toString());
}
public LatchResponse unlock(String accountId, String operationId) {
return HTTP_GET_proxy(new StringBuilder(API_UNLOCK_URL).append("/").append(accountId).append("/op/").append(operationId).toString());
}
public LatchResponse history(String accountId) {
return HTTP_GET_proxy(new StringBuilder(API_HISTORY_URL).append("/").append(accountId).toString());
}
public LatchResponse history(String accountId, Long from, Long to) {
return HTTP_GET_proxy(new StringBuilder(API_HISTORY_URL).append("/").append(accountId)
.append("/").append(from != null ? String.valueOf(from) :"0")
.append("/").append(to != null ? String.valueOf(to) : String.valueOf(new Date().getTime())).toString());
}
public LatchResponse history(String accountId, String operationId) {
return HTTP_GET_proxy(new StringBuilder(API_HISTORY_URL).append("/").append(accountId).append("/op/").append(operationId).toString());
}
public LatchResponse createOperation(String parentId, String name, String twoFactor, String lockOnRequest) {
Map<String, String> data = new HashMap<String, String>();
data.put("parentId", parentId);
data.put("name", name);
data.put("two_factor", twoFactor);
data.put("lock_on_request", lockOnRequest);
return HTTP_PUT_proxy(new StringBuilder(API_OPERATION).toString(), data);
}
public LatchResponse removeOperation(String operationId) {
return HTTP_DELETE_proxy(new StringBuilder(API_OPERATION).append("/").append(operationId).toString());
}
public LatchResponse updateOperation(String operationId, String name, String twoFactor, String lockOnRequest) {
Map<String, String> data = new HashMap<String, String>();
data.put("name", name);
data.put("two_factor", twoFactor);
data.put("lock_on_request", lockOnRequest);
return HTTP_POST_proxy(new StringBuilder(API_OPERATION).append("/").append(operationId).toString(), data);
}
/**
*
* @param data the string to sign
* @return base64 encoding of the HMAC-SHA1 hash of the data parameter using {@code secretKey} as cipher key.
*/
private String signData (String data) {
try {
SecretKeySpec keySpec = new SecretKeySpec(secretKey.getBytes(), HMAC_ALGORITHM);
Mac mac = Mac.getInstance(HMAC_ALGORITHM);
mac.init(keySpec);
return Base64.encode(mac.doFinal(data.getBytes(CHARSET_ISO_8859_1))); // data is ASCII except HTTP header values which can be ISO_8859_1
} catch (Exception e) {
return null;
}
}
/**
* Calculates the headers to be sent with a request to the API so the server
* can verify the signature
* <p>
* Calls {@link #authenticationHeaders(String, String, Map, Map, String)}
* with the current date as {@code utc}.
* @param method The HTTP request method.
* @param querystring The urlencoded string including the path (from the
* first forward slash) and the parameters.
* @param xHeaders The HTTP request headers specific to the API, excluding
* X-11Paths-Date. null if not needed.
* @param params The HTTP request params. Must be only those to be sent in
* the body of the request and must be urldecoded. null if not
* needed.
* @return A map with the {@value AUTHORIZATION_HEADER_NAME} and {@value
* DATE_HEADER_NAME} headers needed to be sent with a request to the
* API.
* @throws UnsupportedEncodingException If {@value CHARSET_UTF_8} charset is
* not supported.
*/
public final Map<String, String> authenticationHeaders(String method, String querystring, Map<String, String> xHeaders, Map<String, String> params) throws UnsupportedEncodingException {
return authenticationHeaders(method, querystring, xHeaders, params, getCurrentUTC());
}
/**
*
* Calculate the authentication headers to be sent with a request to the API
* @param HTTPMethod the HTTP Method, currently only GET is supported
* @param queryString the urlencoded string including the path (from the first forward slash) and the parameters
* @param xHeaders HTTP headers specific to the 11-paths API, excluding X-11Paths-Date. null if not needed.
* @param utc the Universal Coordinated Time for the X-11Paths-Date HTTP header
* @return a map with the Authorization and X-11Paths-Date headers needed to sign a Latch API request
*/
//TODO: nonce
public final Map<String, String> authenticationHeaders(String HTTPMethod, String queryString, Map<String,String>xHeaders, Map<String, String> params, String utc) throws UnsupportedEncodingException {
StringBuilder stringToSign = new StringBuilder();
stringToSign.append(HTTPMethod.toUpperCase().trim());
stringToSign.append("\n");
stringToSign.append(utc);
stringToSign.append("\n");
stringToSign.append(getSerializedHeaders(xHeaders));
stringToSign.append("\n");
stringToSign.append(queryString.trim());
if (params != null && !params.isEmpty()) {
String serializedParams = getSerializedParams(params);
if (serializedParams != null && !serializedParams.isEmpty()) {
stringToSign.append("\n");
stringToSign.append(serializedParams);
}
}
String signedData = signData(stringToSign.toString());
String authorizationHeader = new StringBuilder(AUTHORIZATION_METHOD)
.append(AUTHORIZATION_HEADER_FIELD_SEPARATOR)
.append(this.appId)
.append(AUTHORIZATION_HEADER_FIELD_SEPARATOR)
.append(signedData)
.toString();
HashMap<String, String> headers = new HashMap<String, String>();
headers.put(AUTHORIZATION_HEADER_NAME, authorizationHeader);
headers.put(DATE_HEADER_NAME, utc);
return headers;
}
/**
* Prepares and returns a string ready to be signed from the 11-paths specific HTTP headers received
* @param xHeaders a non necessarily ordered map of the HTTP headers to be ordered without duplicates.
* @return a String with the serialized headers, an empty string if no headers are passed, or null if there's a problem
* such as non specific 11paths headers
*/
private String getSerializedHeaders(Map<String, String> xHeaders) {
if(xHeaders != null) {
TreeMap<String,String> sortedMap = new TreeMap<String,String>();
for(String key : xHeaders.keySet()) {
if(!key.toLowerCase().startsWith(X_11PATHS_HEADER_PREFIX.toLowerCase())) {
//TODO: Log this better
System.err.println("Error serializing headers. Only specific " + X_11PATHS_HEADER_PREFIX + " headers need to be singed");
}
sortedMap.put(key.toLowerCase(), xHeaders.get(key).replace("\n", " "));
}
StringBuilder serializedHeaders = new StringBuilder();
for(String key : sortedMap.keySet()) {
serializedHeaders.append(key).append(X_11PATHS_HEADER_SEPARATOR).append(sortedMap.get(key)).append(" ");
}
return serializedHeaders.toString().trim();
} else {
return "";
}
}
/**
* Prepares and returns a string ready to be signed from the params of an
* HTTP request
* <p>
* The params must be only those included in the body of the HTTP request
* when its content type is application/x-www-urlencoded and must be
* urldecoded.
* @param params The params of an HTTP request.
* @return A serialized representation of the params ready to be signed.
* null if there are no valid params.
* @throws UnsupportedEncodingException If {@value CHARSET_UTF_8} charset is
* not supported.
*/
private String getSerializedParams(Map<String, String> params) throws UnsupportedEncodingException {
String rv = null;
if (params != null && !params.isEmpty()) {
TreeMap<String, String> sortedParams = new TreeMap<String, String>();
for (String key : params.keySet()) {
if (key != null && params.get(key) != null) {
sortedParams.put(key, params.get(key));
}
}
StringBuilder serializedParams = new StringBuilder();
for (String key : sortedParams.keySet()) {
serializedParams.append(URLEncoder.encode(key, CHARSET_UTF_8));
serializedParams.append(PARAM_VALUE_SEPARATOR);
serializedParams.append(URLEncoder.encode(sortedParams.get(key), CHARSET_UTF_8));
if (!key.equals(sortedParams.lastKey())) {
serializedParams.append(PARAM_SEPARATOR);
}
}
if (serializedParams.length() > 0) {
rv = serializedParams.toString();
}
}
return rv;
}
/**
*
* @return a string representation of the current time in UTC to be used in a Date HTTP Header
*/
private final String getCurrentUTC() {
final SimpleDateFormat sdf = new SimpleDateFormat(UTC_STRING_FORMAT);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
return sdf.format(new Date());
}
/**
* Makes an HTTP request
* @param URL The request URL.
* @param method The request method.
* @param headers Headers to add to the HTTP request.
* @param data Parameters to add to the HTTP request body.
* @return The server's JSON response or null if something has gone wrong.
*/
private JsonElement HTTP(String URL, String method, Map<String, String> headers, Map<String, String> data) {
JsonElement rv = null;
InputStream is = null;
OutputStream os = null;
InputStreamReader isr = null;
try {
URL theURL = new URL(URL);
HttpURLConnection theConnection = (HttpURLConnection) theURL.openConnection();
theConnection.setRequestMethod(method);
if (headers != null && !headers.isEmpty()) {
Iterator<String> iterator = headers.keySet().iterator();
while (iterator.hasNext()) {
String headerName = iterator.next();
theConnection.setRequestProperty(headerName, headers.get(headerName));
}
}
if (!("GET".equals(method) || "DELETE".equals(method))) {
StringBuilder sb = new StringBuilder();
if (data != null && !data.isEmpty()) {
String[] paramNames = new String[data.size()];
data.keySet().toArray(paramNames);
for (int i = 0; i < paramNames.length; i++) {
sb.append(URLEncoder.encode(paramNames[i], "UTF-8"));
sb.append("=");
sb.append(URLEncoder.encode(data.get(paramNames[i]), "UTF-8"));
if (i < paramNames.length - 1) {
sb.append("&");
}
}
}
byte[] body = sb.toString().getBytes("US-ASCII");
theConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
theConnection.setRequestProperty("Content-Length", String.valueOf(body.length));
theConnection.setDoOutput(true);
os = theConnection.getOutputStream();
os.write(body);
os.flush();
}
JsonParser parser = new JsonParser();
is = theConnection.getInputStream();
isr = new InputStreamReader(is);
rv = parser.parse(isr);
} catch (MalformedURLException e) {
System.err.println("The URL is malformed (" + URL + ")");
e.printStackTrace();
} catch (IOException e) {
System.err.println("An exception has been thrown when communicating with Latch backend");
e.printStackTrace();
} finally {
if (os != null) {
try {
os.close();
} catch (IOException e) {
System.err.println("An exception has been thrown when trying to close the output stream");
e.printStackTrace();
}
}
if (isr != null) {
try {
isr.close();
} catch (IOException e) {
System.err.println("An exception has been thrown when trying to close the input stream reader");
e.printStackTrace();
}
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
System.err.println("An exception has been thrown when trying to close the input stream");
e.printStackTrace();
}
}
}
return rv;
}
} |
package com.exedio.cope;
import com.exedio.cope.function.LengthFunction;
import com.exedio.cope.function.UppercaseFunction;
import com.exedio.cope.search.GreaterCondition;
import com.exedio.cope.search.GreaterEqualCondition;
import com.exedio.cope.search.LessCondition;
import com.exedio.cope.search.LessEqualCondition;
public final class StringAttribute extends FunctionAttribute implements StringFunction
{
private final int minimumLength;
private final int maximumLength;
private StringAttribute(final boolean readOnly, final boolean mandatory, final boolean unique, final int minimumLength, final int maximumLength)
{
super(readOnly, mandatory, unique, String.class, "string");
this.minimumLength = minimumLength;
this.maximumLength = maximumLength;
if(minimumLength<0)
throw new RuntimeException("mimimum length must be positive.");
if(minimumLength>maximumLength)
throw new RuntimeException("maximum length must be greater or equal mimimum length.");
}
public StringAttribute(final Option option)
{
this(option.readOnly, option.mandatory, option.unique, 0, Integer.MAX_VALUE);
}
/**
* @deprecated use {@link #lengthMin(int)} instead.
*/
public StringAttribute(final Option option, final int minimumLength)
{
this(option.readOnly, option.mandatory, option.unique, minimumLength, Integer.MAX_VALUE);
}
/**
* @deprecated use {@link #lengthRange(int, int)} or {@link #lengthMax(int)} or {@link #lengthExact(int)} instead.
*/
public StringAttribute(final Option option, final int minimumLength, final int maximumLength)
{
this(option.readOnly, option.mandatory, option.unique, minimumLength, maximumLength);
}
public FunctionAttribute copyAsTemplate()
{
return new StringAttribute(readOnly, mandatory, implicitUniqueConstraint!=null, minimumLength, maximumLength);
}
public StringAttribute lengthRange(final int minimumLength, final int maximumLength)
{
return new StringAttribute(readOnly, mandatory, implicitUniqueConstraint!=null, minimumLength, maximumLength);
}
public StringAttribute lengthMin(final int minimumLength)
{
return new StringAttribute(readOnly, mandatory, implicitUniqueConstraint!=null, minimumLength, Integer.MAX_VALUE);
}
public StringAttribute lengthMax(final int maximumLength)
{
return new StringAttribute(readOnly, mandatory, implicitUniqueConstraint!=null, 0, maximumLength);
}
public StringAttribute lengthExact(final int exactLength)
{
return new StringAttribute(readOnly, mandatory, implicitUniqueConstraint!=null, exactLength, exactLength);
}
public final int getMinimumLength()
{
return minimumLength;
}
public final int getMaximumLength()
{
return maximumLength;
}
public final boolean isLengthConstrained()
{
return minimumLength!=0 || maximumLength!=Integer.MAX_VALUE;
}
Column createColumn(final Table table, final String name, final boolean notNull)
{
return new StringColumn(table, name, notNull, minimumLength, maximumLength);
}
Object get(final Row row)
{
return (String)row.get(getColumn());
}
void set(final Row row, final Object surface)
{
final String cell;
if(getType().getModel().supportsEmptyStrings()) // TODO dont fetch this that often
cell = (String)surface;
else
{
if(surface!=null && ((String)surface).length()==0)
cell = null;
else
cell = (String)surface;
}
row.put(getColumn(), cell);
}
void checkNotNullValue(final Object value, final Item item)
throws
LengthViolationException
{
final String stringValue = (String)value;
if(stringValue.length()<minimumLength)
throw new LengthViolationException(item, this, stringValue, true);
if(stringValue.length()>maximumLength)
throw new LengthViolationException(item, this, stringValue, false);
}
public final String get(final Item item)
{
return (String)getObject(item);
}
public final void set(final Item item, final String value)
throws
UniqueViolationException,
MandatoryViolationException,
LengthViolationException,
ReadOnlyViolationException
{
item.set(this, value);
}
public final AttributeValue map(final String value)
{
return new AttributeValue(this, value);
}
public final EqualCondition equal(final String value)
{
return new EqualCondition(this, value);
}
public final EqualCondition equal(final Join join, final String value)
{
return new EqualCondition(new JoinedFunction(this, join), value);
}
public final EqualAttributeCondition equal(final StringAttribute other)
{
return new EqualAttributeCondition(this, other);
}
public final NotEqualCondition notEqual(final String value)
{
return new NotEqualCondition(this, value);
}
public final LikeCondition like(final String value)
{
return new LikeCondition(this, value);
}
public final LessCondition less(final String value)
{
return new LessCondition(this, value);
}
public final LessEqualCondition lessOrEqual(final String value)
{
return new LessEqualCondition(this, value);
}
public final GreaterCondition greater(final String value)
{
return new GreaterCondition(this, value);
}
public final GreaterEqualCondition greaterOrEqual(final String value)
{
return new GreaterEqualCondition(this, value);
}
public final LengthFunction length()
{
return new LengthFunction(this);
}
public final UppercaseFunction uppercase()
{
return new UppercaseFunction(this);
}
} |
package com.hartveld.rx;
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.concurrent.Executor;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Block;
import java.util.function.Function;
import java.util.function.Predicate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public interface IObservable<T> {
static final Logger LOG = LoggerFactory.getLogger(IObservable.class);
/**
* Subscribe to this {@link IObservable}.
*
* @param onNext The {@link Block} that is called when a new value is available. Must be non-<code>null</code>.
* @param onError The {@link Block} that is called when an error occurs. Must be non-<code>null</code>.
* @param onCompleted The {@link Runnable} that is called when the final value has been observed. Must be non-<code>null</code>.
*
* @return An {@link AutoCloseable} that can be used to cancel the subscription.
*/
AutoCloseable subscribe(Block<T> onNext, Block<Throwable> onError, Runnable onCompleted);
/**
* Subscribe to this {@link IObservable}.
*
* @param observer The observer to subscribe. Must be non-<code>null</code>.
*
* @return The {@link AutoCloseable} that can be used to cancel the subscription.
*/
default AutoCloseable subscribe(IObserver<T> observer) {
return subscribe(observer::onNext, observer::onError, observer::onCompleted);
}
/**
* The identity function, i.e. every observation is forwarded as-is.
* <p>
* This function can for example come in handy during testing.
*
* @return The new {@link IObservable} that forwards all observations.
*/
default IObservable<T> id() {
LOG.trace("id()");
return (onNext, onError, onCompleted) -> {
AtomicBoolean stopped = new AtomicBoolean(false);
return subscribe(
el -> {
if (stopped.get()) return;
onNext.accept(el);
},
ex -> {
if (stopped.get()) return;
stopped.set(true);
onError.accept(ex);
},
() -> {
if (stopped.get()) return;
stopped.set(true);
onCompleted.run();
}
);
};
}
/**
* Map observations through a mapping function to new other observations.
*
* @param mapper The function used to do the mapping.
*
* @return A new {@link IObservable} that forwards the result of the application of the mapper to each observation to client subscriptions.
*/
default <R> IObservable<R> map(Function<T, R> mapper) {
LOG.trace("map()");
checkNotNull(mapper, "mapper must be non-null");
return (onNext, onError, onCompleted) -> {
AtomicBoolean stopped = new AtomicBoolean(false);
return subscribe(
e -> {
if (stopped.get()) return;
try {
R inner = mapper.apply(e);
onNext.accept(inner);
} catch (RuntimeException ex) {
LOG.trace("Caught exception: {}", ex.getMessage(), ex);
stopped.set(true);
onError.accept(ex);
}
},
e -> {
if (stopped.get()) return;
stopped.set(true);
onError.accept(e);
},
() -> {
if (stopped.get()) return;
stopped.set(true);
onCompleted.run();
}
);
};
}
/**
* Filter observations based on given predicate.
*
* @param predicate The {@link Predicate} against which each observation is tested. Must be non-<code>null</code>.
*
* @return A new {@link IObservable} that filters observations against the given predicate.
*/
default IObservable<T> filter(Predicate<T> predicate) {
LOG.trace("filter()");
checkNotNull(predicate, "predicate must be non-null");
return (onNext, onError, onCompleted) -> {
AtomicBoolean stopped = new AtomicBoolean(false);
return subscribe(
el -> {
if (stopped.get()) return;
if (predicate.test(el)) {
onNext.accept(el);
}
},
ex -> {
if (stopped.get()) return;
stopped.set(true);
onError.accept(ex);
},
() -> {
if (stopped.get()) return;
stopped.set(true);
onCompleted.run();
}
);
};
}
/**
* Execute observations with the given executor.
* <p>
* This operator can be used to schedule the execution of observations on another thread, for example to run them on a background thread.
*
* @param executor The {@link Executor} to execute the observations through. Must be non-<code>null</code>.
*
* @return A new {@link IObservable} that executes observations for subscribers through the given executor.
*/
default IObservable<T> observeOn(Executor executor) {
LOG.trace("observeOn({})", executor);
checkNotNull(executor, "executor must be non-null");
return (onNext, onError, onCompleted) -> {
AtomicBoolean stopped = new AtomicBoolean(false);
return subscribe(
e -> {
if(stopped.get()) return;
LOG.trace("Executing onNext asynchronously for: {}", e);
executor.execute(() -> {
LOG.trace("onNext({}) (asynchronously called)", e);
onNext.accept(e);
});
},
e -> {
if(stopped.get()) return;
LOG.trace("Executing onError asynchronously for: {}", e);
executor.execute(() -> {
LOG.trace("onNext({}) (asynchronously called)", e);
stopped.set(true);
onError.accept(e);
});
},
() -> {
if(stopped.get()) return;
LOG.trace("Executing onCompleted asynchronously...");
executor.execute(() -> {
LOG.trace("onCompleted() (asynchronously called)");
stopped.set(true);
onCompleted.run();
});
}
);
};
}
/**
* Execute subscription and closing of the subscription with the given executor.
*
* @param executor The {@link Executor} to execute the subscription and closing of the subscription. Must be non-<code>null</code>.
*
* @return A new {@link IObservable} that executes subscription and closing of subscription through the given executor.
*/
default IObservable<T> subscribeOn(Executor executor) {
LOG.trace("subscribeOn({})", executor);
checkNotNull(executor, "executor must be non-null");
return (onNext, onError, onCompleted) -> {
AtomicBoolean stopped = new AtomicBoolean(false);
ForwardingAutoCloseable fac = new ForwardingAutoCloseable();
executor.execute(() -> {
LOG.trace("Executing asynchronous subscription");
fac.set(subscribe(
e -> {
if(stopped.get()) return;
onNext.accept(e);
},
e -> {
if(stopped.get()) return;
onError.accept(e);
stopped.set(true);
},
() -> {
if(stopped.get()) return;
onCompleted.run();
stopped.set(true);
}
));
}
);
return () -> {
LOG.trace("Executing asynchronous close...");
executor.execute(() -> {
LOG.trace("Executing close...");
try {
fac.close();
} catch (Exception e) {
LOG.trace("Caught exception on close: {}", e.getMessage(), e);
// TODO: Create test case for this scenario, then implement a proper handling.
}
});
};
};
}
} |
package com.j256.ormlite.stmt;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.j256.ormlite.dao.CloseableIterator;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.db.DatabaseType;
import com.j256.ormlite.field.FieldType;
import com.j256.ormlite.stmt.QueryBuilder.InternalQueryBuilderWrapper;
import com.j256.ormlite.stmt.query.Between;
import com.j256.ormlite.stmt.query.Clause;
import com.j256.ormlite.stmt.query.Exists;
import com.j256.ormlite.stmt.query.In;
import com.j256.ormlite.stmt.query.InSubQuery;
import com.j256.ormlite.stmt.query.IsNotNull;
import com.j256.ormlite.stmt.query.IsNull;
import com.j256.ormlite.stmt.query.ManyClause;
import com.j256.ormlite.stmt.query.NeedsFutureClause;
import com.j256.ormlite.stmt.query.Not;
import com.j256.ormlite.stmt.query.Raw;
import com.j256.ormlite.stmt.query.SimpleComparison;
import com.j256.ormlite.table.TableInfo;
public class Where<T, ID> {
private final static int START_CLAUSE_SIZE = 4;
private final TableInfo<T, ID> tableInfo;
private final StatementBuilder<T, ID> statementBuilder;
private final FieldType idFieldType;
private final String idColumnName;
private final DatabaseType databaseType;
private Clause[] clauseStack = new Clause[START_CLAUSE_SIZE];
private int clauseStackLevel = 0;
private NeedsFutureClause needsFuture = null;
Where(TableInfo<T, ID> tableInfo, StatementBuilder<T, ID> statementBuilder, DatabaseType databaseType) {
// limit the constructor scope
this.tableInfo = tableInfo;
this.statementBuilder = statementBuilder;
this.idFieldType = tableInfo.getIdField();
if (idFieldType == null) {
this.idColumnName = null;
} else {
this.idColumnName = idFieldType.getDbColumnName();
}
this.databaseType = databaseType;
}
/**
* AND operation which takes the previous clause and the next clause and AND's them together.
*/
public Where<T, ID> and() {
addNeedsFuture(new ManyClause(pop("AND"), ManyClause.AND_OPERATION));
return this;
}
/**
* AND operation which takes 2 (or more) arguments and AND's them together.
*
* <p>
* <b>NOTE:</b> There is no guarantee of the order of the clauses that are generated in the final query.
* </p>
* <p>
* <b>NOTE:</b> I couldn't remove the code warning associated with this method when used with more than 2 arguments.
* </p>
*/
public Where<T, ID> and(Where<T, ID> first, Where<T, ID> second, Where<T, ID>... others) {
Clause[] clauses = buildClauseArray(others, "AND");
Clause secondClause = pop("AND");
Clause firstClause = pop("AND");
addClause(new ManyClause(firstClause, secondClause, clauses, ManyClause.AND_OPERATION));
return this;
}
/**
* This method needs to be used carefully. This will absorb a number of clauses that were registered previously with
* calls to {@link Where#eq(String, Object)} or other methods and will string them together with AND's. There is no
* way to verify the number of previous clauses so the programmer has to count precisely.
*
* <p>
* <b>NOTE:</b> There is no guarantee of the order of the clauses that are generated in the final query.
* </p>
*/
public Where<T, ID> and(int numClauses) {
if (numClauses == 0) {
throw new IllegalArgumentException("Must have at least one clause in and(numClauses)");
}
Clause[] clauses = new Clause[numClauses];
for (int i = numClauses - 1; i >= 0; i
clauses[i] = pop("AND");
}
addClause(new ManyClause(clauses, ManyClause.AND_OPERATION));
return this;
}
/**
* Add a BETWEEN clause so the column must be between the low and high parameters.
*/
public Where<T, ID> between(String columnName, Object low, Object high) throws SQLException {
addClause(new Between(columnName, findColumnFieldType(columnName), low, high));
return this;
}
/**
* Add a '=' clause so the column must be equal to the value.
*/
public Where<T, ID> eq(String columnName, Object value) throws SQLException {
addClause(new SimpleComparison(columnName, findColumnFieldType(columnName), value,
SimpleComparison.EQUAL_TO_OPERATION));
return this;
}
/**
* Add a '>=' clause so the column must be greater-than or equals-to the value.
*/
public Where<T, ID> ge(String columnName, Object value) throws SQLException {
addClause(new SimpleComparison(columnName, findColumnFieldType(columnName), value,
SimpleComparison.GREATER_THAN_EQUAL_TO_OPERATION));
return this;
}
/**
* Add a '>' clause so the column must be greater-than the value.
*/
public Where<T, ID> gt(String columnName, Object value) throws SQLException {
addClause(new SimpleComparison(columnName, findColumnFieldType(columnName), value,
SimpleComparison.GREATER_THAN_OPERATION));
return this;
}
/**
* Add a IN clause so the column must be equal-to one of the objects from the list passed in.
*/
public Where<T, ID> in(String columnName, Iterable<?> objects) throws SQLException {
addClause(new In(columnName, findColumnFieldType(columnName), objects));
return this;
}
/**
* Add a IN clause so the column must be equal-to one of the objects passed in.
*/
public Where<T, ID> in(String columnName, Object... objects) throws SQLException {
if (objects.length == 1) {
if (objects[0].getClass().isArray()) {
throw new IllegalArgumentException("Object argument to IN seems to be an array within an array");
}
if (objects[0].getClass() == Where.class) {
throw new IllegalArgumentException(
"Object argument to IN seems to be a Where.class instead of a QueryBuilder.class");
}
}
addClause(new In(columnName, findColumnFieldType(columnName), objects));
return this;
}
/**
* Add a IN clause which makes sure the column is in one of the columns returned from a sub-query inside of
* parenthesis. The QueryBuilder must return 1 and only one column which can be set with the
* {@link QueryBuilder#selectColumns(String...)} method calls. That 1 argument must match the SQL type of the
* column-name passed to this method.
*
* <p>
* <b>NOTE:</b> The sub-query will be prepared at the same time that the outside query is.
* </p>
*/
public Where<T, ID> in(String columnName, QueryBuilder<?, ?> subQueryBuilder) throws SQLException {
if (subQueryBuilder.getSelectColumnCount() != 1) {
throw new SQLException("Inner query must have only 1 select column specified instead of "
+ subQueryBuilder.getSelectColumnCount());
}
// we do this to turn off the automatic addition of the ID column in the select column list
subQueryBuilder.enableInnerQuery();
addClause(new InSubQuery(columnName, findColumnFieldType(columnName), new InternalQueryBuilderWrapper(
subQueryBuilder)));
return this;
}
/**
* Add a EXISTS clause with a sub-query inside of parenthesis.
*
* <p>
* <b>NOTE:</b> The sub-query will be prepared at the same time that the outside query is.
* </p>
*/
public Where<T, ID> exists(QueryBuilder<?, ?> subQueryBuilder) throws SQLException {
// we do this to turn off the automatic addition of the ID column in the select column list
subQueryBuilder.enableInnerQuery();
addClause(new Exists(new InternalQueryBuilderWrapper(subQueryBuilder)));
return this;
}
/**
* Add a 'IS NULL' clause so the column must be null. '=' NULL does not work.
*/
public Where<T, ID> isNull(String columnName) throws SQLException {
addClause(new IsNull(columnName, findColumnFieldType(columnName)));
return this;
}
/**
* Add a 'IS NOT NULL' clause so the column must not be null. '<>' NULL does not work.
*/
public Where<T, ID> isNotNull(String columnName) throws SQLException {
addClause(new IsNotNull(columnName, findColumnFieldType(columnName)));
return this;
}
/**
* Add a '<=' clause so the column must be less-than or equals-to the value.
*/
public Where<T, ID> le(String columnName, Object value) throws SQLException {
addClause(new SimpleComparison(columnName, findColumnFieldType(columnName), value,
SimpleComparison.LESS_THAN_EQUAL_TO_OPERATION));
return this;
}
/**
* Add a '<' clause so the column must be less-than the value.
*/
public Where<T, ID> lt(String columnName, Object value) throws SQLException {
addClause(new SimpleComparison(columnName, findColumnFieldType(columnName), value,
SimpleComparison.LESS_THAN_OPERATION));
return this;
}
/**
* Add a LIKE clause so the column must mach the value using '%' patterns.
*/
public Where<T, ID> like(String columnName, Object value) throws SQLException {
addClause(new SimpleComparison(columnName, findColumnFieldType(columnName), value,
SimpleComparison.LIKE_OPERATION));
return this;
}
/**
* Add a '<>' clause so the column must be not-equal-to the value.
*/
public Where<T, ID> ne(String columnName, Object value) throws SQLException {
addClause(new SimpleComparison(columnName, findColumnFieldType(columnName), value,
SimpleComparison.NOT_EQUAL_TO_OPERATION));
return this;
}
/**
* Used to NOT the next clause specified.
*/
public Where<T, ID> not() {
addNeedsFuture(new Not());
return this;
}
/**
* Used to NOT the argument clause specified.
*/
public Where<T, ID> not(Where<T, ID> comparison) {
addClause(new Not(pop("NOT")));
return this;
}
/**
* OR operation which takes the previous clause and the next clause and OR's them together.
*/
public Where<T, ID> or() {
addNeedsFuture(new ManyClause(pop("OR"), ManyClause.OR_OPERATION));
return this;
}
/**
* OR operation which takes 2 arguments and OR's them together.
*
* <p>
* <b>NOTE:</b> There is no guarantee of the order of the clauses that are generated in the final query.
* </p>
* <p>
* <b>NOTE:</b> I can't remove the code warning associated with this method. Use the iterator method below.
* </p>
*/
public Where<T, ID> or(Where<T, ID> left, Where<T, ID> right, Where<T, ID>... others) {
Clause[] clauses = buildClauseArray(others, "OR");
Clause secondClause = pop("OR");
Clause firstClause = pop("OR");
addClause(new ManyClause(firstClause, secondClause, clauses, ManyClause.OR_OPERATION));
return this;
}
/**
* This method needs to be used carefully. This will absorb a number of clauses that were registered previously with
* calls to {@link Where#eq(String, Object)} or other methods and will string them together with OR's. There is no
* way to verify the number of previous clauses so the programmer has to count precisely.
*
* <p>
* <b>NOTE:</b> There is no guarantee of the order of the clauses that are generated in the final query.
* </p>
*/
public Where<T, ID> or(int numClauses) {
if (numClauses == 0) {
throw new IllegalArgumentException("Must have at least one clause in or(numClauses)");
}
Clause[] clauses = new Clause[numClauses];
for (int i = numClauses - 1; i >= 0; i
clauses[i] = pop("OR");
}
addClause(new ManyClause(clauses, ManyClause.OR_OPERATION));
return this;
}
/**
* Add a clause where the ID is equal to the argument.
*/
public Where<T, ID> idEq(ID id) throws SQLException {
if (idColumnName == null) {
throw new SQLException("Object has no id column specified");
}
addClause(new SimpleComparison(idColumnName, idFieldType, id, SimpleComparison.EQUAL_TO_OPERATION));
return this;
}
/**
* Add a clause where the ID is from an existing object.
*/
public <OD> Where<T, ID> idEq(Dao<OD, ?> dataDao, OD data) throws SQLException {
if (idColumnName == null) {
throw new SQLException("Object has no id column specified");
}
addClause(new SimpleComparison(idColumnName, idFieldType, dataDao.extractId(data),
SimpleComparison.EQUAL_TO_OPERATION));
return this;
}
/**
* Add a raw statement as part of the where that can be anything that the database supports. Using more structured
* methods is recommended but this gives more control over the query and allows you to utilize database specific
* features.
*
* @param rawStatement
* The statement that we should insert into the WHERE.
*
* @param args
* Optional arguments that correspond to any ? specified in the rawStatement. Each of the arguments must
* have either the corresponding columnName or the sql-type set.
*/
public Where<T, ID> raw(String rawStatement, ArgumentHolder... args) throws SQLException {
for (ArgumentHolder arg : args) {
String columnName = arg.getColumnName();
if (columnName == null) {
if (arg.getSqlType() == null) {
throw new IllegalArgumentException("Either the column name or SqlType must be set on each argument");
}
} else {
arg.setMetaInfo(findColumnFieldType(columnName));
}
}
addClause(new Raw(rawStatement, args));
return this;
}
/**
* Make a comparison where the operator is specified by the caller. It is up to the caller to specify an appropriate
* operator for the database and that it be formatted correctly.
*/
public Where<T, ID> rawComparison(String columnName, String rawOperator, Object value) throws SQLException {
addClause(new SimpleComparison(columnName, findColumnFieldType(columnName), value, rawOperator));
return this;
}
/**
* A short-cut for calling prepare() on the original {@link QueryBuilder#prepare()}.
*/
public PreparedQuery<T> prepare() throws SQLException {
return statementBuilder.prepareStatement();
}
/**
* A short-cut for calling query() on the original {@link QueryBuilder#query()}.
*/
public List<T> query() throws SQLException {
if (statementBuilder instanceof QueryBuilder) {
return ((QueryBuilder<T, ID>) statementBuilder).query();
} else {
throw new SQLException("Cannot call query on a statement of type " + statementBuilder.getType());
}
}
/**
* A short-cut for calling query() on the original {@link QueryBuilder#iterator()}.
*/
public CloseableIterator<T> iterator() throws SQLException {
if (statementBuilder instanceof QueryBuilder) {
return ((QueryBuilder<T, ID>) statementBuilder).iterator();
} else {
throw new SQLException("Cannot call iterator on a statement of type " + statementBuilder.getType());
}
}
/**
* Clear out the Where object so it can be re-used.
*/
public void clear() {
for (int i = 0; i < clauseStackLevel; i++) {
// help with gc
clauseStack[i] = null;
}
clauseStackLevel = 0;
}
/**
* Returns the associated SQL WHERE statement.
*/
public String getStatement() throws SQLException {
StringBuilder sb = new StringBuilder();
appendSql(sb, new ArrayList<ArgumentHolder>());
return sb.toString();
}
/**
* Used by the internal classes to add the where SQL to the {@link StringBuilder}.
*/
void appendSql(StringBuilder sb, List<ArgumentHolder> columnArgList) throws SQLException {
if (clauseStackLevel == 0) {
throw new IllegalStateException("No where clauses defined. Did you miss a where operation?");
}
if (clauseStackLevel != 1) {
throw new IllegalStateException(
"Both the \"left-hand\" and \"right-hand\" clauses have been defined. Did you miss an AND or OR?");
}
// we don't pop here because we may want to run the query multiple times
peek().appendSql(databaseType, sb, columnArgList);
}
private Clause[] buildClauseArray(Where<T, ID>[] others, String label) {
Clause[] clauses;
if (others.length == 0) {
clauses = null;
} else {
clauses = new Clause[others.length];
// fill in reverse order
for (int i = others.length - 1; i >= 0; i
clauses[i] = pop("AND");
}
}
return clauses;
}
private void addNeedsFuture(NeedsFutureClause clause) {
if (needsFuture != null) {
throw new IllegalStateException(needsFuture + " is already waiting for a future clause, can't add: "
+ clause);
}
needsFuture = clause;
push(clause);
}
private void addClause(Clause clause) {
if (needsFuture == null) {
push(clause);
} else {
// we have a binary statement which was called before the right clause was defined
needsFuture.setMissingClause(clause);
needsFuture = null;
}
}
@Override
public String toString() {
if (clauseStackLevel == 0) {
return "empty where clause";
} else {
Clause clause = peek();
return "where clause: " + clause;
}
}
private FieldType findColumnFieldType(String columnName) throws SQLException {
return tableInfo.getFieldTypeByColumnName(columnName);
}
private void push(Clause clause) {
// if the stack is full then we need to grow it
if (clauseStackLevel == clauseStack.length) {
// double its size each time
Clause[] newStack = new Clause[clauseStackLevel * 2];
// copy the entries over to the new stack
for (int i = 0; i < clauseStackLevel; i++) {
newStack[i] = clauseStack[i];
// to help gc
clauseStack[i] = null;
}
clauseStack = newStack;
}
clauseStack[clauseStackLevel++] = clause;
}
private Clause pop(String label) {
if (clauseStackLevel == 0) {
throw new IllegalStateException("Expecting there to be a clause already defined for '" + label
+ "' operation");
}
Clause clause = clauseStack[--clauseStackLevel];
// to help gc
clauseStack[clauseStackLevel] = null;
return clause;
}
private Clause peek() {
return clauseStack[clauseStackLevel - 1];
}
} |
package com.jdev.jsprite;
import java.io.File;
import java.io.IOException;
import com.jdev.net.sf.jargs.CmdLineParser;
/**
* @author jdeverna
*/
public class SpriteMain {
private static void printUsage() {
System.err.println("Sprite Builder Usage:");
System.err.println("-u, --usage : this list");
System.err.println();
System.err.println("Directory Options (Either the -d or -l flag must be passed)");
System.err.println("-l, --files : comma separated list of files to sprite");
System.err.println("-d, --dir : directory containing images to sprite");
System.err.println("-g, --regex : regular expression used to filter file names (used with -d flag only)");
System.err.println("-r, --recurse : if flag is present, the program will look in subdirectories for other image files");
System.err.println("-n, --hidden : include hidden subdirectories (used with -r flag only)");
System.err.println();
System.err.println("Sprite Options");
System.err.println("-o, --output : [sprite.png] the output file");
System.err.println("-f, --format : [png] the output format (e.g, png, jpeg, etc.)");
System.err.println("-p, --padding : [0] the number of pixels to skip between images");
System.err.println();
System.err.println("Css Options");
System.err.println("-c, --css : if flag is present, CSS will NOT be print");
System.err.println("-e, --prefix : an optional prefix for the css class name");
System.err.println("-t, --postfix : an optional postfix for the css class name");
System.err.println("-s, --separator : ['-'] the character used to separate prefix/postfix from classname ");
System.err.println("-a, --appendTo : if specified, will append the css styles to this file, instead of creating a new one");
System.err.println("-x, --extra : extra CSS style(s) to be added (should be a quoted string or valid CSS styles)");
System.err.println("-i, --inline : use data URI scheme (as defined in RFC 2397) for inline images, instead of normal urls");
System.err.println("-P, --imgPrefix : an optional URL for the CSS background attribute that will prefix the output name (from the -o option)");
System.err.println("-U, --imgUrl : an optional URL for the CSS background attribute (the -o and -x flags will be ignored if this is specified)");
System.err.println("-I, --important : if flag is present, '!important' flag will NOT be used for the background-position property");
System.err.println();
System.err.println("HTML Options");
System.err.println("-h, --html : generate a sample html file for the sprite");
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws Exception {
if (args.length > 0 && args[0].equals("test")) {
runTest();
return;
}
CmdLineParser parser = new CmdLineParser();
CmdLineParser.Option recurse = parser.addBooleanOption('r', "recurse");
CmdLineParser.Option directory = parser.addStringOption('d', "dir");
CmdLineParser.Option fileList = parser.addStringOption('l', "files");
CmdLineParser.Option regex = parser.addStringOption('g', "regex");
CmdLineParser.Option hidden = parser.addBooleanOption('n', "hidden");
CmdLineParser.Option output = parser.addStringOption('o', "output");
CmdLineParser.Option format = parser.addStringOption('f', "format");
CmdLineParser.Option padding = parser.addIntegerOption('p', "padding");
CmdLineParser.Option css = parser.addBooleanOption('c', "css");
CmdLineParser.Option prefix = parser.addStringOption('e', "prefix");
CmdLineParser.Option postfix = parser.addStringOption('t', "postfix");
CmdLineParser.Option append = parser.addStringOption('a', "appendTo");
CmdLineParser.Option separator = parser.addStringOption('s', "separator");
CmdLineParser.Option extra = parser.addStringOption('x', "extra");
CmdLineParser.Option inline = parser.addBooleanOption('i', "inline");
CmdLineParser.Option imgPrefix = parser.addStringOption('P', "imgPrefix");
CmdLineParser.Option imgURL = parser.addStringOption('U', "imgUrl");
CmdLineParser.Option important = parser.addBooleanOption('I', "important");
CmdLineParser.Option html = parser.addBooleanOption('h', "html");
CmdLineParser.Option usage = parser.addBooleanOption('u', "usage");
try {
parser.parse(args);
if (parser.getOptionValue(usage) != null) {
printUsage();
System.exit(2);
}
SpriteRequest request = new SpriteRequest();
request.setRecurse((Boolean) parser.getOptionValue(recurse));
request.setHidden((Boolean) parser.getOptionValue(hidden));
String dir = (String) parser.getOptionValue(directory);
String fls = (String) parser.getOptionValue(fileList);
String rgx = (String) parser.getOptionValue(regex);
if (dir != null) {
if (rgx != null) {
request.setFilesByRegex(dir, rgx);
} else {
request.setFilesByDirectory(dir);
}
} else if (fls != null) {
request.setFilesByList(fls);
} else {
System.err.println("Either a directory or file list must be specified");
System.err.println();
printUsage();
System.exit(2);
}
request.setOutputType((String) parser.getOptionValue(format, "PNG"));
request.setOutputFile((String) parser.getOptionValue(output, "sprite.png"));
request.setSpritePadding((Integer) parser.getOptionValue(padding, 0));
request.setCreateCss((Boolean) parser.getOptionValue(css));
request.setCreateHtml((Boolean) parser.getOptionValue(html));
request.setPrefix((String) parser.getOptionValue(prefix));
request.setPostfix((String) parser.getOptionValue(postfix));
request.setAppendTo((String) parser.getOptionValue(append));
request.setSeparator((String) parser.getOptionValue(separator, "-"));
request.setExtraCss((String) parser.getOptionValue(extra, ""));
request.useInlineImage((Boolean) parser.getOptionValue(inline, false));
request.setImagePrefix((String) parser.getOptionValue(imgPrefix, null));
request.setImageURL((String) parser.getOptionValue(imgURL, null));
request.setUseImportantFlag((Boolean) parser.getOptionValue(important));
SpriteMaker maker = new SpriteMaker(request);
maker.processRequest();
} catch (CmdLineParser.OptionException e) {
System.err.println(e.getMessage());
printUsage();
System.exit(2);
} catch (Exception e) {
System.err.println(e.getMessage());
System.exit(2);
}
}
public static void runTest() {
String[] folders = new String[]{"1", "5", "10", "20", "50", "80", "100", "200", "400", "600", "800", "1000"};
for (String folder : folders) {
System.out.println("\nFOLDER: " + folder);
SpriteRequest request = new SpriteRequest();
request.setRecurse(false);
request.setHidden(false);
request.setFilesByDirectory(folder);
request.setOutputType("PNG");
request.setOutputFile("output" + File.separator + "sprite_" + folder + ".png");
request.setSpritePadding(0);
request.setCreateCss(null);
request.setCreateHtml(true);
request.setPrefix("icon");
request.setPostfix(null);
request.setAppendTo(null);
request.setSeparator("_");
request.setExtraCss("");
request.useInlineImage(false);
request.setNormal(false);
System.out.println("\nSPRITE: " + folder);
long start = System.currentTimeMillis();
SpriteMaker makerSprite = new SpriteMaker(request);
makerSprite.processRequest();
System.out.println("\nProcess time: " + (System.currentTimeMillis() - start) + "ms");
System.out.println("CSS size: " + new File(request.getOutputFile() + ".css").length());
System.out.println("HTML size: " + new File(request.getOutputFile() + ".html").length());
try {
System.out.println("Sprite Size: "
+ new ImageFile("test", new File(request.getOutputFile())).getFileSize());
} catch (IOException e) {
throw new RuntimeException(e);
}
request.useInlineImage(true);
request.setOutputFile("output" + File.separator + "inline_" + folder);
System.out.println("\nINLINE: " + folder);
start = System.currentTimeMillis();
SpriteMaker makerInline = new SpriteMaker(request);
makerInline.processRequest();
System.out.println("\nProcess time: " + (System.currentTimeMillis() - start) + "ms");
System.out.println("CSS size: " + new File(request.getOutputFile() + ".css").length());
System.out.println("HTML size: " + new File(request.getOutputFile() + ".html").length());
request.useInlineImage(false);
request.setNormal(true);
request.setOutputFile("output" + File.separator + "normal_" + folder);
System.out.println("\nNORMAL: " + folder);
start = System.currentTimeMillis();
SpriteMaker makerNormal = new SpriteMaker(request);
makerNormal.processRequest();
System.out.println("\nProcess time: " + (System.currentTimeMillis() - start) + "ms");
System.out.println("CSS size: " + new File(request.getOutputFile() + ".css").length());
System.out.println("HTML size: " + new File(request.getOutputFile() + ".html").length());
System.out.println("\n
}
}
} |
package com.justjournal.model;
import com.fasterxml.jackson.annotation.*;
import javax.persistence.*;
import java.io.Serializable;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
/**
* Journal entry transfer object. Contains one journal entry. Maps relationship between table "entry" and java.
*
* @author Lucas Holt
* @version 1.0
* @see com.justjournal.repository.EntryRepository
*/
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY)
@JsonIgnoreProperties(ignoreUnknown = true)
@Entity
@Table(name = "entry")
public class Entry implements Serializable {
private static final long serialVersionUID = 6558001750470601772L;
@Id
@GeneratedValue
private int id = 0;
@Column(name = "date")
@Temporal(value = TemporalType.DATE)
private Date date = new Date();
@Column(name = "modified")
@Temporal(value = TemporalType.TIMESTAMP)
private Date modified;
@JsonProperty("location")
@ManyToOne
@JoinColumn(name = "location")
private Location location;
@Column(name="location", nullable = true, insertable = false, updatable = false)
private int locationId = 0;
@JsonProperty("mood")
@ManyToOne
@JoinColumn(name = "mood", nullable = true)
private Mood mood;
@Column(name="mood", nullable = true, insertable = false, updatable = false)
private int moodId = 0;
@JsonProperty("user")
@ManyToOne
@JoinColumn(name = "uid")
private User user;
@JsonProperty("security")
@ManyToOne
@JoinColumn(name = "security")
private Security security;
@Column(name="security", nullable = true, insertable = false, updatable = false)
private int securityId = 0;
@JsonProperty("subject")
@Column(name = "subject", length = 255, nullable = true)
private String subject = "";
@Basic(fetch = FetchType.LAZY)
@JsonProperty("body")
@Column(name = "body")
@Lob
private String body = "";
@JsonProperty("music")
@Column(name = "music", length = 125)
private String music = "";
@JsonProperty("autoFormat")
@Column(name = "autoformat", nullable = false, length = 1)
@Enumerated(EnumType.STRING)
private PrefBool autoFormat = PrefBool.Y;
@JsonProperty("allowComments")
@Column(name = "allow_comments", nullable = false, length = 1)
@Enumerated(EnumType.STRING)
private PrefBool allowComments = PrefBool.Y;
@JsonProperty("emailComments")
@Column(name = "email_comments", nullable = false, length = 1)
@Enumerated(EnumType.STRING)
private PrefBool emailComments = PrefBool.Y;
@Column(name = "draft", nullable = false, length = 1)
@Enumerated(EnumType.STRING)
private PrefBool draft = PrefBool.N;
// TODO: implement
@JsonIgnore
transient private int attachImage = 0;
@JsonIgnore
transient private int attachFile = 0;
@JsonManagedReference
@JsonProperty("tags")
@OneToMany(cascade = CascadeType.ALL, mappedBy = "entry", fetch = FetchType.EAGER) // TODO: why!
private Set<EntryTag> tags = new HashSet<EntryTag>();
@JsonManagedReference
@JsonProperty("comments")
@OneToMany(cascade = CascadeType.ALL, mappedBy = "entry", fetch = FetchType.EAGER)
private Set<Comment> comments = new HashSet<Comment>();
@JsonCreator
public Entry() {
}
public int getId() {
return id;
}
public void setId(final int id) {
this.id = id;
}
public Date getDate() {
return date;
}
public void setDate(final Date date) {
this.date = date;
}
public Date getModified() {
return modified;
}
public void setModified(final Date modified) {
this.modified = modified;
}
public int getLocationId() {
return locationId;
}
public void setLocationId(final int locationId) {
this.locationId = locationId;
}
public Location getLocation() {
return location;
}
public void setLocation(final Location location) {
this.location = location;
setLocationId(location.getId());
}
public int getMoodId() {
return moodId;
}
public void setMoodId(final int moodId) {
this.moodId = moodId;
}
public Mood getMood() {
return mood;
}
public void setMood(final Mood mood) {
this.mood = mood;
setMoodId(mood.getId());
}
public User getUser() {
return user;
}
public void setUser(final User user) {
this.user = user;
}
public int getSecurityId() {
return securityId;
}
public void setSecurityId(final int securityId) {
this.securityId = securityId;
}
public Security getSecurity() {
return security;
}
public void setSecurity(final Security security) {
this.security = security;
setSecurityId(security.getId());
}
public String getSubject() {
return subject;
}
public void setSubject(final String subject) {
this.subject = subject;
}
public String getBody() {
return body;
}
public void setBody(final String body) {
this.body = body;
}
public String getMusic() {
return music;
}
public void setMusic(final String music) {
this.music = music;
}
public PrefBool getAutoFormat() {
return autoFormat;
}
public void setAutoFormat(final PrefBool autoFormat) {
this.autoFormat = autoFormat;
}
public PrefBool getAllowComments() {
return allowComments;
}
public void setAllowComments(final PrefBool allowComments) {
this.allowComments = allowComments;
}
public PrefBool getEmailComments() {
return emailComments;
}
public void setEmailComments(final PrefBool emailComments) {
this.emailComments = emailComments;
}
public PrefBool getDraft() {
return draft;
}
public void setDraft(final PrefBool draft) {
this.draft = draft;
}
public int getAttachImage() {
return attachImage;
}
public void setAttachImage(final int attachImage) {
this.attachImage = attachImage;
}
public int getAttachFile() {
return attachFile;
}
public void setAttachFile(final int attachFile) {
this.attachFile = attachFile;
}
public Set<EntryTag> getTags() {
return tags;
}
public void setTags(final Set<EntryTag> tags) {
this.tags = tags;
}
public Set<Comment> getComments() {
return comments;
}
public void setComments(final Set<Comment> comments) {
this.comments = comments;
}
} |
package com.lambdaworks.codec;
/**
* @author <a href="mailto:mpaluch@paluch.biz">Mark Paluch</a>
* <ul>
* <li>Name: XMODEM (also known as ZMODEM or CRC-16/ACORN)</li>
* <li>Width: 16 bit</li>
* <li>Poly: 1021 (That is actually x16 + x12 + x5 + 1)</li>
* <li>Initialization: 0000</li>
* <li>Reflect Input byte: False</li>
* <li>Reflect Output CRC: False</li>
* <li>Xor constant to output CRC: 0000</li>
* </ul>
* @since 3.0
*/
public class CRC16 {
private static final int LOOKUP_TABLE[] = { 0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50A5, 0x60C6, 0x70E7, 0x8108, 0x9129,
0xA14A, 0xB16B, 0xC18C, 0xD1AD, 0xE1CE, 0xF1EF, 0x1231, 0x0210, 0x3273, 0x2252, 0x52B5, 0x4294, 0x72F7, 0x62D6,
0x9339, 0x8318, 0xB37B, 0xA35A, 0xD3BD, 0xC39C, 0xF3FF, 0xE3DE, 0x2462, 0x3443, 0x0420, 0x1401, 0x64E6, 0x74C7,
0x44A4, 0x5485, 0xA56A, 0xB54B, 0x8528, 0x9509, 0xE5EE, 0xF5CF, 0xC5AC, 0xD58D, 0x3653, 0x2672, 0x1611, 0x0630,
0x76D7, 0x66F6, 0x5695, 0x46B4, 0xB75B, 0xA77A, 0x9719, 0x8738, 0xF7DF, 0xE7FE, 0xD79D, 0xC7BC, 0x48C4, 0x58E5,
0x6886, 0x78A7, 0x0840, 0x1861, 0x2802, 0x3823, 0xC9CC, 0xD9ED, 0xE98E, 0xF9AF, 0x8948, 0x9969, 0xA90A, 0xB92B,
0x5AF5, 0x4AD4, 0x7AB7, 0x6A96, 0x1A71, 0x0A50, 0x3A33, 0x2A12, 0xDBFD, 0xCBDC, 0xFBBF, 0xEB9E, 0x9B79, 0x8B58,
0xBB3B, 0xAB1A, 0x6CA6, 0x7C87, 0x4CE4, 0x5CC5, 0x2C22, 0x3C03, 0x0C60, 0x1C41, 0xEDAE, 0xFD8F, 0xCDEC, 0xDDCD,
0xAD2A, 0xBD0B, 0x8D68, 0x9D49, 0x7E97, 0x6EB6, 0x5ED5, 0x4EF4, 0x3E13, 0x2E32, 0x1E51, 0x0E70, 0xFF9F, 0xEFBE,
0xDFDD, 0xCFFC, 0xBF1B, 0xAF3A, 0x9F59, 0x8F78, 0x9188, 0x81A9, 0xB1CA, 0xA1EB, 0xD10C, 0xC12D, 0xF14E, 0xE16F,
0x1080, 0x00A1, 0x30C2, 0x20E3, 0x5004, 0x4025, 0x7046, 0x6067, 0x83B9, 0x9398, 0xA3FB, 0xB3DA, 0xC33D, 0xD31C,
0xE37F, 0xF35E, 0x02B1, 0x1290, 0x22F3, 0x32D2, 0x4235, 0x5214, 0x6277, 0x7256, 0xB5EA, 0xA5CB, 0x95A8, 0x8589,
0xF56E, 0xE54F, 0xD52C, 0xC50D, 0x34E2, 0x24C3, 0x14A0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405, 0xA7DB, 0xB7FA,
0x8799, 0x97B8, 0xE75F, 0xF77E, 0xC71D, 0xD73C, 0x26D3, 0x36F2, 0x0691, 0x16B0, 0x6657, 0x7676, 0x4615, 0x5634,
0xD94C, 0xC96D, 0xF90E, 0xE92F, 0x99C8, 0x89E9, 0xB98A, 0xA9AB, 0x5844, 0x4865, 0x7806, 0x6827, 0x18C0, 0x08E1,
0x3882, 0x28A3, 0xCB7D, 0xDB5C, 0xEB3F, 0xFB1E, 0x8BF9, 0x9BD8, 0xABBB, 0xBB9A, 0x4A75, 0x5A54, 0x6A37, 0x7A16,
0x0AF1, 0x1AD0, 0x2AB3, 0x3A92, 0xFD2E, 0xED0F, 0xDD6C, 0xCD4D, 0xBDAA, 0xAD8B, 0x9DE8, 0x8DC9, 0x7C26, 0x6C07,
0x5C64, 0x4C45, 0x3CA2, 0x2C83, 0x1CE0, 0x0CC1, 0xEF1F, 0xFF3E, 0xCF5D, 0xDF7C, 0xAF9B, 0xBFBA, 0x8FD9, 0x9FF8,
0x6E17, 0x7E36, 0x4E55, 0x5E74, 0x2E93, 0x3EB2, 0x0ED1, 0x1EF0 };
/**
* Utility constructor.
*/
private CRC16() {
}
/**
* Create a CRC16 checksum from the bytes.
*
* @param bytes
* @return CRC16 as interger value
*/
public static int crc16(byte[] bytes) {
int crc = 0x0000;
for (byte b : bytes) {
crc = ((crc << 8) ^ LOOKUP_TABLE[((crc >> 8) ^ (b & 0xFF)) & 0xFF]) & 0xFFFF;
}
return crc & 0xFFFF;
}
} |
package com.mdsol.mauth;
import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.crypto.encodings.PKCS1Encoding;
import org.bouncycastle.crypto.engines.RSAEngine;
import org.bouncycastle.crypto.util.PrivateKeyFactory;
import org.bouncycastle.crypto.util.PublicKeyFactory;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openssl.PEMReader;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.ObjectMapper;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.security.KeyPair;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Security;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.TimeZone;
import javax.servlet.http.HttpServletResponse;
/**
* This class implements a set of utilities to be used as a client for several mAuth operations.
* Primarily it can be used to create mAuth signatures and also to validate mAuth signatures coming
* from other applications.
*
* @author Ricardo Chavarria
* @deprecated Use {@link MAuthRequestSigner}
*
*/
@Deprecated
public class MAuthClient
{
private String _appId;
private String _publicKey;
private String _privateKey;
private String _mAuthUrl;
private String _mAuthRequestUrlPath;
private String _securityTokensUrl;
// Cache for public keys
private static Map<String, PublicKey> _publicKeys = new HashMap<String, PublicKey>();
// Cache for private keys (TODO: may only have one key, need to see if better remove it)
private final Map<String, PrivateKey> _privateKeys = new HashMap<String, PrivateKey>();
// Default constructor
public MAuthClient() {}
/**
*
* @param mAuthUrl
* @param mAuthRequestUrlPath
* @param securityTokensUrl
* @param appId
* @param privateKeyFilePath
* @throws Exception
*/
public MAuthClient(String mAuthUrl, String mAuthRequestUrlPath, String securityTokensUrl, String appId, String publicKey, String privateKey) throws Exception
{
init(mAuthUrl, mAuthRequestUrlPath, securityTokensUrl, appId, publicKey, privateKey);
}
/**
*
* @param mAuthUrl
* @param mAuthRequestUrlPath
* @param securityTokensUrl
* @param appId
* @param privateKeyFilePath
* @return
* @throws Exception
*/
public boolean init(String mAuthUrl, String mAuthRequestUrlPath, String securityTokensUrl, String appId, String publicKey, String privateKey) throws Exception
{
if (null==mAuthUrl || mAuthUrl.equals("")) {
throw new Exception("Cannot initialize MAuth client: mAuthUrl cannot be null");
}
if (null==mAuthRequestUrlPath || mAuthRequestUrlPath.equals("")) {
throw new Exception("Cannot initialize MAuth client: mAuthRequestUrlPath cannot be null");
}
if (null==securityTokensUrl || securityTokensUrl.equals("")) {
throw new Exception("Cannot initialize MAuth client: securityTokensUrl cannot be null");
}
if (null==appId || appId.equals("")) {
throw new Exception("Cannot initialize MAuth client: appId cannot be null");
}
if (null==publicKey || publicKey.equals("")) {
throw new Exception("Cannot initialize MAuth client: publicKey cannot be null");
}
if (null==privateKey || privateKey.equals("")) {
throw new Exception("Cannot initialize MAuth client: privateKey cannot be null");
}
_appId = appId;
_publicKey = publicKey;
_privateKey = privateKey;
_mAuthUrl = mAuthUrl;
_mAuthRequestUrlPath = mAuthRequestUrlPath;
_securityTokensUrl = securityTokensUrl;
//Initialize cryptographic security provider: BouncyCastle
Security.addProvider(new BouncyCastleProvider());
return true;
}
/**
* Get signature portion of http header based on mAuth specification
*
* @param header the mAuth header x-mws-authentication
* @return signature portion in header
*/
public String getSignatureInHeader(String header)
{
int pos = header.indexOf(":");
if (pos < 0) {
return "";
}
return header.substring(pos+1);
}
/**
* Get appId portion of http header based on mAuth specification
*
* @param header the mAuth header x-mws-authentication
* @return appId portion in header
*/
public String getAppIdInHeader(String header)
{
int pos = header.indexOf(":");
if (pos < 0) {
return "";
}
return header.substring(4, pos);
}
public HttpServletResponse getSignedResponse(HttpServletResponse response) throws Exception
{
String statusCodeString = "";
String body = "";
String epochTime = String.valueOf(getEpochTime());
Map<String, String> headers = getSignedResponseHeaders(statusCodeString, body, _appId, epochTime);
response.addHeader("x-mws-authentication", headers.get("x-mws-authentication"));
response.addHeader("x-mws-time", headers.get("x-mws-time"));
return response;
}
public Map<String, String> getSignedResponseHeaders(String statusCodeString, String body, String appId, String epochTime) throws Exception
{
String stringToSign = statusCodeString + "\n" +
body + "\n" +
appId + "\n" +
epochTime;
String xMwsAuthentication = signMessageString(stringToSign);
Map<String, String> headers = new HashMap<String, String>();
headers.put("x-mws-authentication", xMwsAuthentication);
headers.put("x-mws-time", epochTime);
return headers;
}
/**
* Validates an incoming http request which contains mAuth headers.
* The validation process consists on recreating the mAuth hashed signature
* and comparing it with the decrypted hash signature from the mAuth header.
* This approach is faster because it computates the hashes locally and the
* mAuth service is not contacted to validate, but just to get the requester's
* public key (if not in cache already). There is an additional way to
* perform an mAuth validation but is is not implemented in this client
*
* @param signatureInHeader the encrypted and hashed mAuth signature in the header x-mws-authentication
* @param epochTime the epoch time from the mAuth header x-mws-time
* @param verb the http verb of the http request
* @param resourceUrl the resource url of the http request
* @param body the body of the http request (if available or empty string if none)
* @param appId the appId of the application under which the validation will be performed
* @return true or false indicating if the request if valid or not with respect to mAuth
* @throws Exception
*/
public Boolean validateRequest(String signatureInHeader, String epochTime, String verb, String resourceUrl, String body, String appId) throws Exception
{
// Perform routine validations of parameters
if (null==signatureInHeader || signatureInHeader.equals("")) {
throw new Exception("validateRequest error: parameter signatureInHeader cannot be null");
}
if (null==epochTime || epochTime.equals("")) {
throw new Exception("validateRequest error: parameter epochTime cannot be null");
}
if (null==verb || verb.equals("")) {
throw new Exception("validateRequest error: parameter verb cannot be null");
}
if (null==resourceUrl || resourceUrl.equals("")) {
throw new Exception("validateRequest error: parameter resourceUrl cannot be null");
}
if ( (null==body || body.equals("")) && (! "GET".equalsIgnoreCase(verb))) {
throw new Exception("validateRequest error: parameter body cannot be null: " + verb);
}
if (null==appId || appId.equals("")) {
throw new Exception("validateRequest error: parameter appId cannot be null");
}
// Check epoc time is not older than 5 minutes
long currentEpoc = getEpochTime();
long lEpocTime = Long.valueOf(epochTime);
if ((currentEpoc - lEpocTime) > 300) {
throw new Exception("validateRequest error: epoc time is older than 5 minutes");
}
// We need the public key of the appId from which the request comes from (this appId is part of the mAuth header x-mws-authentication)
PublicKey key = getPublicKey(appId);
// Decode the signature from its base 64 form
byte[] encryptedSignature = Base64.decodeBase64(signatureInHeader);
// Decrypt the signature with public key from requesting application
PKCS1Encoding decryptEngine = new PKCS1Encoding(new RSAEngine());
decryptEngine.init(false, PublicKeyFactory.createKey(key.getEncoded()));
byte[] decryptedHexMsg_bytes = decryptEngine.processBlock(encryptedSignature, 0, encryptedSignature.length);
// Recreate the plaintext signature, based on the incoming request parameters, and hash it
String stringToSign = getStringToSign(verb, resourceUrl, body, appId, epochTime);
byte[] stringToSign_bytes = stringToSign.getBytes("US-ASCII");
byte[] messageDigest_bytes = getHex(getMessageDigest(stringToSign_bytes).digest()).getBytes();
// Compare the decrypted signature and the recreated signature hashes
// If both match, the request was signed by the requesting application and hence the request is valid
boolean result = Arrays.equals(messageDigest_bytes, decryptedHexMsg_bytes);
return result;
}
/**
* Gets a public key, of a requesting appId, from the mAuth service, and caches it
*
* @param appId appId of an application registered with mAuth
* @return public key object of the appId
* @throws Exception
*/
private PublicKey getPublicKey(String appId) throws Exception
{
// If key is in cache just return it
if (_publicKeys.containsKey(appId))
{
return _publicKeys.get(appId);
}
// Generate url to call mAuth api
String completeMAuthResourceUrlPath = _mAuthRequestUrlPath + String.format(_securityTokensUrl, appId); //this appId is the appId of the app we want the public key from
// Generate mAuth headers (sign request)
Map<String, String> headers = generateHeaders("GET", completeMAuthResourceUrlPath, "", _appId); // notice the appId here is _appId, which is our appId not the appId of the app we want the public key from
// Call mAuth api
String res = callmAuth(_mAuthUrl + completeMAuthResourceUrlPath, headers, "", "GET");
// Get key from json response
ObjectMapper mapper = new ObjectMapper();
JsonNode jsonResponse = null;
String publicKeyString = "";
try
{
jsonResponse = mapper.readTree(res);
publicKeyString = jsonResponse.findValue("public_key_str").getTextValue();
}
catch (Exception ex)
{
throw new Exception("Unable to parse jsonResponse from mAuth service while requesting a public key for: " + appId, ex);
}
// Get a PublicKey Object from the text version of the public key
PEMReader reader = null;
PublicKey key = null;
try
{
reader = new PEMReader(new StringReader(publicKeyString));
key = (PublicKey) reader.readObject();
// Add public key to cache
_publicKeys.put(appId, key);
}
catch (Exception ex)
{
throw new Exception("Unable to create public key for: " + appId, ex);
}
finally
{
// Cleanup
try
{
if (reader != null)
{
reader.close();
}
}
catch (Exception ignore) { }
}
return key;
}
/**
* Generate a map with the mAuth http headers after signing an http request's
* parameters
*
* @param verb
* @param resourceUrl
* @param body
* @param appId
* @return
* @throws Exception
*/
public Map<String, String> generateHeaders(String verb, String resourceUrl, String body, String appId) throws Exception
{
// Get epoch time for now
String epochTime = String.valueOf(getEpochTime());
// Use the http request's parameters to generate a base64encoded/encrypted/signed request
String encryptedHexMsg_base64 = signMessageString(verb, resourceUrl, body, appId, epochTime);
Map<String, String> headers = new HashMap<String, String>();
headers.put("x-mws-authentication", "MWS " + appId + ":" + encryptedHexMsg_base64);
headers.put("x-mws-time", epochTime);
return headers;
}
/**
* Get a SHA-512 message digest object from a byte array
*
* @param rawMessage the raw byte array
* @return message digest object
* @throws NoSuchAlgorithmException
*/
private MessageDigest getMessageDigest(byte[] rawMessage) throws NoSuchAlgorithmException
{
MessageDigest messageDigest = MessageDigest.getInstance("SHA-512");
messageDigest.update(rawMessage);
return messageDigest;
}
/**
* Construct a string to be signed, according to mAuth specifications
*
* @param verb
* @param resourceUrl
* @param body
* @param appId
* @param epochTime
* @return string ready to be signed by mAuth
*/
private String getStringToSign(String verb, String resourceUrl, String body, String appId, String epochTime)
{
String stringToSign =
verb + "\n"
+ resourceUrl + "\n"
+ body + "\n" //TODO: confirm if body should be hashed with SHA-512
+ appId + "\n"
+ epochTime;
return stringToSign;
}
/**
* Sign an mAuth request based on its parameters
*
* @param verb
* @param resourceUrl
* @param body
* @param appId
* @param epochTime
* @return a base64encoded(encrypted(signed prepared)) string
* @throws Exception
*/
public String signMessageString(String verb, String resourceUrl, String body, String appId, String epochTime) throws Exception
{
// Get the string to sign based on parameters
String stringToSign = getStringToSign(verb, resourceUrl, body, appId, epochTime);
return signMessageString(stringToSign);
}
/**
* Sign an mAuth request based on a string prepared from its parameters
*
* @param stringToSign
* @return a base64encoded(encrypted(signed prepared)) string
* @throws Exception
*/
public String signMessageString(String stringToSign) throws Exception
{
//get US-ASCII encoded string to sign bytes
byte[] stringToSign_bytes = stringToSign.getBytes("US-ASCII");
MessageDigest messageDigest = getMessageDigest(stringToSign_bytes);
//Get the hex equivalent of message digest.
byte[] md_hex_bytes = getHex(messageDigest.digest()).getBytes();
PrivateKey key = getPrivateKey(_appId);
if (null == key)
{
throw new Exception("Unable to get private key:");
}
PKCS1Encoding encryptEngine = new PKCS1Encoding(new RSAEngine());
encryptEngine.init(true, PrivateKeyFactory.createKey(key.getEncoded()));
byte[] encryptedHexMsg_bytes = encryptEngine.processBlock(md_hex_bytes, 0, md_hex_bytes.length);
String encryptedHexMsg_base64 = new String(Base64.encodeBase64(encryptedHexMsg_bytes), "UTF-8");
return encryptedHexMsg_base64;
}
/**
* Gets a private key object from the text version of the private key, and caches it.
* Typically the private key will belong to a signer appId which in
* most cases will be the appId of the application calling this client class
*
* @param appId the appId for which we want the privat key object
* @return a private key object of the appId
* @throws Exception
*/
private PrivateKey getPrivateKey(String appId) throws Exception
{
// If private key in cache just return it
if (_privateKeys.containsKey(appId))
{
return _privateKeys.get(appId);
}
//Get a private key object from the text version in the private member _privateKey
PEMReader reader = null;
PrivateKey key = null;
try
{
reader = new PEMReader(new StringReader(_privateKey));
KeyPair r = (KeyPair) reader.readObject();
key = r.getPrivate();
}
catch (Exception ex)
{
throw new Exception("Unable to create private key for: " + appId, ex);
}
finally
{
_privateKeys.put(appId, key);
try
{
if (reader != null)
{
reader.close();
}
}
catch (Exception ignore) { }
}
return key;
}
/**
* This method makes call to mAuth invokeApi and process returned result.
*
* @param url -Resource URL.
* @param params_header -collection(Hashtable<Key, value> ) of header key-value pair.
* @param content -A String object representing body of http request.
* @param method -request method, either GET or POST.
* @return result form the mAuth call.
* @throws Exception.
*/
public synchronized String callmAuth(String url, Map<String, String> params_header, String content, String method) throws Exception
{
StringBuffer res = new StringBuffer("");
String sURL = url;
HttpURLConnection conn = invokeApi(sURL, params_header, content, method);
int lastResponseCode = conn.getResponseCode();
String lastResponseMessage = conn.getResponseMessage();
System.out.println("lastResponseCode=" + lastResponseCode + " lastResponseMessage=" + lastResponseMessage);
if (lastResponseCode >= 200 && lastResponseCode < 300)
{
InputStream strm = conn.getInputStream();
if (strm != null)
{
res.append(readToEnd(strm));
//System.out.println(readToEnd(strm));
}
strm.close();
}
conn.disconnect();
return res.toString();
}
/**
* This method makes the actual http request.
*
* Parameters:
*
* @param sURL -Resource URL.
* @param params_header -collection(Hashtable<Key, value> ) of header key-value pair.
* @param content -A String object representing body of http request.
* @param method -request method, either GET or POST.
* @return HttpURLConnection object.
* @throws MalformedURLException, URISyntaxException, IOException.
*/
private HttpURLConnection invokeApi(String sURL, Map<String, String> params_header, String content, String method)
throws MalformedURLException, URISyntaxException, IOException
{
URL url = new URL(sURL);
/*
* List<Proxy> proxies = ProxySelector.getDefault().select( new
* URI(sURL)); Proxy p = (proxies.size() == 0) ? Proxy.NO_PROXY : proxies.get(0);
*/
System.out.println("Calling : "+sURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();//openConnection(p);
conn.setRequestMethod(method);
//Set http headers
int contentlen = 0;
if (params_header != null)
{
for (String key : params_header.keySet())
{
String v = params_header.get(key);
contentlen = contentlen + v.length();
conn.addRequestProperty(key.toString(), v.toString());
System.out.println("setting header..key=" + key.toString() + " value=" + v.toString());
}
}
//conn.setRequestProperty("Content-Type", "application/json");
conn.setDoInput(true);
if (content != null && content.length() > 0)
{
conn.setDoOutput(true);
OutputStream outputStream = conn.getOutputStream();
outputStream.write(content.getBytes());
outputStream.flush();
}
conn.connect();
return conn;
}
/**
* This method gets difference in seconds between 1970/1/1 and today(UTC time).
*
* @return: epoch time in seconds.
*/
private long getEpochTime()
{
SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy hh:mm:ss a");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
String utcTime = sdf.format(new Date());
long epochSec = 0;
try
{
Date curdate = sdf.parse(utcTime);
epochSec = curdate.getTime() / 1000; //getTime returns time in millisec since 1/1/1970
}
catch (Exception ignore) { }
return epochSec;
}
/**
* This method reads InputSteam and returns content as String.
*
* @param InputStream object.
* @return String containing stream contents.
* @throws IOException.
*/
public String readToEnd(InputStream stream) throws IOException
{
int c = 0;
StringBuffer b = new StringBuffer();
while ((c = stream.read()) > 0)
{
b.append((char) c);
}
return b.toString();
}
/**
* This method returns hex string equivalent of byte array.
*
* @param raw - byte[] object.
* @return HEX String.
*/
public String getHex(byte[] raw)
{
if (raw == null)
{
return null;
}
final String HEXES = "0123456789abcdef";
final StringBuilder hex = new StringBuilder(2 * raw.length);
for (final byte b : raw)
{
hex.append(HEXES.charAt((b & 0xF0) >> 4)).append(HEXES.charAt((b & 0x0F)));
}
return hex.toString();
}
/**
* This method returns the number of elements in the public key cache.
*
* @return number of elements in public key cache
*/
public int getPublicKeyCacheSize()
{
return _publicKeys.size();
}
} |
package com.mitchellbdunn.chip8;
import java.util.Random;
import java.util.Stack;
/**
*
* @author Mitch
*/
public class Cpu {
// Chip8 units
private Keyboard keyboard;
private Screen screen;
private Memory memory;
// Cpu variables
private int[] registerV;
private int registerI;
private Stack<Integer> stack;
private int delayTimer;
private int soundTimer;
private int programCounter;
private final Random rng;
public Cpu() {
initializeCpu();
rng = new Random();
}
public final void initializeCpu() {
registerV = new int[16];
for (int i = 0; i < 0xF; i++) {
registerV[i] = 0;
}
registerI = 0;
stack = new Stack<Integer>();
delayTimer = 0;
soundTimer = 0;
programCounter = 0;
}
public void runOpcode(int opcode) {
// Get the possible variables needed from the opcode
int nnn = Chip8Util.getNNN(opcode);
int nn = Chip8Util.getNN(opcode);
int n = Chip8Util.getN(opcode);
int x = Chip8Util.getX(opcode);
int y = Chip8Util.getY(opcode);
// Increase the program counter; there are some opcodes where
// this won't matter since we set the program counter there
incrementProgramCounter();
// Run the appropriate opcode
switch (opcode & 0xF000) {
case 0x0000:
switch (opcode & 0x000F) {
case 0x0000:
opcode00E0();
break;
case 0x000E:
opcode00EE();
break;
}
break;
case 0x1000:
opcode1NNN(nnn);
break;
case 0x2000:
opcode2NNN(nnn);
break;
case 0x3000:
opcode3XNN(x, nn);
break;
case 0x4000:
opcode4XNN(x, nn);
break;
case 0x5000:
opcode5XY0(x, y);
break;
case 0x6000:
opcode6XNN(x, nn);
break;
case 0x7000:
opcode7XNN(x, nn);
break;
case 0x8000:
switch (opcode & 0x000F) {
case 0x0000:
opcode8XY0(x, y);
break;
case 0x0001:
opcode8XY1(x, y);
break;
case 0x0002:
opcode8XY2(x, y);
break;
case 0x0003:
opcode8XY3(x, y);
break;
case 0x0004:
opcode8XY4(x, y);
break;
case 0x0005:
opcode8XY5(x, y);
break;
case 0x0006:
opcode8XY6(x, y);
break;
case 0x0007:
opcode8XY7(x, y);
break;
case 0x000E:
opcode8XYE(x, y);
break;
}
break;
case 0x9000:
opcode9XY0(x, y);
break;
case 0xA000:
opcodeANNN(nnn);
break;
case 0xB000:
opcodeBNNN(nnn);
break;
case 0xC000:
opcodeCXNN(x, nn);
break;
case 0xD000:
opcodeDXYN(x, y, n);
break;
case 0xE000:
switch (opcode & 0x000F) {
case 0x000E:
opcodeEX9E(x);
break;
case 0x0001:
opcodeEXA1(x);
break;
}
break;
case 0xF000:
switch (opcode & 0x00FF) {
case 0x0007:
opcodeFX07(x);
break;
case 0x000A:
opcodeFX0A(x);
break;
case 0x0015:
opcodeFX15(x);
break;
case 0x0018:
opcodeFX18(x);
break;
case 0x001E:
opcodeFX1E(x);
break;
case 0x0029:
opcodeFX29(x);
break;
case 0x0033:
opcodeFX33(x);
break;
case 0x0055:
opcodeFX55(x);
break;
case 0x0065:
opcodeFX65(x);
break;
}
break;
}
}
/**
* Clears the screen.
*/
private void opcode00E0() {
screen.initializeScreen();
}
/**
* Returns from a subroutine.
*/
private void opcode00EE() {
programCounter = stack.pop();
}
/**
* Jumps to address NNN.
*
* @param nnn address to set program counter to.
*/
private void opcode1NNN(int nnn) {
programCounter = nnn;
}
/**
* Calls subroutine at NNN.
*
* @param nnn address of start of subroutine.
*/
private void opcode2NNN(int nnn) {
stack.push(programCounter - 2);
programCounter = nnn;
}
/**
* Skips the next instruction if VX equals NN.
*
* @param x register to check for equality.
* @param nn value to check if equal to register VX.
*/
private void opcode3XNN(int x, int nn) {
if (registerV[x] == nn) {
incrementProgramCounter();
}
}
/**
* Skips the next instruction if VX doesn't equal NN.
*
* @param x register to check for equality.
* @param nn value to check if not equal to register VX.
*/
private void opcode4XNN(int x, int nn) {
if (registerV[x] != nn) {
incrementProgramCounter();
}
}
/**
* Skips the next instruction if VX equals VY.
*
* @param x register to check for equality.
* @param y register to check for equality.
*/
private void opcode5XY0(int x, int y) {
if (registerV[x] == registerV[y]) {
incrementProgramCounter();
}
}
/**
* Sets VX to NN.
*
* @param x register to set value.
* @param nn value to set for register VX.
*/
private void opcode6XNN(int x, int nn) {
registerV[x] = nn;
}
/**
* Adds NN to VX.
*
* @param x register to add value to.
* @param nn value to add to register VX.
*/
private void opcode7XNN(int x, int nn) {
registerV[x] += nn;
}
/**
* Sets VX to the value of VY.
*
* @param x register to set value.
* @param y register to get the value to set in register VX.
*/
private void opcode8XY0(int x, int y) {
registerV[x] = registerV[y];
}
/**
* Sets VX to VX or VY.
*
* @param x register to set value.
* @param y register to perform bitwise OR with register VX.
*/
private void opcode8XY1(int x, int y) {
registerV[x] = registerV[x] | registerV[y];
}
/**
* Sets VX to VX and VY.
*
* @param x register to set value.
* @param y register to perform bitwise AND with register VX.
*/
private void opcode8XY2(int x, int y) {
registerV[x] = registerV[x] & registerV[y];
}
/**
* Sets VX to VX xor VY.
*
* @param x register to set value.
* @param y register to perform bitwise XOR with register VX.
*/
private void opcode8XY3(int x, int y) {
registerV[x] = registerV[x] ^ registerV[y];
}
/**
* Adds VY to VX. VF is set to 1 when there's a carry, and to 0 when there
* isn't.
*
* @param x register to add value to.
* @param y register to get value and to add to register VX.
*/
private void opcode8XY4(int x, int y) {
registerV[x] += registerV[y];
registerV[0xF] = Chip8Util.getBit(registerV[x], 8)?1:0;
registerV[x] &= 0xFF;
}
/**
* VY is subtracted from VX. VF is set to 0 when there's a borrow, and 1
* when there isn't.
*
* @param x register to subtract value from.
* @param y register to get value to subtract from register VX.
*/
private void opcode8XY5(int x, int y) {
registerV[0xF] = (registerV[x] > registerV[y])?1:0;
registerV[x] -= registerV[y];
registerV[x] &= 0xFF;
}
/**
* Shifts VX right by one. VF is set to the value of the least significant
* bit of VX before the shift.
*
* @param x register to shift bits right by one.
* @param y not used.
*/
private void opcode8XY6(int x, int y) {
registerV[0xF] = Chip8Util.getBit(registerV[x], 0) ? 1 : 0;
registerV[x] >>>= 1;
}
/**
* Sets VX to VY minus VX. VF is set to 0 when there's a borrow, and 1 when
* there isn't.
*
* @param x register to set value of subtraction to as well as get value of
* subtrahend.
* @param y register to get value of minuend for subtraction.
*/
private void opcode8XY7(int x, int y) {
registerV[0xF] = (registerV[x] < registerV[y])?1:0;
registerV[x] = registerV[y] - registerV[x];
registerV[x] &= 0xFF;
}
/**
* Shifts VX left by one. VF is set to the value of the most significant bit
* of VX before the shift.
*
* @param x register to shift bits left by one.
* @param y not used.
*/
private void opcode8XYE(int x, int y) {
registerV[0xF] = Chip8Util.getBit(registerV[x], 7) ? 1 : 0;
registerV[x] <<= 1;
registerV[x] &= 0xFF;
}
/**
* Skips the next instruction if VX doesn't equal VY.
*
* @param x register to check for equality.
* @param y register to check for equality.
*/
private void opcode9XY0(int x, int y) {
if (registerV[x] != registerV[y]) {
incrementProgramCounter();
}
}
/**
* Sets I to the address NNN.
*
* @param nnn value to set for I.
*/
private void opcodeANNN(int nnn) {
registerI = nnn;
}
/**
* Jumps to the address NNN plus V0.
*
* @param nnn value to jump to plus value of register V0.
*/
private void opcodeBNNN(int nnn) {
programCounter = nnn + registerV[0];
}
/**
* Sets VX to a random number and NN.
*
* @param x register to set value.
* @param nn value to get bitwise AND with a random number for register VX.
*/
private void opcodeCXNN(int x, int nn) {
registerV[x] = rng.nextInt() & nn;
}
/**
* Draws a sprite at coordinate (VX, VY) that has a width of 8 pixels and a
* height of N pixels. Each row of 8 pixels is read as bit-coded (with the
* most significant bit of each byte displayed on the left) starting from
* memory location I; I value doesn't change after the execution of this
* instruction. As described above, VF is set to 1 if any screen pixels are
* flipped from set to unset when the sprite is drawn, and to 0 if that
* doesn't happen.
*
* @param x register that holds X location to draw sprite.
* @param y register that holds Y location to draw sprite.
* @param n height of the sprite
*/
private void opcodeDXYN(int x, int y, int n) {
// Reset register VF
registerV[0xF] = 0x0;
for (int i = 0; i < n; i++) {
byte row = memory.getByte(registerI + i);
// Loop through each bit to know how to draw it to
// the screen
for (int j = 0; j < 8; j++) {
// Boolean representing if the bit was set or not
boolean drawPixel = Chip8Util.getBit(row, j);
if (drawPixel) {
// Draw the pixel, and get a boolean representing
// if we should set register VF or not
boolean setVF = screen.drawPixel(x + j, y + i);
if (setVF) {
registerV[0xF] = 0x1;
}
}
}
}
}
/**
* Skips the next instruction if the key stored in VX is pressed.
*
* @param x register that holds a value that will map to a key
*/
private void opcodeEX9E(int x) {
if (keyboard.isKeyPressed(registerV[x])) {
incrementProgramCounter();
}
}
/**
* Skips the next instruction if the key stored in VX isn't pressed.
*
* @param x register that holds a value that will map to a key
*/
private void opcodeEXA1(int x) {
if (!keyboard.isKeyPressed(registerV[x])) {
incrementProgramCounter();
}
}
/**
* Sets VX to the value of the delay timer.
*
* @param x register to set to value of delay timer.
*/
private void opcodeFX07(int x) {
registerV[x] = delayTimer;
}
/**
* A key press is awaited, and then stored in VX.
*
* @param x register to store which key is pressed.
*/
private void opcodeFX0A(int x) {
registerV[x] = keyboard.waitForKeyPress();
}
/**
* Sets the delay timer to VX.
*
* @param x register to set with the value of the delay timer.
*/
private void opcodeFX15(int x) {
delayTimer = registerV[x];
}
/**
* Sets the sound timer to VX.
*
* @param x register to set with the value of the sound timer.
*/
private void opcodeFX18(int x) {
soundTimer = registerV[x];
}
/**
* Adds VX to I.
*
* @param x register to add to I.
*/
private void opcodeFX1E(int x) {
registerI += registerV[x];
}
/**
* Sets I to the location of the sprite for the character in VX. Characters
* 0-F (in hexadecimal) are represented by a 4x5 font.
*
* @param x register to get value of the sprite for the character.
*/
private void opcodeFX29(int x) {
registerI = x * 5;
}
/**
* Stores the Binary-coded decimal representation of VX, with the most
* significant of three digits at the address in I, the middle digit at I
* plus 1, and the least significant digit at I plus 2. (In other words,
* take the decimal representation of VX, place the hundreds digit in memory
* at location in I, the tens digit at location I+1, and the ones digit at
* location I+2.)
*
* @param x register to get decimal value and store the binary-coded
* representation.
*/
private void opcodeFX33(int x) {
int number = registerV[x];
memory.setByte(registerI, (byte) (number / 100));
memory.setByte(registerI + 1, (byte) ((number % 100) / 10));
memory.setByte(registerI + 2, (byte) (number & 10));
}
/**
* Stores V0 to VX in memory starting at address I.
*
* @param x last register to store in memory.
*/
private void opcodeFX55(int x) {
for (int i = 0x0; i <= x; i++) {
memory.setByte(registerI + x, (byte) registerV[x]);
}
}
/**
* Fills V0 to VX with values from memory starting at address I.
*
* @param x last register to store from memory.
*/
private void opcodeFX65(int x) {
for (int i = 0x0; i <= x; i++) {
registerV[x] = memory.getByte(registerI + x);
}
}
private void incrementProgramCounter() {
programCounter = programCounter + 2;
}
public int getRegisterV(int x) {
return registerV[x];
}
public void setRegisterV(int x, int value) {
this.registerV[x] = value;
}
public int getRegisterI() {
return registerI;
}
public void setRegisterI(int registerI) {
this.registerI = registerI;
}
public Stack<Integer> getStack() {
return stack;
}
public void setStack(Stack<Integer> stack) {
this.stack = stack;
}
public int getDelayTimer() {
return delayTimer;
}
public void setDelayTimer(int delayTimer) {
this.delayTimer = delayTimer;
}
public int getSoundTimer() {
return soundTimer;
}
public void setSoundTimer(int soundTimer) {
this.soundTimer = soundTimer;
}
public int getProgramCounter() {
return programCounter;
}
public void setProgramCounter(int programCounter) {
this.programCounter = programCounter;
}
public Keyboard getKeyboard() {
return keyboard;
}
public void setKeyboard(Keyboard keyboard) {
this.keyboard = keyboard;
}
public Screen getScreen() {
return screen;
}
public void setScreen(Screen screen) {
this.screen = screen;
}
public Memory getMemory() {
return memory;
}
public void setMemory(Memory memory) {
this.memory = memory;
}
} |
package com.alamkanak.weekview;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PointF;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Typeface;
import android.support.v4.view.GestureDetectorCompat;
import android.support.v4.view.ViewCompat;
import android.text.Layout;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.GestureDetector;
import android.view.HapticFeedbackConstants;
import android.view.MotionEvent;
import android.view.SoundEffectConstants;
import android.view.View;
import android.widget.OverScroller;
import android.widget.Scroller;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class WeekView extends View {
public static final int LENGTH_SHORT = 1;
public static final int LENGTH_LONG = 2;
private final Context mContext;
private Calendar mToday;
private Calendar mStartDate;
private Paint mTimeTextPaint;
private float mTimeTextWidth;
private float mTimeTextHeight;
private Paint mHeaderTextPaint;
private float mHeaderTextHeight;
private GestureDetectorCompat mGestureDetector;
private OverScroller mScroller;
private PointF mCurrentOrigin = new PointF(0f, 0f);
private Direction mCurrentScrollDirection = Direction.NONE;
private Paint mHeaderBackgroundPaint;
private float mWidthPerDay;
private Paint mDayBackgroundPaint;
private Paint mHourSeparatorPaint;
private float mHeaderMarginBottom;
private Paint mTodayBackgroundPaint;
private Paint mTodayHeaderTextPaint;
private Paint mEventBackgroundPaint;
private float mHeaderColumnWidth;
private List<EventRect> mEventRects;
private TextPaint mEventTextPaint;
private Paint mHeaderColumnBackgroundPaint;
private Scroller mStickyScroller;
private int mFetchedMonths[] = new int[3];
private boolean mRefreshEvents = false;
private float mDistanceY = 0;
private float mDistanceX = 0;
private Direction mCurrentFlingDirection = Direction.NONE;
// Attributes and their default values.
private int mHourHeight = 50;
private int mColumnGap = 10;
private int mFirstDayOfWeek = Calendar.MONDAY;
private int mTextSize = 12;
private int mHeaderColumnPadding = 10;
private int mHeaderColumnTextColor = Color.BLACK;
private int mNumberOfVisibleDays = 3;
private int mHeaderRowPadding = 10;
private int mHeaderRowBackgroundColor = Color.WHITE;
private int mDayBackgroundColor = Color.rgb(245, 245, 245);
private int mHourSeparatorColor = Color.rgb(230, 230, 230);
private int mTodayBackgroundColor = Color.rgb(239, 247, 254);
private int mHourSeparatorHeight = 2;
private int mTodayHeaderTextColor = Color.rgb(39, 137, 228);
private int mEventTextSize = 12;
private int mEventTextColor = Color.BLACK;
private int mEventPadding = 8;
private int mHeaderColumnBackgroundColor = Color.WHITE;
private int mDefaultEventColor;
private boolean mIsFirstDraw = true;
private int mDayNameLength = LENGTH_LONG;
private int mOverlappingEventGap = 0;
private int mEventMarginVertical = 0;
private Calendar mFirstVisibleDay;
private Calendar mLastVisibleDay;
// Listeners.
private EventClickListener mEventClickListener;
private EventLongPressListener mEventLongPressListener;
private MonthChangeListener mMonthChangeListener;
private final GestureDetector.SimpleOnGestureListener mGestureListener = new GestureDetector.SimpleOnGestureListener() {
@Override
public boolean onDown(MotionEvent e) {
mScroller.forceFinished(true);
mStickyScroller.forceFinished(true);
return true;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
if (mCurrentScrollDirection == Direction.NONE) {
if (Math.abs(distanceX) > Math.abs(distanceY)){
mCurrentScrollDirection = Direction.HORIZONTAL;
mCurrentFlingDirection = Direction.HORIZONTAL;
}
else {
mCurrentFlingDirection = Direction.VERTICAL;
mCurrentScrollDirection = Direction.VERTICAL;
}
}
mDistanceX = distanceX;
mDistanceY = distanceY;
invalidate();
return true;
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
mScroller.forceFinished(true);
mStickyScroller.forceFinished(true);
if (mCurrentFlingDirection == Direction.HORIZONTAL){
mScroller.fling((int) mCurrentOrigin.x, 0, (int) velocityX, 0, Integer.MIN_VALUE, Integer.MAX_VALUE, 0, 0);
}
else if (mCurrentFlingDirection == Direction.VERTICAL){
mScroller.fling(0, (int) mCurrentOrigin.y, 0, (int) velocityY, 0, 0, (int) -(mHourHeight * 24 + mHeaderTextHeight + mHeaderRowPadding * 2 - getHeight()), 0);
}
ViewCompat.postInvalidateOnAnimation(WeekView.this);
return true;
}
@Override
public boolean onSingleTapConfirmed(MotionEvent e) {
if (mEventRects != null && mEventClickListener != null) {
List<EventRect> reversedEventRects = mEventRects;
Collections.reverse(reversedEventRects);
for (EventRect event : reversedEventRects) {
if (event.rectF != null && e.getX() > event.rectF.left && e.getX() < event.rectF.right && e.getY() > event.rectF.top && e.getY() < event.rectF.bottom) {
mEventClickListener.onEventClick(event.originalEvent, event.rectF);
playSoundEffect(SoundEffectConstants.CLICK);
break;
}
}
}
return super.onSingleTapConfirmed(e);
}
@Override
public void onLongPress(MotionEvent e) {
super.onLongPress(e);
if (mEventLongPressListener != null && mEventRects != null) {
List<EventRect> reversedEventRects = mEventRects;
Collections.reverse(reversedEventRects);
for (EventRect event : reversedEventRects) {
if (event.rectF != null && e.getX() > event.rectF.left && e.getX() < event.rectF.right && e.getY() > event.rectF.top && e.getY() < event.rectF.bottom) {
mEventLongPressListener.onEventLongPress(event.originalEvent, event.rectF);
performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
break;
}
}
}
}
};
private enum Direction {
NONE, HORIZONTAL, VERTICAL
}
public WeekView(Context context) {
this(context, null);
}
public WeekView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public WeekView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
// Hold references.
mContext = context;
// Get the attribute values (if any).
TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.WeekView, 0, 0);
try {
mFirstDayOfWeek = a.getInteger(R.styleable.WeekView_firstDayOfWeek, mFirstDayOfWeek);
mHourHeight = a.getDimensionPixelSize(R.styleable.WeekView_hourHeight, mHourHeight);
mTextSize = a.getDimensionPixelSize(R.styleable.WeekView_textSize, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, mTextSize, context.getResources().getDisplayMetrics()));
mHeaderColumnPadding = a.getDimensionPixelSize(R.styleable.WeekView_headerColumnPadding, mHeaderColumnPadding);
mColumnGap = a.getDimensionPixelSize(R.styleable.WeekView_columnGap, mColumnGap);
mHeaderColumnTextColor = a.getColor(R.styleable.WeekView_headerColumnTextColor, mHeaderColumnTextColor);
mNumberOfVisibleDays = a.getInteger(R.styleable.WeekView_noOfVisibleDays, mNumberOfVisibleDays);
mHeaderRowPadding = a.getDimensionPixelSize(R.styleable.WeekView_headerRowPadding, mHeaderRowPadding);
mHeaderRowBackgroundColor = a.getColor(R.styleable.WeekView_headerRowBackgroundColor, mHeaderRowBackgroundColor);
mDayBackgroundColor = a.getColor(R.styleable.WeekView_dayBackgroundColor, mDayBackgroundColor);
mHourSeparatorColor = a.getColor(R.styleable.WeekView_hourSeparatorColor, mHourSeparatorColor);
mTodayBackgroundColor = a.getColor(R.styleable.WeekView_todayBackgroundColor, mTodayBackgroundColor);
mHourSeparatorHeight = a.getDimensionPixelSize(R.styleable.WeekView_hourSeparatorHeight, mHourSeparatorHeight);
mTodayHeaderTextColor = a.getColor(R.styleable.WeekView_todayHeaderTextColor, mTodayHeaderTextColor);
mEventTextSize = a.getDimensionPixelSize(R.styleable.WeekView_eventTextSize, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, mEventTextSize, context.getResources().getDisplayMetrics()));
mEventTextColor = a.getColor(R.styleable.WeekView_eventTextColor, mEventTextColor);
mEventPadding = a.getDimensionPixelSize(R.styleable.WeekView_hourSeparatorHeight, mEventPadding);
mHeaderColumnBackgroundColor = a.getColor(R.styleable.WeekView_headerColumnBackground, mHeaderColumnBackgroundColor);
mDayNameLength = a.getInteger(R.styleable.WeekView_dayNameLength, mDayNameLength);
mOverlappingEventGap = a.getDimensionPixelSize(R.styleable.WeekView_overlappingEventGap, mOverlappingEventGap);
mEventMarginVertical = a.getDimensionPixelSize(R.styleable.WeekView_eventMarginVertical, mEventMarginVertical);
} finally {
a.recycle();
}
init();
}
private void init() {
// Get the date today.
mToday = Calendar.getInstance();
mToday.set(Calendar.HOUR_OF_DAY, 0);
mToday.set(Calendar.MINUTE, 0);
mToday.set(Calendar.SECOND, 0);
// Scrolling initialization.
mGestureDetector = new GestureDetectorCompat(mContext, mGestureListener);
mScroller = new OverScroller(mContext);
mStickyScroller = new Scroller(mContext);
// Measure settings for time column.
mTimeTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mTimeTextPaint.setTextAlign(Paint.Align.RIGHT);
mTimeTextPaint.setTextSize(mTextSize);
mTimeTextPaint.setColor(mHeaderColumnTextColor);
Rect rect = new Rect();
mTimeTextPaint.getTextBounds("00 PM", 0, "00 PM".length(), rect);
mTimeTextWidth = mTimeTextPaint.measureText("00 PM");
mTimeTextHeight = rect.height();
mHeaderMarginBottom = mTimeTextHeight / 2;
// Measure settings for header row.
mHeaderTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mHeaderTextPaint.setColor(mHeaderColumnTextColor);
mHeaderTextPaint.setTextAlign(Paint.Align.CENTER);
mHeaderTextPaint.setTextSize(mTextSize);
mHeaderTextPaint.getTextBounds("00 PM", 0, "00 PM".length(), rect);
mHeaderTextHeight = rect.height();
mHeaderTextPaint.setTypeface(Typeface.DEFAULT_BOLD);
// Prepare header background paint.
mHeaderBackgroundPaint = new Paint();
mHeaderBackgroundPaint.setColor(mHeaderRowBackgroundColor);
// Prepare day background color paint.
mDayBackgroundPaint = new Paint();
mDayBackgroundPaint.setColor(mDayBackgroundColor);
// Prepare hour separator color paint.
mHourSeparatorPaint = new Paint();
mHourSeparatorPaint.setStyle(Paint.Style.STROKE);
mHourSeparatorPaint.setStrokeWidth(mHourSeparatorHeight);
mHourSeparatorPaint.setColor(mHourSeparatorColor);
// Prepare today background color paint.
mTodayBackgroundPaint = new Paint();
mTodayBackgroundPaint.setColor(mTodayBackgroundColor);
// Prepare today header text color paint.
mTodayHeaderTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mTodayHeaderTextPaint.setTextAlign(Paint.Align.CENTER);
mTodayHeaderTextPaint.setTextSize(mTextSize);
mTodayHeaderTextPaint.setTypeface(Typeface.DEFAULT_BOLD);
mTodayHeaderTextPaint.setColor(mTodayHeaderTextColor);
// Prepare event background color.
mEventBackgroundPaint = new Paint();
mEventBackgroundPaint.setColor(Color.rgb(174, 208, 238));
// Prepare header column background color.
mHeaderColumnBackgroundPaint = new Paint();
mHeaderColumnBackgroundPaint.setColor(mHeaderColumnBackgroundColor);
// Prepare event text size and color.
mEventTextPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG | Paint.LINEAR_TEXT_FLAG);
mEventTextPaint.setStyle(Paint.Style.FILL);
mEventTextPaint.setColor(mEventTextColor);
mEventTextPaint.setTextSize(mEventTextSize);
mStartDate = (Calendar) mToday.clone();
// Set default event color.
mDefaultEventColor = Color.parseColor("#9fc6e7");
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// Draw the header row.
drawHeaderRowAndEvents(canvas);
// Draw the time column and all the axes/separators.
drawTimeColumnAndAxes(canvas);
// Hide everything in the first cell (top left corner).
canvas.drawRect(0, 0, mTimeTextWidth + mHeaderColumnPadding * 2, mHeaderTextHeight + mHeaderRowPadding * 2, mHeaderBackgroundPaint);
// Hide anything that is in the bottom margin of the header row.
canvas.drawRect(mHeaderColumnWidth, mHeaderTextHeight + mHeaderRowPadding * 2, getWidth(), mHeaderRowPadding * 2 + mHeaderTextHeight + mHeaderMarginBottom + mTimeTextHeight/2 - mHourSeparatorHeight / 2, mHeaderColumnBackgroundPaint);
}
private void drawTimeColumnAndAxes(Canvas canvas) {
// Do not let the view go above/below the limit due to scrolling. Set the max and min limit of the scroll.
if (mCurrentScrollDirection == Direction.VERTICAL) {
if (mCurrentOrigin.y - mDistanceY > 0) mCurrentOrigin.y = 0;
else if (mCurrentOrigin.y - mDistanceY < -(mHourHeight * 24 + mHeaderTextHeight + mHeaderRowPadding * 2 - getHeight())) mCurrentOrigin.y = -(mHourHeight * 24 + mHeaderTextHeight + mHeaderRowPadding * 2 - getHeight());
else mCurrentOrigin.y -= mDistanceY;
}
// Draw the background color for the header column.
canvas.drawRect(0, mHeaderTextHeight + mHeaderRowPadding * 2, mHeaderColumnWidth, getHeight(), mHeaderColumnBackgroundPaint);
for (int i = 0; i < 24; i++) {
float top = mHeaderTextHeight + mHeaderRowPadding * 2 + mCurrentOrigin.y + mHourHeight * i + mHeaderMarginBottom;
// Draw the text if its y position is not outside of the visible area. The pivot point of the text is the point at the bottom-right corner.
if (top < getHeight()) canvas.drawText(getTimeString(i), mTimeTextWidth + mHeaderColumnPadding, top + mTimeTextHeight, mTimeTextPaint);
}
}
private void drawHeaderRowAndEvents(Canvas canvas) {
// Calculate the available width for each day.
mHeaderColumnWidth = mTimeTextWidth + mHeaderColumnPadding *2;
mWidthPerDay = getWidth() - mHeaderColumnWidth - mColumnGap * (mNumberOfVisibleDays - 1);
mWidthPerDay = mWidthPerDay/mNumberOfVisibleDays;
// If the week view is being drawn for the first time, then consider the first day of week.
if (mIsFirstDraw && mNumberOfVisibleDays >= 7) {
if (mToday.get(Calendar.DAY_OF_WEEK) != mFirstDayOfWeek) {
int difference = 7 + (mToday.get(Calendar.DAY_OF_WEEK) - mFirstDayOfWeek);
mCurrentOrigin.x += (mWidthPerDay + mColumnGap) * difference;
}
mIsFirstDraw = false;
}
// Consider scroll offset.
if (mCurrentScrollDirection == Direction.HORIZONTAL) mCurrentOrigin.x -= mDistanceX;
int leftDaysWithGaps = (int) -(Math.ceil(mCurrentOrigin.x / (mWidthPerDay + mColumnGap)));
float startFromPixel = mCurrentOrigin.x + (mWidthPerDay + mColumnGap) * leftDaysWithGaps +
mHeaderColumnWidth;
float startPixel = startFromPixel;
// Prepare to iterate for each day.
Calendar day = (Calendar) mToday.clone();
day.add(Calendar.HOUR, 6);
// Prepare to iterate for each hour to draw the hour lines.
int lineCount = (int) ((getHeight() - mHeaderTextHeight - mHeaderRowPadding * 2 -
mHeaderMarginBottom) / mHourHeight) + 1;
lineCount = (lineCount) * (mNumberOfVisibleDays+1);
float[] hourLines = new float[lineCount * 4];
// Clear the cache for events rectangles.
if (mEventRects != null) {
for (EventRect eventRect: mEventRects) {
eventRect.rectF = null;
}
}
// Iterate through each day.
mFirstVisibleDay = (Calendar) mToday.clone();
mFirstVisibleDay.add(Calendar.DATE, leftDaysWithGaps);
for (int dayNumber = leftDaysWithGaps + 1;
dayNumber <= leftDaysWithGaps + mNumberOfVisibleDays + 1;
dayNumber++) {
// Check if the day is today.
day = (Calendar) mToday.clone();
mLastVisibleDay = (Calendar) day.clone();
day.add(Calendar.DATE, dayNumber - 1);
mLastVisibleDay.add(Calendar.DATE, dayNumber - 2);
boolean sameDay = isSameDay(day, mToday);
// Get more events if necessary. We want to store the events 3 months beforehand. Get
// events only when it is the first iteration of the loop.
if (mEventRects == null || mRefreshEvents || (dayNumber == leftDaysWithGaps + 1 && mFetchedMonths[1] != day.get(Calendar.MONTH)+1 && day.get(Calendar.DAY_OF_MONTH) == 15)) {
getMoreEvents(day);
mRefreshEvents = false;
}
// Draw background color for each day.
float start = (startPixel < mHeaderColumnWidth ? mHeaderColumnWidth : startPixel);
if (mWidthPerDay + startPixel - start> 0)
canvas.drawRect(start, mHeaderTextHeight + mHeaderRowPadding * 2 + mTimeTextHeight/2 + mHeaderMarginBottom, startPixel + mWidthPerDay, getHeight(), sameDay ? mTodayBackgroundPaint : mDayBackgroundPaint);
// Prepare the separator lines for hours.
int i = 0;
for (int hourNumber = 0; hourNumber < 24; hourNumber++) {
float top = mHeaderTextHeight + mHeaderRowPadding * 2 + mCurrentOrigin.y + mHourHeight * hourNumber + mTimeTextHeight/2 + mHeaderMarginBottom;
if (top > mHeaderTextHeight + mHeaderRowPadding * 2 + mTimeTextHeight/2 + mHeaderMarginBottom - mHourSeparatorHeight && top < getHeight() && startPixel + mWidthPerDay - start > 0){
hourLines[i * 4] = start;
hourLines[i * 4 + 1] = top;
hourLines[i * 4 + 2] = startPixel + mWidthPerDay;
hourLines[i * 4 + 3] = top;
i++;
}
}
// Draw the lines for hours.
canvas.drawLines(hourLines, mHourSeparatorPaint);
// Draw the events.
drawEvents(day, startPixel, canvas);
// In the next iteration, start from the next day.
startPixel += mWidthPerDay + mColumnGap;
}
// Draw the header background.
canvas.drawRect(0, 0, getWidth(), mHeaderTextHeight + mHeaderRowPadding * 2, mHeaderBackgroundPaint);
// Draw the header row texts.
startPixel = startFromPixel;
for (int dayNumber=leftDaysWithGaps+1; dayNumber <= leftDaysWithGaps + mNumberOfVisibleDays + 1; dayNumber++) {
// Check if the day is today.
day = (Calendar) mToday.clone();
day.add(Calendar.DATE, dayNumber - 1);
boolean sameDay = isSameDay(day, mToday);
// Draw the day labels.
String dayLabel = String.format("%s %d/%02d", getDayName(day), day.get(Calendar.MONTH) + 1, day.get(Calendar.DAY_OF_MONTH));
canvas.drawText(dayLabel, startPixel + mWidthPerDay / 2, mHeaderTextHeight + mHeaderRowPadding, sameDay ? mTodayHeaderTextPaint : mHeaderTextPaint);
startPixel += mWidthPerDay + mColumnGap;
}
}
/**
* Draw all the events of a particular day.
* @param date The day.
* @param startFromPixel The left position of the day area. The events will never go any left from this value.
* @param canvas The canvas to draw upon.
*/
private void drawEvents(Calendar date, float startFromPixel, Canvas canvas) {
if (mEventRects != null && mEventRects.size() > 0) {
for (int i = 0; i < mEventRects.size(); i++) {
if (isSameDay(mEventRects.get(i).event.getStartTime(), date)) {
// Calculate top.
float top = mHourHeight * 24 * mEventRects.get(i).top / 1440 + mCurrentOrigin.y + mHeaderTextHeight + mHeaderRowPadding * 2 + mHeaderMarginBottom + mTimeTextHeight/2 + mEventMarginVertical;
float originalTop = top;
if (top < mHeaderTextHeight + mHeaderRowPadding * 2 + mHeaderMarginBottom + mTimeTextHeight/2)
top = mHeaderTextHeight + mHeaderRowPadding * 2 + mHeaderMarginBottom + mTimeTextHeight/2;
// Calculate bottom.
float bottom = mEventRects.get(i).bottom;
bottom = mHourHeight * 24 * bottom / 1440 + mCurrentOrigin.y + mHeaderTextHeight + mHeaderRowPadding * 2 + mHeaderMarginBottom + mTimeTextHeight/2 - mEventMarginVertical;
// Calculate left and right.
float left = startFromPixel + mEventRects.get(i).left * mWidthPerDay;
if (left < startFromPixel)
left += mOverlappingEventGap;
float originalLeft = left;
float right = left + mEventRects.get(i).width * mWidthPerDay;
if (right < startFromPixel + mWidthPerDay)
right -= mOverlappingEventGap;
if (left < mHeaderColumnWidth) left = mHeaderColumnWidth;
// Draw the event and the event name on top of it.
RectF eventRectF = new RectF(left, top, right, bottom);
if (bottom > mHeaderTextHeight + mHeaderRowPadding * 2 + mHeaderMarginBottom + mTimeTextHeight/2 && left < right &&
eventRectF.right > mHeaderColumnWidth &&
eventRectF.left < getWidth() &&
eventRectF.bottom > mHeaderTextHeight + mHeaderRowPadding * 2 + mTimeTextHeight / 2 + mHeaderMarginBottom &&
eventRectF.top < getHeight() &&
left < right
) {
mEventRects.get(i).rectF = eventRectF;
mEventBackgroundPaint.setColor(mEventRects.get(i).event.getColor() == 0 ? mDefaultEventColor : mEventRects.get(i).event.getColor());
canvas.drawRect(mEventRects.get(i).rectF, mEventBackgroundPaint);
drawText(mEventRects.get(i).event.getName(), mEventRects.get(i).rectF, canvas, originalTop, originalLeft);
}
else
mEventRects.get(i).rectF = null;
}
}
}
}
/**
* Draw the name of the event on top of the event rectangle.
* @param text The text to draw.
* @param rect The rectangle on which the text is to be drawn.
* @param canvas The canvas to draw upon.
* @param originalTop The original top position of the rectangle. The rectangle may have some of its portion outside of the visible area.
* @param originalLeft The original left position of the rectangle. The rectangle may have some of its portion outside of the visible area.
*/
private void drawText(String text, RectF rect, Canvas canvas, float originalTop, float originalLeft) {
if (rect.right - rect.left - mEventPadding * 2 < 0) return;
// Get text dimensions
StaticLayout textLayout = new StaticLayout(text, mEventTextPaint, (int) (rect.right - originalLeft - mEventPadding * 2), Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
// Crop height
int availableHeight = (int) (rect.bottom - originalTop - mEventPadding * 2);
int lineHeight = textLayout.getHeight() / textLayout.getLineCount();
if (lineHeight < availableHeight && textLayout.getHeight() > rect.height() - mEventPadding * 2) {
int lineCount = textLayout.getLineCount();
int availableLineCount = (int) Math.floor(lineCount * availableHeight / textLayout.getHeight());
float widthAvailable = (rect.right - originalLeft - mEventPadding * 2) * availableLineCount;
textLayout = new StaticLayout(TextUtils.ellipsize(text, mEventTextPaint, widthAvailable, TextUtils.TruncateAt.END), mEventTextPaint, (int) (rect.right - originalLeft - mEventPadding * 2), Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
}
else if (lineHeight >= availableHeight) {
int width = (int) (rect.right - originalLeft - mEventPadding * 2);
textLayout = new StaticLayout(TextUtils.ellipsize(text, mEventTextPaint, width, TextUtils.TruncateAt.END), mEventTextPaint, width, Layout.Alignment.ALIGN_NORMAL, 1.0f, 1.0f, false);
}
// Draw text
canvas.save();
canvas.translate(originalLeft + mEventPadding, originalTop + mEventPadding);
textLayout.draw(canvas);
canvas.restore();
}
/**
* A class to hold reference to the events and their visual representation. An EventRect is
* actually the rectangle that is drawn on the calendar for a given event. There may be more
* than one rectangle for a single event (an event that expands more than one day). In that
* case two instances of the EventRect will be used for a single event. The given event will be
* stored in "originalEvent". But the event that corresponds to rectangle the rectangle
* instance will be stored in "event".
*/
private class EventRect {
public WeekViewEvent event;
public WeekViewEvent originalEvent;
public RectF rectF;
public float left;
public float width;
public float top;
public float bottom;
/**
* Create a new instance of event rect. An EventRect is actually the rectangle that is drawn
* on the calendar for a given event. There may be more than one rectangle for a single
* event (an event that expands more than one day). In that case two instances of the
* EventRect will be used for a single event. The given event will be stored in
* "originalEvent". But the event that corresponds to rectangle the rectangle instance will
* be stored in "event".
* @param event Represents the event which this instance of rectangle represents.
* @param originalEvent The original event that was passed by the user.
* @param rectF The rectangle.
*/
public EventRect(WeekViewEvent event, WeekViewEvent originalEvent, RectF rectF) {
this.event = event;
this.rectF = rectF;
this.originalEvent = originalEvent;
}
}
/**
* Gets more events of one/more month(s) if necessary. This method is called when the user is
* scrolling the week view. The week view stores the events of three months: the visible month,
* the previous month, the next month.
* @param day The day where the user is currently is.
*/
private void getMoreEvents(Calendar day) {
// Delete all events if its not current month +- 1.
deleteFarMonths(day);
// Get more events if the month is changed.
if (mEventRects == null)
mEventRects = new ArrayList<EventRect>();
if (mMonthChangeListener == null && !isInEditMode())
throw new IllegalStateException("You must provide a MonthChangeListener");
// If a refresh was requested then reset some variables.
if (mRefreshEvents) {
mEventRects.clear();
mFetchedMonths = new int[3];
}
// Get events of previous month.
int previousMonth = (day.get(Calendar.MONTH) == 0?12:day.get(Calendar.MONTH));
int nextMonth = (day.get(Calendar.MONTH)+2 == 13 ?1:day.get(Calendar.MONTH)+2);
int[] lastFetchedMonth = mFetchedMonths.clone();
if (mFetchedMonths[0] < 1 || mFetchedMonths[0] != previousMonth || mRefreshEvents) {
if (!containsValue(lastFetchedMonth, previousMonth) && !isInEditMode()){
List<WeekViewEvent> events = mMonthChangeListener.onMonthChange((previousMonth==12)?day.get(Calendar.YEAR)-1:day.get(Calendar.YEAR), previousMonth);
sortEvents(events);
for (WeekViewEvent event: events) {
cacheEvent(event);
}
}
mFetchedMonths[0] = previousMonth;
}
// Get events of this month.
if (mFetchedMonths[1] < 1 || mFetchedMonths[1] != day.get(Calendar.MONTH)+1 || mRefreshEvents) {
if (!containsValue(lastFetchedMonth, day.get(Calendar.MONTH)+1) && !isInEditMode()) {
List<WeekViewEvent> events = mMonthChangeListener.onMonthChange(day.get(Calendar.YEAR), day.get(Calendar.MONTH) + 1);
sortEvents(events);
for (WeekViewEvent event : events) {
cacheEvent(event);
}
}
mFetchedMonths[1] = day.get(Calendar.MONTH)+1;
}
// Get events of next month.
if (mFetchedMonths[2] < 1 || mFetchedMonths[2] != nextMonth || mRefreshEvents) {
if (!containsValue(lastFetchedMonth, nextMonth) && !isInEditMode()) {
List<WeekViewEvent> events = mMonthChangeListener.onMonthChange(nextMonth == 1 ? day.get(Calendar.YEAR) + 1 : day.get(Calendar.YEAR), nextMonth);
sortEvents(events);
for (WeekViewEvent event : events) {
cacheEvent(event);
}
}
mFetchedMonths[2] = nextMonth;
}
// Prepare to calculate positions of each events.
ArrayList<EventRect> tempEvents = new ArrayList<EventRect>(mEventRects);
mEventRects = new ArrayList<EventRect>();
Calendar dayCounter = (Calendar) day.clone();
dayCounter.add(Calendar.MONTH, -1);
dayCounter.set(Calendar.DAY_OF_MONTH, 1);
Calendar maxDay = (Calendar) day.clone();
maxDay.add(Calendar.MONTH, 1);
maxDay.set(Calendar.DAY_OF_MONTH, maxDay.getActualMaximum(Calendar.DAY_OF_MONTH));
// Iterate through each day to calculate the position of the events.
while (dayCounter.getTimeInMillis() <= maxDay.getTimeInMillis()) {
ArrayList<EventRect> eventRects = new ArrayList<EventRect>();
for (EventRect eventRect : tempEvents) {
if (isSameDay(eventRect.event.getStartTime(), dayCounter))
eventRects.add(eventRect);
}
computePositionOfEvents(eventRects);
dayCounter.add(Calendar.DATE, 1);
}
}
private void cacheEvent(WeekViewEvent event) {
if (!isSameDay(event.getStartTime(), event.getEndTime())) {
Calendar endTime = (Calendar) event.getStartTime().clone();
endTime.set(Calendar.HOUR_OF_DAY, 23);
endTime.set(Calendar.MINUTE, 59);
Calendar startTime = (Calendar) event.getEndTime().clone();
startTime.set(Calendar.HOUR_OF_DAY, 00);
startTime.set(Calendar.MINUTE, 0);
WeekViewEvent event1 = new WeekViewEvent(event.getId(), event.getName(), event.getStartTime(), endTime);
event1.setColor(event.getColor());
WeekViewEvent event2 = new WeekViewEvent(event.getId(), event.getName(), startTime, event.getEndTime());
event2.setColor(event.getColor());
mEventRects.add(new EventRect(event1, event, null));
mEventRects.add(new EventRect(event2, event, null));
}
else
mEventRects.add(new EventRect(event, event, null));
}
/**
* Sorts the events in ascending order.
* @param events The events to be sorted.
*/
private void sortEvents(List<WeekViewEvent> events) {
Collections.sort(events, new Comparator<WeekViewEvent>() {
@Override
public int compare(WeekViewEvent event1, WeekViewEvent event2) {
long start1 = event1.getStartTime().getTimeInMillis();
long start2 = event2.getStartTime().getTimeInMillis();
int comparator = start1 > start2 ? 1 : (start1 < start2 ? -1 : 0);
if (comparator == 0) {
long end1 = event1.getEndTime().getTimeInMillis();
long end2 = event2.getEndTime().getTimeInMillis();
comparator = end1 > end2 ? 1 : (end1 < end2 ? -1 : 0);
}
return comparator;
}
});
}
/**
* Calculates the left and right positions of each events. This comes handy specially if events
* are overlapping.
* @param eventRects The events along with their wrapper class.
*/
private void computePositionOfEvents(List<EventRect> eventRects) {
// Make "collision groups" for all events that collide with others.
List<List<EventRect>> collisionGroups = new ArrayList<List<EventRect>>();
for (EventRect eventRect : eventRects) {
boolean isPlaced = false;
outerLoop:
for (List<EventRect> collisionGroup : collisionGroups) {
for (EventRect groupEvent : collisionGroup) {
if (isEventsCollide(groupEvent.event, eventRect.event)) {
collisionGroup.add(eventRect);
isPlaced = true;
break outerLoop;
}
}
}
if (!isPlaced) {
List<EventRect> newGroup = new ArrayList<EventRect>();
newGroup.add(eventRect);
collisionGroups.add(newGroup);
}
}
for (List<EventRect> collisionGroup : collisionGroups) {
expandEventsToMaxWidth(collisionGroup);
}
}
/**
* Expands all the events to maximum possible width. The events will try to occupy maximum
* space available horizontally.
* @param collisionGroup The group of events which overlap with each other.
*/
private void expandEventsToMaxWidth(List<EventRect> collisionGroup) {
// Expand the events to maximum possible width.
List<List<EventRect>> columns = new ArrayList<List<EventRect>>();
columns.add(new ArrayList<EventRect>());
for (EventRect eventRect : collisionGroup) {
boolean isPlaced = false;
for (List<EventRect> column : columns) {
if (column.size() == 0) {
column.add(eventRect);
isPlaced = true;
}
else if (!isEventsCollide(eventRect.event, column.get(column.size()-1).event)) {
column.add(eventRect);
isPlaced = true;
break;
}
}
if (!isPlaced) {
List<EventRect> newColumn = new ArrayList<EventRect>();
newColumn.add(eventRect);
columns.add(newColumn);
}
}
// Calculate left and right position for all the events.
int maxRowCount = columns.get(0).size();
for (int i = 0; i < maxRowCount; i++) {
// Set the left and right values of the event.
float j = 0;
for (List<EventRect> column : columns) {
if (column.size() >= i+1) {
EventRect eventRect = column.get(i);
eventRect.width = 1f / columns.size();
eventRect.left = j / columns.size();
eventRect.top = eventRect.event.getStartTime().get(Calendar.HOUR_OF_DAY) * 60 + eventRect.event.getStartTime().get(Calendar.MINUTE);
eventRect.bottom = eventRect.event.getEndTime().get(Calendar.HOUR_OF_DAY) * 60 + eventRect.event.getEndTime().get(Calendar.MINUTE);
mEventRects.add(eventRect);
}
j++;
}
}
}
/**
* Checks if two events overlap.
* @param event1 The first event.
* @param event2 The second event.
* @return true if the events overlap.
*/
private boolean isEventsCollide(WeekViewEvent event1, WeekViewEvent event2) {
long start1 = event1.getStartTime().getTimeInMillis();
long end1 = event1.getEndTime().getTimeInMillis();
long start2 = event2.getStartTime().getTimeInMillis();
long end2 = event2.getEndTime().getTimeInMillis();
return !((start1 >= end2) || (end1 <= start2));
}
/**
* Checks if time1 occurs after (or at the same time) time2.
* @param time1 The time to check.
* @param time2 The time to check against.
* @return true if time1 and time2 are equal or if time1 is after time2. Otherwise false.
*/
private boolean isTimeAfterOrEquals(Calendar time1, Calendar time2) {
return !(time1 == null || time2 == null) && time1.getTimeInMillis() >= time2.getTimeInMillis();
}
/**
* Deletes the events of the months that are too far away from the current month.
* @param currentDay The current day.
*/
private void deleteFarMonths(Calendar currentDay) {
if (mEventRects == null) return;
Calendar nextMonth = (Calendar) currentDay.clone();
nextMonth.add(Calendar.MONTH, 1);
nextMonth.set(Calendar.DAY_OF_MONTH, nextMonth.getActualMaximum(Calendar.DAY_OF_MONTH));
nextMonth.set(Calendar.HOUR_OF_DAY, 12);
nextMonth.set(Calendar.MINUTE, 59);
nextMonth.set(Calendar.SECOND, 59);
Calendar prevMonth = (Calendar) currentDay.clone();
prevMonth.add(Calendar.MONTH, -1);
prevMonth.set(Calendar.DAY_OF_MONTH, 1);
prevMonth.set(Calendar.HOUR_OF_DAY, 0);
prevMonth.set(Calendar.MINUTE, 0);
prevMonth.set(Calendar.SECOND, 0);
List<EventRect> newEvents = new ArrayList<EventRect>();
for (EventRect eventRect : mEventRects) {
boolean isFarMonth = eventRect.event.getStartTime().getTimeInMillis() > nextMonth.getTimeInMillis() || eventRect.event.getEndTime().getTimeInMillis() < prevMonth.getTimeInMillis();
if (!isFarMonth) newEvents.add(eventRect);
}
mEventRects.clear();
mEventRects.addAll(newEvents);
}
// Functions related to setting and getting the properties.
public void setOnEventClickListener (EventClickListener listener) {
this.mEventClickListener = listener;
}
public EventClickListener getEventClickListener() {
return mEventClickListener;
}
public MonthChangeListener getMonthChangeListener() {
return mMonthChangeListener;
}
public void setMonthChangeListener(MonthChangeListener monthChangeListener) {
this.mMonthChangeListener = monthChangeListener;
}
public EventLongPressListener getEventLongPressListener() {
return mEventLongPressListener;
}
public void setEventLongPressListener(EventLongPressListener eventLongPressListener) {
this.mEventLongPressListener = eventLongPressListener;
}
/**
* Get the number of visible days in a week.
* @return The number of visible days in a week.
*/
public int getNumberOfVisibleDays() {
return mNumberOfVisibleDays;
}
/**
* Set the number of visible days in a week.
* @param numberOfVisibleDays The number of visible days in a week.
*/
public void setNumberOfVisibleDays(int numberOfVisibleDays) {
this.mNumberOfVisibleDays = numberOfVisibleDays;
mCurrentOrigin.x = 0;
mCurrentOrigin.y = 0;
invalidate();
}
public int getHourHeight() {
return mHourHeight;
}
public void setHourHeight(int hourHeight) {
mHourHeight = hourHeight;
invalidate();
}
public int getColumnGap() {
return mColumnGap;
}
public void setColumnGap(int columnGap) {
mColumnGap = columnGap;
invalidate();
}
public int getFirstDayOfWeek() {
return mFirstDayOfWeek;
}
/**
* Set the first day of the week. First day of the week is used only when the week view is first
* drawn. It does not of any effect after user starts scrolling horizontally.
* <p>
* <b>Note:</b> This method will only work if the week view is set to display more than 6 days at
* once.
* </p>
* @param firstDayOfWeek The supported values are {@link java.util.Calendar#SUNDAY},
* {@link java.util.Calendar#MONDAY}, {@link java.util.Calendar#TUESDAY},
* {@link java.util.Calendar#WEDNESDAY}, {@link java.util.Calendar#THURSDAY},
* {@link java.util.Calendar#FRIDAY}.
*/
public void setFirstDayOfWeek(int firstDayOfWeek) {
mFirstDayOfWeek = firstDayOfWeek;
invalidate();
}
public int getTextSize() {
return mTextSize;
}
public void setTextSize(int textSize) {
mTextSize = textSize;
mTodayHeaderTextPaint.setTextSize(mTextSize);
mHeaderTextPaint.setTextSize(mTextSize);
mTimeTextPaint.setTextSize(mTextSize);
invalidate();
}
public int getHeaderColumnPadding() {
return mHeaderColumnPadding;
}
public void setHeaderColumnPadding(int headerColumnPadding) {
mHeaderColumnPadding = headerColumnPadding;
invalidate();
}
public int getHeaderColumnTextColor() {
return mHeaderColumnTextColor;
}
public void setHeaderColumnTextColor(int headerColumnTextColor) {
mHeaderColumnTextColor = headerColumnTextColor;
invalidate();
}
public int getHeaderRowPadding() {
return mHeaderRowPadding;
}
public void setHeaderRowPadding(int headerRowPadding) {
mHeaderRowPadding = headerRowPadding;
invalidate();
}
public int getHeaderRowBackgroundColor() {
return mHeaderRowBackgroundColor;
}
public void setHeaderRowBackgroundColor(int headerRowBackgroundColor) {
mHeaderRowBackgroundColor = headerRowBackgroundColor;
invalidate();
}
public int getDayBackgroundColor() {
return mDayBackgroundColor;
}
public void setDayBackgroundColor(int dayBackgroundColor) {
mDayBackgroundColor = dayBackgroundColor;
invalidate();
}
public int getHourSeparatorColor() {
return mHourSeparatorColor;
}
public void setHourSeparatorColor(int hourSeparatorColor) {
mHourSeparatorColor = hourSeparatorColor;
invalidate();
}
public int getTodayBackgroundColor() {
return mTodayBackgroundColor;
}
public void setTodayBackgroundColor(int todayBackgroundColor) {
mTodayBackgroundColor = todayBackgroundColor;
invalidate();
}
public int getHourSeparatorHeight() {
return mHourSeparatorHeight;
}
public void setHourSeparatorHeight(int hourSeparatorHeight) {
mHourSeparatorHeight = hourSeparatorHeight;
invalidate();
}
public int getTodayHeaderTextColor() {
return mTodayHeaderTextColor;
}
public void setTodayHeaderTextColor(int todayHeaderTextColor) {
mTodayHeaderTextColor = todayHeaderTextColor;
invalidate();
}
public int getEventTextSize() {
return mEventTextSize;
}
public void setEventTextSize(int eventTextSize) {
mEventTextSize = eventTextSize;
mEventTextPaint.setTextSize(mEventTextSize);
invalidate();
}
public int getEventTextColor() {
return mEventTextColor;
}
public void setEventTextColor(int eventTextColor) {
mEventTextColor = eventTextColor;
invalidate();
}
public int getEventPadding() {
return mEventPadding;
}
public void setEventPadding(int eventPadding) {
mEventPadding = eventPadding;
invalidate();
}
public int getHeaderColumnBackgroundColor() {
return mHeaderColumnBackgroundColor;
}
public void setHeaderColumnBackgroundColor(int headerColumnBackgroundColor) {
mHeaderColumnBackgroundColor = headerColumnBackgroundColor;
invalidate();
}
public int getDefaultEventColor() {
return mDefaultEventColor;
}
public void setDefaultEventColor(int defaultEventColor) {
mDefaultEventColor = defaultEventColor;
invalidate();
}
public int getDayNameLength() {
return mDayNameLength;
}
/**
* Set the length of the day name displayed in the header row. Example of short day names is
* 'M' for 'Monday' and example of long day names is 'Mon' for 'Monday'.
* @param length Supported values are {@link com.alamkanak.weekview.WeekView#LENGTH_SHORT} and
* {@link com.alamkanak.weekview.WeekView#LENGTH_LONG}.
*/
public void setDayNameLength(int length) {
if (length != LENGTH_LONG && length != LENGTH_SHORT) {
throw new IllegalArgumentException("length parameter must be either LENGTH_LONG or LENGTH_SHORT");
}
this.mDayNameLength = length;
}
public int getOverlappingEventGap() {
return mOverlappingEventGap;
}
/**
* Set the gap between overlapping events.
* @param overlappingEventGap The gap between overlapping events.
*/
public void setOverlappingEventGap(int overlappingEventGap) {
this.mOverlappingEventGap = overlappingEventGap;
invalidate();
}
public int getEventMarginVertical() {
return mEventMarginVertical;
}
/**
* Set the top and bottom margin of the event. The event will release this margin from the top
* and bottom edge. This margin is useful for differentiation consecutive events.
* @param eventMarginVertical The top and bottom margin.
*/
public void setEventMarginVertical(int eventMarginVertical) {
this.mEventMarginVertical = eventMarginVertical;
invalidate();
}
/**
* Returns the first visible day in the week view.
* @return The first visible day in the week view.
*/
public Calendar getFirstVisibleDay() {
return mFirstVisibleDay;
}
/**
* Returns the last visible day in the week view.
* @return The last visible day in the week view.
*/
public Calendar getLastVisibleDay() {
return mLastVisibleDay;
}
// Functions related to scrolling.
@Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP) {
if (mCurrentScrollDirection == Direction.HORIZONTAL) {
float leftDays = Math.round(mCurrentOrigin.x / (mWidthPerDay + mColumnGap));
int nearestOrigin = (int) (mCurrentOrigin.x - leftDays * (mWidthPerDay+mColumnGap));
mStickyScroller.startScroll((int) mCurrentOrigin.x, 0, - nearestOrigin, 0);
ViewCompat.postInvalidateOnAnimation(WeekView.this);
}
mCurrentScrollDirection = Direction.NONE;
}
return mGestureDetector.onTouchEvent(event);
}
@Override
public void computeScroll() {
super.computeScroll();
if (mScroller.computeScrollOffset()) {
if (Math.abs(mScroller.getFinalX() - mScroller.getCurrX()) < mWidthPerDay + mColumnGap && Math.abs(mScroller.getFinalX() - mScroller.getStartX()) != 0) {
mScroller.forceFinished(true);
float leftDays = Math.round(mCurrentOrigin.x / (mWidthPerDay + mColumnGap));
int nearestOrigin = (int) (mCurrentOrigin.x - leftDays * (mWidthPerDay+mColumnGap));
mStickyScroller.startScroll((int) mCurrentOrigin.x, 0, - nearestOrigin, 0);
ViewCompat.postInvalidateOnAnimation(WeekView.this);
}
else {
if (mCurrentFlingDirection == Direction.VERTICAL) mCurrentOrigin.y = mScroller.getCurrY();
else mCurrentOrigin.x = mScroller.getCurrX();
ViewCompat.postInvalidateOnAnimation(this);
}
}
if (mStickyScroller.computeScrollOffset()) {
mCurrentOrigin.x = mStickyScroller.getCurrX();
ViewCompat.postInvalidateOnAnimation(this);
}
}
// Public methods.
/**
* Show today on the week view.
*/
public void goToToday() {
Calendar today = Calendar.getInstance();
goToDate(today);
}
/**
* Show a specific day on the week view.
* @param date The date to show.
*/
public void goToDate(Calendar date) {
mScroller.forceFinished(true);
date.set(Calendar.HOUR_OF_DAY, 0);
date.set(Calendar.MINUTE, 0);
date.set(Calendar.SECOND, 0);
mRefreshEvents = true;
Calendar today = Calendar.getInstance();
today.set(Calendar.HOUR_OF_DAY, 0);
today.set(Calendar.MINUTE, 0);
today.set(Calendar.SECOND, 0);
int dateDifference = (int) (date.getTimeInMillis() - today.getTimeInMillis()) / (1000 * 60 * 60 * 24);
mCurrentOrigin.x = - dateDifference * (mWidthPerDay + mColumnGap);
invalidate();
}
/**
* Refreshes the view and loads the events again.
*/
public void notifyDatasetChanged(){
mRefreshEvents = true;
invalidate();
}
/**
* Vertically scroll to a specific hour in the week view.
* @param hour The hour to scroll to in 24-hour format. Supported values are 0-24.
*/
public void goToHour(double hour){
if (hour < 0)
throw new IllegalArgumentException("Cannot scroll to an hour of negative value.");
else if (hour > 24)
throw new IllegalArgumentException("Cannot scroll to an hour of value greater than 24.");
else if (hour * mHourHeight > mHourHeight * 24 - getHeight() + mHeaderTextHeight + mHeaderRowPadding * 2 + mHeaderMarginBottom)
throw new IllegalArgumentException("Cannot scroll to an hour which will result the calendar to go off the screen.");
int verticalOffset = (int) (mHourHeight * hour);
mCurrentOrigin.y = -verticalOffset;
invalidate();
}
// Interfaces.
public interface EventClickListener {
public void onEventClick(WeekViewEvent event, RectF eventRect);
}
public interface MonthChangeListener {
public List<WeekViewEvent> onMonthChange(int newYear, int newMonth);
}
public interface EventLongPressListener {
public void onEventLongPress(WeekViewEvent event, RectF eventRect);
}
// Helper methods.
/**
* Checks if an integer array contains a particular value.
* @param list The haystack.
* @param value The needle.
* @return True if the array contains the value. Otherwise returns false.
*/
private boolean containsValue(int[] list, int value) {
for (int i = 0; i < list.length; i++){
if (list[i] == value)
return true;
}
return false;
}
/**
* Converts an int (0-23) to time string (e.g. 12 PM).
* @param hour The time. Limit: 0-23.
* @return The string representation of the time.
*/
private String getTimeString(int hour) {
String amPm;
if (hour >= 0 && hour < 12) amPm = "AM";
else amPm = "PM";
if (hour == 0) hour = 12;
if (hour > 12) hour -= 12;
return String.format("%02d %s", hour, amPm);
}
/**
* Checks if two times are on the same day.
* @param dayOne The first day.
* @param dayTwo The second day.
* @return Whether the times are on the same day.
*/
private boolean isSameDay(Calendar dayOne, Calendar dayTwo) {
return dayOne.get(Calendar.YEAR) == dayTwo.get(Calendar.YEAR) && dayOne.get(Calendar.DAY_OF_YEAR) == dayTwo.get(Calendar.DAY_OF_YEAR);
}
/**
* Get the day name of a given date.
* @param date The date.
* @return The first the characters of the day name.
*/
private String getDayName(Calendar date) {
int dayOfWeek = date.get(Calendar.DAY_OF_WEEK);
if (Calendar.MONDAY == dayOfWeek) return (mDayNameLength == LENGTH_SHORT ? "M" : "MON");
else if (Calendar.TUESDAY == dayOfWeek) return (mDayNameLength == LENGTH_SHORT ? "T" : "TUE");
else if (Calendar.WEDNESDAY == dayOfWeek) return (mDayNameLength == LENGTH_SHORT ? "W" : "WED");
else if (Calendar.THURSDAY == dayOfWeek) return (mDayNameLength == LENGTH_SHORT ? "T" : "THU");
else if (Calendar.FRIDAY == dayOfWeek) return (mDayNameLength == LENGTH_SHORT ? "F" : "FRI");
else if (Calendar.SATURDAY == dayOfWeek) return (mDayNameLength == LENGTH_SHORT ? "S" : "SAT");
else if (Calendar.SUNDAY == dayOfWeek) return (mDayNameLength == LENGTH_SHORT ? "S" : "SUN");
return "";
}
} |
package com.pump.swing.popup;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Window;
import java.awt.Window.Type;
import javax.swing.JComponent;
import javax.swing.JLayeredPane;
import javax.swing.JPanel;
import javax.swing.JToolTip;
import javax.swing.JWindow;
import javax.swing.Popup;
import javax.swing.RootPaneContainer;
import javax.swing.SwingUtilities;
import com.pump.plaf.QPanelUI;
import com.pump.plaf.QPanelUI.CalloutType;
public class QPopup extends Popup {
static class HiddenTargetBoundsException extends Exception {
private static final long serialVersionUID = 1L;
}
/**
* This client property on owners resolves to a CalloutType or an array of
* CalloutType that should be used for that particular owner. If this is
* undefined then any CalloutType may be used.
*/
public static final String PROPERTY_CALLOUT_TYPE = QPopup.class.getName()
+ "#calloutType";
private static final String PROPERTY_IS_QPOPUP = QPopup.class.getName()
+ "#isQPopup";
private static final CalloutType[] ORDERED_CALLOUT_TYPES = new CalloutType[] {
CalloutType.TOP_CENTER, CalloutType.TOP_RIGHT,
CalloutType.TOP_LEFT, CalloutType.BOTTOM_CENTER,
CalloutType.BOTTOM_RIGHT, CalloutType.BOTTOM_LEFT,
CalloutType.LEFT_CENTER, CalloutType.LEFT_TOP,
CalloutType.LEFT_BOTTOM, CalloutType.RIGHT_CENTER,
CalloutType.RIGHT_TOP, CalloutType.RIGHT_BOTTOM };
private static final int CALLOUT_SIZE = 5;
protected JPanel contents;
protected PopupTarget target;
protected Component owner;
protected QPanelUI ui;
protected Point screenLoc;
/**
* Create a QPopup that will use callouts.
*
* @param owner
* @param contents
*/
public QPopup(Component owner, PopupTarget target, JPanel contents) {
this(owner, target, contents, null);
}
/**
* Create a QPopup.
*
* @param owner
* @param contents
* @param screenLoc
* if this is non-null, then the popup should be placed at these
* screen coordinates. If this is null, then callouts will be
* used to align the popup with the owner.
*/
public QPopup(Component owner, PopupTarget target, JPanel contents,
Point screenLoc) {
this.owner = owner;
setTarget(target);
this.contents = contents;
this.screenLoc = screenLoc == null ? null : new Point(screenLoc);
ui = (QPanelUI) contents.getUI();
}
@Override
public void show() {
Point z = getScreenLocation();
if (z != null) {
ui.setCalloutSize(0);
if (showUsingRootPaneContainer(z, null))
return;
showUsingWindow(z, null, true);
} else {
try {
CalloutType[] calloutTypes = getCalloutTypes();
for (CalloutType type : calloutTypes) {
Point p = getScreenLoc(type);
if (showUsingRootPaneContainer(p, type)) {
return;
}
}
for (CalloutType type : calloutTypes) {
Point p = getScreenLoc(type);
if (showUsingWindow(p, type, false))
return;
}
Point p = getScreenLoc(calloutTypes[0]);
showUsingWindow(p, calloutTypes[0], true);
} catch (HiddenTargetBoundsException htbe) {
hide();
}
}
}
protected CalloutType[] getCalloutTypes() {
if (owner instanceof JComponent) {
Object v = ((JComponent) owner)
.getClientProperty(PROPERTY_CALLOUT_TYPE);
if (v instanceof CalloutType) {
return new CalloutType[] { (CalloutType) v };
}
if (v != null
&& v.getClass().isArray()
&& v.getClass().getComponentType()
.equals(CalloutType.class))
return ((CalloutType[]) v);
}
return ORDERED_CALLOUT_TYPES;
}
private Rectangle getShowingTargetBounds(Rectangle screenBounds) {
Component c = getOwner();
while (c != null) {
Point cScreenLoc = new Point(0, 0);
SwingUtilities.convertPointToScreen(cScreenLoc, c);
Rectangle cScreenBounds = new Rectangle(cScreenLoc, c.getSize());
screenBounds = cScreenBounds.intersection(screenBounds);
c = c.getParent();
}
if (screenBounds.width <= 0 || screenBounds.height <= 0)
return null;
return screenBounds;
}
private Point getScreenLoc(CalloutType type)
throws HiddenTargetBoundsException {
Rectangle r = getTarget().getScreenBounds();
r = getShowingTargetBounds(r);
if (r == null)
throw new HiddenTargetBoundsException();
int minX = r.x;
int minY = r.y;
int maxX = r.x + r.width;
int maxY = r.y + r.height;
int midX = (minX + maxX) / 2;
int midY = (minY + maxY) / 2;
Point p;
if (type == CalloutType.TOP_LEFT) {
p = new Point(minX, maxY);
} else if (type == CalloutType.TOP_RIGHT) {
p = new Point(maxX, maxY);
} else if (type == CalloutType.RIGHT_TOP) {
p = new Point(minX, minY);
} else if (type == CalloutType.RIGHT_CENTER) {
p = new Point(minX, midY);
} else if (type == CalloutType.RIGHT_BOTTOM) {
p = new Point(minX, maxY);
} else if (type == CalloutType.BOTTOM_RIGHT) {
p = new Point(maxX, minY);
} else if (type == CalloutType.BOTTOM_CENTER) {
p = new Point(midX, minY);
} else if (type == CalloutType.BOTTOM_LEFT) {
p = new Point(minX, minY);
} else if (type == CalloutType.LEFT_BOTTOM) {
p = new Point(maxX, maxY);
} else if (type == CalloutType.LEFT_CENTER) {
p = new Point(maxX, midY);
} else if (type == CalloutType.LEFT_TOP) {
p = new Point(maxX, minY);
} else { // TOP_CENTER:
p = new Point(midX, maxY);
}
return p;
}
private boolean showUsingRootPaneContainer(Point screenLoc,
CalloutType calloutType) {
Window ownerWindow = owner instanceof Window ? (Window) owner
: SwingUtilities.getWindowAncestor(owner);
RootPaneContainer rpc = ownerWindow instanceof RootPaneContainer ? (RootPaneContainer) ownerWindow
: null;
if (rpc == null)
return false;
JLayeredPane layeredPane = rpc.getLayeredPane();
Point layeredPaneLoc = new Point(screenLoc);
SwingUtilities.convertPointFromScreen(layeredPaneLoc, layeredPane);
if (calloutType == null) {
ui.setCalloutType(CalloutType.TOP_CENTER);
ui.setCalloutSize(0);
} else {
ui.setCalloutType(calloutType);
ui.setCalloutSize(CALLOUT_SIZE);
}
contents.validate();
contents.setSize(contents.getPreferredSize());
Rectangle layeredPaneBounds = new Rectangle(layeredPaneLoc.x,
layeredPaneLoc.y, contents.getWidth(), contents.getHeight());
if (calloutType != null) {
Point calloutTip = ui.getCalloutTip(contents);
layeredPaneBounds.x -= calloutTip.x;
layeredPaneBounds.y -= calloutTip.y;
}
if (new Rectangle(0, 0, layeredPane.getWidth(), layeredPane.getHeight())
.contains(layeredPaneBounds)) {
if (contents.getParent() != layeredPane) {
hide();
layeredPane.add(contents, JLayeredPane.POPUP_LAYER);
}
contents.setBounds(layeredPaneBounds);
contents.setVisible(true);
return true;
}
return false;
}
/**
*
* @param screenLoc
* @param calloutType
* @param forceShow
* if true then this method will always return true and try to
* show a window. If false then this method may decide to return
* false and not show the popup. For example: if the popup would
* fall far outside the window, this may return false in hopes
* that another attempt will get better coverage.
* @return
*/
private boolean showUsingWindow(Point screenLoc, CalloutType calloutType,
boolean forceShow) {
Point windowLoc = new Point(screenLoc);
if (calloutType == null) {
ui.setCalloutType(CalloutType.TOP_CENTER);
ui.setCalloutSize(0);
} else {
ui.setCalloutType(calloutType);
ui.setCalloutSize(CALLOUT_SIZE);
}
contents.validate();
contents.setSize(contents.getPreferredSize());
if (calloutType != null) {
Point calloutTip = ui.getCalloutTip(contents);
windowLoc.x -= calloutTip.x;
windowLoc.y -= calloutTip.y;
}
Rectangle windowBounds = new Rectangle(windowLoc, contents.getSize());
if (!forceShow && !isScreenRectVisible(windowBounds))
return false;
// closing and creating new windows to constantly reposition causes
// flickering; we should reuse the existing window if we're already
// visible.
JWindow window = null;
if (contents.getParent() != null) {
Window w = SwingUtilities.getWindowAncestor(contents);
if (w instanceof JWindow) {
JWindow jw = (JWindow) w;
Boolean b = (Boolean) jw.getRootPane().getClientProperty(
PROPERTY_IS_QPOPUP);
if (Boolean.TRUE.equals(b)) {
window = jw;
}
}
if (window == null) {
hide();
}
}
if (window == null) {
window = createWindow();
}
if (isToolTip())
window.setFocusable(false);
window.setBounds(windowBounds);
window.setVisible(true);
window.setAlwaysOnTop(true);
window.toFront();
return true;
}
private boolean isScreenRectVisible(Rectangle screenRect) {
GraphicsEnvironment ge = GraphicsEnvironment
.getLocalGraphicsEnvironment();
GraphicsDevice[] gds = ge.getScreenDevices();
for (GraphicsDevice gd : gds) {
for (GraphicsConfiguration gc : gd.getConfigurations()) {
if (gc.getBounds().contains(screenRect)) {
return true;
}
}
}
return false;
}
/**
* Return true if this popup is being used to display a tooltip.
*/
protected boolean isToolTip() {
for (int a = 0; a < contents.getComponentCount(); a++) {
Component child = contents.getComponent(a);
if (!(child instanceof JToolTip))
return false;
}
return contents.getComponentCount() > 0;
}
/**
* Create a transparent window
*/
protected JWindow createWindow() {
JWindow window = new JWindow();
window.getRootPane().putClientProperty(PROPERTY_IS_QPOPUP, true);
window.setType(Type.POPUP);
window.getRootPane().putClientProperty("Window.shadow", Boolean.FALSE);
float k = .95f;
window.getRootPane().putClientProperty("Window.opacity", k);
window.setOpacity(k);
window.setBackground(new Color(0, 0, 0, 0));
window.getRootPane().setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
c.weightx = 1;
c.weighty = 1;
c.fill = GridBagConstraints.BOTH;
window.getRootPane().add(contents, c);
return window;
}
@Override
public void hide() {
Window w = SwingUtilities.getWindowAncestor(contents);
Container parent = contents.getParent();
if (parent != null) {
Rectangle r = contents.getBounds();
parent.remove(contents);
parent.repaint(r.x, r.y, r.width, r.height);
}
if (w instanceof RootPaneContainer) {
RootPaneContainer rpc = (RootPaneContainer) w;
Boolean b = (Boolean) rpc.getRootPane().getClientProperty(
PROPERTY_IS_QPOPUP);
if (Boolean.TRUE.equals(b)) {
w.setVisible(false);
w.dispose();
}
}
}
public Component getOwner() {
return owner;
}
public PopupTarget getTarget() {
return target;
}
public void setTarget(PopupTarget target) {
if (target == null)
target = new BasicPopupTarget(owner);
this.target = target;
}
public JPanel getContents() {
return contents;
}
public Point getScreenLocation() {
if (screenLoc == null)
return null;
return new Point(screenLoc);
}
} |
package com.alamkanak.weekview;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PointF;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Region;
import android.graphics.Typeface;
import android.os.Build;
import android.support.annotation.Nullable;
import android.support.v4.view.GestureDetectorCompat;
import android.support.v4.view.ViewCompat;
import android.support.v4.view.animation.FastOutLinearInInterpolator;
import android.text.Layout;
import android.text.SpannableStringBuilder;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.format.DateFormat;
import android.text.style.StyleSpan;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.GestureDetector;
import android.view.HapticFeedbackConstants;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.SoundEffectConstants;
import android.view.View;
import android.view.ViewConfiguration;
import android.widget.OverScroller;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;
public class WeekView extends View {
private enum Direction {
NONE, LEFT, RIGHT, VERTICAL
}
@Deprecated
public static final int LENGTH_SHORT = 1;
@Deprecated
public static final int LENGTH_LONG = 2;
private final Context mContext;
private Paint mTimeTextPaint;
private float mTimeTextWidth;
private float mTimeTextHeight;
private Paint mHeaderTextPaint;
private float mHeaderTextHeight;
private GestureDetectorCompat mGestureDetector;
private OverScroller mScroller;
private PointF mCurrentOrigin = new PointF(0f, 0f);
private Direction mCurrentScrollDirection = Direction.NONE;
private Paint mHeaderBackgroundPaint;
private float mWidthPerDay;
private Paint mDayBackgroundPaint;
private Paint mHourSeparatorPaint;
private float mHeaderMarginBottom;
private Paint mTodayBackgroundPaint;
private Paint mFutureBackgroundPaint;
private Paint mPastBackgroundPaint;
private Paint mFutureWeekendBackgroundPaint;
private Paint mPastWeekendBackgroundPaint;
private Paint mNowLinePaint;
private Paint mTodayHeaderTextPaint;
private Paint mEventBackgroundPaint;
private float mHeaderColumnWidth;
private List<EventRect> mEventRects;
private List<? extends WeekViewEvent> mPreviousPeriodEvents;
private List<? extends WeekViewEvent> mCurrentPeriodEvents;
private List<? extends WeekViewEvent> mNextPeriodEvents;
private TextPaint mEventTextPaint;
private Paint mHeaderColumnBackgroundPaint;
private int mFetchedPeriod = -1; // the middle period the calendar has fetched.
private boolean mRefreshEvents = false;
private Direction mCurrentFlingDirection = Direction.NONE;
private ScaleGestureDetector mScaleDetector;
private boolean mIsZooming;
private Calendar mFirstVisibleDay;
private Calendar mLastVisibleDay;
private int mDefaultEventColor;
private int mMinimumFlingVelocity = 0;
private int mScaledTouchSlop = 0;
// Attributes and their default values.
private int mHourHeight = 50;
private int mNewHourHeight = -1;
private int mMinHourHeight = 0; //no minimum specified (will be dynamic, based on screen)
private int mEffectiveMinHourHeight = mMinHourHeight; //compensates for the fact that you can't keep zooming out.
private int mMaxHourHeight = 250;
private int mColumnGap = 10;
private int mFirstDayOfWeek = Calendar.MONDAY;
private int mTextSize = 12;
private int mHeaderColumnPadding = 10;
private int mHeaderColumnTextColor = Color.BLACK;
private int mNumberOfVisibleDays = 3;
private int mHeaderRowPadding = 10;
private int mHeaderRowBackgroundColor = Color.WHITE;
private int mDayBackgroundColor = Color.rgb(245, 245, 245);
private int mPastBackgroundColor = Color.rgb(227, 227, 227);
private int mFutureBackgroundColor = Color.rgb(245, 245, 245);
private int mPastWeekendBackgroundColor = 0;
private int mFutureWeekendBackgroundColor = 0;
private int mNowLineColor = Color.rgb(102, 102, 102);
private int mNowLineThickness = 5;
private int mHourSeparatorColor = Color.rgb(230, 230, 230);
private int mTodayBackgroundColor = Color.rgb(239, 247, 254);
private int mHourSeparatorHeight = 2;
private int mTodayHeaderTextColor = Color.rgb(39, 137, 228);
private int mEventTextSize = 12;
private int mEventTextColor = Color.BLACK;
private int mEventPadding = 8;
private int mHeaderColumnBackgroundColor = Color.WHITE;
private boolean mIsFirstDraw = true;
private boolean mAreDimensionsInvalid = true;
@Deprecated private int mDayNameLength = LENGTH_LONG;
private int mOverlappingEventGap = 0;
private int mEventMarginVertical = 0;
private float mXScrollingSpeed = 1f;
private Calendar mScrollToDay = null;
private double mScrollToHour = -1;
private int mEventCornerRadius = 0;
private boolean mShowDistinctWeekendColor = false;
private boolean mShowNowLine = false;
private boolean mShowDistinctPastFutureColor = false;
private boolean mHorizontalFlingEnabled = true;
private boolean mVerticalFlingEnabled = true;
// Listeners.
private EventClickListener mEventClickListener;
private EventLongPressListener mEventLongPressListener;
private WeekViewLoader mWeekViewLoader;
private EmptyViewClickListener mEmptyViewClickListener;
private EmptyViewLongPressListener mEmptyViewLongPressListener;
private DateTimeInterpreter mDateTimeInterpreter;
private ScrollListener mScrollListener;
private final GestureDetector.SimpleOnGestureListener mGestureListener = new GestureDetector.SimpleOnGestureListener() {
@Override
public boolean onDown(MotionEvent e) {
goToNearestOrigin();
return true;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
// Check if view is zoomed.
if (mIsZooming)
return true;
switch (mCurrentScrollDirection) {
case NONE: {
// Allow scrolling only in one direction.
if (Math.abs(distanceX) > Math.abs(distanceY)) {
if (distanceX > 0) {
mCurrentScrollDirection = Direction.LEFT;
} else {
mCurrentScrollDirection = Direction.RIGHT;
}
} else {
mCurrentScrollDirection = Direction.VERTICAL;
}
break;
}
case LEFT: {
// Change direction if there was enough change.
if (Math.abs(distanceX) > Math.abs(distanceY) && (distanceX < -mScaledTouchSlop)) {
mCurrentScrollDirection = Direction.RIGHT;
}
break;
}
case RIGHT: {
// Change direction if there was enough change.
if (Math.abs(distanceX) > Math.abs(distanceY) && (distanceX > mScaledTouchSlop)) {
mCurrentScrollDirection = Direction.LEFT;
}
break;
}
}
// Calculate the new origin after scroll.
switch (mCurrentScrollDirection) {
case LEFT:
case RIGHT:
mCurrentOrigin.x -= distanceX * mXScrollingSpeed;
ViewCompat.postInvalidateOnAnimation(WeekView.this);
break;
case VERTICAL:
mCurrentOrigin.y -= distanceY;
ViewCompat.postInvalidateOnAnimation(WeekView.this);
break;
}
return true;
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
if (mIsZooming)
return true;
if ((mCurrentFlingDirection == Direction.LEFT && !mHorizontalFlingEnabled) ||
(mCurrentFlingDirection == Direction.RIGHT && !mHorizontalFlingEnabled) ||
(mCurrentFlingDirection == Direction.VERTICAL && !mVerticalFlingEnabled)) {
return true;
}
mScroller.forceFinished(true);
mCurrentFlingDirection = mCurrentScrollDirection;
switch (mCurrentFlingDirection) {
case LEFT:
case RIGHT:
mScroller.fling((int) mCurrentOrigin.x, (int) mCurrentOrigin.y, (int) (velocityX * mXScrollingSpeed), 0, Integer.MIN_VALUE, Integer.MAX_VALUE, (int) -(mHourHeight * 24 + mHeaderTextHeight + mHeaderRowPadding * 2 + mHeaderMarginBottom + mTimeTextHeight / 2 - getHeight()), 0);
break;
case VERTICAL:
mScroller.fling((int) mCurrentOrigin.x, (int) mCurrentOrigin.y, 0, (int) velocityY, Integer.MIN_VALUE, Integer.MAX_VALUE, (int) -(mHourHeight * 24 + mHeaderTextHeight + mHeaderRowPadding * 2 + mHeaderMarginBottom + mTimeTextHeight/2 - getHeight()), 0);
break;
}
ViewCompat.postInvalidateOnAnimation(WeekView.this);
return true;
}
@Override
public boolean onSingleTapConfirmed(MotionEvent e) {
// If the tap was on an event then trigger the callback.
if (mEventRects != null && mEventClickListener != null) {
List<EventRect> reversedEventRects = mEventRects;
Collections.reverse(reversedEventRects);
for (EventRect event : reversedEventRects) {
if (event.rectF != null && e.getX() > event.rectF.left && e.getX() < event.rectF.right && e.getY() > event.rectF.top && e.getY() < event.rectF.bottom) {
mEventClickListener.onEventClick(event.originalEvent, event.rectF);
playSoundEffect(SoundEffectConstants.CLICK);
return super.onSingleTapConfirmed(e);
}
}
}
// If the tap was on in an empty space, then trigger the callback.
if (mEmptyViewClickListener != null && e.getX() > mHeaderColumnWidth && e.getY() > (mHeaderTextHeight + mHeaderRowPadding * 2 + mHeaderMarginBottom)) {
Calendar selectedTime = getTimeFromPoint(e.getX(), e.getY());
if (selectedTime != null) {
playSoundEffect(SoundEffectConstants.CLICK);
mEmptyViewClickListener.onEmptyViewClicked(selectedTime);
}
}
return super.onSingleTapConfirmed(e);
}
@Override
public void onLongPress(MotionEvent e) {
super.onLongPress(e);
if (mEventLongPressListener != null && mEventRects != null) {
List<EventRect> reversedEventRects = mEventRects;
Collections.reverse(reversedEventRects);
for (EventRect event : reversedEventRects) {
if (event.rectF != null && e.getX() > event.rectF.left && e.getX() < event.rectF.right && e.getY() > event.rectF.top && e.getY() < event.rectF.bottom) {
mEventLongPressListener.onEventLongPress(event.originalEvent, event.rectF);
performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
return;
}
}
}
// If the tap was on in an empty space, then trigger the callback.
if (mEmptyViewLongPressListener != null && e.getX() > mHeaderColumnWidth && e.getY() > (mHeaderTextHeight + mHeaderRowPadding * 2 + mHeaderMarginBottom)) {
Calendar selectedTime = getTimeFromPoint(e.getX(), e.getY());
if (selectedTime != null) {
performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
mEmptyViewLongPressListener.onEmptyViewLongPress(selectedTime);
}
}
}
};
public WeekView(Context context) {
this(context, null);
}
public WeekView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public WeekView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
// Hold references.
mContext = context;
// Get the attribute values (if any).
TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.WeekView, 0, 0);
try {
mFirstDayOfWeek = a.getInteger(R.styleable.WeekView_firstDayOfWeek, mFirstDayOfWeek);
mHourHeight = a.getDimensionPixelSize(R.styleable.WeekView_hourHeight, mHourHeight);
mMinHourHeight = a.getDimensionPixelSize(R.styleable.WeekView_minHourHeight, mMinHourHeight);
mEffectiveMinHourHeight = mMinHourHeight;
mMaxHourHeight = a.getDimensionPixelSize(R.styleable.WeekView_maxHourHeight, mMaxHourHeight);
mTextSize = a.getDimensionPixelSize(R.styleable.WeekView_textSize, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, mTextSize, context.getResources().getDisplayMetrics()));
mHeaderColumnPadding = a.getDimensionPixelSize(R.styleable.WeekView_headerColumnPadding, mHeaderColumnPadding);
mColumnGap = a.getDimensionPixelSize(R.styleable.WeekView_columnGap, mColumnGap);
mHeaderColumnTextColor = a.getColor(R.styleable.WeekView_headerColumnTextColor, mHeaderColumnTextColor);
mNumberOfVisibleDays = a.getInteger(R.styleable.WeekView_noOfVisibleDays, mNumberOfVisibleDays);
mHeaderRowPadding = a.getDimensionPixelSize(R.styleable.WeekView_headerRowPadding, mHeaderRowPadding);
mHeaderRowBackgroundColor = a.getColor(R.styleable.WeekView_headerRowBackgroundColor, mHeaderRowBackgroundColor);
mDayBackgroundColor = a.getColor(R.styleable.WeekView_dayBackgroundColor, mDayBackgroundColor);
mFutureBackgroundColor = a.getColor(R.styleable.WeekView_futureBackgroundColor, mFutureBackgroundColor);
mPastBackgroundColor = a.getColor(R.styleable.WeekView_pastBackgroundColor, mPastBackgroundColor);
mFutureWeekendBackgroundColor = a.getColor(R.styleable.WeekView_futureWeekendBackgroundColor, mFutureBackgroundColor); // If not set, use the same color as in the week
mPastWeekendBackgroundColor = a.getColor(R.styleable.WeekView_pastWeekendBackgroundColor, mPastBackgroundColor);
mNowLineColor = a.getColor(R.styleable.WeekView_nowLineColor, mNowLineColor);
mNowLineThickness = a.getDimensionPixelSize(R.styleable.WeekView_nowLineThickness, mNowLineThickness);
mHourSeparatorColor = a.getColor(R.styleable.WeekView_hourSeparatorColor, mHourSeparatorColor);
mTodayBackgroundColor = a.getColor(R.styleable.WeekView_todayBackgroundColor, mTodayBackgroundColor);
mHourSeparatorHeight = a.getDimensionPixelSize(R.styleable.WeekView_hourSeparatorHeight, mHourSeparatorHeight);
mTodayHeaderTextColor = a.getColor(R.styleable.WeekView_todayHeaderTextColor, mTodayHeaderTextColor);
mEventTextSize = a.getDimensionPixelSize(R.styleable.WeekView_eventTextSize, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, mEventTextSize, context.getResources().getDisplayMetrics()));
mEventTextColor = a.getColor(R.styleable.WeekView_eventTextColor, mEventTextColor);
mEventPadding = a.getDimensionPixelSize(R.styleable.WeekView_eventPadding, mEventPadding);
mHeaderColumnBackgroundColor = a.getColor(R.styleable.WeekView_headerColumnBackground, mHeaderColumnBackgroundColor);
mDayNameLength = a.getInteger(R.styleable.WeekView_dayNameLength, mDayNameLength);
mOverlappingEventGap = a.getDimensionPixelSize(R.styleable.WeekView_overlappingEventGap, mOverlappingEventGap);
mEventMarginVertical = a.getDimensionPixelSize(R.styleable.WeekView_eventMarginVertical, mEventMarginVertical);
mXScrollingSpeed = a.getFloat(R.styleable.WeekView_xScrollingSpeed, mXScrollingSpeed);
mEventCornerRadius = a.getDimensionPixelSize(R.styleable.WeekView_eventCornerRadius, mEventCornerRadius);
mShowDistinctPastFutureColor = a.getBoolean(R.styleable.WeekView_showDistinctPastFutureColor, mShowDistinctPastFutureColor);
mShowDistinctWeekendColor = a.getBoolean(R.styleable.WeekView_showDistinctWeekendColor, mShowDistinctWeekendColor);
mShowNowLine = a.getBoolean(R.styleable.WeekView_showNowLine, mShowNowLine);
mHorizontalFlingEnabled = a.getBoolean(R.styleable.WeekView_horizontalFlingEnabled, mHorizontalFlingEnabled);
mVerticalFlingEnabled = a.getBoolean(R.styleable.WeekView_verticalFlingEnabled, mVerticalFlingEnabled);
} finally {
a.recycle();
}
init();
}
private void init() {
// Scrolling initialization.
mGestureDetector = new GestureDetectorCompat(mContext, mGestureListener);
mScroller = new OverScroller(mContext, new FastOutLinearInInterpolator());
mMinimumFlingVelocity = ViewConfiguration.get(mContext).getScaledMinimumFlingVelocity();
mScaledTouchSlop = ViewConfiguration.get(mContext).getScaledTouchSlop();
// Measure settings for time column.
mTimeTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mTimeTextPaint.setTextAlign(Paint.Align.RIGHT);
mTimeTextPaint.setTextSize(mTextSize);
mTimeTextPaint.setColor(mHeaderColumnTextColor);
Rect rect = new Rect();
mTimeTextPaint.getTextBounds("00 PM", 0, "00 PM".length(), rect);
mTimeTextHeight = rect.height();
mHeaderMarginBottom = mTimeTextHeight / 2;
initTextTimeWidth();
// Measure settings for header row.
mHeaderTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mHeaderTextPaint.setColor(mHeaderColumnTextColor);
mHeaderTextPaint.setTextAlign(Paint.Align.CENTER);
mHeaderTextPaint.setTextSize(mTextSize);
mHeaderTextPaint.getTextBounds("00 PM", 0, "00 PM".length(), rect);
mHeaderTextHeight = rect.height();
mHeaderTextPaint.setTypeface(Typeface.DEFAULT_BOLD);
// Prepare header background paint.
mHeaderBackgroundPaint = new Paint();
mHeaderBackgroundPaint.setColor(mHeaderRowBackgroundColor);
// Prepare day background color paint.
mDayBackgroundPaint = new Paint();
mDayBackgroundPaint.setColor(mDayBackgroundColor);
mFutureBackgroundPaint = new Paint();
mFutureBackgroundPaint.setColor(mFutureBackgroundColor);
mPastBackgroundPaint = new Paint();
mPastBackgroundPaint.setColor(mPastBackgroundColor);
mFutureWeekendBackgroundPaint = new Paint();
mFutureWeekendBackgroundPaint.setColor(mFutureWeekendBackgroundColor);
mPastWeekendBackgroundPaint = new Paint();
mPastWeekendBackgroundPaint.setColor(mPastWeekendBackgroundColor);
// Prepare hour separator color paint.
mHourSeparatorPaint = new Paint();
mHourSeparatorPaint.setStyle(Paint.Style.STROKE);
mHourSeparatorPaint.setStrokeWidth(mHourSeparatorHeight);
mHourSeparatorPaint.setColor(mHourSeparatorColor);
// Prepare the "now" line color paint
mNowLinePaint = new Paint();
mNowLinePaint.setStrokeWidth(mNowLineThickness);
mNowLinePaint.setColor(mNowLineColor);
// Prepare today background color paint.
mTodayBackgroundPaint = new Paint();
mTodayBackgroundPaint.setColor(mTodayBackgroundColor);
// Prepare today header text color paint.
mTodayHeaderTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mTodayHeaderTextPaint.setTextAlign(Paint.Align.CENTER);
mTodayHeaderTextPaint.setTextSize(mTextSize);
mTodayHeaderTextPaint.setTypeface(Typeface.DEFAULT_BOLD);
mTodayHeaderTextPaint.setColor(mTodayHeaderTextColor);
// Prepare event background color.
mEventBackgroundPaint = new Paint();
mEventBackgroundPaint.setColor(Color.rgb(174, 208, 238));
// Prepare header column background color.
mHeaderColumnBackgroundPaint = new Paint();
mHeaderColumnBackgroundPaint.setColor(mHeaderColumnBackgroundColor);
// Prepare event text size and color.
mEventTextPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG | Paint.LINEAR_TEXT_FLAG);
mEventTextPaint.setStyle(Paint.Style.FILL);
mEventTextPaint.setColor(mEventTextColor);
mEventTextPaint.setTextSize(mEventTextSize);
// Set default event color.
mDefaultEventColor = Color.parseColor("#9fc6e7");
mScaleDetector = new ScaleGestureDetector(mContext, new ScaleGestureDetector.OnScaleGestureListener() {
@Override
public void onScaleEnd(ScaleGestureDetector detector) {
mIsZooming = false;
}
@Override
public boolean onScaleBegin(ScaleGestureDetector detector) {
mIsZooming = true;
goToNearestOrigin();
return true;
}
@Override
public boolean onScale(ScaleGestureDetector detector) {
mNewHourHeight = Math.round(mHourHeight * detector.getScaleFactor());
invalidate();
return true;
}
});
}
// fix rotation changes
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
mAreDimensionsInvalid = true;
}
/**
* Initialize time column width. Calculate value with all possible hours (supposed widest text).
*/
private void initTextTimeWidth() {
mTimeTextWidth = 0;
for (int i = 0; i < 24; i++) {
// Measure time string and get max width.
String time = getDateTimeInterpreter().interpretTime(i);
if (time == null)
throw new IllegalStateException("A DateTimeInterpreter must not return null time");
mTimeTextWidth = Math.max(mTimeTextWidth, mTimeTextPaint.measureText(time));
}
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// Hide everything in the first cell (top left corner).
canvas.drawRect(0, 0, mTimeTextWidth + mHeaderColumnPadding * 2, mHeaderTextHeight + mHeaderRowPadding * 2, mHeaderBackgroundPaint);
// Draw the header row.
drawHeaderRowAndEvents(canvas);
// Draw the time column and all the axes/separators.
drawTimeColumnAndAxes(canvas);
}
private void drawTimeColumnAndAxes(Canvas canvas) {
// Draw the background color for the header column.
canvas.drawRect(0, mHeaderTextHeight + mHeaderRowPadding * 2, mHeaderColumnWidth, getHeight(), mHeaderColumnBackgroundPaint);
// Clip to paint in left column only.
canvas.clipRect(0, mHeaderTextHeight + mHeaderRowPadding * 2, mHeaderColumnWidth, getHeight(), Region.Op.REPLACE);
for (int i = 0; i < 24; i++) {
float top = mHeaderTextHeight + mHeaderRowPadding * 2 + mCurrentOrigin.y + mHourHeight * i + mHeaderMarginBottom;
// Draw the text if its y position is not outside of the visible area. The pivot point of the text is the point at the bottom-right corner.
String time = getDateTimeInterpreter().interpretTime(i);
if (time == null)
throw new IllegalStateException("A DateTimeInterpreter must not return null time");
if (top < getHeight()) canvas.drawText(time, mTimeTextWidth + mHeaderColumnPadding, top + mTimeTextHeight, mTimeTextPaint);
}
}
private void drawHeaderRowAndEvents(Canvas canvas) {
// Calculate the available width for each day.
mHeaderColumnWidth = mTimeTextWidth + mHeaderColumnPadding *2;
mWidthPerDay = getWidth() - mHeaderColumnWidth - mColumnGap * (mNumberOfVisibleDays - 1);
mWidthPerDay = mWidthPerDay/mNumberOfVisibleDays;
Calendar today = today();
if (mAreDimensionsInvalid) {
mEffectiveMinHourHeight= Math.max(mMinHourHeight, (int) ((getHeight() - mHeaderTextHeight - mHeaderRowPadding * 2 - mHeaderMarginBottom) / 24));
mAreDimensionsInvalid = false;
if(mScrollToDay != null)
goToDate(mScrollToDay);
mAreDimensionsInvalid = false;
if(mScrollToHour >= 0)
goToHour(mScrollToHour);
mScrollToDay = null;
mScrollToHour = -1;
mAreDimensionsInvalid = false;
}
if (mIsFirstDraw){
mIsFirstDraw = false;
// If the week view is being drawn for the first time, then consider the first day of the week.
if(mNumberOfVisibleDays >= 7 && today.get(Calendar.DAY_OF_WEEK) != mFirstDayOfWeek) {
int difference = 7 + (today.get(Calendar.DAY_OF_WEEK) - mFirstDayOfWeek);
mCurrentOrigin.x += (mWidthPerDay + mColumnGap) * difference;
}
}
// Calculate the new height due to the zooming.
if (mNewHourHeight > 0){
if (mNewHourHeight < mEffectiveMinHourHeight)
mNewHourHeight = mEffectiveMinHourHeight;
else if (mNewHourHeight > mMaxHourHeight)
mNewHourHeight = mMaxHourHeight;
mCurrentOrigin.y = (mCurrentOrigin.y/mHourHeight)*mNewHourHeight;
mHourHeight = mNewHourHeight;
mNewHourHeight = -1;
}
// If the new mCurrentOrigin.y is invalid, make it valid.
if (mCurrentOrigin.y < getHeight() - mHourHeight * 24 - mHeaderTextHeight - mHeaderRowPadding * 2 - mHeaderMarginBottom - mTimeTextHeight/2)
mCurrentOrigin.y = getHeight() - mHourHeight * 24 - mHeaderTextHeight - mHeaderRowPadding * 2 - mHeaderMarginBottom - mTimeTextHeight/2;
// Don't put an "else if" because it will trigger a glitch when completely zoomed out and
// scrolling vertically.
if (mCurrentOrigin.y > 0) {
mCurrentOrigin.y = 0;
}
// Consider scroll offset.
int leftDaysWithGaps = (int) -(Math.ceil(mCurrentOrigin.x / (mWidthPerDay + mColumnGap)));
float startFromPixel = mCurrentOrigin.x + (mWidthPerDay + mColumnGap) * leftDaysWithGaps +
mHeaderColumnWidth;
float startPixel = startFromPixel;
// Prepare to iterate for each day.
Calendar day = (Calendar) today.clone();
day.add(Calendar.HOUR, 6);
// Prepare to iterate for each hour to draw the hour lines.
int lineCount = (int) ((getHeight() - mHeaderTextHeight - mHeaderRowPadding * 2 -
mHeaderMarginBottom) / mHourHeight) + 1;
lineCount = (lineCount) * (mNumberOfVisibleDays+1);
float[] hourLines = new float[lineCount * 4];
// Clear the cache for event rectangles.
if (mEventRects != null) {
for (EventRect eventRect: mEventRects) {
eventRect.rectF = null;
}
}
// Clip to paint events only.
canvas.clipRect(mHeaderColumnWidth, mHeaderTextHeight + mHeaderRowPadding * 2 + mHeaderMarginBottom + mTimeTextHeight/2, getWidth(), getHeight(), Region.Op.REPLACE);
// Iterate through each day.
Calendar oldFirstVisibleDay = mFirstVisibleDay;
mFirstVisibleDay = (Calendar) today.clone();
mFirstVisibleDay.add(Calendar.DATE, -(Math.round(mCurrentOrigin.x / (mWidthPerDay + mColumnGap))));
if(!mFirstVisibleDay.equals(oldFirstVisibleDay) && mScrollListener != null){
mScrollListener.onFirstVisibleDayChanged(mFirstVisibleDay, oldFirstVisibleDay);
}
for (int dayNumber = leftDaysWithGaps + 1;
dayNumber <= leftDaysWithGaps + mNumberOfVisibleDays + 1;
dayNumber++) {
// Check if the day is today.
day = (Calendar) today.clone();
mLastVisibleDay = (Calendar) day.clone();
day.add(Calendar.DATE, dayNumber - 1);
mLastVisibleDay.add(Calendar.DATE, dayNumber - 2);
boolean sameDay = isSameDay(day, today);
// Get more events if necessary. We want to store the events 3 months beforehand. Get
// events only when it is the first iteration of the loop.
if (mEventRects == null || mRefreshEvents ||
(dayNumber == leftDaysWithGaps + 1 && mFetchedPeriod != (int) mWeekViewLoader.toWeekViewPeriodIndex(day) &&
Math.abs(mFetchedPeriod - mWeekViewLoader.toWeekViewPeriodIndex(day)) > 0.5)) {
getMoreEvents(day);
mRefreshEvents = false;
}
// Draw background color for each day.
float start = (startPixel < mHeaderColumnWidth ? mHeaderColumnWidth : startPixel);
if (mWidthPerDay + startPixel - start > 0){
if (mShowDistinctPastFutureColor){
boolean isWeekend = day.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY || day.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY;
Paint pastPaint = isWeekend && mShowDistinctWeekendColor ? mPastWeekendBackgroundPaint : mPastBackgroundPaint;
Paint futurePaint = isWeekend && mShowDistinctWeekendColor ? mFutureWeekendBackgroundPaint : mFutureBackgroundPaint;
float startY = mHeaderTextHeight + mHeaderRowPadding * 2 + mTimeTextHeight/2 + mHeaderMarginBottom + mCurrentOrigin.y;
if (sameDay){
Calendar now = Calendar.getInstance();
float beforeNow = (now.get(Calendar.HOUR_OF_DAY) + now.get(Calendar.MINUTE)/60.0f) * mHourHeight;
canvas.drawRect(start, startY, startPixel + mWidthPerDay, startY+beforeNow, pastPaint);
canvas.drawRect(start, startY+beforeNow, startPixel + mWidthPerDay, getHeight(), futurePaint);
}
else if (day.before(today)) {
canvas.drawRect(start, startY, startPixel + mWidthPerDay, getHeight(), pastPaint);
}
else {
canvas.drawRect(start, startY, startPixel + mWidthPerDay, getHeight(), futurePaint);
}
}
else {
canvas.drawRect(start, mHeaderTextHeight + mHeaderRowPadding * 2 + mTimeTextHeight / 2 + mHeaderMarginBottom, startPixel + mWidthPerDay, getHeight(), sameDay ? mTodayBackgroundPaint : mDayBackgroundPaint);
}
}
// Prepare the separator lines for hours.
int i = 0;
for (int hourNumber = 0; hourNumber < 24; hourNumber++) {
float top = mHeaderTextHeight + mHeaderRowPadding * 2 + mCurrentOrigin.y + mHourHeight * hourNumber + mTimeTextHeight/2 + mHeaderMarginBottom;
if (top > mHeaderTextHeight + mHeaderRowPadding * 2 + mTimeTextHeight/2 + mHeaderMarginBottom - mHourSeparatorHeight && top < getHeight() && startPixel + mWidthPerDay - start > 0){
hourLines[i * 4] = start;
hourLines[i * 4 + 1] = top;
hourLines[i * 4 + 2] = startPixel + mWidthPerDay;
hourLines[i * 4 + 3] = top;
i++;
}
}
// Draw the lines for hours.
canvas.drawLines(hourLines, mHourSeparatorPaint);
// Draw the events.
drawEvents(day, startPixel, canvas);
// Draw the line at the current time.
if (mShowNowLine && sameDay){
float startY = mHeaderTextHeight + mHeaderRowPadding * 2 + mTimeTextHeight/2 + mHeaderMarginBottom + mCurrentOrigin.y;
Calendar now = Calendar.getInstance();
float beforeNow = (now.get(Calendar.HOUR_OF_DAY) + now.get(Calendar.MINUTE)/60.0f) * mHourHeight;
canvas.drawLine(start, startY + beforeNow, startPixel + mWidthPerDay, startY + beforeNow, mNowLinePaint);
}
// In the next iteration, start from the next day.
startPixel += mWidthPerDay + mColumnGap;
}
// Clip to paint header row only.
canvas.clipRect(mHeaderColumnWidth, 0, getWidth(), mHeaderTextHeight + mHeaderRowPadding * 2, Region.Op.REPLACE);
// Draw the header background.
canvas.drawRect(0, 0, getWidth(), mHeaderTextHeight + mHeaderRowPadding * 2, mHeaderBackgroundPaint);
// Draw the header row texts.
startPixel = startFromPixel;
for (int dayNumber=leftDaysWithGaps+1; dayNumber <= leftDaysWithGaps + mNumberOfVisibleDays + 1; dayNumber++) {
// Check if the day is today.
day = (Calendar) today.clone();
day.add(Calendar.DATE, dayNumber - 1);
boolean sameDay = isSameDay(day, today);
// Draw the day labels.
String dayLabel = getDateTimeInterpreter().interpretDate(day);
if (dayLabel == null)
throw new IllegalStateException("A DateTimeInterpreter must not return null date");
canvas.drawText(dayLabel, startPixel + mWidthPerDay / 2, mHeaderTextHeight + mHeaderRowPadding, sameDay ? mTodayHeaderTextPaint : mHeaderTextPaint);
startPixel += mWidthPerDay + mColumnGap;
}
}
/**
* Get the time and date where the user clicked on.
* @param x The x position of the touch event.
* @param y The y position of the touch event.
* @return The time and date at the clicked position.
*/
private Calendar getTimeFromPoint(float x, float y){
int leftDaysWithGaps = (int) -(Math.ceil(mCurrentOrigin.x / (mWidthPerDay + mColumnGap)));
float startPixel = mCurrentOrigin.x + (mWidthPerDay + mColumnGap) * leftDaysWithGaps +
mHeaderColumnWidth;
for (int dayNumber = leftDaysWithGaps + 1;
dayNumber <= leftDaysWithGaps + mNumberOfVisibleDays + 1;
dayNumber++) {
float start = (startPixel < mHeaderColumnWidth ? mHeaderColumnWidth : startPixel);
if (mWidthPerDay + startPixel - start > 0 && x > start && x < startPixel + mWidthPerDay){
Calendar day = today();
day.add(Calendar.DATE, dayNumber - 1);
float pixelsFromZero = y - mCurrentOrigin.y - mHeaderTextHeight
- mHeaderRowPadding * 2 - mTimeTextHeight/2 - mHeaderMarginBottom;
int hour = (int)(pixelsFromZero / mHourHeight);
int minute = (int) (60 * (pixelsFromZero - hour * mHourHeight) / mHourHeight);
day.add(Calendar.HOUR, hour);
day.set(Calendar.MINUTE, minute);
return day;
}
startPixel += mWidthPerDay + mColumnGap;
}
return null;
}
/**
* Draw all the events of a particular day.
* @param date The day.
* @param startFromPixel The left position of the day area. The events will never go any left from this value.
* @param canvas The canvas to draw upon.
*/
private void drawEvents(Calendar date, float startFromPixel, Canvas canvas) {
if (mEventRects != null && mEventRects.size() > 0) {
for (int i = 0; i < mEventRects.size(); i++) {
if (isSameDay(mEventRects.get(i).event.getStartTime(), date)) {
// Calculate top.
float top = mHourHeight * 24 * mEventRects.get(i).top / 1440 + mCurrentOrigin.y + mHeaderTextHeight + mHeaderRowPadding * 2 + mHeaderMarginBottom + mTimeTextHeight/2 + mEventMarginVertical;
// Calculate bottom.
float bottom = mEventRects.get(i).bottom;
bottom = mHourHeight * 24 * bottom / 1440 + mCurrentOrigin.y + mHeaderTextHeight + mHeaderRowPadding * 2 + mHeaderMarginBottom + mTimeTextHeight/2 - mEventMarginVertical;
// Calculate left and right.
float left = startFromPixel + mEventRects.get(i).left * mWidthPerDay;
if (left < startFromPixel)
left += mOverlappingEventGap;
float right = left + mEventRects.get(i).width * mWidthPerDay;
if (right < startFromPixel + mWidthPerDay)
right -= mOverlappingEventGap;
// Draw the event and the event name on top of it.
if (left < right &&
left < getWidth() &&
top < getHeight() &&
right > mHeaderColumnWidth &&
bottom > mHeaderTextHeight + mHeaderRowPadding * 2 + mTimeTextHeight / 2 + mHeaderMarginBottom
) {
mEventRects.get(i).rectF = new RectF(left, top, right, bottom);
mEventBackgroundPaint.setColor(mEventRects.get(i).event.getColor() == 0 ? mDefaultEventColor : mEventRects.get(i).event.getColor());
canvas.drawRoundRect(mEventRects.get(i).rectF, mEventCornerRadius, mEventCornerRadius, mEventBackgroundPaint);
drawEventTitle(mEventRects.get(i).event, mEventRects.get(i).rectF, canvas, top, left);
}
else
mEventRects.get(i).rectF = null;
}
}
}
}
/**
* Draw the name of the event on top of the event rectangle.
* @param event The event of which the title (and location) should be drawn.
* @param rect The rectangle on which the text is to be drawn.
* @param canvas The canvas to draw upon.
* @param originalTop The original top position of the rectangle. The rectangle may have some of its portion outside of the visible area.
* @param originalLeft The original left position of the rectangle. The rectangle may have some of its portion outside of the visible area.
*/
private void drawEventTitle(WeekViewEvent event, RectF rect, Canvas canvas, float originalTop, float originalLeft) {
if (rect.right - rect.left - mEventPadding * 2 < 0) return;
if (rect.bottom - rect.top - mEventPadding * 2 < 0) return;
// Prepare the name of the event.
SpannableStringBuilder bob = new SpannableStringBuilder();
if (event.getName() != null) {
bob.append(event.getName());
bob.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 0, bob.length(), 0);
bob.append(' ');
}
// Prepare the location of the event.
if (event.getLocation() != null) {
bob.append(event.getLocation());
}
int availableHeight = (int) (rect.bottom - originalTop - mEventPadding * 2);
int availableWidth = (int) (rect.right - originalLeft - mEventPadding * 2);
// Get text dimensions.
StaticLayout textLayout = new StaticLayout(bob, mEventTextPaint, availableWidth, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
int lineHeight = textLayout.getHeight() / textLayout.getLineCount();
if (availableHeight >= lineHeight) {
// Calculate available number of line counts.
int availableLineCount = availableHeight / lineHeight;
do {
// Ellipsize text to fit into event rect.
textLayout = new StaticLayout(TextUtils.ellipsize(bob, mEventTextPaint, availableLineCount * availableWidth, TextUtils.TruncateAt.END), mEventTextPaint, (int) (rect.right - originalLeft - mEventPadding * 2), Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
// Reduce line count.
availableLineCount
// Repeat until text is short enough.
} while (textLayout.getHeight() > availableHeight);
// Draw text.
canvas.save();
canvas.translate(originalLeft + mEventPadding, originalTop + mEventPadding);
textLayout.draw(canvas);
canvas.restore();
}
}
/**
* A class to hold reference to the events and their visual representation. An EventRect is
* actually the rectangle that is drawn on the calendar for a given event. There may be more
* than one rectangle for a single event (an event that expands more than one day). In that
* case two instances of the EventRect will be used for a single event. The given event will be
* stored in "originalEvent". But the event that corresponds to rectangle the rectangle
* instance will be stored in "event".
*/
private class EventRect {
public WeekViewEvent event;
public WeekViewEvent originalEvent;
public RectF rectF;
public float left;
public float width;
public float top;
public float bottom;
/**
* Create a new instance of event rect. An EventRect is actually the rectangle that is drawn
* on the calendar for a given event. There may be more than one rectangle for a single
* event (an event that expands more than one day). In that case two instances of the
* EventRect will be used for a single event. The given event will be stored in
* "originalEvent". But the event that corresponds to rectangle the rectangle instance will
* be stored in "event".
* @param event Represents the event which this instance of rectangle represents.
* @param originalEvent The original event that was passed by the user.
* @param rectF The rectangle.
*/
public EventRect(WeekViewEvent event, WeekViewEvent originalEvent, RectF rectF) {
this.event = event;
this.rectF = rectF;
this.originalEvent = originalEvent;
}
}
/**
* Gets more events of one/more month(s) if necessary. This method is called when the user is
* scrolling the week view. The week view stores the events of three months: the visible month,
* the previous month, the next month.
* @param day The day where the user is currently is.
*/
private void getMoreEvents(Calendar day) {
// Get more events if the month is changed.
if (mEventRects == null)
mEventRects = new ArrayList<EventRect>();
if (mWeekViewLoader == null && !isInEditMode())
throw new IllegalStateException("You must provide a MonthChangeListener");
// If a refresh was requested then reset some variables.
if (mRefreshEvents) {
mEventRects.clear();
mPreviousPeriodEvents = null;
mCurrentPeriodEvents = null;
mNextPeriodEvents = null;
mFetchedPeriod = -1;
}
if (mWeekViewLoader != null){
int periodToFetch = (int) mWeekViewLoader.toWeekViewPeriodIndex(day);
if (!isInEditMode() && (mFetchedPeriod < 0 || mFetchedPeriod != periodToFetch || mRefreshEvents)) {
List<? extends WeekViewEvent> previousPeriodEvents = null;
List<? extends WeekViewEvent> currentPeriodEvents = null;
List<? extends WeekViewEvent> nextPeriodEvents = null;
if (mPreviousPeriodEvents != null && mCurrentPeriodEvents != null && mNextPeriodEvents != null){
if (periodToFetch == mFetchedPeriod-1){
currentPeriodEvents = mPreviousPeriodEvents;
nextPeriodEvents = mCurrentPeriodEvents;
}
else if (periodToFetch == mFetchedPeriod){
previousPeriodEvents = mPreviousPeriodEvents;
currentPeriodEvents = mCurrentPeriodEvents;
nextPeriodEvents = mNextPeriodEvents;
}
else if (periodToFetch == mFetchedPeriod+1){
previousPeriodEvents = mCurrentPeriodEvents;
currentPeriodEvents = mNextPeriodEvents;
}
}
if (currentPeriodEvents == null)
currentPeriodEvents = mWeekViewLoader.onLoad(periodToFetch);
if (previousPeriodEvents == null)
previousPeriodEvents = mWeekViewLoader.onLoad(periodToFetch-1);
if (nextPeriodEvents == null)
nextPeriodEvents = mWeekViewLoader.onLoad(periodToFetch+1);
// Clear events.
mEventRects.clear();
sortAndCacheEvents(previousPeriodEvents);
sortAndCacheEvents(currentPeriodEvents);
sortAndCacheEvents(nextPeriodEvents);
mPreviousPeriodEvents = previousPeriodEvents;
mCurrentPeriodEvents = currentPeriodEvents;
mNextPeriodEvents = nextPeriodEvents;
mFetchedPeriod = periodToFetch;
}
}
// Prepare to calculate positions of each events.
List<EventRect> tempEvents = mEventRects;
mEventRects = new ArrayList<EventRect>();
// Iterate through each day with events to calculate the position of the events.
while (tempEvents.size() > 0) {
ArrayList<EventRect> eventRects = new ArrayList<>(tempEvents.size());
// Get first event for a day.
EventRect eventRect1 = tempEvents.remove(0);
eventRects.add(eventRect1);
int i = 0;
while (i < tempEvents.size()) {
// Collect all other events for same day.
EventRect eventRect2 = tempEvents.get(i);
if (isSameDay(eventRect1.event.getStartTime(), eventRect2.event.getStartTime())) {
tempEvents.remove(i);
eventRects.add(eventRect2);
} else {
i++;
}
}
computePositionOfEvents(eventRects);
}
}
/**
* Cache the event for smooth scrolling functionality.
* @param event The event to cache.
*/
private void cacheEvent(WeekViewEvent event) {
if(event.getStartTime().compareTo(event.getEndTime()) >= 0)
return;
if (!isSameDay(event.getStartTime(), event.getEndTime())) {
// Add first day.
Calendar endTime = (Calendar) event.getStartTime().clone();
endTime.set(Calendar.HOUR_OF_DAY, 23);
endTime.set(Calendar.MINUTE, 59);
WeekViewEvent event1 = new WeekViewEvent(event.getId(), event.getName(), event.getLocation(), event.getStartTime(), endTime);
event1.setColor(event.getColor());
mEventRects.add(new EventRect(event1, event, null));
// Add other days.
Calendar otherDay = (Calendar) event.getStartTime().clone();
otherDay.add(Calendar.DATE, 1);
while (!isSameDay(otherDay, event.getEndTime())) {
Calendar overDay = (Calendar) otherDay.clone();
overDay.set(Calendar.HOUR_OF_DAY, 0);
overDay.set(Calendar.MINUTE, 0);
Calendar endOfOverDay = (Calendar) overDay.clone();
endOfOverDay.set(Calendar.HOUR_OF_DAY, 23);
endOfOverDay.set(Calendar.MINUTE, 59);
WeekViewEvent eventMore = new WeekViewEvent(event.getId(), event.getName(), overDay, endOfOverDay);
eventMore.setColor(event.getColor());
mEventRects.add(new EventRect(eventMore, event, null));
// Add next day.
otherDay.add(Calendar.DATE, 1);
}
// Add last day.
Calendar startTime = (Calendar) event.getEndTime().clone();
startTime.set(Calendar.HOUR_OF_DAY, 0);
startTime.set(Calendar.MINUTE, 0);
WeekViewEvent event2 = new WeekViewEvent(event.getId(), event.getName(), event.getLocation(), startTime, event.getEndTime());
event2.setColor(event.getColor());
mEventRects.add(new EventRect(event2, event, null));
}
else {
mEventRects.add(new EventRect(event, event, null));
}
}
/**
* Sort and cache events.
* @param events The events to be sorted and cached.
*/
private void sortAndCacheEvents(List<? extends WeekViewEvent> events) {
sortEvents(events);
for (WeekViewEvent event : events) {
cacheEvent(event);
}
}
/**
* Sorts the events in ascending order.
* @param events The events to be sorted.
*/
private void sortEvents(List<? extends WeekViewEvent> events) {
Collections.sort(events, new Comparator<WeekViewEvent>() {
@Override
public int compare(WeekViewEvent event1, WeekViewEvent event2) {
long start1 = event1.getStartTime().getTimeInMillis();
long start2 = event2.getStartTime().getTimeInMillis();
int comparator = start1 > start2 ? 1 : (start1 < start2 ? -1 : 0);
if (comparator == 0) {
long end1 = event1.getEndTime().getTimeInMillis();
long end2 = event2.getEndTime().getTimeInMillis();
comparator = end1 > end2 ? 1 : (end1 < end2 ? -1 : 0);
}
return comparator;
}
});
}
/**
* Calculates the left and right positions of each events. This comes handy specially if events
* are overlapping.
* @param eventRects The events along with their wrapper class.
*/
private void computePositionOfEvents(List<EventRect> eventRects) {
// Make "collision groups" for all events that collide with others.
List<List<EventRect>> collisionGroups = new ArrayList<List<EventRect>>();
for (EventRect eventRect : eventRects) {
boolean isPlaced = false;
outerLoop:
for (List<EventRect> collisionGroup : collisionGroups) {
for (EventRect groupEvent : collisionGroup) {
if (isEventsCollide(groupEvent.event, eventRect.event)) {
collisionGroup.add(eventRect);
isPlaced = true;
break outerLoop;
}
}
}
if (!isPlaced) {
List<EventRect> newGroup = new ArrayList<EventRect>();
newGroup.add(eventRect);
collisionGroups.add(newGroup);
}
}
for (List<EventRect> collisionGroup : collisionGroups) {
expandEventsToMaxWidth(collisionGroup);
}
}
/**
* Expands all the events to maximum possible width. The events will try to occupy maximum
* space available horizontally.
* @param collisionGroup The group of events which overlap with each other.
*/
private void expandEventsToMaxWidth(List<EventRect> collisionGroup) {
// Expand the events to maximum possible width.
List<List<EventRect>> columns = new ArrayList<List<EventRect>>();
columns.add(new ArrayList<EventRect>());
for (EventRect eventRect : collisionGroup) {
boolean isPlaced = false;
for (List<EventRect> column : columns) {
if (column.size() == 0) {
column.add(eventRect);
isPlaced = true;
}
else if (!isEventsCollide(eventRect.event, column.get(column.size()-1).event)) {
column.add(eventRect);
isPlaced = true;
break;
}
}
if (!isPlaced) {
List<EventRect> newColumn = new ArrayList<EventRect>();
newColumn.add(eventRect);
columns.add(newColumn);
}
}
// Calculate left and right position for all the events.
// Get the maxRowCount by looking in all columns.
int maxRowCount = 0;
for (List<EventRect> column : columns){
maxRowCount = Math.max(maxRowCount, column.size());
}
for (int i = 0; i < maxRowCount; i++) {
// Set the left and right values of the event.
float j = 0;
for (List<EventRect> column : columns) {
if (column.size() >= i+1) {
EventRect eventRect = column.get(i);
eventRect.width = 1f / columns.size();
eventRect.left = j / columns.size();
eventRect.top = eventRect.event.getStartTime().get(Calendar.HOUR_OF_DAY) * 60 + eventRect.event.getStartTime().get(Calendar.MINUTE);
eventRect.bottom = eventRect.event.getEndTime().get(Calendar.HOUR_OF_DAY) * 60 + eventRect.event.getEndTime().get(Calendar.MINUTE);
mEventRects.add(eventRect);
}
j++;
}
}
}
/**
* Checks if two events overlap.
* @param event1 The first event.
* @param event2 The second event.
* @return true if the events overlap.
*/
private boolean isEventsCollide(WeekViewEvent event1, WeekViewEvent event2) {
long start1 = event1.getStartTime().getTimeInMillis();
long end1 = event1.getEndTime().getTimeInMillis();
long start2 = event2.getStartTime().getTimeInMillis();
long end2 = event2.getEndTime().getTimeInMillis();
return !((start1 >= end2) || (end1 <= start2));
}
/**
* Checks if time1 occurs after (or at the same time) time2.
* @param time1 The time to check.
* @param time2 The time to check against.
* @return true if time1 and time2 are equal or if time1 is after time2. Otherwise false.
*/
private boolean isTimeAfterOrEquals(Calendar time1, Calendar time2) {
return !(time1 == null || time2 == null) && time1.getTimeInMillis() >= time2.getTimeInMillis();
}
@Override
public void invalidate() {
super.invalidate();
mAreDimensionsInvalid = true;
}
// Functions related to setting and getting the properties.
public void setOnEventClickListener (EventClickListener listener) {
this.mEventClickListener = listener;
}
public EventClickListener getEventClickListener() {
return mEventClickListener;
}
public @Nullable MonthLoader.MonthChangeListener getMonthChangeListener() {
if (mWeekViewLoader instanceof MonthLoader)
return ((MonthLoader) mWeekViewLoader).getOnMonthChangeListener();
return null;
}
public void setMonthChangeListener(MonthLoader.MonthChangeListener monthChangeListener) {
this.mWeekViewLoader = new MonthLoader(monthChangeListener);
}
/**
* Get event loader in the week view. Event loaders define the interval after which the events
* are loaded in week view. For a MonthLoader events are loaded for every month. You can define
* your custom event loader by extending WeekViewLoader.
* @return The event loader.
*/
public WeekViewLoader getWeekViewLoader(){
return mWeekViewLoader;
}
/**
* Set event loader in the week view. For example, a MonthLoader. Event loaders define the
* interval after which the events are loaded in week view. For a MonthLoader events are loaded
* for every month. You can define your custom event loader by extending WeekViewLoader.
* @param loader The event loader.
*/
public void setWeekViewLoader(WeekViewLoader loader){
this.mWeekViewLoader = loader;
}
public EventLongPressListener getEventLongPressListener() {
return mEventLongPressListener;
}
public void setEventLongPressListener(EventLongPressListener eventLongPressListener) {
this.mEventLongPressListener = eventLongPressListener;
}
public void setEmptyViewClickListener(EmptyViewClickListener emptyViewClickListener){
this.mEmptyViewClickListener = emptyViewClickListener;
}
public EmptyViewClickListener getEmptyViewClickListener(){
return mEmptyViewClickListener;
}
public void setEmptyViewLongPressListener(EmptyViewLongPressListener emptyViewLongPressListener){
this.mEmptyViewLongPressListener = emptyViewLongPressListener;
}
public EmptyViewLongPressListener getEmptyViewLongPressListener(){
return mEmptyViewLongPressListener;
}
public void setScrollListener(ScrollListener scrolledListener){
this.mScrollListener = scrolledListener;
}
public ScrollListener getScrollListener(){
return mScrollListener;
}
/**
* Get the interpreter which provides the text to show in the header column and the header row.
* @return The date, time interpreter.
*/
public DateTimeInterpreter getDateTimeInterpreter() {
if (mDateTimeInterpreter == null) {
mDateTimeInterpreter = new DateTimeInterpreter() {
@Override
public String interpretDate(Calendar date) {
try {
SimpleDateFormat sdf = mDayNameLength == LENGTH_SHORT ? new SimpleDateFormat("EEEEE M/dd", Locale.getDefault()) : new SimpleDateFormat("EEE M/dd", Locale.getDefault());
return sdf.format(date.getTime()).toUpperCase();
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
@Override
public String interpretTime(int hour) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, hour);
calendar.set(Calendar.MINUTE, 0);
try {
SimpleDateFormat sdf = DateFormat.is24HourFormat(getContext()) ? new SimpleDateFormat("HH:mm", Locale.getDefault()) : new SimpleDateFormat("hh a", Locale.getDefault());
return sdf.format(calendar.getTime());
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
};
}
return mDateTimeInterpreter;
}
/**
* Set the interpreter which provides the text to show in the header column and the header row.
* @param dateTimeInterpreter The date, time interpreter.
*/
public void setDateTimeInterpreter(DateTimeInterpreter dateTimeInterpreter){
this.mDateTimeInterpreter = dateTimeInterpreter;
// Refresh time column width.
initTextTimeWidth();
}
/**
* Get the number of visible days in a week.
* @return The number of visible days in a week.
*/
public int getNumberOfVisibleDays() {
return mNumberOfVisibleDays;
}
/**
* Set the number of visible days in a week.
* @param numberOfVisibleDays The number of visible days in a week.
*/
public void setNumberOfVisibleDays(int numberOfVisibleDays) {
this.mNumberOfVisibleDays = numberOfVisibleDays;
mCurrentOrigin.x = 0;
mCurrentOrigin.y = 0;
invalidate();
}
public int getHourHeight() {
return mHourHeight;
}
public void setHourHeight(int hourHeight) {
mNewHourHeight = hourHeight;
invalidate();
}
public int getColumnGap() {
return mColumnGap;
}
public void setColumnGap(int columnGap) {
mColumnGap = columnGap;
invalidate();
}
public int getFirstDayOfWeek() {
return mFirstDayOfWeek;
}
/**
* Set the first day of the week. First day of the week is used only when the week view is first
* drawn. It does not of any effect after user starts scrolling horizontally.
* <p>
* <b>Note:</b> This method will only work if the week view is set to display more than 6 days at
* once.
* </p>
* @param firstDayOfWeek The supported values are {@link java.util.Calendar#SUNDAY},
* {@link java.util.Calendar#MONDAY}, {@link java.util.Calendar#TUESDAY},
* {@link java.util.Calendar#WEDNESDAY}, {@link java.util.Calendar#THURSDAY},
* {@link java.util.Calendar#FRIDAY}.
*/
public void setFirstDayOfWeek(int firstDayOfWeek) {
mFirstDayOfWeek = firstDayOfWeek;
invalidate();
}
public int getTextSize() {
return mTextSize;
}
public void setTextSize(int textSize) {
mTextSize = textSize;
mTodayHeaderTextPaint.setTextSize(mTextSize);
mHeaderTextPaint.setTextSize(mTextSize);
mTimeTextPaint.setTextSize(mTextSize);
invalidate();
}
public int getHeaderColumnPadding() {
return mHeaderColumnPadding;
}
public void setHeaderColumnPadding(int headerColumnPadding) {
mHeaderColumnPadding = headerColumnPadding;
invalidate();
}
public int getHeaderColumnTextColor() {
return mHeaderColumnTextColor;
}
public void setHeaderColumnTextColor(int headerColumnTextColor) {
mHeaderColumnTextColor = headerColumnTextColor;
mHeaderTextPaint.setColor(mHeaderColumnTextColor);
mTimeTextPaint.setColor(mHeaderColumnTextColor);
invalidate();
}
public int getHeaderRowPadding() {
return mHeaderRowPadding;
}
public void setHeaderRowPadding(int headerRowPadding) {
mHeaderRowPadding = headerRowPadding;
invalidate();
}
public int getHeaderRowBackgroundColor() {
return mHeaderRowBackgroundColor;
}
public void setHeaderRowBackgroundColor(int headerRowBackgroundColor) {
mHeaderRowBackgroundColor = headerRowBackgroundColor;
mHeaderBackgroundPaint.setColor(mHeaderRowBackgroundColor);
invalidate();
}
public int getDayBackgroundColor() {
return mDayBackgroundColor;
}
public void setDayBackgroundColor(int dayBackgroundColor) {
mDayBackgroundColor = dayBackgroundColor;
mDayBackgroundPaint.setColor(mDayBackgroundColor);
invalidate();
}
public int getHourSeparatorColor() {
return mHourSeparatorColor;
}
public void setHourSeparatorColor(int hourSeparatorColor) {
mHourSeparatorColor = hourSeparatorColor;
mHourSeparatorPaint.setColor(mHourSeparatorColor);
invalidate();
}
public int getTodayBackgroundColor() {
return mTodayBackgroundColor;
}
public void setTodayBackgroundColor(int todayBackgroundColor) {
mTodayBackgroundColor = todayBackgroundColor;
mTodayBackgroundPaint.setColor(mTodayBackgroundColor);
invalidate();
}
public int getHourSeparatorHeight() {
return mHourSeparatorHeight;
}
public void setHourSeparatorHeight(int hourSeparatorHeight) {
mHourSeparatorHeight = hourSeparatorHeight;
mHourSeparatorPaint.setStrokeWidth(mHourSeparatorHeight);
invalidate();
}
public int getTodayHeaderTextColor() {
return mTodayHeaderTextColor;
}
public void setTodayHeaderTextColor(int todayHeaderTextColor) {
mTodayHeaderTextColor = todayHeaderTextColor;
mTodayHeaderTextPaint.setColor(mTodayHeaderTextColor);
invalidate();
}
public int getEventTextSize() {
return mEventTextSize;
}
public void setEventTextSize(int eventTextSize) {
mEventTextSize = eventTextSize;
mEventTextPaint.setTextSize(mEventTextSize);
invalidate();
}
public int getEventTextColor() {
return mEventTextColor;
}
public void setEventTextColor(int eventTextColor) {
mEventTextColor = eventTextColor;
mEventTextPaint.setColor(mEventTextColor);
invalidate();
}
public int getEventPadding() {
return mEventPadding;
}
public void setEventPadding(int eventPadding) {
mEventPadding = eventPadding;
invalidate();
}
public int getHeaderColumnBackgroundColor() {
return mHeaderColumnBackgroundColor;
}
public void setHeaderColumnBackgroundColor(int headerColumnBackgroundColor) {
mHeaderColumnBackgroundColor = headerColumnBackgroundColor;
mHeaderColumnBackgroundPaint.setColor(mHeaderColumnBackgroundColor);
invalidate();
}
public int getDefaultEventColor() {
return mDefaultEventColor;
}
public void setDefaultEventColor(int defaultEventColor) {
mDefaultEventColor = defaultEventColor;
invalidate();
}
/**
* <b>Note:</b> Use {@link #setDateTimeInterpreter(DateTimeInterpreter)} and
* {@link #getDateTimeInterpreter()} instead.
* @return Either long or short day name is being used.
*/
@Deprecated
public int getDayNameLength() {
return mDayNameLength;
}
/**
* Set the length of the day name displayed in the header row. Example of short day names is
* 'M' for 'Monday' and example of long day names is 'Mon' for 'Monday'.
* <p>
* <b>Note:</b> Use {@link #setDateTimeInterpreter(DateTimeInterpreter)} instead.
* </p>
* @param length Supported values are {@link com.alamkanak.weekview.WeekView#LENGTH_SHORT} and
* {@link com.alamkanak.weekview.WeekView#LENGTH_LONG}.
*/
@Deprecated
public void setDayNameLength(int length) {
if (length != LENGTH_LONG && length != LENGTH_SHORT) {
throw new IllegalArgumentException("length parameter must be either LENGTH_LONG or LENGTH_SHORT");
}
this.mDayNameLength = length;
}
public int getOverlappingEventGap() {
return mOverlappingEventGap;
}
/**
* Set the gap between overlapping events.
* @param overlappingEventGap The gap between overlapping events.
*/
public void setOverlappingEventGap(int overlappingEventGap) {
this.mOverlappingEventGap = overlappingEventGap;
invalidate();
}
public int getEventCornerRadius() {
return mEventCornerRadius;
}
/**
* Set corner radius for event rect.
*
* @param eventCornerRadius the radius in px.
*/
public void setEventCornerRadius(int eventCornerRadius) {
mEventCornerRadius = eventCornerRadius;
}
public int getEventMarginVertical() {
return mEventMarginVertical;
}
/**
* Set the top and bottom margin of the event. The event will release this margin from the top
* and bottom edge. This margin is useful for differentiation consecutive events.
* @param eventMarginVertical The top and bottom margin.
*/
public void setEventMarginVertical(int eventMarginVertical) {
this.mEventMarginVertical = eventMarginVertical;
invalidate();
}
/**
* Returns the first visible day in the week view.
* @return The first visible day in the week view.
*/
public Calendar getFirstVisibleDay() {
return mFirstVisibleDay;
}
/**
* Returns the last visible day in the week view.
* @return The last visible day in the week view.
*/
public Calendar getLastVisibleDay() {
return mLastVisibleDay;
}
/**
* Get the scrolling speed factor in horizontal direction.
* @return The speed factor in horizontal direction.
*/
public float getXScrollingSpeed() {
return mXScrollingSpeed;
}
/**
* Sets the speed for horizontal scrolling.
* @param xScrollingSpeed The new horizontal scrolling speed.
*/
public void setXScrollingSpeed(float xScrollingSpeed) {
this.mXScrollingSpeed = xScrollingSpeed;
}
/**
* Whether weekends should have a background color different from the normal day background
* color. The weekend background colors are defined by the attributes
* `futureWeekendBackgroundColor` and `pastWeekendBackgroundColor`.
* @return True if weekends should have different background colors.
*/
public boolean isShowDistinctWeekendColor() {
return mShowDistinctWeekendColor;
}
/**
* Set whether weekends should have a background color different from the normal day background
* color. The weekend background colors are defined by the attributes
* `futureWeekendBackgroundColor` and `pastWeekendBackgroundColor`.
* @param showDistinctWeekendColor True if weekends should have different background colors.
*/
public void setShowDistinctWeekendColor(boolean showDistinctWeekendColor) {
this.mShowDistinctWeekendColor = showDistinctWeekendColor;
invalidate();
}
/**
* Whether past and future days should have two different background colors. The past and
* future day colors are defined by the attributes `futureBackgroundColor` and
* `pastBackgroundColor`.
* @return True if past and future days should have two different background colors.
*/
public boolean isShowDistinctPastFutureColor() {
return mShowDistinctPastFutureColor;
}
/**
* Set whether weekends should have a background color different from the normal day background
* color. The past and future day colors are defined by the attributes `futureBackgroundColor`
* and `pastBackgroundColor`.
* @param showDistinctPastFutureColor True if past and future should have two different
* background colors.
*/
public void setShowDistinctPastFutureColor(boolean showDistinctPastFutureColor) {
this.mShowDistinctPastFutureColor = showDistinctPastFutureColor;
invalidate();
}
/**
* Get whether "now" line should be displayed. "Now" line is defined by the attributes
* `nowLineColor` and `nowLineThickness`.
* @return True if "now" line should be displayed.
*/
public boolean isShowNowLine() {
return mShowNowLine;
}
/**
* Set whether "now" line should be displayed. "Now" line is defined by the attributes
* `nowLineColor` and `nowLineThickness`.
* @param showNowLine True if "now" line should be displayed.
*/
public void setShowNowLine(boolean showNowLine) {
this.mShowNowLine = showNowLine;
invalidate();
}
/**
* Get the "now" line color.
* @return The color of the "now" line.
*/
public int getNowLineColor() {
return mNowLineColor;
}
/**
* Set the "now" line color.
* @param nowLineColor The color of the "now" line.
*/
public void setNowLineColor(int nowLineColor) {
this.mNowLineColor = nowLineColor;
invalidate();
}
/**
* Get the "now" line thickness.
* @return The thickness of the "now" line.
*/
public int getNowLineThickness() {
return mNowLineThickness;
}
/**
* Set the "now" line thickness.
* @param nowLineThickness The thickness of the "now" line.
*/
public void setNowLineThickness(int nowLineThickness) {
this.mNowLineThickness = nowLineThickness;
invalidate();
}
public boolean isHorizontalFlingEnabled() {
return mHorizontalFlingEnabled;
}
public void setHorizontalFlingEnabled(boolean enabled) {
mHorizontalFlingEnabled = enabled;
}
public boolean isVerticalFlingEnabled() {
return mVerticalFlingEnabled;
}
public void setVerticalFlingEnabled(boolean enabled) {
mVerticalFlingEnabled = enabled;
}
// Functions related to scrolling.
@Override
public boolean onTouchEvent(MotionEvent event) {
mScaleDetector.onTouchEvent(event);
boolean val = mGestureDetector.onTouchEvent(event);
// Check after call of mGestureDetector, so mCurrentFlingDirection and mCurrentScrollDirection are set.
if (event.getAction() == MotionEvent.ACTION_UP && !mIsZooming && mCurrentFlingDirection == Direction.NONE) {
if (mCurrentScrollDirection == Direction.RIGHT || mCurrentScrollDirection == Direction.LEFT) {
goToNearestOrigin();
}
mCurrentScrollDirection = Direction.NONE;
}
return val;
}
private void goToNearestOrigin(){
double leftDays = mCurrentOrigin.x / (mWidthPerDay + mColumnGap);
if (mCurrentFlingDirection != Direction.NONE) {
// snap to nearest day
leftDays = Math.round(leftDays);
} else if (mCurrentScrollDirection == Direction.LEFT) {
// snap to last day
leftDays = Math.floor(leftDays);
} else if (mCurrentScrollDirection == Direction.RIGHT) {
// snap to next day
leftDays = Math.ceil(leftDays);
} else {
// snap to nearest day
leftDays = Math.round(leftDays);
}
int nearestOrigin = (int) (mCurrentOrigin.x - leftDays * (mWidthPerDay + mColumnGap));
if (nearestOrigin != 0) {
// Stop current animation.
mScroller.forceFinished(true);
// Snap to date.
mScroller.startScroll((int) mCurrentOrigin.x, (int) mCurrentOrigin.y, -nearestOrigin, 0, (int) (Math.abs(nearestOrigin) / mWidthPerDay * 500));
ViewCompat.postInvalidateOnAnimation(WeekView.this);
}
// Reset scrolling and fling direction.
mCurrentScrollDirection = mCurrentFlingDirection = Direction.NONE;
}
@Override
public void computeScroll() {
super.computeScroll();
if (mScroller.isFinished()) {
if (mCurrentFlingDirection != Direction.NONE) {
// Snap to day after fling is finished.
goToNearestOrigin();
}
} else {
if (mCurrentFlingDirection != Direction.NONE && forceFinishScroll()) {
goToNearestOrigin();
} else if (mScroller.computeScrollOffset()) {
mCurrentOrigin.y = mScroller.getCurrY();
mCurrentOrigin.x = mScroller.getCurrX();
ViewCompat.postInvalidateOnAnimation(this);
}
}
}
/**
* Check if scrolling should be stopped.
* @return true if scrolling should be stopped before reaching the end of animation.
*/
private boolean forceFinishScroll() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
// current velocity only available since api 14
return mScroller.getCurrVelocity() <= mMinimumFlingVelocity;
} else {
return false;
}
}
// Public methods.
/**
* Show today on the week view.
*/
public void goToToday() {
Calendar today = Calendar.getInstance();
goToDate(today);
}
/**
* Show a specific day on the week view.
* @param date The date to show.
*/
public void goToDate(Calendar date) {
mScroller.forceFinished(true);
mCurrentScrollDirection = mCurrentFlingDirection = Direction.NONE;
date.set(Calendar.HOUR_OF_DAY, 0);
date.set(Calendar.MINUTE, 0);
date.set(Calendar.SECOND, 0);
date.set(Calendar.MILLISECOND, 0);
if(mAreDimensionsInvalid) {
mScrollToDay = date;
return;
}
mRefreshEvents = true;
Calendar today = Calendar.getInstance();
today.set(Calendar.HOUR_OF_DAY, 0);
today.set(Calendar.MINUTE, 0);
today.set(Calendar.SECOND, 0);
today.set(Calendar.MILLISECOND, 0);
long day = 1000L * 60L * 60L * 24L;
long dateInMillis = date.getTimeInMillis() + date.getTimeZone().getOffset(date.getTimeInMillis());
long todayInMillis = today.getTimeInMillis() + today.getTimeZone().getOffset(today.getTimeInMillis());
long dateDifference = (dateInMillis/day) - (todayInMillis/day);
mCurrentOrigin.x = - dateDifference * (mWidthPerDay + mColumnGap);
invalidate();
}
/**
* Refreshes the view and loads the events again.
*/
public void notifyDatasetChanged(){
mRefreshEvents = true;
invalidate();
}
/**
* Vertically scroll to a specific hour in the week view.
* @param hour The hour to scroll to in 24-hour format. Supported values are 0-24.
*/
public void goToHour(double hour){
if (mAreDimensionsInvalid) {
mScrollToHour = hour;
return;
}
int verticalOffset = 0;
if (hour > 24)
verticalOffset = mHourHeight * 24;
else if (hour > 0)
verticalOffset = (int) (mHourHeight * hour);
if (verticalOffset > mHourHeight * 24 - getHeight() + mHeaderTextHeight + mHeaderRowPadding * 2 + mHeaderMarginBottom)
verticalOffset = (int)(mHourHeight * 24 - getHeight() + mHeaderTextHeight + mHeaderRowPadding * 2 + mHeaderMarginBottom);
mCurrentOrigin.y = -verticalOffset;
invalidate();
}
/**
* Get the first hour that is visible on the screen.
* @return The first hour that is visible.
*/
public double getFirstVisibleHour(){
return -mCurrentOrigin.y / mHourHeight;
}
// Interfaces.
public interface EventClickListener {
/**
* Triggered when clicked on one existing event
* @param event: event clicked.
* @param eventRect: view containing the clicked event.
*/
void onEventClick(WeekViewEvent event, RectF eventRect);
}
public interface EventLongPressListener {
/**
* Similar to {@link com.alamkanak.weekview.WeekView.EventClickListener} but with a long press.
* @param event: event clicked.
* @param eventRect: view containing the clicked event.
*/
void onEventLongPress(WeekViewEvent event, RectF eventRect);
}
public interface EmptyViewClickListener {
/**
* Triggered when the users clicks on a empty space of the calendar.
* @param time: {@link Calendar} object set with the date and time of the clicked position on the view.
*/
void onEmptyViewClicked(Calendar time);
}
public interface EmptyViewLongPressListener {
/**
* Similar to {@link com.alamkanak.weekview.WeekView.EmptyViewClickListener} but with long press.
* @param time: {@link Calendar} object set with the date and time of the long pressed position on the view.
*/
void onEmptyViewLongPress(Calendar time);
}
public interface ScrollListener {
/**
* Called when the first visible day has changed.
*
* (this will also be called during the first draw of the weekview)
* @param newFirstVisibleDay The new first visible day
* @param oldFirstVisibleDay The old first visible day (is null on the first call).
*/
void onFirstVisibleDayChanged(Calendar newFirstVisibleDay, Calendar oldFirstVisibleDay);
}
// Helper methods.
/**
* Checks if two times are on the same day.
* @param dayOne The first day.
* @param dayTwo The second day.
* @return Whether the times are on the same day.
*/
private boolean isSameDay(Calendar dayOne, Calendar dayTwo) {
return dayOne.get(Calendar.YEAR) == dayTwo.get(Calendar.YEAR) && dayOne.get(Calendar.DAY_OF_YEAR) == dayTwo.get(Calendar.DAY_OF_YEAR);
}
/**
* Returns a calendar instance at the start of this day
* @return the calendar instance
*/
private Calendar today(){
Calendar today = Calendar.getInstance();
today.set(Calendar.HOUR_OF_DAY, 0);
today.set(Calendar.MINUTE, 0);
today.set(Calendar.SECOND, 0);
today.set(Calendar.MILLISECOND, 0);
return today;
}
} |
// samskivert library - useful routines for java programs
// This library is free software; you can redistribute it and/or modify it
// (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// You should have received a copy of the GNU Lesser General Public
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.samskivert.util;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
/**
* Provides utility routines to simplify obtaining randomized values.
*
* <p>Each instance of Randoms contains an underlying {@link java.util.Random} instance and is
* only as thread-safe as that is. If you wish to have a private stream of pseudorandom numbers,
* use the {@link #with} factory.
*/
public class Randoms
{
/** A default Randoms that is thread-safe and can be safely shared by any caller. */
public static final Randoms RAND = with(new Random());
/**
* A factory to create a new Randoms object.
*/
public static Randoms with (Random rand)
{
return new Randoms(rand);
}
/**
* Get a thread-local Randoms instance that will not contend with any other thread
* for random number generation.
*
* <p><b>Note:</b> This method will return a Randoms instance that is not thread-safe.
* It can generate random values with less overhead, however it may be dangerous to share
* the reference. Instead you should probably always use it immediately as in the following
* example:
* <pre style="code">
* Puppy pick = Randoms.threadLocal().pick(Puppy.LITTER, null);
* </pre>
*/
public static Randoms threadLocal ()
{
return _localRandoms.get();
}
public int getInt (int high)
{
return _r.nextInt(high);
}
public int getInRange (int low, int high)
{
return low + _r.nextInt(high - low);
}
/**
* Returns a pseudorandom, uniformly distributed <code>float</code> value between
* <code>0.0</code> (inclusive) and the <code>high</code> (exclusive).
*
* @param high the high value limiting the random number sought.
*/
public float getFloat (float high)
{
return _r.nextFloat() * high;
}
/**
* Returns a pseudorandom, uniformly distributed <code>float</code> value between
* <code>low</code> (inclusive) and <code>high</code> (exclusive).
*/
public float getInRange (float low, float high)
{
return low + (_r.nextFloat() * (high - low));
}
public boolean getChance (int n)
{
return (0 == _r.nextInt(n));
}
/**
* Has a probability <code>p</code> of returning true.
*/
public boolean getProbability (float p)
{
return _r.nextFloat() < p;
}
/**
* Returns <code>true</code> or <code>false</code> with approximately even probability.
*/
public boolean getBoolean ()
{
return _r.nextBoolean();
}
/**
* Returns a pseudorandom, normally distributed <code>float</code> value around the
* <code>mean</code> with the standard deviation <code>dev</code>.
*/
public float getNormal (float mean, float dev)
{
return (float)_r.nextGaussian() * dev + mean;
}
/**
* Pick a random element from the specified Iterator, or return <code>ifEmpty</code>
* if it is empty.
*
* <p><b>Implementation note:</b> because the total size of the Iterator is not known,
* the random number generator is queried after the second element and every element
* thereafter.
*
* @throws NullPointerException if the iterator is null.
*/
public <T> T pick (Iterator<? extends T> iterator, T ifEmpty)
{
if (!iterator.hasNext()) {
return ifEmpty;
}
T pick = iterator.next();
for (int count = 2; iterator.hasNext(); count++) {
T next = iterator.next();
if (0 == _r.nextInt(count)) {
pick = next;
}
}
return pick;
}
/**
* Pick a random element from the specified Iterable, or return <code>ifEmpty</code>
* if it is empty.
*
* <p><b>Implementation note:</b> optimized implementations are used if the Iterable
* is a List or Collection. Otherwise, it behaves as if calling {@link #pick(Iterator, Object)}
* with the Iterable's Iterator.
*
* @throws NullPointerException if the iterable is null.
*/
public <T> T pick (Iterable<? extends T> iterable, T ifEmpty)
{
return pickPluck(iterable, ifEmpty, false);
}
public <T> T pick (Map<? extends T, ? extends Number> weightMap, T ifEmpty)
{
T pick = ifEmpty;
double total = 0.0;
for (Map.Entry<? extends T, ? extends Number> entry : weightMap.entrySet()) {
double weight = entry.getValue().doubleValue();
if (weight > 0.0) {
total += weight;
if ((total == weight) || ((_r.nextDouble() * total) < weight)) {
pick = entry.getKey();
}
} else if (weight < 0.0) {
throw new IllegalArgumentException("Weight less than 0: " + entry);
} // else: weight == 0.0 is OK
}
return pick;
}
/**
* Pluck (remove) a random element from the specified Iterable, or return <code>ifEmpty</code>
* if it is empty.
*
* <p><b>Implementation note:</b> optimized implementations are used if the Iterable
* is a List or Collection. Otherwise, two Iterators are created from the Iterable
* and a random number is generated after the second element and all beyond.
*
* @throws NullPointerException if the iterable is null.
* @throws UnsupportedOperationException if the iterable is unmodifiable or its Iterator
* does not support {@link Iterator#remove()}.
*/
public <T> T pluck (Iterable<? extends T> iterable, T ifEmpty)
{
return pickPluck(iterable, ifEmpty, true);
}
/**
* Construct a Randoms.
*/
protected Randoms (Random rand)
{
_r = rand;
}
/**
* Shared code for pick and pluck.
*/
protected <T> T pickPluck (Iterable<? extends T> iterable, T ifEmpty, boolean remove)
{
if (iterable instanceof Collection) {
// optimized path for Collection
@SuppressWarnings("unchecked")
Collection<? extends T> coll = (Collection<? extends T>)iterable;
int size = coll.size();
if (size == 0) {
return ifEmpty;
}
if (coll instanceof List) {
// extra-special optimized path for Lists
@SuppressWarnings("unchecked")
List<? extends T> list = (List<? extends T>)coll;
int idx = _r.nextInt(size);
if (remove) { // ternary conditional causes warning here with javac 1.6, :(
return list.remove(idx);
}
return list.get(idx);
}
// for other Collections, we must iterate
Iterator<? extends T> it = coll.iterator();
for (int idx = _r.nextInt(size); idx > 0; idx
it.next();
}
try {
return it.next();
} finally {
if (remove) {
it.remove();
}
}
}
if (!remove) {
return pick(iterable.iterator(), ifEmpty);
}
// from here on out, we're doing a pluck with a complicated two-iterator solution
Iterator<? extends T> it = iterable.iterator();
if (!it.hasNext()) {
return ifEmpty;
}
Iterator<? extends T> lagIt = iterable.iterator();
T pick = it.next();
lagIt.next();
for (int count = 2, lag = 1; it.hasNext(); count++, lag++) {
T next = it.next();
if (0 == _r.nextInt(count)) {
pick = next;
// catch up lagIt so that it has just returned 'pick' as well
for ( ; lag > 0; lag
lagIt.next();
}
}
}
lagIt.remove(); // remove 'pick' from the lagging iterator
return pick;
}
/** The random number generator. */
protected final Random _r;
/** A ThreadLocal for accessing a thread-local version of Randoms. */
protected static final ThreadLocal<Randoms> _localRandoms = new ThreadLocal<Randoms>() {
@Override
public Randoms initialValue () {
return with(new ThreadLocalRandom());
}
};
protected static class ThreadLocalRandom extends Random {
// same constants as Random, but must be redeclared because private
private final static long multiplier = 0x5DEECE66DL;
private final static long addend = 0xBL;
private final static long mask = (1L << 48) - 1;
/**
* The random seed. We can't use super.seed.
*/
private long rnd;
/**
* Initialization flag to permit calls to setSeed to succeed only
* while executing the Random constructor. We can't allow others
* since it would cause setting seed in one part of a program to
* unintentionally impact other usages by the thread.
*/
boolean initialized;
// Padding to help avoid memory contention among seed updates in
// different TLRs in the common case that they are located near
// each other.
@SuppressWarnings("unused")
private long pad0, pad1, pad2, pad3, pad4, pad5, pad6, pad7;
/**
* Constructor called only by localRandom.initialValue.
*/
ThreadLocalRandom() {
super();
initialized = true;
}
/**
* Throws {@code UnsupportedOperationException}. Setting seeds in
* this generator is not supported.
*
* @throws UnsupportedOperationException always
*/
@Override
public void setSeed(long seed) {
if (initialized)
throw new UnsupportedOperationException();
rnd = (seed ^ multiplier) & mask;
}
@Override
protected int next(int bits) {
rnd = (rnd * multiplier + addend) & mask;
return (int) (rnd >>> (48-bits));
}
// as of JDK 1.6, this method does not exist in java.util.Random
// public int nextInt(int least, int bound) {
// if (least >= bound)
// return nextInt(bound - least) + least;
public long nextLong(long n) {
if (n <= 0)
throw new IllegalArgumentException("n must be positive");
// Divide n by two until small enough for nextInt. On each
// iteration (at most 31 of them but usually much less),
// randomly choose both whether to include high bit in result
// (offset) and whether to continue with the lower vs upper
// half (which makes a difference only if odd).
long offset = 0;
while (n >= Integer.MAX_VALUE) {
int bits = next(2);
long half = n >>> 1;
long nextn = ((bits & 2) == 0) ? half : n - half;
if ((bits & 1) == 0)
offset += n - nextn;
n = nextn;
}
return offset + nextInt((int) n);
}
public long nextLong(long least, long bound) {
if (least >= bound)
throw new IllegalArgumentException();
return nextLong(bound - least) + least;
}
public double nextDouble(double n) {
if (n <= 0)
throw new IllegalArgumentException("n must be positive");
return nextDouble() * n;
}
public double nextDouble(double least, double bound) {
if (least >= bound)
throw new IllegalArgumentException();
return nextDouble() * (bound - least) + least;
}
private static final long serialVersionUID = -5851777807851030925L;
}
} |
package com.sb.elsinore.html;
import java.io.IOException;
import org.rendersnake.HtmlCanvas;
import org.rendersnake.Renderable;
import com.sb.elsinore.LaunchControl;
import static org.rendersnake.HtmlAttributesFactory.*;
/**
* Create a top bar for the web page.
* @author Doug Edey
*/
public class TopBar implements Renderable {
@Override
public final void renderOn(HtmlCanvas htmlCanvas) throws IOException {
htmlCanvas.div(id("topbar").class_("row"))
.div(id("breweryTitle").class_("left col-md-2"))
.h1(class_("breweryNameHeader").onClick("editBreweryName()"))
.div(id("breweryName")).write("Elsinore")._div()
.small()
.a(href(LaunchControl.RepoURL))
.content("StrangeBrew Elsinore")
._small()
._h1()
._div()
.div(class_("center-left col-md-4"))._div()
.div(class_("center-right col-md-4"))._div()
._div()
.div(id("messages").class_("row").style("display:none"))
.div(class_("panel panel-warning"))
.div(id("messages-title").class_("title panel-heading"))._div()
.div(id("messages-body").class_("panel-body"))._div()
._div()
._div();
}
} |
import javax.swing.JFrame;
import javax.swing.JLabel;
/*
* This snippet shows how to make a very basic Swing window.
*
* Usage:
* - compile: javac Hello.java
* - execute: java Hello
*/
public class Hello {
public static void main(String args[]) {
// Create a frame and set the title
JFrame frame = new JFrame("Hello World!");
// Set the default close operation
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
// Add a label
frame.getContentPane().add(new JLabel("Hello, World!"));
// Set the frame size
frame.pack();
// Center the frame
frame.setLocationRelativeTo(null);
// Show the frame
frame.setVisible(true);
}
} |
package cspfj.problem;
import java.util.Arrays;
import cspfj.util.BitVector;
public final class BooleanDomain implements Domain {
private static final int HISTORY_INCREMENT = 20;
private static final int[] UNKNOWN_ARRAY = new int[] { 0, 1 };
private static final int[] TRUE_ARRAY = new int[] { 1 };
private static final int[] FALSE_ARRAY = new int[] { 0 };
private static final int[] EMPTY_ARRAY = new int[] {};
private static final BitVector UNKNOWN_BV;
private static final BitVector TRUE_BV;
private static final BitVector FALSE_BV;
private static final BitVector EMPTY_BV;
static {
UNKNOWN_BV = BitVector.factory(2, true);
TRUE_BV = BitVector.factory(2, false);
TRUE_BV.set(1);
FALSE_BV = BitVector.factory(2, false);
FALSE_BV.set(0);
EMPTY_BV = BitVector.factory(2, false);
}
public static enum Status {
UNKNOWN(2), TRUE(1), FALSE(1), EMPTY(0);
private final int size;
private Status(final int size) {
this.size = size;
}
private int[] asArray() {
switch (this) {
case TRUE:
return TRUE_ARRAY;
case FALSE:
return FALSE_ARRAY;
case UNKNOWN:
return UNKNOWN_ARRAY;
case EMPTY:
return EMPTY_ARRAY;
default:
throw new IllegalStateException();
}
}
private BitVector asBitVector() {
switch (this) {
case TRUE:
return TRUE_BV;
case FALSE:
return FALSE_BV;
case UNKNOWN:
return UNKNOWN_BV;
case EMPTY:
return EMPTY_BV;
default:
throw new IllegalStateException();
}
}
@Override
public String toString() {
switch (this) {
case UNKNOWN:
return "[false, true]";
case TRUE:
return "[true]";
case FALSE:
return "[false]";
case EMPTY:
return "[]";
default:
throw new IllegalStateException();
}
}
}
private Status status;
private Status[] history;
private int currentLevel = 0;
public BooleanDomain() {
status = Status.UNKNOWN;
history = new Status[HISTORY_INCREMENT];
}
public BooleanDomain(boolean constant) {
if (constant) {
status = Status.TRUE;
} else {
status = Status.FALSE;
}
history = new Status[HISTORY_INCREMENT];
}
@Override
public int first() {
switch (status) {
case TRUE:
return 1;
case EMPTY:
return -1;
case FALSE:
case UNKNOWN:
return 0;
default:
throw new IllegalStateException();
}
}
@Override
public int size() {
return status.size;
}
@Override
public int last() {
switch (status) {
case FALSE:
return 0;
case EMPTY:
return -1;
case TRUE:
case UNKNOWN:
return 1;
default:
throw new IllegalStateException();
}
}
@Override
public int next(final int i) {
if (i == 0 && status == Status.UNKNOWN) {
return 1;
}
return -1;
}
@Override
public int prev(final int i) {
if (i == 1 && status == Status.UNKNOWN) {
return 0;
}
return -1;
}
@Override
public int lastAbsent() {
throw new UnsupportedOperationException();
}
@Override
public int prevAbsent(final int i) {
throw new UnsupportedOperationException();
}
/**
* @param value
* the value we seek the index for
* @return the index of the given value or -1 if it could not be found
*/
public int index(final int value) {
return value;
}
/**
* @param index
* index to test
* @return true iff index is present
*/
@Override
public boolean present(final int index) {
switch (status) {
case UNKNOWN:
return true;
case TRUE:
return index == 1;
case FALSE:
return index == 0;
case EMPTY:
return false;
default:
throw new IllegalStateException();
}
}
@Override
public void setSingle(final int index) {
if (index == 0) {
setStatus(Status.FALSE);
} else {
setStatus(Status.TRUE);
}
}
public void setStatus(final Status status) {
assert this.status == Status.UNKNOWN || this.status == status;
this.status = status;
if (history[currentLevel] == null) {
history[currentLevel] = Status.UNKNOWN;
}
}
@Override
public int value(final int index) {
return index;
}
@Override
public void remove(final int index) {
assert present(index);
if (status.size == 1) {
status = Status.EMPTY;
} else if (index == 0) {
status = Status.TRUE;
} else {
status = Status.FALSE;
}
if (history[currentLevel] == null) {
history[currentLevel] = Status.UNKNOWN;
}
}
public BitVector getBitVector() {
return status.asBitVector();
}
public BooleanDomain clone() {
final BooleanDomain clone;
try {
clone = (BooleanDomain) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException(e);
}
clone.status = status;
clone.history = history.clone();
return clone;
}
@Override
public int maxSize() {
return 2;
}
@Override
public void setLevel(final int level) {
assert level > currentLevel;
ensureCapacity(level);
if (history[currentLevel] != null) {
history[currentLevel] = status;
}
currentLevel = level;
}
private void ensureCapacity(final int size) {
if (size >= history.length) {
history = Arrays.copyOf(history, currentLevel + HISTORY_INCREMENT);
}
}
@Override
public void restoreLevel(final int level) {
assert level < currentLevel;
boolean change = false;
for (int l = currentLevel; l > level; l
if (history[l] != null) {
change = true;
history[l] = null;
}
}
if (change) {
for (int l = level;; l
if (l < 0) {
status = Status.UNKNOWN;
break;
}
if (history[l] != null) {
assert history[l] != Status.EMPTY;
status = history[l];
break;
}
}
}
currentLevel = level;
}
@Override
public BitVector getAtLevel(final int level) {
if (level < currentLevel) {
for (int l = level; --l >= 0;) {
if (history[l] != null) {
return history[l].asBitVector();
}
}
return Status.UNKNOWN.asBitVector();
}
return status.asBitVector();
}
@Override
public int[] allValues() {
return Status.UNKNOWN.asArray();
}
@Override
public int[] currentValues() {
return status.asArray();
}
@Override
public String toString() {
return status.toString();
}
public Status getStatus() {
return status;
}
public boolean canBe(final boolean value) {
switch (status) {
case UNKNOWN:
return true;
case EMPTY:
return false;
case TRUE:
return value;
case FALSE:
return !value;
default:
throw new IllegalStateException();
}
}
@Override
public int greatest(final int value) {
throw new UnsupportedOperationException();
}
@Override
public int removeFrom(final int lb) {
throw new UnsupportedOperationException();
}
@Override
public int removeTo(final int ub) {
throw new UnsupportedOperationException();
}
@Override
public int lowest(final int value) {
throw new UnsupportedOperationException();
}
} |
package de.prob2.ui.beditor;
import java.io.IOException;
import java.io.PushbackReader;
import java.io.StringReader;
import java.time.Duration;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.fxmisc.richtext.StyleClassedTextArea;
import org.fxmisc.richtext.model.StyleSpans;
import org.fxmisc.richtext.model.StyleSpansBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import de.be4.classicalb.core.parser.BLexer;
import de.be4.classicalb.core.parser.lexer.LexerException;
import de.be4.classicalb.core.parser.node.*;
import javafx.concurrent.Task;
public class BEditor extends StyleClassedTextArea {
private static final Logger logger = LoggerFactory.getLogger(BEditor.class);
private ExecutorService executor = Executors.newSingleThreadExecutor();
private static final Map<Class<? extends Token>, String> syntaxClasses = new HashMap<>();
static {
addTokens("editor_identifier", TIdentifierLiteral.class);
addTokens("editor_assignment_logical", TAssign.class, TOutputParameters.class, TDoubleVerticalBar.class, TAssert.class,
TClosure.class, TClosure1.class, TConjunction.class, TDirectProduct.class, TDivision.class, TEmptySet.class, TDoubleColon.class,
TDoubleEqual.class, TEqual.class, TElementOf.class, TEquivalence.class, TGreaterEqual.class, TLessEqual.class, TNotEqual.class,
TGreater.class, TLess.class, TImplies.class, TLogicalOr.class, TInterval.class, TUnion.class, TOr.class, TNonInclusion.class,
TTotalBijection.class, TTotalFunction.class, TTotalInjection.class, TTotalRelation.class, TTotalSurjection.class,
TTotalSurjectionRelation.class, TPartialBijection.class, TPartialFunction.class, TPartialInjection.class, TPartialSurjection.class, TSetRelation.class,
TFin.class, TFin1.class, TPerm.class, TSeq.class, TSeq1.class, TIseq.class,
TIseq1.class, TBool.class, TNat.class, TNat1.class, TNatural.class, TNatural1.class, TStruct.class,
TInteger.class, TInt.class, TString.class, TEither.class);
addTokens("editor_string", TStringLiteral.class);
addTokens("editor_unsupported", TTree.class, TLeft.class, TRight.class, TInfix.class, TArity.class,
TSubtree.class, TPow.class, TPow1.class,
TSon.class, TFather.class, TRank.class, TMirror.class, TSizet.class, TPostfix.class, TPrefix.class,
TSons.class, TTop.class, TConst.class, TBtree.class);
addTokens("editor_ctrlkeyword", TSkip.class, TLet.class, TBe.class, TVar.class, TIn.class, TAny.class,
TWhile.class,
TDo.class, TVariant.class, TElsif.class, TIf.class, TThen.class, TElse.class,
TCase.class, TSelect.class, TAssert.class, TAssertions.class, TWhen.class, TPre.class, TBegin.class,
TChoice.class, TWhere.class, TOf.class, TEnd.class);
addTokens("editor_keyword", TMachine.class, TRefinement.class, TImplementation.class,
TOperations.class, TAssertions.class, TInitialisation.class, TSees.class, TPromotes.class,
TUses.class, TIncludes.class, TImports.class, TRefines.class, TExtends.class, TSystem.class,
TModel.class,
TInvariant.class, TConcreteVariables.class, TAbstractVariables.class, TVariables.class,
TProperties.class,
TConstants.class, TAbstractConstants.class, TConcreteConstants.class, TConstraints.class, TSets.class,
TDefinitions.class);
addTokens("editor_comment", TComment.class, TCommentBody.class, TCommentEnd.class);
}
public BEditor() {
this.richChanges()
.filter(ch -> !ch.getInserted().equals(ch.getRemoved()))
.successionEnds(Duration.ofMillis(500))
.supplyTask(this::computeHighlightingAsync)
.awaitLatest(this.richChanges())
.filterMap(t -> {
if (t.isSuccess()) {
return Optional.of(t.get());
} else {
t.getFailure().printStackTrace();
return Optional.empty();
}
}).subscribe(this::applyHighlighting);
}
@SafeVarargs
private static void addTokens(String syntaxclass, Class<? extends Token>... tokens) {
for (Class<? extends Token> c : tokens) {
syntaxClasses.put(c, syntaxclass);
}
}
private void applyHighlighting(StyleSpans<Collection<String>> highlighting) {
this.setStyleSpans(0, highlighting);
}
private Task<StyleSpans<Collection<String>>> computeHighlightingAsync() {
String text = this.getText();
Task<StyleSpans<Collection<String>>> task = new Task<StyleSpans<Collection<String>>>() {
@Override
protected StyleSpans<Collection<String>> call() throws Exception {
return computeHighlighting(text);
}
};
executor.execute(task);
return task;
}
private static StyleSpans<Collection<String>> computeHighlighting(String text) {
BLexer lexer = new BLexer(new PushbackReader(new StringReader(text), text.length()));
StyleSpansBuilder<Collection<String>> spansBuilder = new StyleSpansBuilder<>();
try {
Token t;
do {
t = lexer.next();
String string = syntaxClasses.get(t.getClass());
int length = t.getText().length();
if (t instanceof TStringLiteral)
length = length + 2;
if (string != null) {
spansBuilder.add(Collections.singleton(string), length);
} else {
spansBuilder.add(Collections.singleton("default"), length);
}
} while (!(t instanceof EOF));
} catch (LexerException | IOException e) {
logger.error("BLexer Exception: ", e);
}
return spansBuilder.create();
}
} |
package graphsearcher;
import java.io.File;
import java.util.ArrayList;
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.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.Pair;
import org.neo4j.graphalgo.GraphAlgoFactory;
import org.neo4j.graphalgo.PathFinder;
import org.neo4j.graphdb.Direction;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Label;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Path;
import org.neo4j.graphdb.PathExpanders;
import org.neo4j.graphdb.Relationship;
import org.neo4j.graphdb.RelationshipType;
import org.neo4j.graphdb.ResourceIterable;
import org.neo4j.graphdb.Transaction;
import org.neo4j.graphdb.factory.GraphDatabaseFactory;
import org.tartarus.snowball.ext.EnglishStemmer;
import graphdb.extractors.linkers.codeindoc_ch.CodeInDocxFileExtractor;
import graphdb.extractors.linkers.designtorequire_ch.DesignToRequireExtractor;
import graphdb.extractors.miners.codeembedding.line.LINEExtracter;
import graphdb.extractors.miners.tokenization_ch.TokenChExtractor;
import graphdb.extractors.parsers.javacode.JavaCodeExtractor;
public class GraphSearcher {
GraphDatabaseService db = null;
PathFinder<Path> pathFinder = GraphAlgoFactory
.shortestPath(PathExpanders.forTypesAndDirections(RelationshipType.withName(JavaCodeExtractor.EXTEND),
Direction.BOTH, RelationshipType.withName(JavaCodeExtractor.IMPLEMENT), Direction.BOTH,
RelationshipType.withName(JavaCodeExtractor.THROW),
Direction.BOTH,
RelationshipType.withName(JavaCodeExtractor.PARAM), Direction.BOTH,
RelationshipType.withName(JavaCodeExtractor.RT), Direction.BOTH,
RelationshipType.withName(JavaCodeExtractor.HAVE_METHOD), Direction.BOTH,
RelationshipType.withName(JavaCodeExtractor.HAVE_FIELD), Direction.BOTH,
RelationshipType.withName(JavaCodeExtractor.CALL_METHOD), Direction.BOTH,
RelationshipType.withName(JavaCodeExtractor.CALL_FIELD), Direction.BOTH,
RelationshipType.withName(JavaCodeExtractor.TYPE), Direction.BOTH,
RelationshipType.withName(JavaCodeExtractor.VARIABLE), Direction.BOTH), 5);
boolean debug = true;
static EnglishStemmer stemmer = new EnglishStemmer();
static QueryStringToQueryWordsConverter converter = new QueryStringToQueryWordsConverter();
public Map<Long, List<Double>> id2Vec = new HashMap<>();
Map<Long, String> id2Sig = new HashMap<>();
Map<Long, String> id2Name = new HashMap<>();
Map<Long, Set<String>> id2Words = new HashMap<>();
Set<Long> typeSet = new HashSet<>();
Map<String, Set<Long>> word2Ids = new HashMap<>();
Map<String, Set<Long>> queryWord2Ids = new HashMap<>();
Set<String> queryWordSet = new HashSet<>();
public static void main(String[] args){
GraphDatabaseService db=new GraphDatabaseFactory().newEmbeddedDatabase(new File("E:\\SnowGraphData\\lucene\\graphdb"));
GraphSearcher searcher=new GraphSearcher(db);
searcher.querySingle("Affix");
}
public GraphSearcher(GraphDatabaseService db) {
this.db = db;
try (Transaction tx = db.beginTx()) {
ResourceIterable<Node> nodes = db.getAllNodes();
for (Node node : nodes) {
if (!node.hasLabel(Label.label(JavaCodeExtractor.CLASS))
&& !node.hasLabel(Label.label(JavaCodeExtractor.INTERFACE))
&& !node.hasLabel(Label.label(JavaCodeExtractor.METHOD)))
continue;
if (!node.hasProperty(LINEExtracter.LINE_VEC))
continue;
String[] eles = ((String) node.getProperty(LINEExtracter.LINE_VEC)).trim().split("\\s+");
List<Double> vec = new ArrayList<Double>();
for (String e : eles)
vec.add(Double.parseDouble(e));
long id = node.getId();
String sig = (String) node.getProperty(JavaCodeExtractor.SIGNATURE);
if (sig.toLowerCase().contains("test"))
continue;
String name = "";
if (node.hasLabel(Label.label(JavaCodeExtractor.CLASS)))
name = (String) node.getProperty(JavaCodeExtractor.CLASS_NAME);
if (node.hasLabel(Label.label(JavaCodeExtractor.INTERFACE)))
name = (String) node.getProperty(JavaCodeExtractor.INTERFACE_NAME);
if (node.hasLabel(Label.label(JavaCodeExtractor.METHOD)))
name = (String) node.getProperty(JavaCodeExtractor.METHOD_NAME);
if (node.hasLabel(Label.label(JavaCodeExtractor.METHOD)) && name.matches("[A-Z]\\w+"))
continue;
Set<String> words = new HashSet<>();
for (String e : name.split("[^A-Za-z]+"))
for (String word : camelSplit(e)) {
word = stem(word);
if (!word2Ids.containsKey(word))
word2Ids.put(word, new HashSet<>());
word2Ids.get(word).add(id);
words.add(word);
}
if (node.hasProperty(TokenChExtractor.TOKENS_CH)) {
String cTokenString = (String)node.getProperty(TokenChExtractor.TOKENS_CH);
for (String word : cTokenString.trim().split("\\s+")) {
if (!word2Ids.containsKey(word))
word2Ids.put(word, new HashSet<>());
word2Ids.get(word).add(id);
words.add(word);
}
}
id2Words.put(id, words);
id2Vec.put(id, vec);
id2Sig.put(id, sig);
if (node.hasLabel(Label.label(JavaCodeExtractor.CLASS))
|| node.hasLabel(Label.label(JavaCodeExtractor.INTERFACE)))
typeSet.add(id);
id2Name.put(id, stem(name.toLowerCase()));
}
tx.success();
}
}
public SearchResult querySingle(String queryString) {
List<SearchResult> list=query(queryString);
return list.size()>0?list.get(0):new SearchResult();
}
public List<SearchResult> query(String queryString) {
List<SearchResult> r=new ArrayList<>();
/*
* anchorMap:
* - key:
* - value:
*/
Map<Set<Long>, Double> anchorMap = computeAnchors(queryString);
try (Transaction tx = db.beginTx()) {
for (Set<Long> anchors : anchorMap.keySet()) {
SearchResult searchResult = new SearchResult();
searchResult.nodes.addAll(anchors);
for (long anchor1 : anchors)
for (long anchor2 : anchors) {
Path path = pathFinder.findSinglePath(db.getNodeById(anchor1), db.getNodeById(anchor2));
if (path != null) {
for (Node node : path.nodes())
searchResult.nodes.add(node.getId());
for (Relationship edge : path.relationships())
searchResult.edges.add(edge.getId());
}
}
Set<Long> tmpSet = new HashSet<>();
tmpSet.addAll(searchResult.nodes);
for (long node : tmpSet) {
Iterator<Relationship> classInter = db.getNodeById(node).getRelationships(
RelationshipType.withName(JavaCodeExtractor.HAVE_METHOD), Direction.INCOMING).iterator();
if (!classInter.hasNext())
continue;
Relationship edge = classInter.next();
searchResult.nodes.add(edge.getStartNodeId());
searchResult.edges.add(edge.getId());
}
tmpSet.clear();
tmpSet.addAll(searchResult.nodes);
for (long node:tmpSet){
Iterator<Relationship> iter = db.getNodeById(node).getRelationships(
RelationshipType.withName(CodeInDocxFileExtractor.API_EXPLAINED_BY), Direction.BOTH).iterator();
while (iter.hasNext()){
Relationship edge=iter.next();
searchResult.nodes.add(edge.getOtherNodeId(node));
searchResult.edges.add(edge.getId());
}
}
tmpSet.clear();
tmpSet.addAll(searchResult.nodes);
for (long node:tmpSet){
Iterator<Relationship> iter = db.getNodeById(node).getRelationships(
RelationshipType.withName(DesignToRequireExtractor.DESIGNED_BY), Direction.BOTH).iterator();
while (iter.hasNext()){
Relationship edge=iter.next();
searchResult.nodes.add(edge.getOtherNodeId(node));
searchResult.edges.add(edge.getId());
}
}
searchResult.cost=anchorMap.get(anchors);
r.add(searchResult);
}
tx.success();
}
Collections.sort(r,(r1, r2) -> Double.compare(r1.cost, r2.cost));
int K=5;
if (r.size()<K)
return r;
else
return r.subList(0, K);
}
/**
*
* @param queryString ()
* @return
*/
Map<Set<Long>, Double> computeAnchors(String queryString) {
Map<Set<Long>, Double> r = new HashMap<>();
queryWord2Ids = new HashMap<>();
queryWordSet = new HashSet<>();
queryWordSet = converter.convert(queryString);
if (debug) {
System.out.println("queryWordSet = { " + String.join(", ", queryWordSet) + " }");
System.out.println();
}
/*
*
* queryWordSet:
* queryWord2Ids:
*/
queryWord2Ids(queryWordSet);
/*
* queryWordSet
*/
Set<Long> candidateNodes = candidate();
for (long cNode : candidateNodes) {
Set<Long> minDistNodeSet = new HashSet<>();
minDistNodeSet.add(cNode);
for (String queryWord : queryWordSet) {
if (queryWord2Ids.get(queryWord).contains(cNode))
continue;
double minDist = Double.MAX_VALUE;
long minDistNode = -1;
for (long node : queryWord2Ids.get(queryWord)) {
double dist = dist(cNode, node);
if (dist < minDist) {
minDist = dist;
minDistNode = node;
}
}
if (minDistNode == -1)
continue;
minDistNodeSet.add(minDistNode);
}
double cost = sumDist(cNode, minDistNodeSet);
r.put(minDistNodeSet, cost);
}
return r;
}
/**
* queryWordSet
* @return
*/
Set<Long> candidate() {
Set<Long> candidateNodes = new HashSet<>();
for (long node : typeSet)
if (queryWordSet.contains(id2Name.get(node)))
candidateNodes.add(node);
/**
* countSet: {<key=value=>|value>=2}
*/
Set<Pair<Long, Integer>> countSet=new HashSet<>();
int maxCount=0;
for (long node : id2Name.keySet()) {
int count = 0;
for (String word : id2Words.get(node))
if (queryWordSet.contains(word))
count++;
if (count >= 2){
countSet.add(new ImmutablePair<Long, Integer>(node, count));
if (count>maxCount)
maxCount=count;
}
}
/**
*
* SoftKittyWarmKittyLittleBallOfFur, soft,kitty, warm, little, fur
*/
for (Pair<Long, Integer> pair:countSet){
if (pair.getValue()==maxCount)
candidateNodes.add(pair.getKey());
}
if (candidateNodes.size() > 0)
return candidateNodes;
for (String queryWord : queryWordSet)
for (long node : queryWord2Ids.get(queryWord)) {
if (!typeSet.contains(node))
continue;
candidateNodes.add(node);
}
if (candidateNodes.size() > 0)
return candidateNodes;
for (String queryWord : queryWordSet)
for (long node : queryWord2Ids.get(queryWord)) {
candidateNodes.add(node);
}
return candidateNodes;
}
double sumDist(long cNode, Set<Long> minDistNodeSet) {
double r = 0;
for (long node : minDistNodeSet) {
double dist = dist(cNode, node);
r += dist;
}
return r;
}
void queryWord2Ids(Set<String> queryWordSet) {
for (String queryWord : queryWordSet) {
queryWord2Ids.put(queryWord, new HashSet<>());
for (long node : id2Name.keySet())
if (id2Name.get(node).equals(queryWord))
queryWord2Ids.get(queryWord).add(node);
}
queryWordSet.clear();
for (String word : queryWord2Ids.keySet())
if (queryWord2Ids.get(word).size() > 0)
queryWordSet.add(word);
}
String stem(String word) {
if (word.matches("\\w+")) {
stemmer.setCurrent(word.toLowerCase());
stemmer.stem();
word = stemmer.getCurrent();
}
return word;
}
static List<String> camelSplit(String e) {
List<String> r = new ArrayList<String>();
Matcher m = Pattern.compile("^([a-z]+)|([A-Z][a-z]+)|([A-Z]+(?=([A-Z]|$)))").matcher(e);
if (m.find()) {
String s = m.group().toLowerCase();
r.add(s);
if (s.length() < e.length())
r.addAll(camelSplit(e.substring(s.length())));
}
return r;
}
public double dist(long node1, long node2) {
if (!id2Vec.containsKey(node1))
return Double.MAX_VALUE;
if (!id2Vec.containsKey(node2))
return Double.MAX_VALUE;
double r = 0;
for (int i = 0; i < id2Vec.get(node1).size(); i++)
r += (id2Vec.get(node1).get(i) - id2Vec.get(node2).get(i))
* (id2Vec.get(node1).get(i) - id2Vec.get(node2).get(i));
r = Math.sqrt(r);
return r;
}
} |
package hu.bme.mit.spaceship;
/**
* A simple spaceship with two proton torpedos and four lasers
*/
public class GT4500 implements SpaceShip {
private TorpedoStore primaryTorpedoStore;
private TorpedoStore secondaryTorpedoStore;
private boolean wasPrimaryFiredLast = false;
public GT4500() {
this.primaryTorpedoStore = new TorpedoStore(10);
this.secondaryTorpedoStore = new TorpedoStore(10);
}
public boolean fireLasers(FiringMode firingMode) {
// TODO not implemented yet
// csak 1 kis comment asdasd
return false;
}
/**
* Tries to fire the torpedo stores of the ship.
*
* @param firingMode how many torpedo bays to fire
* SINGLE: fires only one of the bays.
* - For the first time the primary store is fired.
* - To give some cooling time to the torpedo stores, torpedo stores are fired alternating.
* - But if the store next in line is empty the ship tries to fire the other store.
* - If the fired store reports a failure, the ship does not try to fire the other one.
* ALL: tries to fire both of the torpedo stores.
*
* @return whether at least one torpedo was fired successfully
*/
@Override
public boolean fireTorpedos(FiringMode firingMode) {
boolean firingSuccess = false;
switch (firingMode) {
case SINGLE:
if (wasPrimaryFiredLast) {
// try to fire the secondary first
if (! secondaryTorpedoStore.isEmpty()) {
firingSuccess = secondaryTorpedoStore.fire(1);
wasPrimaryFiredLast = false;
}
else {
// although primary was fired last time, but the secondary is empty
// thus try to fire primary again
if (! primaryTorpedoStore.isEmpty()) {
firingSuccess = primaryTorpedoStore.fire(1);
wasPrimaryFiredLast = true;
}
// if both of the stores are empty, nothing can be done, return failure
}
}
else {
// try to fire the primary first
if (! primaryTorpedoStore.isEmpty()) {
firingSuccess = primaryTorpedoStore.fire(1);
wasPrimaryFiredLast = true;
}
else {
// although secondary was fired last time, but primary is empty
// thus try to fire secondary again
if (! secondaryTorpedoStore.isEmpty()) {
firingSuccess = secondaryTorpedoStore.fire(1);
wasPrimaryFiredLast = false;
}
// if both of the stores are empty, nothing can be done, return failure
}
}
break;
case ALL:
// try to fire both of the torpedos
//TODO implement feature
break;
}
return firingSuccess;
}
} |
package hudson.plugins.ec2;
import static javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST;
import static javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
import com.amazonaws.ClientConfiguration;
import com.amazonaws.auth.DefaultAWSCredentialsProviderChain;
import com.cloudbees.jenkins.plugins.awscredentials.AWSCredentialsImpl;
import com.cloudbees.jenkins.plugins.awscredentials.AmazonWebServicesCredentials;
import com.cloudbees.plugins.credentials.Credentials;
import com.cloudbees.plugins.credentials.CredentialsMatchers;
import com.cloudbees.plugins.credentials.CredentialsProvider;
import com.cloudbees.plugins.credentials.CredentialsScope;
import com.cloudbees.plugins.credentials.CredentialsStore;
import com.cloudbees.plugins.credentials.SystemCredentialsProvider;
import com.cloudbees.plugins.credentials.common.StandardListBoxModel;
import com.cloudbees.plugins.credentials.domains.Domain;
import edu.umd.cs.findbugs.annotations.CheckForNull;
import edu.umd.cs.findbugs.annotations.Nullable;
import hudson.ProxyConfiguration;
import hudson.model.Computer;
import hudson.model.Descriptor;
import hudson.model.Hudson;
import hudson.model.Label;
import hudson.model.Node;
import hudson.security.ACL;
import hudson.slaves.Cloud;
import hudson.slaves.NodeProvisioner.PlannedNode;
import hudson.util.FormValidation;
import hudson.util.HttpResponses;
import hudson.util.ListBoxModel;
import hudson.util.Secret;
import hudson.util.StreamTaskListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.StringReader;
import java.io.StringWriter;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.Proxy;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.Callable;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;
import javax.servlet.ServletException;
import hudson.model.TaskListener;
import jenkins.model.Jenkins;
import org.apache.commons.lang.StringUtils;
import org.kohsuke.stapler.HttpResponse;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import com.amazonaws.AmazonClientException;
import com.amazonaws.ClientConfiguration;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.auth.InstanceProfileCredentialsProvider;
import com.amazonaws.internal.StaticCredentialsProvider;
import com.amazonaws.services.ec2.AmazonEC2;
import com.amazonaws.services.ec2.AmazonEC2Client;
import com.amazonaws.services.ec2.model.CreateKeyPairRequest;
import com.amazonaws.services.ec2.model.DescribeSpotInstanceRequestsRequest;
import com.amazonaws.services.ec2.model.Filter;
import com.amazonaws.services.ec2.model.Instance;
import com.amazonaws.services.ec2.model.InstanceStateName;
import com.amazonaws.services.ec2.model.InstanceType;
import com.amazonaws.services.ec2.model.KeyPair;
import com.amazonaws.services.ec2.model.KeyPairInfo;
import com.amazonaws.services.ec2.model.Reservation;
import com.amazonaws.services.ec2.model.SpotInstanceRequest;
import com.amazonaws.services.ec2.model.Tag;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.GeneratePresignedUrlRequest;
import hudson.ProxyConfiguration;
import hudson.model.Computer;
import hudson.model.Descriptor;
import hudson.model.Hudson;
import hudson.model.Label;
import hudson.model.Node;
import hudson.slaves.Cloud;
import hudson.slaves.NodeProvisioner.PlannedNode;
import hudson.util.FormValidation;
import hudson.util.HttpResponses;
import hudson.util.Secret;
import hudson.util.StreamTaskListener;
/**
* Hudson's view of EC2.
*
* @author Kohsuke Kawaguchi
*/
public abstract class EC2Cloud extends Cloud {
private static final Logger LOGGER = Logger.getLogger(EC2Cloud.class.getName());
public static final String DEFAULT_EC2_HOST = "us-east-1";
public static final String AWS_URL_HOST = "amazonaws.com";
public static final String EC2_SLAVE_TYPE_SPOT = "spot";
public static final String EC2_SLAVE_TYPE_DEMAND = "demand";
private static final SimpleFormatter sf = new SimpleFormatter();
private final boolean useInstanceProfileForCredentials;
/**
* Id of the {@link AmazonWebServicesCredentials} used to connect to Amazon ECS
*/
@CheckForNull
private String credentialsId;
@CheckForNull
@Deprecated
private transient String accessId;
@CheckForNull
@Deprecated
private transient Secret secretKey;
protected final EC2PrivateKey privateKey;
/**
* Upper bound on how many instances we may provision.
*/
public final int instanceCap;
private final List<? extends SlaveTemplate> templates;
private transient KeyPair usableKeyPair;
protected transient AmazonEC2 connection;
private static AWSCredentialsProvider awsCredentialsProvider;
protected EC2Cloud(String id, boolean useInstanceProfileForCredentials, String credentialsId, String privateKey,
String instanceCapStr, List<? extends SlaveTemplate> templates) {
super(id);
this.useInstanceProfileForCredentials = useInstanceProfileForCredentials;
this.credentialsId = credentialsId;
this.privateKey = new EC2PrivateKey(privateKey);
if (templates == null) {
this.templates = Collections.emptyList();
} else {
this.templates = templates;
}
if (instanceCapStr.isEmpty()) {
this.instanceCap = Integer.MAX_VALUE;
} else {
this.instanceCap = Integer.parseInt(instanceCapStr);
}
readResolve(); // set parents
}
public abstract URL getEc2EndpointUrl() throws IOException;
public abstract URL getS3EndpointUrl() throws IOException;
protected Object readResolve() {
for (SlaveTemplate t : templates)
t.parent = this;
if (this.accessId != null && credentialsId == null) {
// REPLACE this.accessId and this.secretId by a credential
SystemCredentialsProvider systemCredentialsProvider = SystemCredentialsProvider.getInstance();
// ITERATE ON EXISTING CREDS AND DON'T CREATE IF EXIST
for (Credentials credentials: systemCredentialsProvider.getCredentials()) {
if (credentials instanceof AmazonWebServicesCredentials) {
AmazonWebServicesCredentials awsCreds = (AmazonWebServicesCredentials) credentials;
AWSCredentials awsCredentials = awsCreds.getCredentials();
if (accessId.equals(awsCredentials.getAWSAccessKeyId()) &&
Secret.toString(this.secretKey).equals(awsCredentials.getAWSSecretKey())) {
this.credentialsId = awsCreds.getId();
this.accessId = null;
this.secretKey = null;
return this;
}
}
}
// CREATE
for (CredentialsStore credentialsStore: CredentialsProvider.lookupStores(Jenkins.getInstance())) {
if (credentialsStore instanceof SystemCredentialsProvider.StoreImpl) {
try {
String credsId = UUID.randomUUID().toString();
credentialsStore.addCredentials(Domain.global(), new AWSCredentialsImpl(
CredentialsScope.SYSTEM,
credsId,
this.accessId,
this.secretKey.getEncryptedValue(),
"EC2 Cloud - " + getDisplayName()));
this.credentialsId = credsId;
this.accessId = null;
this.secretKey = null;
return this;
} catch (IOException e) {
this.credentialsId = null;
LOGGER.log(Level.WARNING, "Exception converting legacy configuration to the new credentials API", e);
}
}
}
// PROBLEM, GLOBAL STORE NOT FOUND
LOGGER.log(Level.WARNING, "EC2 Plugin could not migrate credentials to the Jenkins Global Credentials Store, EC2 Plugin for cloud {0} must be manually reconfigured", getDisplayName());
}
return this;
}
public boolean isUseInstanceProfileForCredentials() {
return useInstanceProfileForCredentials;
}
public String getCredentialsId() {
return credentialsId;
}
public EC2PrivateKey getPrivateKey() {
return privateKey;
}
public String getInstanceCapStr() {
if (instanceCap == Integer.MAX_VALUE)
return "";
else
return String.valueOf(instanceCap);
}
public List<SlaveTemplate> getTemplates() {
return Collections.unmodifiableList(templates);
}
public SlaveTemplate getTemplate(String template) {
for (SlaveTemplate t : templates) {
if (t.description.equals(template)) {
return t;
}
}
return null;
}
/**
* Gets {@link SlaveTemplate} that has the matching {@link Label}.
*/
public SlaveTemplate getTemplate(Label label) {
for (SlaveTemplate t : templates) {
if (t.getMode() == Node.Mode.NORMAL) {
if (label == null || label.matches(t.getLabelSet())) {
return t;
}
} else if (t.getMode() == Node.Mode.EXCLUSIVE) {
if (label != null && label.matches(t.getLabelSet())) {
return t;
}
}
}
return null;
}
/**
* Gets the {@link KeyPairInfo} used for the launch.
*/
public synchronized KeyPair getKeyPair() throws AmazonClientException, IOException {
if (usableKeyPair == null)
usableKeyPair = privateKey.find(connect());
return usableKeyPair;
}
/**
* Debug command to attach to a running instance.
*/
public void doAttach(StaplerRequest req, StaplerResponse rsp, @QueryParameter String id)
throws ServletException, IOException, AmazonClientException {
checkPermission(PROVISION);
SlaveTemplate t = getTemplates().get(0);
StringWriter sw = new StringWriter();
StreamTaskListener listener = new StreamTaskListener(sw);
EC2AbstractSlave node = t.attach(id, listener);
Jenkins.getInstance().addNode(node);
rsp.sendRedirect2(req.getContextPath() + "/computer/" + node.getNodeName());
}
public HttpResponse doProvision(@QueryParameter String template) throws ServletException, IOException {
checkPermission(PROVISION);
if (template == null) {
throw HttpResponses.error(SC_BAD_REQUEST, "The 'template' query parameter is missing");
}
SlaveTemplate t = getTemplate(template);
if (t == null) {
throw HttpResponses.error(SC_BAD_REQUEST, "No such template: " + template);
}
try {
EC2AbstractSlave node = getNewOrExistingAvailableSlave(t, null, true);
if (node == null)
throw HttpResponses.error(SC_BAD_REQUEST, "Cloud or AMI instance cap would be exceeded for: " + template);
Jenkins.getInstance().addNode(node);
return HttpResponses.redirectViaContextPath("/computer/" + node.getNodeName());
} catch (AmazonClientException e) {
throw HttpResponses.error(SC_INTERNAL_SERVER_ERROR, e);
}
}
/**
* Counts the number of instances in EC2 that can be used with the specified image and a template. Also removes any
* nodes associated with canceled requests.
*
* @param template If left null, then all instances are counted.
*/
private int countCurrentEC2Slaves(SlaveTemplate template) throws AmazonClientException {
LOGGER.log(Level.FINE, "Counting current slaves: " + (template != null ? (" AMI: " + template.getAmi()) : " All AMIS"));
int n = 0;
Set<String> instanceIds = new HashSet<String>();
String description = template != null ? template.description : null;
for (Reservation r : connect().describeInstances().getReservations()) {
for (Instance i : r.getInstances()) {
if (isEc2ProvisionedAmiSlave(i.getTags(), description) && (template == null
|| template.getAmi().equals(i.getImageId()))) {
InstanceStateName stateName = InstanceStateName.fromValue(i.getState().getName());
if (stateName != InstanceStateName.Terminated && stateName != InstanceStateName.ShuttingDown) {
LOGGER.log(Level.FINE, "Existing instance found: " + i.getInstanceId() + " AMI: " + i.getImageId()
+ " Template: " + description);
n++;
instanceIds.add(i.getInstanceId());
}
}
}
}
List<SpotInstanceRequest> sirs = null;
List<Filter> filters = new ArrayList<Filter>();
List<String> values;
if (template != null) {
values = new ArrayList<String>();
values.add(template.getAmi());
filters.add(new Filter("launch.image-id", values));
}
values = new ArrayList<String>();
values.add(EC2Tag.TAG_NAME_JENKINS_SLAVE_TYPE);
filters.add(new Filter("tag-key", values));
DescribeSpotInstanceRequestsRequest dsir = new DescribeSpotInstanceRequestsRequest().withFilters(filters);
try {
sirs = connect().describeSpotInstanceRequests(dsir).getSpotInstanceRequests();
} catch (Exception ex) {
// Some ec2 implementations don't implement spot requests (Eucalyptus)
LOGGER.log(Level.FINEST, "Describe spot instance requests failed", ex);
}
Set<SpotInstanceRequest> sirSet = new HashSet();
if (sirs != null) {
for (SpotInstanceRequest sir : sirs) {
sirSet.add(sir);
if (sir.getState().equals("open") || sir.getState().equals("active")) {
if (sir.getInstanceId() != null && instanceIds.contains(sir.getInstanceId()))
continue;
LOGGER.log(Level.FINE, "Spot instance request found: " + sir.getSpotInstanceRequestId() + " AMI: "
+ sir.getInstanceId() + " state: " + sir.getState() + " status: " + sir.getStatus());
n++;
if (sir.getInstanceId() != null)
instanceIds.add(sir.getInstanceId());
} else {
// Canceled or otherwise dead
for (Node node : Jenkins.getInstance().getNodes()) {
try {
if (!(node instanceof EC2SpotSlave))
continue;
EC2SpotSlave ec2Slave = (EC2SpotSlave) node;
if (ec2Slave.getSpotInstanceRequestId().equals(sir.getSpotInstanceRequestId())) {
LOGGER.log(Level.INFO, "Removing dead request: " + sir.getSpotInstanceRequestId() + " AMI: "
+ sir.getInstanceId() + " state: " + sir.getState() + " status: " + sir.getStatus());
Jenkins.getInstance().removeNode(node);
break;
}
} catch (IOException e) {
LOGGER.log(Level.WARNING, "Failed to remove node for dead request: " + sir.getSpotInstanceRequestId()
+ " AMI: " + sir.getInstanceId() + " state: " + sir.getState() + " status: " + sir.getStatus(),
e);
}
}
}
}
}
// Count nodes where the spot request does not yet exist (sometimes it takes time for the request to appear
// in the EC2 API)
for (Node node : Jenkins.getInstance().getNodes()) {
if (!(node instanceof EC2SpotSlave))
continue;
EC2SpotSlave ec2Slave = (EC2SpotSlave) node;
SpotInstanceRequest sir = ec2Slave.getSpotRequest();
if (sir == null) {
LOGGER.log(Level.FINE, "Found spot node without request: " + ec2Slave.getSpotInstanceRequestId());
n++;
continue;
}
if (sirSet.contains(sir))
continue;
sirSet.add(sir);
if (sir.getState().equals("open") || sir.getState().equals("active")) {
if (template != null) {
List<Tag> instanceTags = sir.getTags();
for (Tag tag : instanceTags) {
if (StringUtils.equals(tag.getKey(), EC2Tag.TAG_NAME_JENKINS_SLAVE_TYPE) && StringUtils.equals(tag.getValue(), getSlaveTypeTagValue(EC2_SLAVE_TYPE_SPOT, template.description)) && sir.getLaunchSpecification().getImageId().equals(template.getAmi())) {
if (sir.getInstanceId() != null && instanceIds.contains(sir.getInstanceId()))
continue;
LOGGER.log(Level.FINE, "Spot instance request found (from node): " + sir.getSpotInstanceRequestId() + " AMI: "
+ sir.getInstanceId() + " state: " + sir.getState() + " status: " + sir.getStatus());
n++;
if (sir.getInstanceId() != null)
instanceIds.add(sir.getInstanceId());
}
}
}
}
}
return n;
}
private boolean isEc2ProvisionedAmiSlave(List<Tag> tags, String description) {
for (Tag tag : tags) {
if (StringUtils.equals(tag.getKey(), EC2Tag.TAG_NAME_JENKINS_SLAVE_TYPE)) {
if (description == null) {
return true;
} else if (StringUtils.equals(tag.getValue(), EC2Cloud.EC2_SLAVE_TYPE_DEMAND)
|| StringUtils.equals(tag.getValue(), EC2Cloud.EC2_SLAVE_TYPE_SPOT)) {
// To handle cases where description is null and also upgrade cases for existing slave nodes.
return true;
} else if (StringUtils.equals(tag.getValue(), getSlaveTypeTagValue(EC2Cloud.EC2_SLAVE_TYPE_DEMAND, description))
|| StringUtils.equals(tag.getValue(), getSlaveTypeTagValue(EC2Cloud.EC2_SLAVE_TYPE_SPOT, description))) {
return true;
} else {
return false;
}
}
}
return false;
}
/**
* Returns the maximum number of possible slaves that can be created.
*/
private int getPossibleNewSlavesCount(SlaveTemplate template) throws AmazonClientException {
int estimatedTotalSlaves = countCurrentEC2Slaves(null);
int estimatedAmiSlaves = countCurrentEC2Slaves(template);
int availableTotalSlaves = instanceCap - estimatedTotalSlaves;
int availableAmiSlaves = template.getInstanceCap() - estimatedAmiSlaves;
LOGGER.log(Level.FINE, "Available Total Slaves: " + availableTotalSlaves + " Available AMI slaves: " + availableAmiSlaves
+ " AMI: " + template.getAmi() + " TemplateDesc: " + template.description);
return Math.min(availableAmiSlaves, availableTotalSlaves);
}
/**
* Obtains a slave whose AMI matches the AMI of the given template, and that also has requiredLabel (if requiredLabel is non-null)
* forceCreateNew specifies that the creation of a new slave is required. Otherwise, an existing matching slave may be re-used
*/
private synchronized EC2AbstractSlave getNewOrExistingAvailableSlave(SlaveTemplate template, Label requiredLabel, boolean forceCreateNew) {
/*
* Note this is synchronized between counting the instances and then allocating the node. Once the node is
* allocated, we don't look at that instance as available for provisioning.
*/
int possibleSlavesCount = getPossibleNewSlavesCount(template);
if (possibleSlavesCount < 0) {
LOGGER.log(Level.INFO, "Cannot provision - no capacity for instances: " + possibleSlavesCount);
return null;
}
try {
EnumSet<SlaveTemplate.ProvisionOptions> provisionOptions = EnumSet.noneOf(SlaveTemplate.ProvisionOptions.class);
if (forceCreateNew)
provisionOptions = EnumSet.of(SlaveTemplate.ProvisionOptions.FORCE_CREATE);
else if (possibleSlavesCount > 0)
provisionOptions = EnumSet.of(SlaveTemplate.ProvisionOptions.ALLOW_CREATE);
return template.provision(StreamTaskListener.fromStdout(), requiredLabel, provisionOptions);
} catch (IOException e) {
LOGGER.log(Level.WARNING, "Exception during provisioning", e);
return null;
}
}
@Override
public Collection<PlannedNode> provision(Label label, int excessWorkload) {
try {
List<PlannedNode> r = new ArrayList<PlannedNode>();
final SlaveTemplate t = getTemplate(label);
LOGGER.log(Level.INFO, "Attempting to provision slave from template " + t + " needed by excess workload of " + excessWorkload + " units of label '" + label + "'");
if (label == null) {
LOGGER.log(Level.WARNING, String.format("Label is null - can't calculate how many executors slave will have. Using %s number of executors", t.getNumExecutors()));
}
while (excessWorkload > 0) {
final EC2AbstractSlave slave = getNewOrExistingAvailableSlave(t, label, false);
// Returned null if a new node could not be created
if (slave == null)
break;
LOGGER.log(Level.INFO, String.format("We have now %s computers", Jenkins.getInstance().getComputers().length));
if (!(t.isNode())) {
Jenkins.getInstance().addNode(slave);
LOGGER.log(Level.INFO, String.format("Added node named: %s, We have now %s computers", slave.getNodeName(), Jenkins.getInstance().getComputers().length));
r.add(new PlannedNode(t.getDisplayName(), Computer.threadPoolForRemoting.submit(new Callable<Node>() {
public Node call() throws Exception {
long startTime = System.currentTimeMillis(); // fetch starting time
while ((System.currentTimeMillis() - startTime) < slave.launchTimeout * 1000) {
return tryToCallSlave(slave, t);
}
LOGGER.log(Level.WARNING, "Expected - Instance - failed to connect within launch timeout");
return tryToCallSlave(slave, t);
}
}), t.getNumExecutors()));
}
excessWorkload -= t.getNumExecutors();
}
LOGGER.log(Level.INFO, "Attempting provision - finished, excess workload: " + excessWorkload);
return r;
} catch (AmazonClientException e) {
LOGGER.log(Level.WARNING, "Exception during provisioning", e);
return Collections.emptyList();
} catch (IOException e) {
LOGGER.log(Level.WARNING, "Exception during provisioning", e);
return Collections.emptyList();
}
}
private EC2AbstractSlave tryToCallSlave(EC2AbstractSlave slave, SlaveTemplate template) {
try {
slave.toComputer().connect(false).get();
} catch (Exception e) {
if (template.spotConfig != null) {
if(StringUtils.isNotEmpty(slave.getInstanceId()) && slave.isConnected) {
LOGGER.log(Level.INFO, String.format("Instance id: %s for node: %s is connected now.", slave.getInstanceId(), slave.getNodeName()));
return slave;
}
}
}
return slave;
}
@Override
public boolean canProvision(Label label) {
return getTemplate(label) != null;
}
private AWSCredentialsProvider createCredentialsProvider() {
return createCredentialsProvider(useInstanceProfileForCredentials, credentialsId);
}
public static String getSlaveTypeTagValue(String slaveType, String templateDescription) {
return templateDescription != null ? slaveType + "_" + templateDescription : slaveType;
}
public static AWSCredentialsProvider createCredentialsProvider(final boolean useInstanceProfileForCredentials, final String credentialsId) {
if (useInstanceProfileForCredentials) {
return new InstanceProfileCredentialsProvider();
} else if (StringUtils.isBlank(credentialsId)) {
return new DefaultAWSCredentialsProviderChain();
} else {
AmazonWebServicesCredentials credentials = getCredentials(credentialsId);
return new StaticCredentialsProvider(credentials.getCredentials());
}
}
@CheckForNull
private static AmazonWebServicesCredentials getCredentials(@Nullable String credentialsId) {
if (StringUtils.isBlank(credentialsId)) {
return null;
}
return (AmazonWebServicesCredentials) CredentialsMatchers.firstOrNull(
CredentialsProvider.lookupCredentials(AmazonWebServicesCredentials.class, Jenkins.getInstance(),
ACL.SYSTEM, Collections.EMPTY_LIST),
CredentialsMatchers.withId(credentialsId));
}
/**
* Connects to EC2 and returns {@link AmazonEC2}, which can then be used to communicate with EC2.
*/
public synchronized AmazonEC2 connect() throws AmazonClientException {
try {
if (connection == null) {
connection = connect(createCredentialsProvider(), getEc2EndpointUrl());
}
return connection;
} catch (IOException e) {
throw new AmazonClientException("Failed to retrieve the endpoint", e);
}
}
/***
* Connect to an EC2 instance.
*
* @return {@link AmazonEC2} client
*/
public synchronized static AmazonEC2 connect(AWSCredentialsProvider credentialsProvider, URL endpoint) {
awsCredentialsProvider = credentialsProvider;
ClientConfiguration config = new ClientConfiguration();
config.setMaxErrorRetry(16); // Default retry limit (3) is low and often
// cause problems. Raise it a bit.
config.setSignerOverride("AWS4SignerType");
ProxyConfiguration proxyConfig = Jenkins.getInstance().proxy;
Proxy proxy = proxyConfig == null ? Proxy.NO_PROXY : proxyConfig.createProxy(endpoint.getHost());
if (!proxy.equals(Proxy.NO_PROXY) && proxy.address() instanceof InetSocketAddress) {
InetSocketAddress address = (InetSocketAddress) proxy.address();
config.setProxyHost(address.getHostName());
config.setProxyPort(address.getPort());
if (null != proxyConfig.getUserName()) {
config.setProxyUsername(proxyConfig.getUserName());
config.setProxyPassword(proxyConfig.getPassword());
}
}
AmazonEC2 client = new AmazonEC2Client(credentialsProvider, config);
client.setEndpoint(endpoint.toString());
return client;
}
/***
* Convert a configured hostname like 'us-east-1' to a FQDN or ip address
*/
public static String convertHostName(String ec2HostName) {
if (ec2HostName == null || ec2HostName.length() == 0)
ec2HostName = DEFAULT_EC2_HOST;
if (!ec2HostName.contains("."))
ec2HostName = "ec2." + ec2HostName + "." + AWS_URL_HOST;
return ec2HostName;
}
/***
* Convert a user entered string into a port number "" -> -1 to indicate default based on SSL setting
*/
public static Integer convertPort(String ec2Port) {
if (ec2Port == null || ec2Port.length() == 0)
return -1;
return Integer.parseInt(ec2Port);
}
/**
* Computes the presigned URL for the given S3 resource.
*
* @param path String like "/bucketName/folder/folder/abc.txt" that represents the resource to request.
*/
public URL buildPresignedURL(String path) throws AmazonClientException {
AWSCredentials credentials = awsCredentialsProvider.getCredentials();
long expires = System.currentTimeMillis() + 60 * 60 * 1000;
GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(path, credentials.getAWSSecretKey());
request.setExpiration(new Date(expires));
AmazonS3 s3 = new AmazonS3Client(credentials);
return s3.generatePresignedUrl(request);
}
/* Parse a url or return a sensible error */
public static URL checkEndPoint(String url) throws FormValidation {
try {
return new URL(url);
} catch (MalformedURLException ex) {
throw FormValidation.error("Endpoint URL is not a valid URL");
}
}
public static abstract class DescriptorImpl extends Descriptor<Cloud> {
public InstanceType[] getInstanceTypes() {
return InstanceType.values();
}
public FormValidation doCheckUseInstanceProfileForCredentials(@QueryParameter boolean value) {
if (value) {
try {
new InstanceProfileCredentialsProvider().getCredentials();
} catch (AmazonClientException e) {
return FormValidation.error(Messages.EC2Cloud_FailedToObtainCredentailsFromEC2(), e.getMessage());
}
}
return FormValidation.ok();
}
public FormValidation doCheckPrivateKey(@QueryParameter String value) throws IOException, ServletException {
boolean hasStart = false, hasEnd = false;
BufferedReader br = new BufferedReader(new StringReader(value));
String line;
while ((line = br.readLine()) != null) {
if (line.equals("
hasStart = true;
if (line.equals("
hasEnd = true;
}
if (!hasStart)
return FormValidation.error("This doesn't look like a private key at all");
if (!hasEnd)
return FormValidation
.error("The private key is missing the trailing 'END RSA PRIVATE KEY' marker. Copy&paste error?");
return FormValidation.ok();
}
protected FormValidation doTestConnection(URL ec2endpoint, boolean useInstanceProfileForCredentials, String credentialsId, String privateKey)
throws IOException, ServletException {
try {
AWSCredentialsProvider credentialsProvider = createCredentialsProvider(useInstanceProfileForCredentials, credentialsId);
AmazonEC2 ec2 = connect(credentialsProvider, ec2endpoint);
ec2.describeInstances();
if (privateKey == null)
return FormValidation.error("Private key is not specified. Click 'Generate Key' to generate one.");
if (privateKey.trim().length() > 0) {
// check if this key exists
EC2PrivateKey pk = new EC2PrivateKey(privateKey);
if (pk.find(ec2) == null)
return FormValidation
.error("The EC2 key pair private key isn't registered to this EC2 region (fingerprint is "
+ pk.getFingerprint() + ")");
}
return FormValidation.ok(Messages.EC2Cloud_Success());
} catch (AmazonClientException e) {
LOGGER.log(Level.WARNING, "Failed to check EC2 credential", e);
return FormValidation.error(e.getMessage());
}
}
public FormValidation doGenerateKey(StaplerResponse rsp, URL ec2EndpointUrl, boolean useInstanceProfileForCredentials, String credentialsId)
throws IOException, ServletException {
try {
AWSCredentialsProvider credentialsProvider = createCredentialsProvider(useInstanceProfileForCredentials, credentialsId);
AmazonEC2 ec2 = connect(credentialsProvider, ec2EndpointUrl);
List<KeyPairInfo> existingKeys = ec2.describeKeyPairs().getKeyPairs();
int n = 0;
while (true) {
boolean found = false;
for (KeyPairInfo k : existingKeys) {
if (k.getKeyName().equals("hudson-" + n))
found = true;
}
if (!found)
break;
n++;
}
CreateKeyPairRequest request = new CreateKeyPairRequest("hudson-" + n);
KeyPair key = ec2.createKeyPair(request).getKeyPair();
rsp.addHeader("script",
"findPreviousFormItem(button,'privateKey').value='" + key.getKeyMaterial().replace("\n", "\\n") + "'");
return FormValidation.ok(Messages.EC2Cloud_Success());
} catch (AmazonClientException e) {
LOGGER.log(Level.WARNING, "Failed to check EC2 credential", e);
return FormValidation.error(e.getMessage());
}
}
public ListBoxModel doFillCredentialsIdItems() {
return new StandardListBoxModel()
.withEmptySelection()
.withMatching(
CredentialsMatchers.always(),
CredentialsProvider.lookupCredentials(AmazonWebServicesCredentials.class,
Jenkins.getInstance(),
ACL.SYSTEM,
Collections.EMPTY_LIST));
}
}
public static void log(Logger logger, Level level, TaskListener listener, String message) {
log(logger, level, listener, message, null);
}
public static void log(Logger logger, Level level, TaskListener listener, String message, Throwable exception) {
logger.log(level, message, exception);
if (listener != null) {
if (exception != null)
message += " Exception: " + exception;
LogRecord lr = new LogRecord(level, message);
PrintStream printStream = listener.getLogger();
printStream.print(sf.format(lr));
}
}
} |
package hudson.remoting;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import javax.annotation.CheckForNull;
/**
* Restricts what classes can be received through remoting.
*
* @author Kohsuke Kawaguchi
* @since 2.53
*/
public abstract class ClassFilter {
/**
* Property to set to <b>override</b> the blacklist used by {{@link #DEFAULT} with a different set.
* The location should point to a a file containing regular expressions (one per line) of classes to blacklist.
* If this property is set but the file can not be read the default blacklist will be used.
* @since 2.53.2
*/
public static final String FILE_OVERRIDE_LOCATION_PROPERTY = "hudson.remoting.ClassFilter.DEFAULTS_OVERRIDE_LOCATION";
private static final Logger LOGGER = Logger.getLogger(ClassFilter.class.getName());
protected boolean isBlacklisted(String name) {
return false;
}
protected boolean isBlacklisted(Class c) {
return false;
}
public final String check(String name) {
if (isBlacklisted(name))
throw new SecurityException("Rejected: " +name);
return name;
}
public final Class check(Class c) {
if (isBlacklisted(c))
throw new SecurityException("Rejected: " +c.getName());
return c;
}
private static final String[] DEFAULT_PATTERNS = {
"^bsh[.].*",
"^com[.]google[.]inject[.].*",
"^com[.]mchange[.]v2[.]c3p0[.].*",
"^com[.]sun[.]jndi[.].*",
"^com[.]sun[.]corba[.].*",
"^com[.]sun[.]javafx[.].*",
"^com[.]sun[.]org[.]apache[.]regex[.]internal[.].*",
"^java[.]awt[.].*",
"^java[.]rmi[.].*",
"^javax[.]management[.].*",
"^javax[.]naming[.].*",
"^javax[.]script[.].*",
"^javax[.]swing[.].*",
"^org[.]apache[.]commons[.]beanutils[.].*",
"^org[.]apache[.]commons[.]collections[.]functors[.].*",
"^org[.]apache[.]myfaces[.].*",
"^org[.]apache[.]wicket[.].*",
".*org[.]apache[.]xalan.*",
"^org[.]codehaus[.]groovy[.]runtime[.].*",
"^org[.]hibernate[.].*",
"^org[.]python[.].*",
"^org[.]springframework[.](?!(\\p{Alnum}+[.])*\\p{Alnum}*Exception$).*",
"^sun[.]rmi[.].*"
};
/**
* A set of sensible default filtering rules to apply,
* unless the context guarantees the trust between two channels.
*/
public static final ClassFilter DEFAULT = createDefaultInstance();
/**
* No filtering whatsoever.
*/
public static final ClassFilter NONE = new ClassFilter() {
};
/**
* The default filtering rules to apply, unless the context guarantees the trust between two channels. The defaults
* values provide for user specified overrides - see {@link #FILE_OVERRIDE_LOCATION_PROPERTY}.
*/
/*package*/ static ClassFilter createDefaultInstance() {
try {
List<String> patternOverride = loadPatternOverride();
if (patternOverride != null) {
LOGGER.log(Level.FINE, "Using user specified overrides for class blacklisting");
return new RegExpClassFilter(patternOverride.toArray(new String[patternOverride.size()]));
} else {
LOGGER.log(Level.FINE, "Using default in built class blacklisting");
return new RegExpClassFilter(DEFAULT_PATTERNS);
}
}
catch (Error e) {
// when being used by something like XStream the actual cause gets swallowed
LOGGER.log(Level.SEVERE, "Failed to initialize the default class filter", e);
throw e;
}
}
@CheckForNull
private static List<String> loadPatternOverride() {
String prop = System.getProperty(FILE_OVERRIDE_LOCATION_PROPERTY);
if (prop==null) {
return null;
}
LOGGER.log(Level.FINE, "Attempting to load user provided overrides for ClassFiltering from ''{0}''.", prop);
File f = new File(prop);
if (!f.exists() || !f.canRead()) {
throw new Error("Could not load user provided overrides for ClassFiltering from as " + prop + " does not exist or is not readable.");
}
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(new FileInputStream(prop), Charset.defaultCharset()));
ArrayList<String> patterns = new ArrayList<String>();
for (String line = br.readLine(); line != null; line = br.readLine()) {
try {
Pattern.compile(line);
patterns.add(line);
} catch (PatternSyntaxException pex) {
throw new Error("Error compiling blacklist expressions - '" + line + "' is not a valid regular expression.", pex);
}
}
return patterns;
} catch (IOException ex) {
throw new Error("Could not load user provided overrides for ClassFiltering from as "+prop+" does not exist or is not readable.",ex);
} finally {
if (br != null) {
try {
br.close();
} catch (IOException ioEx) {
LOGGER.log(Level.WARNING, "Failed to cleanly close input stream", ioEx);
}
}
}
}
/**
* A class that uses a given set of regular expression patterns to determine if the class is blacklisted.
*/
private static final class RegExpClassFilter extends ClassFilter {
/**
* Any regex that is {@code ^some[.]package[.]name[.].*} or {@code ^some\.package\.name\.*} is really just a
* {@link String#startsWith(String)} test and we can reduce CPU usage by performing that test explicitly as
* well as reduce GC pressure.
*/
private static final Pattern OPTIMIZE1 = Pattern.compile(
"^\\^(([\\p{L}_$][\\p{L}\\p{N}_$]*(\\.|\\[\\.\\])?)+)\\.\\*$");
/**
* Any regex that is {@code ^\Qsome.package.name\E.*} is really just a {@link String#startsWith(String)}
* test and we can reduce CPU usage by performing that test explicitly as well as reduce GC pressure.
*/
private static final Pattern OPTIMIZE2 = Pattern.compile("^\\^\\Q[^\\\\]+\\\\E\\.\\*$");
private final Object[] blacklistPatterns;
public RegExpClassFilter(List<Pattern> blacklistPatterns) {
this.blacklistPatterns = blacklistPatterns.toArray(new Pattern[blacklistPatterns.size()]);
}
RegExpClassFilter(String[] patterns) {
blacklistPatterns = new Object[patterns.length];
for (int i = 0, patternsLength = patterns.length; i < patternsLength; i++) {
if (OPTIMIZE1.matcher(patterns[i]).matches()) {
// this is a simple startsWith test, no need to slow things down with a regex
blacklistPatterns[i] = patterns[i].substring(1,patterns[i].length()-2).replace("[.]",".");
} else if (OPTIMIZE2.matcher(patterns[i]).matches()) {
// this is a simple startsWith test, no need to slow things down with a regex
blacklistPatterns[i] = patterns[i].substring(3,patterns[i].length()-4);
} else {
blacklistPatterns[i] = Pattern.compile(patterns[i]);
}
}
}
@Override
protected boolean isBlacklisted(String name) {
for (int i = 0; i < blacklistPatterns.length; i++) {
Object p = blacklistPatterns[i];
if (p instanceof Pattern && ((Pattern)p).matcher(name).matches()) {
return true;
} else if (p instanceof String && name.startsWith((String)p)) {
return true;
}
}
return false;
}
/**
* Report the patterns that it's using to help users verify the use of custom filtering rule
* and inspect its content at runtime if necessary.
*/
@Override
public String toString() {
return Arrays.toString(blacklistPatterns);
}
}
}
/*
Publicized attack payload:
ObjectInputStream.readObject()
PriorityQueue.readObject()
Comparator.compare() (Proxy)
ConvertedClosure.invoke()
MethodClosure.call()
Method.invoke()
Runtime.exec()
ObjectInputStream.readObject()
AnnotationInvocationHandler.readObject()
Map(Proxy).entrySet()
AnnotationInvocationHandler.invoke()
LazyMap.get()
ChainedTransformer.transform()
ConstantTransformer.transform()
InvokerTransformer.transform()
Method.invoke()
Class.getMethod()
InvokerTransformer.transform()
Method.invoke()
Runtime.getRuntime()
InvokerTransformer.transform()
Method.invoke()
Runtime.exec()
ObjectInputStream.readObject()
PriorityQueue.readObject()
TransformingComparator.compare()
InvokerTransformer.transform()
Method.invoke()
Runtime.exec()
ObjectInputStream.readObject()
SerializableTypeWrapper.MethodInvokeTypeProvider.readObject()
SerializableTypeWrapper.TypeProvider(Proxy).getType()
AnnotationInvocationHandler.invoke()
HashMap.get()
ReflectionUtils.findMethod()
SerializableTypeWrapper.TypeProvider(Proxy).getType()
AnnotationInvocationHandler.invoke()
HashMap.get()
ReflectionUtils.invokeMethod()
Method.invoke()
Templates(Proxy).newTransformer()
AutowireUtils.ObjectFactoryDelegatingInvocationHandler.invoke()
ObjectFactory(Proxy).getObject()
AnnotationInvocationHandler.invoke()
HashMap.get()
Method.invoke()
TemplatesImpl.newTransformer()
TemplatesImpl.getTransletInstance()
TemplatesImpl.defineTransletClasses()
TemplatesImpl.TransletClassLoader.defineClass()
Pwner*(Javassist-generated).<static init>
Runtime.exec()
*/ |
/* Find the common ancestor of two nodes.
* */
public class P0413 {
private class Node {
int value;
Node left, right;
public Node(int value) {
this.value = value;
}
}
public Node findLCA(Node root, Node p, Node q) {
//if (root == null || p == null || q == null)
// return null;
// invalid inputs
if (p == null || q == null)
return null;
// invalid inputs or not find the nodes
if (root == null)
return null;
if (root == p || root == q) return root;
// find p and q in the left subtree
Node left = findLCA(root.left, p, q);
// find them in the right subtree
Node right = findLCA(root.right, p, q);
// find them in the right and left subtrees respecitvely
if (left != null && right != null) return root;
// find one of them in the left
return (left != null) ? left : right;
}
public Node buildTree() {
Node root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
root.left.right.right = new Node(9);
root.right.left = new Node(6);
root.right.right= new Node(10);
root.left.left.left = new Node(7);
root.left.left.left.left = new Node(8);
return root;
}
public static void main(String[] args) {
P0413 p0413 = new P0413();
Node root = p0413.buildTree();
Node p = root.left.left.left;
//Node q = root.left.left.left.left;
Node q = root.left.right.right;
Node res = p0413.findLCA(root, p, q);
System.out.println(res.value);
}
} |
package cruise.umple.compiler;
import static org.junit.Assert.*;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import cruise.umple.util.SampleFileWriter;
public class UmpleImportTest {
private static String pathToInput = SampleFileWriter.rationalize("test/cruise/umple/compiler");
private static String getAbsFile(final String name) {
return pathToInput + "/" + name;
}
private static String loadScxmlFile(final String name) throws Exception {
assertTrue((new File(name)).exists());
ScxmlImportHandler handler = new ScxmlImportHandler();
UmpleImportModel umple = handler.readDataFromXML(name);
return umple.generateUmple();
}
private static String loadECoreFile(final String name) throws Exception {
assertTrue((new File(name)).exists());
EcoreImportHandler handler = new EcoreImportHandler();
UmpleImportModel umple = handler.readDataFromXML(name);
return umple.generateUmple();
}
private static String loadPapyrusFile(final String name) throws Exception {
assertTrue((new File(name)).exists());
PapyrusImportHandler handler = new PapyrusImportHandler();
UmpleImportModel umple = handler.readDataFromXML(name);
return umple.generateUmple();
}
private static void assertImportFile(final UmpleImportType type,
final String expectedPath,
final String importFile) throws Exception {
final String realImportFile = getAbsFile(importFile);
String content;
if (type == UmpleImportType.ECORE) {
content = loadECoreFile(realImportFile);
} else if (type == UmpleImportType.SCXML) {
content = loadScxmlFile(realImportFile);
} else if (type == UmpleImportType.PAPYRUS) {
content = loadPapyrusFile(realImportFile);
} else {
throw new IllegalArgumentException("Unknown UmpleImportType parameter = " + type);
}
final File expectedFile = new File(getAbsFile(expectedPath));
assertTrue(expectedFile.exists());
SampleFileWriter.assertFileContent(expectedFile, content);
}
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
@Test
public void EcoreClassParsingTest() throws Exception {
assertImportFile(UmpleImportType.ECORE,
"ECoreImport_ClassWithNamespace.ump",
"ECoreImport_ClassWithNamespace.ecore");
}
@Test
public void EcoreInterfaceParsingTest() throws Exception {
assertImportFile(UmpleImportType.ECORE,
"ECoreImport_InterfaceWithNamespace.ump",
"ECoreImport_InterfaceWithNamespace.ecore");
}
@Test
public void EcoreClassAttributesParsingTest() throws Exception {
assertImportFile(UmpleImportType.ECORE,
"ECoreImport_ClassAttributes.ump",
"ECoreImport_ClassAttributes.ecore");
}
@Test
public void EcoreClassAssociationParsingTest() throws Exception {
assertImportFile(UmpleImportType.ECORE,
"ECoreImport_Association.ump",
"ECoreImport_Association.ecore");
}
@Test
public void EcoreLargeScaleACGParsingTest() throws Exception {
assertImportFile(UmpleImportType.ECORE,
"ECoreImport_largeScale_ACG.ump",
"ECoreImport_largeScale_ACG.ecore");
}
@Test
public void EcoreLargeScaleACMEParsingTest() throws Exception {
assertImportFile(UmpleImportType.ECORE,
"ECoreImport_largeScale_ACME.ump",
"ECoreImport_largeScale_ACME.ecore");
}
@Test
public void ScxmlEmptyStateMachineTest() throws Exception {
assertImportFile(UmpleImportType.SCXML,
"ScxmlImport_empty.ump",
"ScxmlImport_empty.scxml.txt");
}
@Test
public void ScxmlOneStateTest() throws Exception {
assertImportFile(UmpleImportType.SCXML,
"ScxmlImport_one_state.ump",
"ScxmlImport_one_state.scxml.txt");
}
@Test
public void ScxmlMultipleStatesTest() throws Exception {
assertImportFile(UmpleImportType.SCXML,
"ScxmlImport_multiple_states.ump",
"ScxmlImport_multiple_states.scxml.txt");
}
@Test
public void ScxmlOneNestedStateTest() throws Exception {
assertImportFile(UmpleImportType.SCXML,
"ScxmlImport_one_nested_state.ump",
"ScxmlImport_one_nested_state.scxml.txt");
}
@Test
public void ScxmlMultipleNestedStatesTest() throws Exception {
assertImportFile(UmpleImportType.SCXML,
"ScxmlImport_multiple_nested_states.ump",
"ScxmlImport_multiple_nested_states.scxml.txt");
}
@Test
public void ScxmlTransitionTest() throws Exception {
assertImportFile(UmpleImportType.SCXML,
"ScxmlImport_transition.ump",
"ScxmlImport_transition.scxml.txt");
}
@Test
public void ScxmlTransitionWithGuardTest() throws Exception {
assertImportFile(UmpleImportType.SCXML,
"ScxmlImport_transition_with_guard.ump",
"ScxmlImport_transition_with_guard.scxml.txt");
}
@Test
public void ScxmlOnEntryEmptyTest() throws Exception {
assertImportFile(UmpleImportType.SCXML,
"ScxmlImport_onentry_empty.ump",
"ScxmlImport_onentry_empty.scxml.txt");
}
@Test
public void ScxmlOnEntryWithActionTest() throws Exception {
assertImportFile(UmpleImportType.SCXML,
"ScxmlImport_onentry_with_action.ump",
"ScxmlImport_onentry_with_action.scxml.txt");
}
@Test
public void ScxmlOnEntryWithMultilineActionTest() throws Exception {
assertImportFile(UmpleImportType.SCXML,
"ScxmlImport_onentry_with_multiline_action.ump",
"ScxmlImport_onentry_with_multiline_action.scxml.txt");
}
@Test
public void ScxmlOnEntryAndOnExitTest() throws Exception {
assertImportFile(UmpleImportType.SCXML,
"ScxmlImport_onentry_and_onexit.ump",
"ScxmlImport_onentry_and_onexit.scxml.txt");
}
@Test
public void ScxmlTransitionActionTest() throws Exception {
assertImportFile(UmpleImportType.SCXML,
"ScxmlImport_transition_action.ump",
"ScxmlImport_transition_action.scxml.txt");
}
@Test
public void ScxmlInitialStateTest() throws Exception {
assertImportFile(UmpleImportType.SCXML,
"ScxmlImport_initial_state.ump",
"ScxmlImport_initial_state.scxml.txt");
}
@Test
public void ScxmlInitialNestedStateTest() throws Exception {
assertImportFile(UmpleImportType.SCXML,
"ScxmlImport_initial_nested_state.ump",
"ScxmlImport_initial_nested_state.scxml.txt");
}
@Test
public void ScxmlAutoTransitionTest() throws Exception {
assertImportFile(UmpleImportType.SCXML,
"ScxmlImport_autotransition.ump",
"ScxmlImport_autotransition.scxml.txt");
}
@Test
public void PapyrusClassAttributesParsingTest() throws Exception {
assertImportFile(UmpleImportType.PAPYRUS,
"PapyrusImport_ClassAttributes.ump",
"PapyrusImport_ClassAttributes.uml.txt");
}
@Test
public void PapyrusClassAssociationParsingTest() throws Exception {
assertImportFile(UmpleImportType.PAPYRUS,
"PapyrusImport_ClassAssociations.ump",
"PapyrusImport_ClassAssociations.uml.txt");
}
} |
package io.sigpipe.sing.query;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import io.sigpipe.sing.dataset.feature.Feature;
import io.sigpipe.sing.graph.Vertex;
import io.sigpipe.sing.serialization.ByteSerializable;
import io.sigpipe.sing.serialization.SerializationException;
import io.sigpipe.sing.serialization.SerializationInputStream;
import io.sigpipe.sing.serialization.SerializationOutputStream;
/**
* General query interface. In SING, queries are executed against a graph
* (defined by its root vertex).
*
* @author malensek
*/
public abstract class Query implements ByteSerializable {
protected Map<String, List<Expression>> expressions = new HashMap<>();
public Query() {
}
public abstract void execute(Vertex root)
throws IOException, QueryException;
public void addExpression(Expression e) {
String name = e.getOperand().getName();
List<Expression> expList = expressions.get(name);
if (expList == null) {
expList = new ArrayList<>();
expressions.put(name, expList);
}
expList.add(e);
}
protected Set<Vertex> evaluate(Vertex vertex, List<Expression> expressions)
throws QueryException {
Set<Vertex> matches = new HashSet<>(vertex.numNeighbors(), 1.0f);
for (Expression expression : expressions) {
Operator operator = expression.getOperator();
Feature operand = expression.getOperand();
switch (operator) {
case EQUAL: {
matches.add(vertex.getNeighbor(operand));
break;
}
case NOTEQUAL: {
boolean exists = matches.contains(operand);
matches.addAll(vertex.getAllNeighbors());
if (exists == false) {
/* If the operand (not equal value) wasn't already added
* by another expression, we can safely remove it now.
* In other words, if another expression includes the
* value excluded by this expression, the user has
* effectively requested the entire neighbor set. */
matches.remove(operand);
}
break;
}
case LESS: {
matches.addAll(
vertex.getNeighborsLessThan(operand, false)
.values());
break;
}
case LESSEQUAL: {
matches.addAll(
vertex.getNeighborsLessThan(operand, true)
.values());
break;
}
case GREATER: {
matches.addAll(
vertex.getNeighborsGreaterThan(operand, false)
.values());
break;
}
case GREATEREQUAL: {
matches.addAll(
vertex.getNeighborsGreaterThan(operand, true)
.values());
break;
}
case RANGE_INC: {
Feature secondOperand = expression.getSecondOperand();
matches.addAll(vertex.getNeighborsInRange(
operand, true,
secondOperand, true)
.values());
break;
}
case RANGE_EXC: {
Feature secondOperand = expression.getSecondOperand();
matches.addAll(vertex.getNeighborsInRange(
operand, false,
secondOperand, false)
.values());
break;
}
case RANGE_INC_EXC: {
Feature secondOperand = expression.getSecondOperand();
matches.addAll(vertex.getNeighborsInRange(
operand, true,
secondOperand, false)
.values());
break;
}
case RANGE_EXC_INC: {
Feature secondOperand = expression.getSecondOperand();
matches.addAll(vertex.getNeighborsInRange(
operand, false,
secondOperand, true)
.values());
break;
}
case STR_PREFIX: {
vertex
.getAllNeighbors()
.stream()
.filter(v -> v
.getLabel()
.getString()
.startsWith(operand.getString()))
.forEach(matches::add);
break;
}
case STR_SUFFIX: {
vertex
.getAllNeighbors()
.stream()
.filter(v -> v
.getLabel()
.getString()
.endsWith(operand.getString()))
.forEach(matches::add);
break;
}
default:
throw new QueryException("Unknown operator: " + operator);
}
}
return matches;
}
@Deserialize
public Query(SerializationInputStream in)
throws IOException, SerializationException {
int size = in.readInt();
this.expressions = new HashMap<>(size);
for (int i = 0; i < size; ++i) {
int listSize = in.readInt();
List<Expression> expList = new ArrayList<>(listSize);
for (int j = 0; j < listSize; ++j) {
Expression exp = new Expression(in);
expList.add(exp);
}
String featureName = expList.get(0).getOperand().getName();
this.expressions.put(featureName, expList);
}
}
@Override
public void serialize(SerializationOutputStream out)
throws IOException {
out.writeInt(this.expressions.size());
for (List<Expression> expList : this.expressions.values()) {
out.writeInt(expList.size());
for (Expression expression : expList) {
expression.serialize(out);
}
}
}
} |
package io.sqooba.traildbj;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
/**
* This class is used to perform native call to the TrailDB C library. Base on the available Python bindings.
*
* @author Vilya
*
*/
public enum TrailDBj {
INSTANCE;
/**
* Convert a raw 16-byte UUID into its hexadecimal string representation.
*
* @param rawUUID 16-byte UUID.
* @return A 32-byte hexadecimal string representation.
*/
public String UUIDHex(byte[] rawUUID) {
return Hex.encodeHexString(rawUUID);
}
/**
* Convert a 32-byte hexadecimal string representation of an UUID into a raw 16-byte UUID.
*
* @param hexUUID The UUID to be converted.
* @return The raw 16-byte UUID.
*/
public byte[] UUIDRaw(String hexUUID) {
byte[] b = null;
try {
b = Hex.decodeHex(hexUUID.toCharArray());
} catch(DecoderException e) {
LOGGER.log(Level.SEVERE, "Failed to convert hexstring to string.", e);
}
return b;
}
private static final Logger LOGGER = Logger.getLogger(TrailDBj.class.getName());
/** 8 bytes are need to represents 64 bits. */
private static final int UINT64 = 8;
static {
loadLib("traildb4j");
}
/**
* Extract the library from the jar/project, copy it outside so we can load it because this is not possible from
* inside the jar.
*
* @param name The name of the library, without prefix/suffix.
*/
private static void loadLib(String name) {
name = System.mapLibraryName(name);
try {
InputStream in = TrailDBj.class.getResourceAsStream("/" + name);
File dirOut = new File("TrailDBWrapper/");
dirOut.mkdir();
File fileOut = File.createTempFile("traildb4j", name.substring(name.indexOf(".")), dirOut);
System.out.println("Writing lib to: " + fileOut.getAbsolutePath());
OutputStream out = FileUtils.openOutputStream(fileOut);
IOUtils.copy(in, out);
in.close();
out.close();
fileOut.deleteOnExit();
System.load(fileOut.getAbsolutePath());
} catch(Exception e) {
LOGGER.log(Level.SEVERE, "Failed to load library.", e);
System.exit(-1);
}
}
// Construct a new TrailDB
/** tdb_cons *tdb_cons_init(void) */
private native ByteBuffer tdbConsInit();
/** tdb_error tdb_cons_open(tdb_const *cons, const char *root, const char **ofield_names, uint64_t num_ofields) */
private native int tdbConsOpen(ByteBuffer cons, String root, String[] ofieldNames, long numOfields);
/** void tdb_cons_close(tdb_cons *cons) */
private native void tdbConsClose(ByteBuffer cons);
/**
* tdb_error tdb_cons_add(tdb_cons *cons,const uint8_t uuid[16],const uint64_t timestamp,const char **values,const
* uint64_t *value_lengths)
*/
private native int tdbConsAdd(ByteBuffer cons, byte[] uuid, long timestamp, String[] values,
long[] valueLengths);
/** tdb_error tdb_cons_append(tdb_cons *cons, const tdb *db) */
private native int tdbConsAppend(ByteBuffer cons, ByteBuffer db);
/** tdb_error tdb_cons_finalize(tdb_cons *cons) */
private native int tdbConsFinalize(ByteBuffer cons);
// Open a TrailDB and access metadata.
/** tdb *tdb_init(void) */
private native ByteBuffer tdbInit();
/** tdb_error tdb_open(tdb *tdb, const char *root) */
private native int tdbOpen(ByteBuffer tdb, String root);
/** void tdb_close(tdb *db) */
private native void tdbClose(ByteBuffer db);
/** uint64_t tdb_num_trails(const tdb *db) */
private native long tdbNumTrails(ByteBuffer db);
/** uint64_t tdb_num_events(const tdb *db) */
private native long tdbNumEvents(ByteBuffer db);
/** uint64_t tdb_num_fields(const tdb *db) */
private native long tdbNumFields(ByteBuffer db);
/** uint64_t tdb_min_timestamp(const tdb *db) */
private native long tdbMinTimestamp(ByteBuffer db);
/** uint64_t tdb_max_timestamp(const tdb *db) */
private native long tdbMaxTimestamp(ByteBuffer db);
/** uint64_t tdb_version(const tdb *db) */
private native long tdbVersion(ByteBuffer db);
/** const char *tdb_error_str(tdb_error errcode) */
private native String tdbErrorStr(int errcode);
// Working with items, fields and values.
/** uint64_t tdb_lexicon_size(const tdb *db, tdb_field field) */
private native long tdbLexiconSize(ByteBuffer db, long field); // tdb_field is a C uint32_t, ID of the field.
/** tdb_error tdb_get_field(tdb *db, const char *field_name, tdb_field *field) */
private native int tdbGetField(ByteBuffer db, String fieldName, ByteBuffer field);
/** const char *tdb_get_field_name(tdb *db, tdb_field field) */
private native String tdbGetFieldName(ByteBuffer db, long field);
/** tdb_item tdb_get_item(tdb *db, tdb_field field, const char *value, uint64_t value_length) */
private native long tdbGetItem(ByteBuffer db, long field, String value);
/** const char *tdb_get_value(tdb *db, tdb_field field, tdb_val val, uint64_t *value_length) */
// TODO WARNING be extremely careful here with val(uint64_t)
private native String tdbGetValue(ByteBuffer db, long field, long val, ByteBuffer value_length);
/** const char *tdb_get_item_value(tdb *db, tdb_item item, uint64_t *value_length) */
private native String tdbGetItemValue(ByteBuffer db, long item, ByteBuffer value_length);
// Working with UUIDs.
/** const uint8_t *tdb_get_uuid(const tdb *db, uint64_t trail_id) */
private native ByteBuffer tdbGetUUID(ByteBuffer db, long traildId);
/** tdb_error tdb_get_trail_id(const tdb *db, const uint8_t uuid[16], uint64_t *trail_id) */
private native int tdbGetTrailId(ByteBuffer db, byte[] uuid, ByteBuffer trailId);
// Query events with cursors.
/** tdb_cursor *tdb_cursor_new(const tdb *db) */
private native ByteBuffer tdbCursorNew(ByteBuffer db); // A cursor is a void *.
/** void tdb_cursor_free(tdb_cursor *cursor) */
private native void tdbCursorFree(ByteBuffer cursor);
/** tdb_error tdb_get_trail(tdb_cursor *cursor, uint64_t trail_id) */
private native int tdbGetTrail(ByteBuffer cursor, long trailID);
/** uint64_t tdb_get_trail_length(tdb_cursor *cursor) */
private native long tdbGetTrailLength(ByteBuffer cursor);
/** const tdb_event *tdb_cursor_next(tdb_cursor *cursor) */
private native int tdbCursorNext(ByteBuffer cursor, Event event); // Fill the event in jni.
// Helper classes.
/**
* Class allowing to easily construct a new TrailDB.
*
* @author Vilya
*/
public static class TrailDBConstructor {
private TrailDBj trailDBj = TrailDBj.INSTANCE;
/** New TrailDB output path, without .tdb. */
private String path;
/** Names of fields in the new TrailDB. */
private String[] ofields;
/** Handle to the TrailDB, returned by init method. */
private ByteBuffer cons;
/**
* Construct a new TrailDB.
*
* @param path TrailDB output path.
* @param ofields Names of fields.
* @throws NullPointerException If given path is null.
* @throws TrailDBError If allocation fails or can not open constructor.
*/
public TrailDBConstructor(String path, String[] ofields) {
if (path == null) {
throw new NullPointerException("Path must not be null.");
}
if (Arrays.asList(ofields).contains("")) {
throw new IllegalArgumentException("Fields must not contain empty String.");
}
// Initialisation.
this.cons = this.trailDBj.tdbConsInit();
if (this.cons == null) {
throw new TrailDBError("Failed to allocate memory for constructor.");
}
if (this.trailDBj.tdbConsOpen(this.cons, path, ofields, ofields.length) != 0) {
throw new TrailDBError("Can not open constructor.");
}
this.path = path;
this.ofields = ofields;
}
public void add(String uuid, long timestamp, String[] values) {
int n = values.length;
if (n != this.ofields.length) {
// FIXME this is a hack to avoid random errors in the C lib.
// Need to investigate add function in JNI.
throw new TrailDBError("Number of values does not match number of fields.");
}
long[] value_lenghts = new long[n];
for(int i = 0; i < n; i++) {
value_lenghts[i] = values[i].length();
}
byte[] rawUUID = this.trailDBj.UUIDRaw(uuid);
if (rawUUID == null) {
throw new IllegalArgumentException("uuid is invalid.");
}
int errCode = this.trailDBj.tdbConsAdd(this.cons, rawUUID, timestamp, values, value_lenghts);
if (errCode != 0) {
throw new TrailDBError("Failed to add: " + errCode);
}
}
/**
* Merge an existing TrailDB to this constructor. The fields must be equal between the existing and the new
* TrailDB.
*
* @param db The db to merge to this one.
* @throws TrailDBError if the merge fails.
*/
public void append(TrailDB db) {
int errCode = this.trailDBj.tdbConsAppend(this.cons, db.db);
if (errCode != 0) {
throw new TrailDBError("Failed to merge dbs: " + errCode);
}
}
/**
* Finalize TrailDB construction. Finalization takes care of compacting the events and creating a valid TrailDB
* file. Events can not be added after this has been called.
*/
public TrailDB finalise() {
if (this.trailDBj.tdbConsFinalize(this.cons) != 0) {
throw new TrailDBError("Failed to finalize.");
}
LOGGER.log(Level.INFO, "Finalisation done.");
return new TrailDB(this.path);
}
@Override
protected void finalize() {
if (this.cons != null) {
LOGGER.log(Level.INFO, "Closing TrailDB.");
this.trailDBj.tdbConsClose(this.cons);
}
}
}
/**
* Class used to query an existing TrailDB.
*
* @author Vilya
*
*/
public static class TrailDB {
private TrailDBj trailDBj = TrailDBj.INSTANCE;
/** ByteBuffer holding a pointer to the traildb. */
private ByteBuffer db;
private long numTrails;
private long numEvents;
private long numFields;
private List<String> fields;
/**
* Construct a TrailDB on the given .tdb file.
*
* @param path The path to the TrailDB file.
*/
public TrailDB(String path) {
if (path == null) {
throw new IllegalArgumentException("Path must not be null.");
}
ByteBuffer db = this.trailDBj.tdbInit();
this.db = db;
if (this.trailDBj.tdbOpen(this.db, path) != 0) {
throw new TrailDBError("Failed to opend db.");
}
this.numTrails = this.trailDBj.tdbNumTrails(db);
this.numEvents = this.trailDBj.tdbNumEvents(db);
this.numFields = this.trailDBj.tdbNumFields(db);
this.fields = new ArrayList<>((int)this.numFields);
for(int i = 0; i < this.numFields; i++) {
this.fields.add(this.trailDBj.tdbGetFieldName(this.db, i));
}
}
/**
* Return the number of trails in the TrailDB.
*
* @return The number of trails.
*/
public long length() {
return this.numTrails;
}
/**
* Get the oldest timestamp.
*
* @return The oldest timestamp.
*/
public long getMinTimestamp() {
long min = this.trailDBj.tdbMinTimestamp(this.db);
if (min < 0) {
LOGGER.log(Level.WARNING, "long overflow, received a negtive value for min timestamp.");
}
return min;
}
/**
* Get the newest timestamp.
*
* @return The newest timestmap.
*/
public long getMaxTimestamp() {
long max = this.trailDBj.tdbMaxTimestamp(this.db);
if (max < 0) {
LOGGER.log(Level.WARNING, "long overflow, received a negtive value for max timestamp.");
}
return max;
}
/**
* Get the version.
*
* @return The version.
*/
public long getVersion() {
long version = this.trailDBj.tdbVersion(this.db);
if (version < 0) {
LOGGER.log(Level.WARNING, "version overflow.");
}
return version;
}
/**
* Get the field ID given a field name.
*
* @param fieldName The field name.
* @return The corresponding field ID.
* @throws TrailDBError if the specified field is not found.
*/
public long getField(String fieldName) {
ByteBuffer b = ByteBuffer.allocate(4);
if (this.trailDBj.tdbGetField(this.db, fieldName, b) != 0) {
throw new TrailDBError("Failed to retreive field. Field not found");
}
return b.getInt(0);
}
/**
* Get the number of distinct values in the given field, +1 counting the empty string if not present.
*
* @param field The field ID.
* @return The number of distinct values.
* @throws TrailDBError if the field index is invalid ( <=0 | > number of fields).
*/
public long getLexiconSize(long field) {
long value = this.trailDBj.tdbLexiconSize(this.db, field);
if (value == 0) {
throw new TrailDBError("Invalid field index.");
}
return value;
}
/**
* Get the field name given a field ID.
*
* @param fieldId The field ID.
* @return The corresponding field name.
* @throws TrailDBError if the field id is invalid ( <=0 | > number of fields).
*/
public String getFieldName(long fieldId) {
String res = this.trailDBj.tdbGetFieldName(this.db, fieldId);
if (res == null) {
throw new TrailDBError("Invalid field id.");
}
return res;
}
/**
* <p>Get the item corresponding to a value. Note that this is a relatively slow operation that may need to scan
* through all values in the field.
*
* <p> WARNING: the returned value maybe suffer overflow!
*
* @param fieldID The field ID.
* @param value The value in the field.
* @return An item encoded in a long, which was casted from uint64_t.
* @throws TrailDBError if no item is found.
*/
public long getItem(long fieldID, String value) {
long item = this.trailDBj.tdbGetItem(this.db, fieldID, value);
if (item == 0) {
throw new TrailDBError("No item found.");
}
if (item < 0) {
LOGGER.warning("Returned item overflow, deal with it carefully!");
}
return item;
}
/**
* <p> Get the value corresponding to a field ID and value ID pair.
*
* <p> Calling with the empty string for {@code val} will result in an error.
*
* @param field The field ID.
* @param val The value ID.
* @return The corresponding field value.
* @throws TrailDBError if the returned value is too big for Java or not found in the db.
*/
public String getValue(long field, long val) {
ByteBuffer bb = ByteBuffer.allocate(8);
String value = this.trailDBj.tdbGetValue(this.db, field, val, bb);
if (value == null) {
throw new TrailDBError("Error reading value.");
}
long value_length = bb.getLong(0);
if (value_length > Integer.MAX_VALUE) {
throw new TrailDBError(
"Overflow, received a String value that is larger than the java String capacity.");
}
return value.substring(0, (int)value_length);
}
/**
* Get the value corresponding to an item. This is a shorthand version of getValue().
*
* @param item The item.
* @return The corresponding field value.
* @throws TrailDBError if the value was not found or the returned value is too big for Java.
*/
public String getItemValue(long item) {
ByteBuffer bb = ByteBuffer.allocate(8);
String value = this.trailDBj.tdbGetItemValue(this.db, item, bb);
if (value == null) {
throw new TrailDBError("Value not found.");
}
long value_length = bb.getLong(0);
if (value_length > Integer.MAX_VALUE) {
throw new TrailDBError(
"Overflow, received a String value that is larger than the java String capacity.");
}
return value.substring(0, (int)value_length);
}
public String getUUID(long trailID) {
if (trailID < 0 || trailID >= this.length()) {
throw new IllegalArgumentException("Invalid trail ID.");
}
ByteBuffer uuid = this.trailDBj.tdbGetUUID(this.db, trailID);
if (uuid == null) {
throw new TrailDBError("Invalid trail ID.");
}
byte[] bytes = new byte[uuid.capacity()];
uuid.position(0);
uuid.get(bytes, 0, uuid.capacity());
return this.trailDBj.UUIDHex(bytes);
}
public long getTrailID(String uuid) {
ByteBuffer trailID = ByteBuffer.allocate(UINT64);
byte[] rawUUID = this.trailDBj.UUIDRaw(uuid);
if (rawUUID == null) {
throw new IllegalArgumentException("Invalid UUID.");
}
int errCode = this.trailDBj.tdbGetTrailId(this.db, rawUUID, trailID);
if (errCode != 0) {
throw new TrailDBError("UUID not found. " + errCode);
}
long res = trailID.getLong(0);
if (res < 0) {
LOGGER.warning("Received trail ID overflow: " + res);
}
return res;
}
public TrailDBCursor trail(long trailID) { // Python has more params.
ByteBuffer cursor = this.trailDBj.tdbCursorNew(this.db);
if (cursor == null) {
throw new TrailDBError("Memory allocation failed for cursor.");
}
int errCode = this.trailDBj.tdbGetTrail(cursor, trailID);
if (errCode != 0) {
throw new TrailDBError("Falied to create cursor: " + errCode);
}
Event e = new Event(this, this.fields);
return new TrailDBCursor(cursor, e);
}
public Map<String, TrailDBCursor> trails() {
Map<String, TrailDBCursor> res = new HashMap<>();
for(int i = 0; i < this.length(); i++) {
res.put(this.getUUID(i), this.trail(i));
}
return res;
}
@Override
protected void finalize() {
if (this.db != null) {
this.trailDBj.tdbClose(this.db);
}
}
}
public static class TrailDBCursor implements Iterable<Event> {
private ByteBuffer cursor;
private Event event;
protected TrailDBCursor(ByteBuffer cursor, Event event) {
this.event = event;
this.cursor = cursor;
}
@Override
protected void finalize() {
if (this.cursor != null) {
TrailDBj.INSTANCE.tdbCursorFree(this.cursor);
}
}
@Override
public Iterator<Event> iterator() {
return new Iterator<TrailDBj.Event>() {
int errCode = 0;
@Override
public Event next() {
if (!TrailDBCursor.this.event.isBuilt()) {
TrailDBj.INSTANCE.tdbCursorNext(TrailDBCursor.this.cursor, TrailDBCursor.this.event);
}
return TrailDBCursor.this.event;
}
@Override
public boolean hasNext() {
return TrailDBj.INSTANCE.tdbCursorNext(TrailDBCursor.this.cursor, TrailDBCursor.this.event) == 0;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
}
public static class Event {
private TrailDB trailDB;
private long timestamp;
private long numItems;
private List<Long> items; // items encoded on uint64_t.
/** This one contains the timestamp name. */
private List<String> fieldsNames;
/** Does NOT contain the timestamp value. */
private List<String> fieldsValues;
private boolean built = false;
/**
* The constructor just initialise the name of the fields (timestamp, field1, field2,...) and doest NOT fill
* items.
*
* @param fieldsNames
*/
protected Event(TrailDB trailDB, List<String> fieldsNames) {
this.trailDB = trailDB;
this.fieldsNames = fieldsNames;
}
public long getTimestamp() {
return this.timestamp;
}
public long getNumItems() {
return this.numItems;
}
public List<String> getFieldNames() {
return Collections.unmodifiableList(this.fieldsNames);
}
public List<String> getFieldsValues() {
return Collections.unmodifiableList(this.fieldsValues);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
String sep = ", ";
for(int i = 0; i < this.numItems; i++) {
if (i == this.numItems - 1) {
sep = "";
}
// Skip the "time" in names.
sb.append(this.fieldsNames.get(i + 1) + "=" + this.fieldsValues.get(i) + sep);
}
return "Event(time=" + this.timestamp + ", " + sb.toString() + ")";
}
protected void build(long timestamp, long numItems) {
this.timestamp = timestamp;
this.numItems = numItems;
this.items = new ArrayList<>((int)numItems);
this.fieldsValues = new ArrayList<>();
this.built = true;
}
protected void addItem(long item) {
this.items.add(item);
this.fieldsValues.add(this.trailDB.getItemValue(item));
}
protected boolean isBuilt() {
return this.built;
}
}
/**
* Exception thrown when something bad happens while performing action on the TrailDB.
*
* @author Vilya
*/
public static class TrailDBError extends RuntimeException {
private static final long serialVersionUID = -6086129664942253809L;
public TrailDBError(String message) {
super(message);
}
}
} |
package is.ru.hugb;
import java.util.ArrayList;
public class TicTacToeService {
private TicTacToe ticTacToe = new TicTacToe();
private int turnCount = 0;
public String toString() {
return ticTacToe.toString();
}
public void initialize() {
turnCount = 0;
ticTacToe.initializeGameboard();
}
public boolean insertSymbol(int number) {
if(ticTacToe.insertSymbol(turnCount % 2 + 1, number)) {
turnCount++;
return true;
}
return false;
}
public int isGameOver() {
return ticTacToe.isGameOver();
}
public ArrayList<String> getArray() {
return ticTacToe.getArray();
}
} |
package is.ru.tictactoe;
import java.awt.Point;
public class Application {
private Game game;
private UI ui;
public Application (Game game, UI ui) {
this.game = game;
this.ui = ui;
}
public void runApp () {
while (true) {
if (quitApp(getMenuChoice())) {
break;
}
else {
playGame();
ui.drawBoard(game.getBoard());
if (game.getWinner()) {
game.switchPlayer();
(game.getCurrPlayer()).incrementScore();
ui.printWinner(game.getCurrPlayer());
}
else if (game.getDraw()) {
ui.printDraw();
}
ui.printScore(game.getPlayerO(), game.getPlayerX());
}
}
}
private int getMenuChoice () {
String choice;
boolean validChoice;
int num;
do {
choice = ui.getChoice();
num = convertStringToInt(choice);
validChoice = game.validMenuInput(num);
if (!validChoice) {
ui.printInvalidInput(0, 1);
}
} while(!validChoice);
return num;
}
private void playGame () {
game.newGame();
while (!game.getWinner() && !game.getDraw()) {
ui.drawBoard(game.getBoard());
String input;
boolean validInput, isFree;
int num;
do{
input = ui.getNextMove(game.getCurrPlayer());
num = convertStringToInt(input);
validInput = game.validInput(num);
if (validInput) {
isFree = game.getBoard().isFree(game.convertToPoint(num));
if(!isFree) {
ui.printFieldTaken();
}
}
else {
ui.printInvalidInput(1, 9);
}
} while (!validInput);
game.makeMove(num);
game.switchPlayer();
}
}
private int convertStringToInt(String str) {
return Character.getNumericValue(str.charAt(0));
}
private boolean quitApp (int choice) {
return (choice == 0);
}
public static void main (String[] args) {
Game game = new Game();
UI ui = new UI();
Application app = new Application(game,ui);
app.runApp();
}
} |
package ixa.kaflib;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.Comment;
import org.jdom2.Namespace;
import org.jdom2.output.XMLOutputter;
import org.jdom2.output.Format;
import org.jdom2.input.SAXBuilder;
import org.jdom2.JDOMException;
import org.jdom2.xpath.XPathExpression;
import java.util.List;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.io.File;
import java.io.Writer;
import java.io.Reader;
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.Charset;
/** Reads XML files in KAF format and loads the content in a KAFDocument object, and writes the content into XML files. */
class ReadWriteManager {
/** Loads the content of a KAF file into the given KAFDocument object */
static KAFDocument load(File file) throws IOException, JDOMException, KAFNotValidException {
SAXBuilder builder = new SAXBuilder();
Document document = (Document) builder.build(file);
Element rootElem = document.getRootElement();
return DOMToKAF(document);
}
/** Loads the content of a String in KAF format into the given KAFDocument object */
static KAFDocument load(Reader stream) throws IOException, JDOMException, KAFNotValidException {
SAXBuilder builder = new SAXBuilder();
Document document = (Document) builder.build(stream);
Element rootElem = document.getRootElement();
return DOMToKAF(document);
}
/** Writes the content of a given KAFDocument to a file. */
static void save(KAFDocument kaf, String filename) {
try {
File file = new File(filename);
Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF8"));
out.write(kafToStr(kaf));
out.flush();
} catch (Exception e) {
System.out.println("Error writing to file");
}
}
/** Writes the content of a KAFDocument object to standard output. */
static void print(KAFDocument kaf) {
try {
Writer out = new BufferedWriter(new OutputStreamWriter(System.out, "UTF8"));
out.write(kafToStr(kaf));
out.flush();
} catch (Exception e) {
System.out.println(e);
}
}
/** Returns a string containing the XML content of a KAFDocument object. */
static String kafToStr(KAFDocument kaf) {
XMLOutputter out = new XMLOutputter(Format.getPrettyFormat());
Document jdom = KAFToDOM(kaf);
return out.outputString(jdom);
}
/** Loads a KAFDocument object from XML content in DOM format */
private static KAFDocument DOMToKAF(Document dom) throws KAFNotValidException {
HashMap<String, WF> wfIndex = new HashMap<String, WF>();
HashMap<String, Term> termIndex = new HashMap<String, Term>();
HashMap<String, Relational> relationalIndex = new HashMap<String, Relational>();
Element rootElem = dom.getRootElement();
String lang = getAttribute("lang", rootElem, Namespace.XML_NAMESPACE);
String kafVersion = getAttribute("version", rootElem);
KAFDocument kaf = new KAFDocument(lang, kafVersion);
List<Element> rootChildrenElems = rootElem.getChildren();
for (Element elem : rootChildrenElems) {
if (elem.getName().equals("kafHeader")) {
List<Element> lpsElems = elem.getChildren("linguisticProcessors");
for (Element lpsElem : lpsElems) {
String layer = getAttribute("layer", lpsElem);
List<Element> lpElems = lpsElem.getChildren();
for (Element lpElem : lpElems) {
String name = getAttribute("name", lpElem);
String timestamp = getOptAttribute("timestamp", lpElem);
String version = getOptAttribute("version", lpElem);
kaf.addLinguisticProcessor(layer, name, timestamp, version);
}
}
Element fileDescElem = elem.getChild("fileDesc");
if (fileDescElem != null) {
KAFDocument.FileDesc fd = kaf.createFileDesc();
String author = getOptAttribute("author", fileDescElem);
if (author != null) {
fd.author = author;
}
String title = getOptAttribute("title", fileDescElem);
if (title != null) {
fd.title = title;
}
String creationtime = getOptAttribute("creationtime", fileDescElem);
if (creationtime != null) {
fd.creationtime = creationtime;
}
String filename = getOptAttribute("filename", fileDescElem);
if (filename != null) {
fd.filename = filename;
}
String filetype = getOptAttribute("filetype", fileDescElem);
if (filetype != null) {
fd.filetype = filetype;
}
String pages = getOptAttribute("pages", fileDescElem);
if (pages != null) {
fd.pages = Integer.parseInt(pages);
}
}
Element publicElem = elem.getChild("public");
if (publicElem != null) {
String publicId = getAttribute("publicId", publicElem);
KAFDocument.Public pub = kaf.createPublic(publicId);
String uri = getOptAttribute("uri", publicElem);
if (uri != null) {
pub.uri = uri;
}
}
}
if (elem.getName().equals("text")) {
List<Element> wfElems = elem.getChildren();
for (Element wfElem : wfElems) {
String wid = getAttribute("wid", wfElem);
String wForm = wfElem.getText();
WF newWf = kaf.createWF(wid, wForm);
String wSent = getOptAttribute("sent", wfElem);
if (wSent != null) {
newWf.setSent(Integer.valueOf(wSent));
}
String wPara = getOptAttribute("para", wfElem);
if (wPara != null) {
newWf.setPara(Integer.valueOf(wPara));
}
String wPage = getOptAttribute("page", wfElem);
if (wPage != null) {
newWf.setPage(Integer.valueOf(wPage));
}
String wOffset = getOptAttribute("offset", wfElem);
if (wOffset != null) {
newWf.setOffset(Integer.valueOf(wOffset));
}
String wLength = getOptAttribute("length", wfElem);
if (wLength != null) {
newWf.setLength(Integer.valueOf(wLength));
}
String wXpath = getOptAttribute("xpath", wfElem);
if (wXpath != null) {
newWf.setXpath(wXpath);
}
wfIndex.put(newWf.getId(), newWf);
}
}
if (elem.getName().equals("terms")) {
List<Element> termElems = elem.getChildren();
for (Element termElem : termElems) {
String tid = getAttribute("tid", termElem);
String type = getAttribute("type", termElem);
String lemma = getAttribute("lemma", termElem);
String pos = getAttribute("pos", termElem);
Element spanElem = termElem.getChild("span");
if (spanElem == null) {
throw new IllegalStateException("Every term must contain a span element");
}
List<Element> termsWfElems = spanElem.getChildren("target");
Span<WF> span = kaf.createWFSpan();
for (Element termsWfElem : termsWfElems) {
String wfId = getAttribute("id", termsWfElem);
boolean isHead = isHead(termsWfElem);
WF wf = wfIndex.get(wfId);
if (wf == null) {
throw new KAFNotValidException("Wf " + wfId + " not found when loading term " + tid);
}
span.addTarget(wf, isHead);
}
Term newTerm = kaf.createTerm(tid, type, lemma, pos, span);
String tMorphofeat = getOptAttribute("morphofeat", termElem);
if (tMorphofeat != null) {
newTerm.setMorphofeat(tMorphofeat);
}
String tHead = getOptAttribute("head", termElem);
String termcase = getOptAttribute("case", termElem);
if (termcase != null) {
newTerm.setCase(termcase);
}
List<Element> sentimentElems = termElem.getChildren("sentiment");
if (sentimentElems.size() > 0) {
Element sentimentElem = sentimentElems.get(0);
Term.Sentiment newSentiment = kaf.createSentiment();
String sentResource = getOptAttribute("resource", sentimentElem);
if (sentResource != null) {
newSentiment.setResource(sentResource);
}
String sentPolarity = getOptAttribute("polarity", sentimentElem);
if (sentPolarity != null) {
newSentiment.setPolarity(sentPolarity);
}
String sentStrength = getOptAttribute("strength", sentimentElem);
if (sentStrength != null) {
newSentiment.setStrength(sentStrength);
}
String sentSubjectivity = getOptAttribute("subjectivity", sentimentElem);
if (sentSubjectivity != null) {
newSentiment.setSubjectivity(sentSubjectivity);
}
String sentSentimentSemanticType = getOptAttribute("sentimentSemanticType", sentimentElem);
if (sentSentimentSemanticType != null) {
newSentiment.setSentimentSemanticType(sentSentimentSemanticType);
}
String sentSentimentModifier = getOptAttribute("sentimentModifier", sentimentElem);
if (sentSentimentModifier != null) {
newSentiment.setSentimentModifier(sentSentimentModifier);
}
String sentSentimentMarker = getOptAttribute("sentimentMarker", sentimentElem);
if (sentSentimentMarker != null) {
newSentiment.setSentimentMarker(sentSentimentMarker);
}
String sentSentimentProductFeature = getOptAttribute("sentimentProductFeature", sentimentElem);
if (sentSentimentProductFeature != null) {
newSentiment.setSentimentProductFeature(sentSentimentProductFeature);
}
newTerm.setSentiment(newSentiment);
}
List<Element> termsComponentElems = termElem.getChildren("component");
for (Element termsComponentElem : termsComponentElems) {
String compId = getAttribute("id", termsComponentElem);
boolean isHead = ((tHead != null) && tHead.equals(compId));
String compLemma = getAttribute("lemma", termsComponentElem);
String compPos = getAttribute("pos", termsComponentElem);
Term.Component newComponent = kaf.createComponent(compId, newTerm, compLemma, compPos);
List<Element> externalReferencesElems = termsComponentElem.getChildren("externalReferences");
if (externalReferencesElems.size() > 0) {
List<ExternalRef> externalRefs = getExternalReferences(externalReferencesElems.get(0), kaf);
newComponent.addExternalRefs(externalRefs);
}
newTerm.addComponent(newComponent, isHead);
}
List<Element> externalReferencesElems = termElem.getChildren("externalReferences");
if (externalReferencesElems.size() > 0) {
List<ExternalRef> externalRefs = getExternalReferences(externalReferencesElems.get(0), kaf);
newTerm.addExternalRefs(externalRefs);
}
termIndex.put(newTerm.getId(), newTerm);
}
}
if (elem.getName().equals("deps")) {
List<Element> depElems = elem.getChildren();
for (Element depElem : depElems) {
String fromId = getAttribute("from", depElem);
String toId = getAttribute("to", depElem);
Term from = termIndex.get(fromId);
if (from == null) {
throw new KAFNotValidException("Term " + fromId + " not found when loading Dep (" + fromId + ", " + toId + ")");
}
Term to = termIndex.get(toId);
if (to == null) {
throw new KAFNotValidException("Term " + toId + " not found when loading Dep (" + fromId + ", " + toId + ")");
}
String rfunc = getAttribute("rfunc", depElem);
Dep newDep = kaf.createDep(from, to, rfunc);
String depcase = getOptAttribute("case", depElem);
if (depcase != null) {
newDep.setCase(depcase);
}
}
}
if (elem.getName().equals("chunks")) {
List<Element> chunkElems = elem.getChildren();
for (Element chunkElem : chunkElems) {
String chunkId = getAttribute("cid", chunkElem);
String headId = getAttribute("head", chunkElem);
Term chunkHead = termIndex.get(headId);
if (chunkHead == null) {
throw new KAFNotValidException("Term " + headId + " not found when loading chunk " + chunkId);
}
String chunkPhrase = getAttribute("phrase", chunkElem);
Element spanElem = chunkElem.getChild("span");
if (spanElem == null) {
throw new IllegalStateException("Every chunk must contain a span element");
}
List<Element> chunksTermElems = spanElem.getChildren("target");
Span<Term> span = kaf.createTermSpan();
for (Element chunksTermElem : chunksTermElems) {
String termId = getAttribute("id", chunksTermElem);
boolean isHead = isHead(chunksTermElem);
Term targetTerm = termIndex.get(termId);
if (targetTerm == null) {
throw new KAFNotValidException("Term " + termId + " not found when loading chunk " + chunkId);
}
span.addTarget(targetTerm, ((targetTerm == chunkHead) || isHead));
}
if (!span.hasTarget(chunkHead)) {
throw new KAFNotValidException("The head of the chunk is not in it's span.");
}
Chunk newChunk = kaf.createChunk(chunkId, chunkPhrase, span);
String chunkCase = getOptAttribute("case", chunkElem);
if (chunkCase != null) {
newChunk.setCase(chunkCase);
}
}
}
if (elem.getName().equals("entities")) {
List<Element> entityElems = elem.getChildren();
for (Element entityElem : entityElems) {
String entId = getAttribute("eid", entityElem);
String entType = getAttribute("type", entityElem);
List<Element> referencesElem = entityElem.getChildren("references");
if (referencesElem.size() < 1) {
throw new IllegalStateException("Every entity must contain a 'references' element");
}
List<Element> spanElems = referencesElem.get(0).getChildren();
if (spanElems.size() < 1) {
throw new IllegalStateException("Every entity must contain a 'span' element inside 'references'");
}
List<Span<Term>> references = new ArrayList<Span<Term>>();
for (Element spanElem : spanElems) {
Span<Term> span = kaf.createTermSpan();
List<Element> targetElems = spanElem.getChildren();
if (targetElems.size() < 1) {
throw new IllegalStateException("Every span in an entity must contain at least one target inside");
}
for (Element targetElem : targetElems) {
String targetTermId = getAttribute("id", targetElem);
Term targetTerm = termIndex.get(targetTermId);
if (targetTerm == null) {
throw new KAFNotValidException("Term " + targetTermId + " not found when loading entity " + entId);
}
boolean isHead = isHead(targetElem);
span.addTarget(targetTerm, isHead);
}
references.add(span);
}
Entity newEntity = kaf.createEntity(entId, entType, references);
List<Element> externalReferencesElems = entityElem.getChildren("externalReferences");
if (externalReferencesElems.size() > 0) {
List<ExternalRef> externalRefs = getExternalReferences(externalReferencesElems.get(0), kaf);
newEntity.addExternalRefs(externalRefs);
}
relationalIndex.put(newEntity.getId(), newEntity);
}
}
if (elem.getName().equals("coreferences")) {
List<Element> corefElems = elem.getChildren();
for (Element corefElem : corefElems) {
String coId = getAttribute("coid", corefElem);
List<Element> referencesElem = corefElem.getChildren("references");
if (referencesElem.size() < 1) {
throw new IllegalStateException("Every coref must contain a 'references' element");
}
List<Element> spanElems = referencesElem.get(0).getChildren();
if (spanElems.size() < 1) {
throw new IllegalStateException("Every coref must contain a 'span' element inside 'references'");
}
List<Span<Term>> references = new ArrayList<Span<Term>>();
for (Element spanElem : spanElems) {
Span<Term> span = kaf.createTermSpan();
List<Element> targetElems = spanElem.getChildren();
if (targetElems.size() < 1) {
throw new IllegalStateException("Every span in an entity must contain at least one target inside");
}
for (Element targetElem : targetElems) {
String targetTermId = getAttribute("id", targetElem);
Term targetTerm = termIndex.get(targetTermId);
if (targetTerm == null) {
throw new KAFNotValidException("Term " + targetTermId + " not found when loading coref " + coId);
}
boolean isHead = isHead(targetElem);
span.addTarget(targetTerm, isHead);
}
references.add(span);
}
Coref newCoref = kaf.createCoref(coId, references);
}
}
if (elem.getName().equals("features")) {
Element propertiesElem = elem.getChild("properties");
Element categoriesElem = elem.getChild("categories");
if (propertiesElem != null) {
List<Element> propertyElems = propertiesElem.getChildren("property");
for (Element propertyElem : propertyElems) {
String pid = getAttribute("pid", propertyElem);
String lemma = getAttribute("lemma", propertyElem);
Element referencesElem = propertyElem.getChild("references");
if (referencesElem == null) {
throw new IllegalStateException("Every property must contain a 'references' element");
}
List<Element> spanElems = referencesElem.getChildren("span");
if (spanElems.size() < 1) {
throw new IllegalStateException("Every property must contain a 'span' element inside 'references'");
}
List<Span<Term>> references = new ArrayList<Span<Term>>();
for (Element spanElem : spanElems) {
Span<Term> span = kaf.createTermSpan();
List<Element> targetElems = spanElem.getChildren();
if (targetElems.size() < 1) {
throw new IllegalStateException("Every span in a property must contain at least one target inside");
}
for (Element targetElem : targetElems) {
String targetTermId = getAttribute("id", targetElem);
Term targetTerm = termIndex.get(targetTermId);
if (targetTerm == null) {
throw new KAFNotValidException("Term " + targetTermId + " not found when loading property " + pid);
}
boolean isHead = isHead(targetElem);
span.addTarget(targetTerm, isHead);
}
references.add(span);
}
Feature newProperty = kaf.createProperty(pid, lemma, references);
List<Element> externalReferencesElems = propertyElem.getChildren("externalReferences");
if (externalReferencesElems.size() > 0) {
List<ExternalRef> externalRefs = getExternalReferences(externalReferencesElems.get(0), kaf);
newProperty.addExternalRefs(externalRefs);
}
relationalIndex.put(newProperty.getId(), newProperty);
}
}
if (categoriesElem != null) {
List<Element> categoryElems = categoriesElem.getChildren("category");
for (Element categoryElem : categoryElems) {
String cid = getAttribute("cid", categoryElem);
String lemma = getAttribute("lemma", categoryElem);
Element referencesElem = categoryElem.getChild("references");
if (referencesElem == null) {
throw new IllegalStateException("Every category must contain a 'references' element");
}
List<Element> spanElems = referencesElem.getChildren("span");
if (spanElems.size() < 1) {
throw new IllegalStateException("Every category must contain a 'span' element inside 'references'");
}
List<Span<Term>> references = new ArrayList<Span<Term>>();
for (Element spanElem : spanElems) {
Span<Term> span = kaf.createTermSpan();
List<Element> targetElems = spanElem.getChildren();
if (targetElems.size() < 1) {
throw new IllegalStateException("Every span in a property must contain at least one target inside");
}
for (Element targetElem : targetElems) {
String targetTermId = getAttribute("id", targetElem);
Term targetTerm = termIndex.get(targetTermId);
if (targetTerm == null) {
throw new KAFNotValidException("Term " + targetTermId + " not found when loading category " + cid);
}
boolean isHead = isHead(targetElem);
span.addTarget(targetTerm, isHead);
}
references.add(span);
}
Feature newCategory = kaf.createCategory(cid, lemma, references);
List<Element> externalReferencesElems = categoryElem.getChildren("externalReferences");
if (externalReferencesElems.size() > 0) {
List<ExternalRef> externalRefs = getExternalReferences(externalReferencesElems.get(0), kaf);
newCategory.addExternalRefs(externalRefs);
}
relationalIndex.put(newCategory.getId(), newCategory);
}
}
}
if (elem.getName().equals("opinions")) {
List<Element> opinionElems = elem.getChildren("opinion");
for (Element opinionElem : opinionElems) {
String opinionId = getAttribute("oid", opinionElem);
Opinion opinion = kaf.createOpinion(opinionId);
Element opinionHolderElem = opinionElem.getChild("opinion_holder");
if (opinionHolderElem != null) {
Span<Term> span = kaf.createTermSpan();
Opinion.OpinionHolder opinionHolder = opinion.createOpinionHolder(span);
Element spanElem = opinionHolderElem.getChild("span");
if (spanElem != null) {
List<Element> targetElems = spanElem.getChildren("target");
for (Element targetElem : targetElems) {
String refId = getOptAttribute("id", targetElem);
boolean isHead = isHead(targetElem);
Term targetTerm = termIndex.get(refId);
if (targetTerm == null) {
throw new KAFNotValidException("Term " + refId + " not found when loading opinion " + opinionId);
}
span.addTarget(targetTerm, isHead);
}
}
}
Element opinionTargetElem = opinionElem.getChild("opinion_target");
if (opinionTargetElem != null) {
Span<Term> span = kaf.createTermSpan();
Opinion.OpinionTarget opinionTarget = opinion.createOpinionTarget(span);
Element spanElem = opinionTargetElem.getChild("span");
if (spanElem != null) {
List<Element> targetElems = spanElem.getChildren("target");
for (Element targetElem : targetElems) {
String refId = getOptAttribute("id", targetElem);
boolean isHead = isHead(targetElem);
Term targetTerm = termIndex.get(refId);
if (targetTerm == null) {
throw new KAFNotValidException("Term " + refId + " not found when loading opinion " + opinionId);
}
span.addTarget(targetTerm, isHead);
}
}
}
Element opinionExpressionElem = opinionElem.getChild("opinion_expression");
if (opinionExpressionElem != null) {
Span<Term> span = kaf.createTermSpan();
String polarity = getOptAttribute("polarity", opinionExpressionElem);
String strength = getOptAttribute("strength", opinionExpressionElem);
String subjectivity = getOptAttribute("subjectivity", opinionExpressionElem);
String sentimentSemanticType = getOptAttribute("sentiment_semantic_type", opinionExpressionElem);
String sentimentProductFeature = getOptAttribute("sentiment_product_feature", opinionExpressionElem);
Opinion.OpinionExpression opinionExpression = opinion.createOpinionExpression(span);
if (polarity != null) {
opinionExpression.setPolarity(polarity);
}
if (strength != null) {
opinionExpression.setStrength(strength);
}
if (subjectivity != null) {
opinionExpression.setSubjectivity(subjectivity);
}
if (sentimentSemanticType != null) {
opinionExpression.setSentimentSemanticType(sentimentSemanticType);
}
if (sentimentProductFeature != null) {
opinionExpression.setSentimentProductFeature(sentimentProductFeature);
}
Element spanElem = opinionExpressionElem.getChild("span");
if (spanElem != null) {
List<Element> targetElems = spanElem.getChildren("target");
for (Element targetElem : targetElems) {
String refId = getOptAttribute("id", targetElem);
boolean isHead = isHead(targetElem);
Term targetTerm = termIndex.get(refId);
if (targetTerm == null) {
throw new KAFNotValidException("Term " + refId + " not found when loading opinion " + opinionId);
}
span.addTarget(targetTerm, isHead);
}
}
}
}
}
if (elem.getName().equals("relations")) {
List<Element> relationElems = elem.getChildren("relation");
for (Element relationElem : relationElems) {
String id = getAttribute("rid", relationElem);
String fromId = getAttribute("from", relationElem);
String toId = getAttribute("to", relationElem);
String confidenceStr = getOptAttribute("confidence", relationElem);
float confidence = -1.0f;
if (confidenceStr != null) {
confidence = Float.parseFloat(confidenceStr);
}
Relational from = relationalIndex.get(fromId);
if (from == null) {
throw new KAFNotValidException("Entity/feature object " + fromId + " not found when loading relation " + id);
}
Relational to = relationalIndex.get(toId);
if (to == null) {
throw new KAFNotValidException("Entity/feature object " + toId + " not found when loading relation " + id);
}
Relation newRelation = kaf.createRelation(id, from, to);
if (confidence >= 0) {
newRelation.setConfidence(confidence);
}
}
}
if (elem.getName().equals("srl")) {
List<Element> predicateElems = elem.getChildren("predicate");
for (Element predicateElem : predicateElems) {
String id = getAttribute("prid", predicateElem);
String uri = getOptAttribute("uri", predicateElem);
Span<Term> span = kaf.createTermSpan();
Element spanElem = predicateElem.getChild("span");
if (spanElem != null) {
List<Element> targetElems = spanElem.getChildren("target");
for (Element targetElem : targetElems) {
String targetId = getAttribute("id", targetElem);
boolean isHead = isHead(targetElem);
Term targetTerm = termIndex.get(targetId);
if (targetTerm == null) {
throw new KAFNotValidException("Term object " + targetId + " not found when loading predicate " + id);
}
span.addTarget(targetTerm, isHead);
}
}
Predicate newPredicate = kaf.createPredicate(id, span);
if (uri != null) {
newPredicate.setUri(uri);
}
List<Element> roleElems = predicateElem.getChildren("role");
for (Element roleElem : roleElems) {
String rid = getAttribute("rid", roleElem);
String semRole = getAttribute("semRole", roleElem);
Span<Term> roleSpan = kaf.createTermSpan();
Element roleSpanElem = roleElem.getChild("span");
if (roleSpanElem != null) {
List<Element> targetElems = roleSpanElem.getChildren("target");
for (Element targetElem : targetElems) {
String targetId = getAttribute("id", targetElem);
boolean isHead = isHead(targetElem);
Term targetTerm = termIndex.get(targetId);
if (targetTerm == null) {
throw new KAFNotValidException("Term object " + targetId + " not found when loading role " + rid);
}
roleSpan.addTarget(targetTerm, isHead);
}
}
Predicate.Role newRole = kaf.createRole(rid, newPredicate, semRole, roleSpan);
newPredicate.addRole(newRole);
}
Span<Term> spana = kaf.createTermSpan();
Predicate.Role rolea = kaf.createRole(newPredicate, "kaka", spana);
newPredicate.addRole(rolea);
}
}
if (elem.getName().equals("parsing")) {
List<Element> treeElems = elem.getChildren();
for (Element treeElem : treeElems) {
String treeid = getAttribute("treeid", treeElem);
Tree tree = kaf.createParsingTree(treeid);
Element treeRootElem = treeElem.getChildren().get(0);
if (treeRootElem.getName().equals("nt")) {
String rootLabel = getAttribute("label", treeRootElem);
NonTerminal root = tree.createNRoot(rootLabel);
for (Element childElem : treeRootElem.getChildren()) {
loadNodeElement(childElem, root, termIndex);
}
}
else {
String termId = getAttribute("id", treeRootElem.getChildren().get(0).getChildren().get(0));
Term term = termIndex.get(termId);
Terminal t = tree.createTRoot(term);
}
}
}
}
return kaf;
}
private static void loadNodeElement(Element nodeElem, NonTerminal parentNode, HashMap<String, Term> termIndex) {
if (nodeElem.getName().equals("nt")) {
String label = getAttribute("label", nodeElem);
NonTerminal nt = parentNode.createNonTerminal(label);
for (Element childElem : nodeElem.getChildren()) {
loadNodeElement(childElem, nt, termIndex);
}
}
else {
String headAttr = getOptAttribute("head", nodeElem);
boolean isHead = (headAttr != null);
String termId = getAttribute("id", nodeElem.getChildren().get(0).getChildren().get(0));
Term term = termIndex.get(termId);
Terminal t = parentNode.createTerminal(term, isHead);
}
}
private static List<ExternalRef> getExternalReferences(Element externalReferencesElem, KAFDocument kaf) {
List<ExternalRef> externalRefs = new ArrayList<ExternalRef>();
List<Element> externalRefElems = externalReferencesElem.getChildren();
for (Element externalRefElem : externalRefElems) {
ExternalRef externalRef = getExternalRef(externalRefElem, kaf);
externalRefs.add(externalRef);
}
return externalRefs;
}
private static ExternalRef getExternalRef(Element externalRefElem, KAFDocument kaf) {
String resource = getAttribute("resource", externalRefElem);
String references = getAttribute("reference", externalRefElem);
ExternalRef newExternalRef = kaf.createExternalRef(resource, references);
String confidence = getOptAttribute("confidence", externalRefElem);
if (confidence != null) {
newExternalRef.setConfidence(Float.valueOf(confidence));
}
List<Element> subRefElems = externalRefElem.getChildren("externalRef");
if (subRefElems.size() > 0) {
Element subRefElem = subRefElems.get(0);
ExternalRef subRef = getExternalRef(subRefElem, kaf);
newExternalRef.setExternalRef(subRef);
}
return newExternalRef;
}
private static String getAttribute(String attName, Element elem) {
String value = elem.getAttributeValue(attName);
if (value==null) {
throw new IllegalStateException(attName+" attribute must be defined for element "+elem.getName());
}
return value;
}
private static String getAttribute(String attName, Element elem, Namespace nmspace) {
String value = elem.getAttributeValue(attName, nmspace);
if (value==null) {
throw new IllegalStateException(attName+" attribute must be defined for element "+elem.getName());
}
return value;
}
private static String getOptAttribute(String attName, Element elem) {
String value = elem.getAttributeValue(attName);
if (value==null) {
return null;
}
return value;
}
private static boolean isHead(Element elem) {
String value = elem.getAttributeValue("head");
if (value == null) {
return false;
}
if (value.equals("yes")) {
return true;
}
return false;
}
/** Returns the content of the given KAFDocument in a DOM document. */
private static Document KAFToDOM(KAFDocument kaf) {
AnnotationContainer annotationContainer = kaf.getAnnotationContainer();
Element root = new Element("KAF");
root.setAttribute("lang", kaf.getLang(), Namespace.XML_NAMESPACE);
root.setAttribute("version", kaf.getVersion());
Document doc = new Document(root);
Element kafHeaderElem = new Element("kafHeader");
root.addContent(kafHeaderElem);
KAFDocument.FileDesc fd = kaf.getFileDesc();
if (fd != null) {
Element fdElem = new Element("fileDesc");
if (fd.author != null) {
fdElem.setAttribute("author", fd.author);
}
if (fd.author != null) {
fdElem.setAttribute("title", fd.title);
}
if (fd.creationtime != null) {
fdElem.setAttribute("creationtime", fd.creationtime);
}
if (fd.author != null) {
fdElem.setAttribute("filename", fd.filename);
}
if (fd.author != null) {
fdElem.setAttribute("filetype", fd.filetype);
}
if (fd.author != null) {
fdElem.setAttribute("pages", Integer.toString(fd.pages));
}
kafHeaderElem.addContent(fdElem);
}
KAFDocument.Public pub = kaf.getPublic();
if (pub != null) {
Element pubElem = new Element("public");
pubElem.setAttribute("publicId", pub.publicId);
if (pub.uri != null) {
pubElem.setAttribute("uri", pub.uri);
}
kafHeaderElem.addContent(pubElem);
}
HashMap<String, List<KAFDocument.LinguisticProcessor>> lps = kaf.getLinguisticProcessors();
for (Map.Entry entry : lps.entrySet()) {
Element lpsElem = new Element("linguisticProcessors");
lpsElem.setAttribute("layer", (String) entry.getKey());
for (KAFDocument.LinguisticProcessor lp : (List<KAFDocument.LinguisticProcessor>) entry.getValue()) {
Element lpElem = new Element("lp");
lpElem.setAttribute("name", lp.name);
lpElem.setAttribute("timestamp", lp.timestamp);
lpElem.setAttribute("version", lp.version);
lpsElem.addContent(lpElem);
}
kafHeaderElem.addContent(lpsElem);
}
List<WF> text = annotationContainer.getText();
if (text.size() > 0) {
Element textElem = new Element("text");
for (WF wf : text) {
Element wfElem = new Element("wf");
wfElem.setAttribute("wid", wf.getId());
if (wf.hasSent()) {
wfElem.setAttribute("sent", Integer.toString(wf.getSent()));
}
if (wf.hasPara()) {
wfElem.setAttribute("para", Integer.toString(wf.getPara()));
}
if (wf.hasPage()) {
wfElem.setAttribute("page", Integer.toString(wf.getPage()));
}
if (wf.hasOffset()) {
wfElem.setAttribute("offset", Integer.toString(wf.getOffset()));
}
if (wf.hasLength()) {
wfElem.setAttribute("length", Integer.toString(wf.getLength()));
}
if (wf.hasXpath()) {
wfElem.setAttribute("xpath", wf.getXpath());
}
wfElem.setText(wf.getForm());
textElem.addContent(wfElem);
}
root.addContent(textElem);
}
List<Term> terms = annotationContainer.getTerms();
if (terms.size() > 0) {
Element termsElem = new Element("terms");
for (Term term : terms) {
String morphofeat;
Term.Component head;
String termcase;
Comment termComment = new Comment(term.getStr());
termsElem.addContent(termComment);
Element termElem = new Element("term");
termElem.setAttribute("tid", term.getId());
termElem.setAttribute("type", term.getType());
termElem.setAttribute("lemma", term.getLemma());
termElem.setAttribute("pos", term.getPos());
if (term.hasMorphofeat()) {
termElem.setAttribute("morphofeat", term.getMorphofeat());
}
if (term.hasHead()) {
termElem.setAttribute("head", term.getHead().getId());
}
if (term.hasCase()) {
termElem.setAttribute("case", term.getCase());
}
if (term.hasSentiment()) {
Term.Sentiment sentiment = term.getSentiment();
Element sentimentElem = new Element("sentiment");
if (sentiment.hasResource()) {
sentimentElem.setAttribute("resource", sentiment.getResource());
}
if (sentiment.hasPolarity()) {
sentimentElem.setAttribute("polarity", sentiment.getPolarity());
}
if (sentiment.hasStrength()) {
sentimentElem.setAttribute("strength", sentiment.getStrength());
}
if (sentiment.hasSubjectivity()) {
sentimentElem.setAttribute("subjectivity", sentiment.getSubjectivity());
}
if (sentiment.hasSentimentSemanticType()) {
sentimentElem.setAttribute("sentimentSemanticType", sentiment.getSentimentSemanticType());
}
if (sentiment.hasSentimentModifier()) {
sentimentElem.setAttribute("sentimentModifier", sentiment.getSentimentModifier());
}
if (sentiment.hasSentimentMarker()) {
sentimentElem.setAttribute("sentimentMarker", sentiment.getSentimentMarker());
}
if (sentiment.hasSentimentProductFeature()) {
sentimentElem.setAttribute("sentimentProductFeature", sentiment.getSentimentProductFeature());
}
termElem.addContent(sentimentElem);
}
Element spanElem = new Element("span");
Span<WF> span = term.getSpan();
for (WF target : term.getWFs()) {
Element targetElem = new Element("target");
targetElem.setAttribute("id", target.getId());
if (target == span.getHead()) {
targetElem.setAttribute("head", "yes");
}
spanElem.addContent(targetElem);
}
termElem.addContent(spanElem);
List<Term.Component> components = term.getComponents();
if (components.size() > 0) {
for (Term.Component component : components) {
Element componentElem = new Element("component");
componentElem.setAttribute("id", component.getId());
componentElem.setAttribute("lemma", component.getLemma());
componentElem.setAttribute("pos", component.getPos());
if (component.hasCase()) {
componentElem.setAttribute("case", component.getCase());
}
List<ExternalRef> externalReferences = component.getExternalRefs();
if (externalReferences.size() > 0) {
Element externalReferencesElem = externalReferencesToDOM(externalReferences);
componentElem.addContent(externalReferencesElem);
}
termElem.addContent(componentElem);
}
}
List<ExternalRef> externalReferences = term.getExternalRefs();
if (externalReferences.size() > 0) {
Element externalReferencesElem = externalReferencesToDOM(externalReferences);
termElem.addContent(externalReferencesElem);
}
termsElem.addContent(termElem);
}
root.addContent(termsElem);
}
List<Dep> deps = annotationContainer.getDeps();
if (deps.size() > 0) {
Element depsElem = new Element("deps");
for (Dep dep : deps) {
Comment depComment = new Comment(dep.getStr());
depsElem.addContent(depComment);
Element depElem = new Element("dep");
depElem.setAttribute("from", dep.getFrom().getId());
depElem.setAttribute("to", dep.getTo().getId());
depElem.setAttribute("rfunc", dep.getRfunc());
if (dep.hasCase()) {
depElem.setAttribute("case", dep.getCase());
}
depsElem.addContent(depElem);
}
root.addContent(depsElem);
}
List<Chunk> chunks = annotationContainer.getChunks();
if (chunks.size() > 0) {
Element chunksElem = new Element("chunks");
for (Chunk chunk : chunks) {
Comment chunkComment = new Comment(chunk.getStr());
chunksElem.addContent(chunkComment);
Element chunkElem = new Element("chunk");
chunkElem.setAttribute("cid", chunk.getId());
chunkElem.setAttribute("head", chunk.getHead().getId());
chunkElem.setAttribute("phrase", chunk.getPhrase());
if (chunk.hasCase()) {
chunkElem.setAttribute("case", chunk.getCase());
}
Element spanElem = new Element("span");
for (Term target : chunk.getTerms()) {
Element targetElem = new Element("target");
targetElem.setAttribute("id", target.getId());
spanElem.addContent(targetElem);
}
chunkElem.addContent(spanElem);
chunksElem.addContent(chunkElem);
}
root.addContent(chunksElem);
}
List<Entity> entities = annotationContainer.getEntities();
if (entities.size() > 0) {
Element entitiesElem = new Element("entities");
for (Entity entity : entities) {
Element entityElem = new Element("entity");
entityElem.setAttribute("eid", entity.getId());
entityElem.setAttribute("type", entity.getType());
Element referencesElem = new Element("references");
for (Span<Term> span : entity.getReferences()) {
Comment spanComment = new Comment(entity.getSpanStr(span));
referencesElem.addContent(spanComment);
Element spanElem = new Element("span");
for (Term term : span.getTargets()) {
Element targetElem = new Element("target");
targetElem.setAttribute("id", term.getId());
if (term == span.getHead()) {
targetElem.setAttribute("head", "yes");
}
spanElem.addContent(targetElem);
}
referencesElem.addContent(spanElem);
}
entityElem.addContent(referencesElem);
List<ExternalRef> externalReferences = entity.getExternalRefs();
if (externalReferences.size() > 0) {
Element externalReferencesElem = externalReferencesToDOM(externalReferences);
entityElem.addContent(externalReferencesElem);
}
entitiesElem.addContent(entityElem);
}
root.addContent(entitiesElem);
}
List<Coref> corefs = annotationContainer.getCorefs();
if (corefs.size() > 0) {
Element corefsElem = new Element("coreferences");
for (Coref coref : corefs) {
Element corefElem = new Element("coref");
corefElem.setAttribute("coid", coref.getId());
Element referencesElem = new Element("references");
for (Span<Term> span : coref.getReferences()) {
Comment spanComment = new Comment(coref.getSpanStr(span));
referencesElem.addContent(spanComment);
Element spanElem = new Element("span");
for (Term target : span.getTargets()) {
Element targetElem = new Element("target");
targetElem.setAttribute("id", target.getId());
if (target == span.getHead()) {
targetElem.setAttribute("head", "yes");
}
spanElem.addContent(targetElem);
}
referencesElem.addContent(spanElem);
}
corefElem.addContent(referencesElem);
corefsElem.addContent(corefElem);
}
root.addContent(corefsElem);
}
Element featuresElem = new Element("features");
List<Feature> properties = annotationContainer.getProperties();
if (properties.size() > 0) {
Element propertiesElem = new Element("properties");
for (Feature property : properties) {
Element propertyElem = new Element("property");
propertyElem.setAttribute("pid", property.getId());
propertyElem.setAttribute("lemma", property.getLemma());
List<Span<Term>> references = property.getReferences();
Element referencesElem = new Element("references");
for (Span<Term> span : references) {
Comment spanComment = new Comment(property.getSpanStr(span));
referencesElem.addContent(spanComment);
Element spanElem = new Element("span");
for (Term term : span.getTargets()) {
Element targetElem = new Element("target");
targetElem.setAttribute("id", term.getId());
if (term == span.getHead()) {
targetElem.setAttribute("head", "yes");
}
spanElem.addContent(targetElem);
}
referencesElem.addContent(spanElem);
}
propertyElem.addContent(referencesElem);
propertiesElem.addContent(propertyElem);
}
featuresElem.addContent(propertiesElem);
}
List<Feature> categories = annotationContainer.getCategories();
if (categories.size() > 0) {
Element categoriesElem = new Element("categories");
for (Feature category : categories) {
Element categoryElem = new Element("category");
categoryElem.setAttribute("cid", category.getId());
categoryElem.setAttribute("lemma", category.getLemma());
List<Span<Term>> references = category.getReferences();
Element referencesElem = new Element("references");
for (Span<Term> span : references) {
Comment spanComment = new Comment(category.getSpanStr(span));
referencesElem.addContent(spanComment);
Element spanElem = new Element("span");
for (Term term : span.getTargets()) {
Element targetElem = new Element("target");
targetElem.setAttribute("id", term.getId());
if (term == span.getHead()) {
targetElem.setAttribute("head", "yes");
}
spanElem.addContent(targetElem);
}
referencesElem.addContent(spanElem);
}
categoryElem.addContent(referencesElem);
categoriesElem.addContent(categoryElem);
}
featuresElem.addContent(categoriesElem);
}
if (featuresElem.getChildren().size() > 0) {
root.addContent(featuresElem);
}
List<Opinion> opinions = annotationContainer.getOpinions();
if (opinions.size() > 0) {
Element opinionsElem = new Element("opinions");
for (Opinion opinion : opinions) {
Element opinionElem = new Element("opinion");
opinionElem.setAttribute("oid", opinion.getId());
Opinion.OpinionHolder holder = opinion.getOpinionHolder();
if (holder != null) {
Element opinionHolderElem = new Element("opinion_holder");
Comment comment = new Comment(opinion.getSpanStr(opinion.getOpinionHolder().getSpan()));
opinionHolderElem.addContent(comment);
List<Term> targets = holder.getTerms();
Span<Term> span = holder.getSpan();
if (targets.size() > 0) {
Element spanElem = new Element("span");
opinionHolderElem.addContent(spanElem);
for (Term target : targets) {
Element targetElem = new Element("target");
targetElem.setAttribute("id", target.getId());
if (target == span.getHead()) {
targetElem.setAttribute("head", "yes");
}
spanElem.addContent(targetElem);
}
}
opinionElem.addContent(opinionHolderElem);
}
Opinion.OpinionTarget opTarget = opinion.getOpinionTarget();
if (opTarget != null) {
Element opinionTargetElem = new Element("opinion_target");
Comment comment = new Comment(opinion.getSpanStr(opinion.getOpinionTarget().getSpan()));
opinionTargetElem.addContent(comment);
List<Term> targets = opTarget.getTerms();
Span<Term> span = opTarget.getSpan();
if (targets.size() > 0) {
Element spanElem = new Element("span");
opinionTargetElem.addContent(spanElem);
for (Term target : targets) {
Element targetElem = new Element("target");
targetElem.setAttribute("id", target.getId());
if (target == span.getHead()) {
targetElem.setAttribute("head", "yes");
}
spanElem.addContent(targetElem);
}
}
opinionElem.addContent(opinionTargetElem);
}
Opinion.OpinionExpression expression = opinion.getOpinionExpression();
if (expression != null) {
Element opinionExpressionElem = new Element("opinion_expression");
Comment comment = new Comment(opinion.getSpanStr(opinion.getOpinionExpression().getSpan()));
opinionExpressionElem.addContent(comment);
if (expression.hasPolarity()) {
opinionExpressionElem.setAttribute("polarity", expression.getPolarity());
}
if (expression.hasStrength()) {
opinionExpressionElem.setAttribute("strength", expression.getStrength());
}
if (expression.hasSubjectivity()) {
opinionExpressionElem.setAttribute("subjectivity", expression.getSubjectivity());
}
if (expression.hasSentimentSemanticType()) {
opinionExpressionElem.setAttribute("sentiment_semantic_type", expression.getSentimentSemanticType());
}
if (expression.hasSentimentProductFeature()) {
opinionExpressionElem.setAttribute("sentiment_product_feature", expression.getSentimentProductFeature());
}
List<Term> targets = expression.getTerms();
Span<Term> span = expression.getSpan();
if (targets.size() > 0) {
Element spanElem = new Element("span");
opinionExpressionElem.addContent(spanElem);
for (Term target : targets) {
Element targetElem = new Element("target");
targetElem.setAttribute("id", target.getId());
if (target == span.getHead()) {
targetElem.setAttribute("head", "yes");
}
spanElem.addContent(targetElem);
}
}
opinionElem.addContent(opinionExpressionElem);
}
opinionsElem.addContent(opinionElem);
}
root.addContent(opinionsElem);
}
List<Relation> relations = annotationContainer.getRelations();
if (relations.size() > 0) {
Element relationsElem = new Element("relations");
for (Relation relation : relations) {
Comment comment = new Comment(relation.getStr());
relationsElem.addContent(comment);
Element relationElem = new Element("relation");
relationElem.setAttribute("rid", relation.getId());
relationElem.setAttribute("from", relation.getFrom().getId());
relationElem.setAttribute("to", relation.getTo().getId());
if (relation.hasConfidence()) {
relationElem.setAttribute("confidence", String.valueOf(relation.getConfidence()));
}
relationsElem.addContent(relationElem);
}
root.addContent(relationsElem);
}
List<Predicate> predicates = annotationContainer.getPredicates();
if (predicates.size() > 0) {
Element predicatesElem = new Element("srl");
for (Predicate predicate : predicates) {
Comment predicateComment = new Comment(predicate.getStr());
predicatesElem.addContent(predicateComment);
Element predicateElem = new Element("predicate");
predicateElem.setAttribute("prid", predicate.getId());
if (predicate.hasUri()) {
predicateElem.setAttribute("uri", predicate.getUri());
}
Span<Term> span = predicate.getSpan();
if (span.getTargets().size() > 0) {
Comment spanComment = new Comment(predicate.getSpanStr());
Element spanElem = new Element("span");
predicateElem.addContent(spanComment);
predicateElem.addContent(spanElem);
for (Term target : span.getTargets()) {
Element targetElem = new Element("target");
targetElem.setAttribute("id", target.getId());
if (target == span.getHead()) {
targetElem.setAttribute("head", "yes");
}
spanElem.addContent(targetElem);
}
}
for (Predicate.Role role : predicate.getRoles()) {
Element roleElem = new Element("role");
roleElem.setAttribute("rid", role.getId());
roleElem.setAttribute("semRole", role.getSemRole());
Span<Term> roleSpan = role.getSpan();
if (roleSpan.getTargets().size() > 0) {
Comment spanComment = new Comment(role.getStr());
Element spanElem = new Element("span");
roleElem.addContent(spanComment);
roleElem.addContent(spanElem);
for (Term target : roleSpan.getTargets()) {
Element targetElem = new Element("target");
targetElem.setAttribute("id", target.getId());
if (target == roleSpan.getHead()) {
targetElem.setAttribute("head", "yes");
}
spanElem.addContent(targetElem);
}
}
predicateElem.addContent(roleElem);
}
predicatesElem.addContent(predicateElem);
}
root.addContent(predicatesElem);
}
List<Tree> trees = annotationContainer.getTrees();
if (trees.size() > 0) {
Element treesElem = new Element("parsing");
for (Tree tree : trees) {
Element treeElem = new Element("tree");
treeElem.setAttribute("treeid", tree.getId());
TreeNode rootNode = tree.getRoot();
Element rootElem = rootNode.getDOMElem();
treeElem.addContent(rootElem);
treesElem.addContent(treeElem);
}
root.addContent(treesElem);
}
return doc;
}
private static Element externalReferencesToDOM(List<ExternalRef> externalRefs) {
Element externalReferencesElem = new Element("externalReferences");
for (ExternalRef externalRef : externalRefs) {
Element externalRefElem = externalRefToDOM(externalRef);
externalReferencesElem.addContent(externalRefElem);
}
return externalReferencesElem;
}
private static Element externalRefToDOM(ExternalRef externalRef) {
Element externalRefElem = new Element("externalRef");
externalRefElem.setAttribute("resource", externalRef.getResource());
externalRefElem.setAttribute("reference", externalRef.getReference());
if (externalRef.hasConfidence()) {
externalRefElem.setAttribute("confidence", Float.toString(externalRef.getConfidence()));
}
if (externalRef.hasExternalRef()) {
Element subExternalRefElem = externalRefToDOM(externalRef.getExternalRef());
externalRefElem.addContent(subExternalRefElem);
}
return externalRefElem;
}
} |
package joptsimple.internal;
import java.util.Iterator;
import static java.lang.System.*;
import static java.util.Arrays.*;
/**
* @author <a href="mailto:pholser@alumni.rice.edu">Paul Holser</a>
*/
public final class Strings {
public static final String EMPTY = "";
public static final String LINE_SEPARATOR = getProperty( "line.separator" );
private Strings() {
throw new UnsupportedOperationException();
}
/**
* Gives a string consisting of the given character repeated the given number of times.
*
* @param ch the character to repeat
* @param count how many times to repeat the character
* @return the resultant string
*/
public static String repeat( char ch, int count ) {
StringBuilder buffer = new StringBuilder();
for ( int i = 0; i < count; ++i )
buffer.append( ch );
return buffer.toString();
}
/**
* Tells whether the given string is either {@code} or consists solely of whitespace characters.
*
* @param target string to check
* @return {@code true} if the target string is null or empty
*/
public static boolean isNullOrEmpty( String target ) {
return target == null || target.isEmpty();
}
/**
* Gives a string consisting of a given string prepended and appended with surrounding characters.
*
* @param target a string
* @param begin character to prepend
* @param end character to append
* @return the surrounded string
*/
public static String surround( String target, char begin, char end ) {
return begin + target + end;
}
/**
* Gives a string consisting of the elements of a given array of strings, each separated by a given separator
* string.
*
* @param pieces the strings to join
* @param separator the separator
* @return the joined string
*/
public static String join( String[] pieces, String separator ) {
return join( asList( pieces ), separator );
}
/**
* Gives a string consisting of the string representations of the elements of a given array of objects,
* each separated by a given separator string.
*
* @param pieces the elements whose string representations are to be joined
* @param separator the separator
* @return the joined string
*/
public static String join( Iterable<String> pieces, String separator ) {
StringBuilder buffer = new StringBuilder();
for ( Iterator<String> iter = pieces.iterator(); iter.hasNext(); ) {
buffer.append( iter.next() );
if ( iter.hasNext() )
buffer.append( separator );
}
return buffer.toString();
}
} |
package looly.github.hutool;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.net.Socket;
import java.net.SocketException;
import java.net.URL;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Set;
import looly.github.hutool.exceptions.UtilException;
/**
*
* @author xiaoleilu
*
*/
public class NetUtil {
public final static String LOCAL_IP = "127.0.0.1";
/**
* longip v4
*
* @param longIP IPlong
* @return IP V4
*/
public static String longToIpv4(long longIP) {
StringBuffer sb = new StringBuffer();
sb.append(String.valueOf(longIP >>> 24));
sb.append(".");
// 8016
sb.append(String.valueOf((longIP & 0x00FFFFFF) >>> 16));
sb.append(".");
sb.append(String.valueOf((longIP & 0x0000FFFF) >>> 8));
sb.append(".");
sb.append(String.valueOf(longIP & 0x000000FF));
return sb.toString();
}
/**
* iplong
*
* @param strIP IP V4
* @return long
*/
public static long ipv4ToLong(String strIP) {
if (ReUtil.isIpv4(strIP)) {
long[] ip = new long[4];
int position1 = strIP.indexOf(".");
int position2 = strIP.indexOf(".", position1 + 1);
int position3 = strIP.indexOf(".", position2 + 1);
ip[0] = Long.parseLong(strIP.substring(0, position1));
ip[1] = Long.parseLong(strIP.substring(position1 + 1, position2));
ip[2] = Long.parseLong(strIP.substring(position2 + 1, position3));
ip[3] = Long.parseLong(strIP.substring(position3 + 1));
return (ip[0] << 24) + (ip[1] << 16) + (ip[2] << 8) + ip[3];
}
return 0;
}
/**
*
*
* @param port
* @return
*/
public static boolean isUsableLocalPort(int port) {
if (! isValidPort(port)) {
return false;
}
try {
new Socket(LOCAL_IP, port).close();
// socket
return false;
} catch (Exception e) {
return true;
}
}
/**
*
* @param port
* @return
*/
public static boolean isValidPort(int port) {
//065535
return port >= 0 && port <= 0xFFFF;
}
/**
* IP<br>
* IPA 10.0.0.0-10.255.255.255 B 172.16.0.0-172.31.255.255 C
* 192.168.0.0-192.168.255.255 127
**/
public static boolean isInnerIP(String ipAddress) {
boolean isInnerIp = false;
long ipNum = NetUtil.ipv4ToLong(ipAddress);
long aBegin = NetUtil.ipv4ToLong("10.0.0.0");
long aEnd = NetUtil.ipv4ToLong("10.255.255.255");
long bBegin = NetUtil.ipv4ToLong("172.16.0.0");
long bEnd = NetUtil.ipv4ToLong("172.31.255.255");
long cBegin = NetUtil.ipv4ToLong("192.168.0.0");
long cEnd = NetUtil.ipv4ToLong("192.168.255.255");
isInnerIp = isInner(ipNum, aBegin, aEnd) || isInner(ipNum, bBegin, bEnd) || isInner(ipNum, cBegin, cEnd) || ipAddress.equals(LOCAL_IP);
return isInnerIp;
}
/**
* IP
* @return IP
*/
public static Set<String> localIpv4s() {
Enumeration<NetworkInterface> networkInterfaces = null;
try {
networkInterfaces = NetworkInterface.getNetworkInterfaces();
} catch (SocketException e) {
throw new UtilException(e.getMessage(), e);
}
if(networkInterfaces == null) {
throw new UtilException("Get network interface error!");
}
final HashSet<String> ipSet = new HashSet<String>();
while(networkInterfaces.hasMoreElements()) {
final NetworkInterface networkInterface = networkInterfaces.nextElement();
final Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
while(inetAddresses.hasMoreElements()) {
final InetAddress inetAddress = inetAddresses.nextElement();
if(inetAddress != null && inetAddress instanceof Inet4Address) {
ipSet.add(inetAddress.getHostAddress());
}
}
}
return ipSet;
}
/**
* URLURL
* @param absoluteBasePath
* @param relativePath
* @return
*/
public static String toAbsoluteUrl(String absoluteBasePath, String relativePath) {
try {
URL absoluteUrl = new URL(absoluteBasePath);
return new URL(absoluteUrl ,relativePath).toString();
} catch (Exception e) {
throw new UtilException(StrUtil.format("To absolute url [{}] base [{}] error!", relativePath, absoluteBasePath), e);
}
}
/**
* IP *
* @param ip IP
* @return IP
*/
public static String hideIpPart(String ip) {
return new StringBuffer(ip.length())
.append(ip.substring(0, ip.lastIndexOf(".") + 1))
.append("*").toString();
}
/**
* IP *
* @param ip IP
* @return IP
*/
public static String hideIpPart(long ip) {
return hideIpPart(longToIpv4(ip));
}
public static InetSocketAddress buildInetSocketAddress(String host, int defaultPort) {
String destHost = null;
int port = 0;
int index = host.indexOf(":");
if (index != -1) {
// host:port
destHost = host.substring(0, index);
port = Integer.parseInt(host.substring(index + 1));
} else {
destHost = host;
port = defaultPort;
}
return new InetSocketAddress(destHost, port);
}
/**
* IPlong
* @param userIp IP
* @param begin IP
* @param end IP
* @return
*/
private static boolean isInner(long userIp, long begin, long end) {
return (userIp >= begin) && (userIp <= end);
}
} |
package me.qmx.jitescript;
import org.objectweb.asm.MethodVisitor;
import java.util.ArrayList;
import java.util.List;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Opcodes;
import static me.qmx.jitescript.util.CodegenUtils.*;
/**
*
* @author qmx
*/
public class JiteClass implements Opcodes {
private final List<MethodDefinition> methods = new ArrayList<MethodDefinition>();
private final String className;
public JiteClass(String className) {
this.className = className;
}
public void defineMethod(String methodName, int modifiers, String signature, MethodBody methodBody) {
this.methods.add(new MethodDefinition(methodName, modifiers, signature, methodBody));
}
byte[] toBytes() {
ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES);
cw.visit(V1_7, ACC_PUBLIC + ACC_SUPER, this.className, null, "java/lang/Object", null);
for(MethodDefinition def : methods){
MethodVisitor mv = cw.visitMethod(def.getModifiers(), def.getMethodName(), def.getSignature(), null, null);
mv.visitCode();
MethodBody methodBody = def.getMethodBody();
methodBody.setMethodVisitor(mv);
methodBody.executableMethodBody(mv);
mv.visitMaxs(1, 1);
mv.visitEnd();
}
cw.visitEnd();
return cw.toByteArray();
}
} |
package mezz.jei.input;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.List;
import net.minecraft.client.Minecraft;
import net.minecraft.client.entity.EntityPlayerSP;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fml.client.FMLClientHandler;
import org.lwjgl.input.Keyboard;
import org.lwjgl.input.Mouse;
import mezz.jei.config.Config;
import mezz.jei.config.KeyBindings;
import mezz.jei.gui.ItemListOverlay;
import mezz.jei.gui.RecipesGui;
import mezz.jei.util.Commands;
import mezz.jei.util.MouseHelper;
import mezz.jei.util.Permissions;
public class InputHandler {
private final RecipesGui recipesGui;
private final ItemListOverlay itemListOverlay;
private final MouseHelper mouseHelper;
private final List<IMouseHandler> mouseHandlers = new ArrayList<>();
private final List<IKeyable> keyables = new ArrayList<>();
private final List<IShowsItemStacks> showsItemStacks = new ArrayList<>();
private boolean clickHandled = false;
public InputHandler(RecipesGui recipesGui, ItemListOverlay itemListOverlay, GuiContainer guiContainer) {
this.recipesGui = recipesGui;
this.itemListOverlay = itemListOverlay;
this.mouseHelper = new MouseHelper();
List<ICloseable> objects = new ArrayList<>();
objects.add(recipesGui);
objects.add(itemListOverlay);
objects.add(new GuiContainerWrapper(guiContainer, recipesGui));
for (Object gui : objects) {
if (gui instanceof IMouseHandler) {
mouseHandlers.add((IMouseHandler) gui);
}
if (gui instanceof IKeyable) {
keyables.add((IKeyable) gui);
}
if (gui instanceof IShowsItemStacks) {
showsItemStacks.add((IShowsItemStacks) gui);
}
}
}
public boolean handleMouseEvent(int mouseX, int mouseY) {
boolean cancelEvent = false;
if (Mouse.getEventButton() > -1) {
if (Mouse.getEventButtonState()) {
if (!clickHandled) {
cancelEvent = handleMouseClick(Mouse.getEventButton(), mouseX, mouseY);
clickHandled = true;
}
} else {
clickHandled = false;
}
} else if (Mouse.getEventDWheel() != 0) {
cancelEvent = handleMouseScroll(Mouse.getEventDWheel(), mouseX, mouseY);
}
return cancelEvent;
}
private boolean handleMouseScroll(int dWheel, int mouseX, int mouseY) {
for (IMouseHandler scrollable : mouseHandlers) {
if (scrollable.handleMouseScrolled(mouseX, mouseY, dWheel)) {
return true;
}
}
return false;
}
private boolean handleMouseClick(int mouseButton, int mouseX, int mouseY) {
ItemStack itemStack = getStackUnderMouseForClick(mouseX, mouseY);
if (itemStack != null) {
if (handleMouseClickedItemStack(mouseButton, itemStack)) {
return true;
}
}
for (IMouseHandler clickable : mouseHandlers) {
if (clickable.handleMouseClicked(mouseX, mouseY, mouseButton)) {
return true;
}
}
return recipesGui.isOpen();
}
@Nullable
private ItemStack getStackUnderMouseForClick(int mouseX, int mouseY) {
for (IShowsItemStacks gui : showsItemStacks) {
if (!(gui instanceof IMouseHandler)) {
continue;
}
ItemStack itemStack = gui.getStackUnderMouse(mouseX, mouseY);
if (itemStack != null) {
return itemStack;
}
}
return null;
}
@Nullable
private ItemStack getStackUnderMouseForKey(int mouseX, int mouseY) {
for (IShowsItemStacks gui : showsItemStacks) {
ItemStack itemStack = gui.getStackUnderMouse(mouseX, mouseY);
if (itemStack != null) {
return itemStack;
}
}
return null;
}
private boolean handleMouseClickedItemStack(int mouseButton, @Nonnull ItemStack itemStack) {
EntityPlayerSP player = FMLClientHandler.instance().getClientPlayerEntity();
if (Config.cheatItemsEnabled && Permissions.canPlayerSpawnItems(player)) {
if (mouseButton == 0) {
Commands.giveFullStack(itemStack);
return true;
} else if (mouseButton == 1) {
Commands.giveOneFromStack(itemStack);
return true;
}
} else {
if (mouseButton == 0) {
recipesGui.showRecipes(itemStack);
return true;
} else if (mouseButton == 1) {
recipesGui.showUses(itemStack);
return true;
}
}
return false;
}
public boolean handleKeyEvent() {
boolean cancelEvent = false;
if (Keyboard.getEventKeyState()) {
int eventKey = Keyboard.getEventKey();
cancelEvent = handleKeyDown(eventKey);
}
return cancelEvent;
}
private boolean handleKeyDown(int eventKey) {
for (IKeyable keyable : keyables) {
if (keyable.isOpen() && keyable.hasKeyboardFocus()) {
if (isInventoryCloseKey(eventKey)) {
keyable.setKeyboardFocus(false);
return true;
} else if (keyable.onKeyPressed(eventKey)) {
return true;
}
}
}
if (isInventoryCloseKey(eventKey) || isInventoryToggleKey(eventKey)) {
if (recipesGui.isOpen()) {
recipesGui.close();
return true;
} else if (itemListOverlay.isOpen()) {
itemListOverlay.close();
return false;
}
}
if (eventKey == KeyBindings.showRecipe.getKeyCode()) {
ItemStack itemStack = getStackUnderMouseForKey(mouseHelper.getX(), mouseHelper.getY());
if (itemStack != null) {
recipesGui.showRecipes(itemStack);
return true;
}
} else if (eventKey == KeyBindings.showUses.getKeyCode()) {
ItemStack itemStack = getStackUnderMouseForKey(mouseHelper.getX(), mouseHelper.getY());
if (itemStack != null) {
recipesGui.showUses(itemStack);
return true;
}
} else if (eventKey == KeyBindings.toggleOverlay.getKeyCode()) {
itemListOverlay.toggleEnabled();
return false;
}
for (IKeyable keyable : keyables) {
if (keyable.isOpen() && keyable.onKeyPressed(eventKey)) {
return true;
}
}
return false;
}
private boolean isInventoryToggleKey(int keyCode) {
return keyCode == Minecraft.getMinecraft().gameSettings.keyBindInventory.getKeyCode();
}
private boolean isInventoryCloseKey(int keyCode) {
return keyCode == Keyboard.KEY_ESCAPE;
}
} |
package com.hulab.debugkit;
import android.content.Context;
import android.content.SharedPreferences;
import java.util.concurrent.Callable;
/**
* Use this class to add a function to the debug tool. The return type of {@code call()} method will
* be logged to the console.
*
* @see Callable
*/
public abstract class DebugFunction implements Callable<String> {
private DevToolFragment mDevToolFragment;
public String title = null;
public DebugFunction() {
}
/**
* By default, the buttons of the tool are F1, F2... You can give a title to this button
* using this constructor.
*
* @param title the title of the function you want the button to display
*/
public DebugFunction(String title) {
this.title = title;
}
protected Context getContext() {
return mDevToolFragment.getActivity();
}
/**
* The method that will be executed when matching button is clicked.
*
* @return The string message that will be logged to the console.
* if null is returned, no log message will be displayed.
* @throws Exception
*/
@Override
public abstract String call() throws Exception;
/**
* Calling this method will log a message in the console.
*
* @param string the message that will be logged to to the console.
* <p>
* string will be logged in the console on a new line as following:
* <br>
* {@code HH:mm:ss > string}
*
*/
protected void log(String string) {
if (mDevToolFragment != null)
mDevToolFragment.log(string);
}
/**
* Calling this method will clear the console.
*/
protected void clear() {
if (mDevToolFragment != null)
mDevToolFragment.clear();
}
/*package*/ void setDevToolFragment(DevToolFragment devToolFragment) {
this.mDevToolFragment = devToolFragment;
}
public static class Clear extends DebugFunction {
@Override
public String call() throws Exception {
clear();
return null;
}
}
/**
* This is a sample function to dump shared preferences
*/
public static class DumpSharedPreferences extends DebugFunction {
private String FILE_NAME;
private int mode = Context.MODE_PRIVATE;
private DumpSharedPreferences() {
}
/**
* Constructor
*
* @param title the title of the function
* @param fileName the name of your shared preference file
* @param mode the file creation mode. By default {@link android.content.Context#MODE_PRIVATE Context.MODE_PRIVATE}
*/
public DumpSharedPreferences(String title, String fileName, int mode) {
super(title);
this.FILE_NAME = fileName;
this.mode = mode;
}
/**
* Constructor
*
* @param title the title of the function
* @param fileName the name of your shared preference file
*/
public DumpSharedPreferences(String title, String fileName) {
super(title);
this.FILE_NAME = fileName;
}
/**
* Constructor
*
* @param fileName the name of your shared preference file
* @param mode the file creation mode. By default {@link android.content.Context#MODE_PRIVATE Context.MODE_PRIVATE}
*/
public DumpSharedPreferences(String fileName, int mode) {
this.FILE_NAME = fileName;
this.mode = mode;
}
/**
* Constructor
*
* @param fileName the name of your shared preference file
*/
public DumpSharedPreferences(String fileName) {
this.FILE_NAME = fileName;
}
@Override
public String call() throws Exception {
return dumpSharedPreferences(this.getContext());
}
private String dumpSharedPreferences(Context context) {
SharedPreferences preferences = context.getSharedPreferences(FILE_NAME, mode);
java.util.Map<String, ?> keys = preferences.getAll();
StringBuilder sb = new StringBuilder();
for (java.util.Map.Entry<String, ?> entry : keys.entrySet())
sb.append(entry).append(",\n");
return sb.toString();
}
}
} |
package org.amc.servlet;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;
import javax.persistence.PersistenceException;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import org.amc.dao.DAO;
import org.amc.dao.UserRolesDAO;
import org.amc.model.User;
import org.amc.model.UserRoles;
import org.amc.servlet.validator.UserValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Validator;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import org.apache.log4j.Logger;
/**
*
* @author Adrian Mclaughlin
* @version 1
*/
@Controller
public class UserServlet
{
private final static String MANAGER="manager";//Super User of the system
private UserRolesDAO userRolesDAO;
private DAO<User> userDAO;
private static Logger logger=Logger.getLogger(UserServlet.class);
// @InitBinder("user")
// protected void initBinder(WebDataBinder binder)
// binder.addValidators(new UserValidator());
@RequestMapping("/User")
public String getUserPage()
{
return "UserInfo";
}
/**
*
* @param model
* @return ModelAndView containing list of users from the database
*/
@RequestMapping("/Users")
public ModelAndView getUsersPage(ModelAndView model,HttpServletRequest request)
{
if(request.isUserInRole(MANAGER))
{
List<User> list=userDAO.findEntities();
model.getModel().put("users", list);
model.setViewName("UsersSearchPage");
}
else
{
//Not Manager so return to Main.jsp
model.setViewName("Main");
}
return model;
}
@RequestMapping("/User_Save")
public String saveUser(Model model,
@Valid @ModelAttribute("user") User user,
BindingResult result,
@RequestParam("mode") String mode,
@RequestParam(value="active",required=false) String active,
@RequestParam(value="role",required=false) String[] roles,
HttpServletRequest request
)
{
if(!request.isUserInRole(MANAGER))
{
//Return to the Main page
return "Main";
}
//Set the user's active state
if(active==null)
user.setActive(false);
else
user.setActive(true);
//Get the roles currently assigned to the user
List<UserRoles> currentListOfRoles=userRolesDAO.getEntities(user);
//Create a new list of roles
List<UserRoles> newListOfRoles=new ArrayList<UserRoles>();
//Check if roles equals null or no roles selected
if(roles==null)
{
roles=new String[0];
}
//Check to see if the User's role already exists
for(int i=0;i<roles.length;i++)
{
boolean exists=false;
for(UserRoles tempRole:currentListOfRoles)
{
if(tempRole.getRoleName().equals(roles[i]))
{
//If the role already exists copy to new list
newListOfRoles.add(tempRole);
exists=true;
}
}
if(!exists)
{
//If the role doesn't exist then create a new role for the user and add to new list
UserRoles newRole=new UserRoles();
newRole.setRoleName(roles[i]);
newRole.setUser(user);
newListOfRoles.add(newRole);
}
}
//Check to see what roles are no longer required and delete them
for(int i=0;i<currentListOfRoles.size();i++)
{
boolean exists=false;
for(int t=0;t<roles.length;t++)
{
if(currentListOfRoles.get(i).getRoleName().equals(roles[t]))
{
exists=true;
}
}
if(exists==false)
{
userRolesDAO.deleteEntity(currentListOfRoles.get(i));
}
}
logger.info(newListOfRoles);
//Set the user's roles
user.setRoles(newListOfRoles);
logger.info(user);
//Check validation if fails return to page to get correct information
Validator v=new UserValidator();//@ToDo to be Injected
v.validate(user, result);
if(result.hasErrors())
{
logger.debug("Errors in Model User found:"+result);
model.addAttribute("errors", result.getAllErrors());
model.addAttribute("user", user);
return "UserAddOrEdit";
}
//If in Edit mode update user otherwise add user
if(mode.equals("edit"))
{
userDAO.updateEntity(user);
}
else
{
userDAO.addEntity(user);
}
//Return to the search page
return "forward:/user/Users";
}
/**
*
* @param mode The mode the page is in: Edit or add
* @param id The database id of the User from page
* @param model
* @return ModelAndView containing the user to edit and setting view to User.jsp
*/
@RequestMapping("/Users_edit")
public ModelAndView editUsers(
@RequestParam("mode") String mode,
@RequestParam(value="edit",required=false) Integer id,
ModelAndView model,
HttpServletRequest request
)
{
//If not in role manager return the Main.jsp
if(!request.isUserInRole(MANAGER))
{
model.setViewName("Main");
return model;
}
logger.debug("UserServlet:In mode "+mode);
logger.debug("UserServlet:UserDAO is "+userDAO);
User u=null;
model.getModel().put("mode", mode);
if(mode.equals("edit"))
{
u=userDAO.getEntity(String.valueOf(id));
logger.debug("Users_edit: User retrieved"+u);
}
else
if(mode.equals("add"))
{
u=new User();
}
else if(mode.equals("delete"))
{
u=userDAO.getEntity(String.valueOf(id));
logger.debug("User about to be deleted "+u);
userDAO.deleteEntity(u);
return getUsersPage(new ModelAndView(), request);
}
else
{
logger.debug("UserServlet:editUsers: passed straight through if/else block shouldn't happen");
}
model.setViewName("UserAddOrEdit");
model.getModel().put("user", u);
return model;
}
@ExceptionHandler(PersistenceException.class)
public ModelAndView handleJPAException(PersistenceException exception)
{
ModelAndView mv=new ModelAndView();
mv.setViewName("ErrorPage");
mv.getModel().put("exception", exception);
return mv;
}
/*
* Spring injected
*/
@Resource(name="myUserDAO")
public void setUserDAO(DAO<User> ud)
{
userDAO=ud;
logger.debug("UserDAO added to UserServlet:"+userDAO);
}
/*
* Spring injected
*/
@Autowired
public void setUserRolesDAO(UserRolesDAO ud)
{
userRolesDAO=ud;
}
} |
package org.apdplat.word.util;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
/**
*
* @author
*/
public class Utils {
private static final Pattern PATTERN = Pattern.compile("^[\\u4e00-\\u9fa5]{2,}$");
/**
*
* @param word
* @return
*/
public static boolean isChineseCharAndLengthAtLeastTwo(String word){
if(PATTERN.matcher(word).find()){
return true;
}
return false;
}
/**
* MAPVALUE
* @param <K> key
* @param <V> value
* @param map map
* @return MAPVALUE
*/
public static <K, V extends Number> List<Map.Entry<K, V>> getSortedMapByValue(Map<K, V> map) {
List<Map.Entry<K, V>> list = new ArrayList<>(map.entrySet());
Collections.sort(list, new Comparator<Map.Entry<K,V>>() {
@Override
public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {
if(o1.getValue() instanceof Integer){
return o2.getValue().intValue() - o1.getValue().intValue();
}
if(o1.getValue() instanceof Long){
return (int)(o2.getValue().longValue() - o1.getValue().longValue());
}
if(o1.getValue() instanceof Float){
return (int)(o2.getValue().floatValue() - o1.getValue().floatValue());
}
if(o1.getValue() instanceof Double){
return (int)(o2.getValue().doubleValue() - o1.getValue().doubleValue());
}
return 0;
}
});
return list;
}
} |
package org.basex.core.cmd;
import static org.basex.core.Text.*;
import java.io.File;
import java.io.IOException;
import org.basex.build.FSParser;
import org.basex.core.CommandBuilder;
import org.basex.core.Prop;
import org.basex.core.Commands.Cmd;
import org.basex.core.Commands.CmdCreate;
public final class CreateFS extends ACreate {
/**
* Default constructor.
* @param name name of database
* @param path filesystem path
*/
public CreateFS(final String name, final String path) {
super(name, path);
}
@Override
protected boolean run() {
prop.set(Prop.CHOP, true);
prop.set(Prop.ENTITY, true);
final String path;
try {
final File f = new File(args[1]).getCanonicalFile();
if(!f.exists()) return error(FILEWHICH, f.getAbsolutePath());
path = f.getCanonicalPath();
} catch(final IOException ex) {
return error(ex.getMessage());
}
final String db = args[0];
final FSParser fs = new FSParser(path, context, db);
progress(fs);
fs.parse();
final Optimize opt = new Optimize();
progress(opt);
return opt.run(context) ? info(DBCREATED, db, perf) : error(opt.info());
}
@Override
public void abort() {
new Open(args[0]).run(context);
new Optimize().run(context);
}
@Override
public void build(final CommandBuilder cb) {
cb.init(Cmd.CREATE + " " + CmdCreate.FS).args();
}
} |
package org.basex.server;
import static org.basex.util.Token.*;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import org.basex.core.BaseXException;
import org.basex.core.Context;
import org.basex.io.PrintOutput;
import org.basex.query.QueryException;
public class LocalQuery extends Query {
/** Active query process. */
private final QueryProcess qp;
/** Buffer output; {@code null} if an {@link OutputStream} is specified. */
private final ByteArrayOutputStream buf;
/** Iterator flag. */
private boolean ready;
/**
* Constructor. Query output will be returned by each called methods.
* @param q query string
* @param ctx database context
* @throws BaseXException query exception
*/
public LocalQuery(final String q, final Context ctx) throws BaseXException {
buf = new ByteArrayOutputStream();
try {
qp = new QueryProcess(q, PrintOutput.get(buf), ctx);
} catch(QueryException ex) {
throw new BaseXException(ex);
}
}
/**
* Constructor. Query output will be written to the provided output stream.
* All methods will return {@code null}.
* @param q query string
* @param ctx database context
* @param o output stream to write query output
* @throws BaseXException query exception
*/
public LocalQuery(final String q, final Context ctx, final OutputStream o)
throws BaseXException {
buf = null;
try {
qp = new QueryProcess(q, PrintOutput.get(o), ctx);
} catch(QueryException ex) {
throw new BaseXException(ex);
}
}
@Override
public void bind(final String n, final String v, final String t)
throws BaseXException {
try {
qp.bind(n, v, t);
} catch(QueryException ex) {
throw new BaseXException(ex);
}
}
@Override
public String init() throws BaseXException {
try {
qp.init();
} catch(Exception ex) {
throw new BaseXException(ex);
}
return output();
}
@Override
public boolean more() throws BaseXException {
try {
ready = true;
return qp.next();
} catch(Exception ex) {
throw new BaseXException(ex);
}
}
@Override
public String next() throws BaseXException {
try {
if(ready) ready = false;
else qp.next();
} catch(Exception ex) {
throw new BaseXException(ex);
}
return output();
}
@Override
public String execute() throws BaseXException {
try {
qp.execute();
} catch(Exception ex) {
throw new BaseXException(ex);
}
return output();
}
@Override
public String info() throws BaseXException {
try {
qp.info();
} catch(IOException ex) {
throw new BaseXException(ex);
}
return output();
}
@Override
public String close() throws BaseXException {
try {
qp.close(false);
} catch(IOException ex) {
throw new BaseXException(ex);
}
return output();
}
/**
* Query output.
* @return {@code null} if query output is directly sent to an output stream
*/
private String output() {
// if another output stream is specified, the query process has already
// written the data, so there is nothing to output
if(buf == null) return null;
final String result = string(buf.toByteArray());
buf.reset();
return result;
}
} |
package org.jtrfp.trcl;
import java.util.concurrent.ExecutionException;
import javax.media.opengl.GL3;
import org.apache.commons.math3.geometry.euclidean.threed.Vector3D;
import org.jtrfp.trcl.core.TR;
import org.jtrfp.trcl.core.TriangleVertex2FlatDoubleWindow;
import org.jtrfp.trcl.core.TriangleVertex2FlatDoubleWindow.Variable;
import org.jtrfp.trcl.core.TriangleVertexWindow;
import org.jtrfp.trcl.core.WindowAnimator;
public class TriangleList extends PrimitiveList<Triangle,GPUTriangleVertex>{
private Controller controller;
private int timeBetweenFramesMsec;
private final boolean animateUV;
private final TR tr;
private final WindowAnimator xyzAnimator;
private final TriangleVertex2FlatDoubleWindow flatTVWindow;
public TriangleList(Triangle [][] triangles, int timeBetweenFramesMsec, String debugName, boolean animateUV, Controller controller, TR tr)
{super(debugName,triangles,GPUTriangleVertex.createVertexBlock(triangles[0].length*3,tr),tr);
this.timeBetweenFramesMsec=timeBetweenFramesMsec;
this.animateUV=animateUV;
this.controller=controller;
this.tr=tr;
this.flatTVWindow = tr.getTv2fdWindow();
if(getPrimitives().length>1){
this.xyzAnimator = new WindowAnimator(flatTVWindow,
this.getNumPrimitives()*3*3,// 3 vertices per triangle, XYZ per vertex
getPrimitives().length, true, controller,new XYZXferFunc(getGPUPrimitiveStartIndex()*5));
animators.add(xyzAnimator);}
else{this.xyzAnimator=null;}
}
private static class XYZXferFunc implements IntTransferFunction{
private final int startIndex;
public XYZXferFunc(int startIndex){
this.startIndex=startIndex;
}//end constructor
@Override
public int transfer(int input) {
return (input/3)*5+(input%3)+startIndex;
}//end transfer(...)
}//end class XYZXferFunc
private static class UVXferFunc implements IntTransferFunction{
private final int startIndex;
public UVXferFunc(int startIndex){
this.startIndex=startIndex;
}//end constructor
@Override
public int transfer(int input) {
return (input/2)*5+(input%2)+startIndex+3;
}//end transfer(...)
}//end class XYZXferFunc
public TriangleList [] getAllLists(){
return getAllArrayLists().toArray(new TriangleList [] {});}
private Controller getVertexSequencer(int timeBetweenFramesMsec, int nFrames){
return controller;
}
private Triangle triangleAt(int frame, int tIndex)
{return getPrimitives()[frame][tIndex];}
private void setupVertex(int vIndex, int gpuTVIndex, int triangleIndex) throws ExecutionException, InterruptedException
{final int numFrames = getPrimitives().length;
Triangle t=triangleAt(0,triangleIndex);
final TriangleVertexWindow vw = tr.getTriangleVertexWindow();
if(numFrames==1){
vw.setX(gpuTVIndex, (short)applyScale(t.x[vIndex]));
vw.setY(gpuTVIndex, (short)applyScale(t.y[vIndex]));
vw.setZ(gpuTVIndex, (short)applyScale(t.z[vIndex]));
}
else if(numFrames>1){
float []xFrames = new float[numFrames];
float []yFrames = new float[numFrames];
float []zFrames = new float[numFrames];
for(int i=0; i<numFrames; i++)
{xFrames[i]=Math.round(triangleAt(i,triangleIndex).x[vIndex]/scale);}
xyzAnimator.addFrames(xFrames);
for(int i=0; i<numFrames; i++)
{yFrames[i]=Math.round(triangleAt(i,triangleIndex).y[vIndex]/scale);}
xyzAnimator.addFrames(yFrames);
for(int i=0; i<numFrames; i++)
{zFrames[i]=Math.round(triangleAt(i,triangleIndex).z[vIndex]/scale);}
xyzAnimator.addFrames(zFrames);
}
else{throw new RuntimeException("Empty triangle vertex!");}
TextureDescription td = t.getTexture().get();
if(td instanceof Texture){//Static texture
final Texture.TextureTreeNode tx;
tx= ((Texture)t.getTexture().get()).getNodeForThisTexture();
if(animateUV&&numFrames>1){//Animated UV
float []uFrames = new float[numFrames];
float []vFrames = new float[numFrames];
final WindowAnimator uvAnimator = new WindowAnimator(flatTVWindow,
2,// UV per vertex
numFrames, false, getVertexSequencer(timeBetweenFramesMsec,numFrames),
new UVXferFunc(gpuTVIndex*5));
animators.add(uvAnimator);
for(int i=0; i<numFrames; i++){
uFrames[i]=(float)(uvUpScaler*tx.getGlobalUFromLocal(triangleAt(i,triangleIndex).u[vIndex]));
vFrames[i]=(float)(uvUpScaler*tx.getGlobalVFromLocal(triangleAt(i,triangleIndex).v[vIndex]));
}//end for(numFrames)
uvAnimator.addFrames(uFrames);
uvAnimator.addFrames(vFrames);
}else{//end if(animateUV)
vw.setU(gpuTVIndex, (short)(uvUpScaler*tx.getGlobalUFromLocal(t.u[vIndex])));
vw.setV(gpuTVIndex, (short)(uvUpScaler*tx.getGlobalVFromLocal(t.v[vIndex])));
}//end if(!animateUV)
}//end if(Texture)
else {//Animated texture
AnimatedTexture at =((AnimatedTexture)t.getTexture().get());
Texture.TextureTreeNode tx=at.
getFrames()
[0].get().
getNodeForThisTexture();//Default frame
final WindowAnimator uvAnimator = new WindowAnimator(flatTVWindow,
2,// UV per vertex
at.getFrames().length, false, at.getTextureSequencer(),
new UVXferFunc(gpuTVIndex*5));
animators.add(uvAnimator);
final int numTextureFrames = at.getFrames().length;
float [] uFrames = new float[numTextureFrames];
float [] vFrames = new float[numTextureFrames];
for(int ti=0; ti<numTextureFrames;ti++){
tx=at.getFrames()[ti].get().getNodeForThisTexture();
uFrames[ti]=(short)(uvUpScaler*tx.getGlobalUFromLocal(t.u[vIndex]));
vFrames[ti]=(short)(uvUpScaler*tx.getGlobalVFromLocal(t.v[vIndex]));
}//end for(frame)
uvAnimator.addFrames(uFrames);
uvAnimator.addFrames(vFrames);
}//end animated texture
}//end setupVertex
private void setupTriangle(int gpuTriangleVertIndex, int triangleIndex) throws ExecutionException,InterruptedException{
setupVertex(0,gpuTriangleVertIndex+0,triangleIndex);
setupVertex(1,gpuTriangleVertIndex+1,triangleIndex);
setupVertex(2,gpuTriangleVertIndex+2,triangleIndex);
}
public void uploadToGPU(GL3 gl){
int nPrimitives=getNumPrimitives();
try{
for(int tIndex=0;tIndex<nPrimitives;tIndex++)
{setupTriangle(getGPUPrimitiveStartIndex()+tIndex*3,tIndex);}
}catch(InterruptedException e){e.printStackTrace();}
catch(ExecutionException e){e.printStackTrace();}
}//end allocateIndices(...)
@Override
public int getPrimitiveSizeInVec4s(){return 3;}
@Override
public int getGPUVerticesPerPrimitive(){return 3;}
@Override
public byte getPrimitiveRenderMode()
{return PrimitiveRenderMode.RENDER_MODE_TRIANGLES;}
@Override
public org.jtrfp.trcl.PrimitiveList.RenderStyle getRenderStyle()
{return RenderStyle.OPAQUE;}
public Vector3D getMaximumVertexDims(){
Vector3D result=Vector3D.ZERO;
Triangle [][]t=getPrimitives();
for(Triangle [] frame:t){
for(Triangle tri:frame){
for(int i=0; i<3; i++){
double v;
v=(tri.x[i]);
result=result.getX()<v?new Vector3D(v,result.getY(),result.getZ()):result;
v=(tri.y[i]);
result=result.getY()<v?new Vector3D(result.getX(),v,result.getZ()):result;
v=(tri.z[i]);
result=result.getZ()<v?new Vector3D(result.getX(),result.getY(),v):result;
}//end for(vertex)
}//end for(triangle)
}//end for(triangles)
return result;
}//end getMaximumVertexDims()
public Vector3D getMinimumVertexDims(){
Vector3D result=new Vector3D(Double.POSITIVE_INFINITY,Double.POSITIVE_INFINITY,Double.POSITIVE_INFINITY);
Triangle [][]t=getPrimitives();
for(Triangle [] frame:t){
for(Triangle tri:frame){
for(int i=0; i<3; i++){
double v;
v=(tri.x[i]);
result=result.getX()>v?new Vector3D(v,result.getY(),result.getZ()):result;
v=(tri.y[i]);
result=result.getY()>v?new Vector3D(result.getX(),v,result.getZ()):result;
v=(tri.z[i]);
result=result.getZ()>v?new Vector3D(result.getX(),result.getY(),v):result;
}//end for(vertex)
}//end for(triangle)
}//end for(triangles)
return result;
}//end getMaximumVertexDims()
public double getMaximumVertexValue(){
double result=0;
Triangle [][]t=getPrimitives();
for(Triangle [] frame:t){
for(Triangle tri:frame){
for(int i=0; i<3; i++){
double v;
v=Math.abs(tri.x[i]);
result=result<v?v:result;
v=Math.abs(tri.y[i]);
result=result<v?v:result;
v=Math.abs(tri.z[i]);
result=result<v?v:result;
}//end for(vertex)
}//end for(triangle)
}//end for(triangles)
return result;
}//end getMaximumVertexValue()
}//end SingleTextureTriangleList |
package org.jtrfp.trcl;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import javax.media.opengl.GL3;
import javax.media.opengl.GLAutoDrawable;
import javax.media.opengl.GLRunnable;
import org.apache.commons.math3.geometry.euclidean.threed.Vector3D;
import org.jtrfp.trcl.core.TR;
import org.jtrfp.trcl.core.Texture;
import org.jtrfp.trcl.core.TextureDescription;
import org.jtrfp.trcl.core.TriangleVertex2FlatDoubleWindow;
import org.jtrfp.trcl.core.TriangleVertexWindow;
import org.jtrfp.trcl.core.WindowAnimator;
import org.jtrfp.trcl.mem.MemoryWindow;
public class TriangleList extends PrimitiveList<Triangle> {
private Controller controller;
private int timeBetweenFramesMsec;
private final boolean animateUV;
private final WindowAnimator xyzAnimator;
private TriangleVertex2FlatDoubleWindow flatTVWindow;
public TriangleList(Triangle[][] triangles, int timeBetweenFramesMsec,
String debugName, boolean animateUV, Controller controller, TR tr, Model m) {
super(debugName, triangles, new TriangleVertexWindow(tr, debugName), tr,m);
this.timeBetweenFramesMsec = timeBetweenFramesMsec;
this.animateUV = animateUV;
this.controller = controller;
if (getPrimitives().length > 1) {
this.xyzAnimator = new WindowAnimator(
getFlatTVWindow(),
this.getNumElements() * 3 * XYZXferFunc.FRONT_STRIDE_LEN,
// 3 vertices per triangle,
// XYZ+NxNyNz per vertex
getPrimitives().length, true, controller,
new XYZXferFunc(0));
getModel().addTickableAnimator(xyzAnimator);
} else if (animateUV) {
this.xyzAnimator = null;
} else {
this.xyzAnimator = null;
}
}//end constructor
private static class XYZXferFunc implements IntTransferFunction {
private final int startIndex;
public static final int BACK_STRIDE_LEN = 8;
public static final int FRONT_STRIDE_LEN = 6;
private static final byte [] STRIDE_PATTERN = new byte[]{
0,1,2,//XYZ
5,6,7//NxNyNz
};
public XYZXferFunc(int startIndex) {
this.startIndex = startIndex;
}// end constructor
@Override
public int transfer(int input) {
return startIndex + STRIDE_PATTERN[input%FRONT_STRIDE_LEN]+(input/FRONT_STRIDE_LEN)*BACK_STRIDE_LEN;
}// end transfer(...)
}// end class XYZXferFunc
private static class UVXferFunc implements IntTransferFunction {
private final int startIndex;
public static final int BACK_STRIDE_LEN=8;
private final int FRONT_STRIDE_LEN=2;
public UVXferFunc(int startIndex) {
this.startIndex = startIndex;
}// end constructor
@Override
public int transfer(int input) {
return (input / FRONT_STRIDE_LEN) * BACK_STRIDE_LEN + (input % FRONT_STRIDE_LEN) + startIndex + 3;
}// end transfer(...)
}// end class XYZXferFunc
private Controller getVertexSequencer(int timeBetweenFramesMsec, int nFrames) {
return controller;
}
private Triangle triangleAt(int frame, int tIndex) {
return getPrimitives()[frame][tIndex];
}
private void setupVertex(int vIndex, int gpuTVIndex, int triangleIndex, TextureDescription td)
throws ExecutionException, InterruptedException {
final int numFrames = getPrimitives().length;
final Triangle t = triangleAt(0, triangleIndex);
final Vector3D pos = t.getVertices()[vIndex].getPosition();
final TriangleVertexWindow vw = (TriangleVertexWindow) getMemoryWindow();
////////////////////// V E R T E X //////////////////////////////
if (numFrames == 1) {
vw.x.set(gpuTVIndex, (short) applyScale(pos.getX()));
vw.y.set(gpuTVIndex, (short) applyScale(pos.getY()));
vw.z.set(gpuTVIndex, (short) applyScale(pos.getZ()));
final Vector3D normal = t.getVertices()[vIndex].getNormal();
vw.normX.set(gpuTVIndex, (byte)(normal.getX()*127));
vw.normY.set(gpuTVIndex, (byte)(normal.getY()*127));
vw.normZ.set(gpuTVIndex, (byte)(normal.getZ()*127));
} else if (numFrames > 1) {
float[] xFrames = new float[numFrames];
float[] yFrames = new float[numFrames];
float[] zFrames = new float[numFrames];
float[] nxFrames = new float[numFrames];
float[] nyFrames = new float[numFrames];
float[] nzFrames = new float[numFrames];
for (int i = 0; i < numFrames; i++) {
xFrames[i] = Math.round(triangleAt(i, triangleIndex).getVertices()[vIndex].getPosition().getX()
/ scale);
}
xyzAnimator.addFrames(xFrames);
for (int i = 0; i < numFrames; i++) {
yFrames[i] = Math.round(triangleAt(i, triangleIndex).getVertices()[vIndex].getPosition().getY()
/ scale);
}
xyzAnimator.addFrames(yFrames);
for (int i = 0; i < numFrames; i++) {
zFrames[i] = Math.round(triangleAt(i, triangleIndex).getVertices()[vIndex].getPosition().getZ()
/ scale);
}
xyzAnimator.addFrames(zFrames);
for (int i = 0; i < numFrames; i++) {
nxFrames[i] = Math.round(triangleAt(i, triangleIndex).getVertices()[vIndex].getNormal().getX()*127);
}
xyzAnimator.addFrames(nxFrames);
for (int i = 0; i < numFrames; i++) {
nyFrames[i] = Math.round(triangleAt(i, triangleIndex).getVertices()[vIndex].getNormal().getY()*127);
}
xyzAnimator.addFrames(nyFrames);
for (int i = 0; i < numFrames; i++) {
nzFrames[i] = Math.round(triangleAt(i, triangleIndex).getVertices()[vIndex].getNormal().getZ()*127);
}
xyzAnimator.addFrames(nzFrames);
} else {
throw new RuntimeException("Empty triangle vertex!");
}
//////////////// T E X T U R E ///////////////////////////
if(td==null){
System.err.println("Stack trace of triangle creation below. NullPointerException follows.");
for(StackTraceElement el:t.getCreationStackTrace()){
System.err.println("\tat "+el.getClassName()+"."+el.getMethodName()+"("+el.getFileName()+":"+el.getLineNumber()+")");
}//end for(stackTrace)
throw new NullPointerException("Texture for triangle in "+debugName+" intolerably null.");}
if (td instanceof Texture ) {// Static texture
final Texture.TextureTreeNode tx;
tx = ((Texture) td).getNodeForThisTexture();
if (animateUV && numFrames > 1) {// Animated UV
float[] uFrames = new float[numFrames];
float[] vFrames = new float[numFrames];
final WindowAnimator uvAnimator = new WindowAnimator(
getFlatTVWindow(), 2,// UV per vertex
numFrames, false, getVertexSequencer(
timeBetweenFramesMsec, numFrames),
new UVXferFunc(gpuTVIndex * UVXferFunc.BACK_STRIDE_LEN));
getModel().addTickableAnimator(uvAnimator);
for (int i = 0; i < numFrames; i++) {
uFrames[i] = (float) (uvUpScaler * tx
.getGlobalUFromLocal(triangleAt(i, triangleIndex).getUV(vIndex).getX()));
vFrames[i] = (float) (uvUpScaler * tx
.getGlobalVFromLocal(triangleAt(i, triangleIndex).getUV(vIndex).getY()));
}// end for(numFrames)
uvAnimator.addFrames(uFrames);
uvAnimator.addFrames(vFrames);
} else {// end if(animateUV)
vw.u.set(gpuTVIndex, (short) (uvUpScaler * tx
.getGlobalUFromLocal(t.getUV(vIndex).getX())));
vw.v.set(gpuTVIndex, (short) (uvUpScaler * tx
.getGlobalVFromLocal(t.getUV(vIndex).getY())));
}// end if(!animateUV)
final int textureID = tx.getTexturePage();
vw.textureIDLo .set(gpuTVIndex, (byte)(textureID & 0xFF));
vw.textureIDMid.set(gpuTVIndex, (byte)((textureID >> 8) & 0xFF));
vw.textureIDHi .set(gpuTVIndex, (byte)((textureID >> 16) & 0xFF));
}// end if(Texture)
//TODO: Temporary. Remove this check and replace with else {}, this is a kludge to avoid nonfunctional animation.
else if(!tr.getTrConfig().isUsingNewTexturing()) {// Animated texture
AnimatedTexture at = ((AnimatedTexture) td);
Texture.TextureTreeNode tx = at.getFrames()[0].get()
.getNodeForThisTexture();// Default frame
final int numTextureFrames = at.getFrames().length;
final WindowAnimator uvAnimator = new WindowAnimator(
getFlatTVWindow(),
2,// UV per vertex
numTextureFrames, false, at.getTextureSequencer(),
new UVXferFunc(gpuTVIndex * UVXferFunc.BACK_STRIDE_LEN));
uvAnimator.setDebugName(debugName + ".uvAnimator");
getModel().addTickableAnimator(uvAnimator);
float[] uFrames = new float[numTextureFrames];
float[] vFrames = new float[numTextureFrames];
for (int ti = 0; ti < numTextureFrames; ti++) {
tx = at.getFrames()[ti].get().getNodeForThisTexture();
uFrames[ti] = (short) (uvUpScaler * tx
.getGlobalUFromLocal(t.getUV(vIndex).getX()));
vFrames[ti] = (short) (uvUpScaler * tx
.getGlobalVFromLocal(t.getUV(vIndex).getY()));
}// end for(frame)
uvAnimator.addFrames(uFrames);
uvAnimator.addFrames(vFrames);
final int textureID = tx.getTexturePage();
vw.textureIDLo .set(gpuTVIndex, (byte)(textureID & 0xFF));
vw.textureIDMid.set(gpuTVIndex, (byte)((textureID >> 8) & 0xFF));
vw.textureIDHi .set(gpuTVIndex, (byte)((textureID >> 16) & 0xFF));
}// end animated texture
if(tr.getTrConfig().isUsingNewTexturing() && td instanceof AnimatedTexture){//Animated texture (new system)
if (animateUV && numFrames > 1) {// Animated UV
float[] uFrames = new float[numFrames];
float[] vFrames = new float[numFrames];
final WindowAnimator uvAnimator = new WindowAnimator(
getFlatTVWindow(), 2,// UV per vertex
numFrames, false, getVertexSequencer(
timeBetweenFramesMsec, numFrames),
new UVXferFunc(gpuTVIndex * UVXferFunc.BACK_STRIDE_LEN));
getModel().addTickableAnimator(uvAnimator);
for (int i = 0; i < numFrames; i++) {
uFrames[i] = (float) (uvUpScaler * triangleAt(i, triangleIndex).getUV(vIndex).getX());
vFrames[i] = (float) (uvUpScaler * triangleAt(i, triangleIndex).getUV(vIndex).getY());
}// end for(numFrames)
uvAnimator.addFrames(uFrames);
uvAnimator.addFrames(vFrames);
} else {// end if(animateUV)
vw.u.set(gpuTVIndex, (short) (uvUpScaler * t.getUV(vIndex).getX()));
vw.v.set(gpuTVIndex, (short) (uvUpScaler * t.getUV(vIndex).getY()));
}// end if(!animateUV)
AnimatedTexture at = ((AnimatedTexture) td);
final TexturePageAnimator texturePageAnimator = new TexturePageAnimator(at,vw,gpuTVIndex);
texturePageAnimator.setDebugName(debugName + ".texturePageAnimator");
getModel().addTickableAnimator(texturePageAnimator);
}
}// end setupVertex
private void setupTriangle(final int triangleIndex, final TextureDescription textureDescription,final int [] vertexIndices) throws ExecutionException,
InterruptedException {
setupVertex(0, vertexIndices[triangleIndex*3+0], triangleIndex,textureDescription);
setupVertex(1, vertexIndices[triangleIndex*3+1], triangleIndex,textureDescription);
setupVertex(2, vertexIndices[triangleIndex*3+2], triangleIndex,textureDescription);
}//setupTriangle
public void uploadToGPU(GL3 gl) {
final int nPrimitives = getNumElements();
final int [] triangleVertexIndices = new int[nPrimitives*3];
final TextureDescription [] textureDescriptions = new TextureDescription[nPrimitives];
final MemoryWindow mw = getMemoryWindow();
for (int vIndex = 0; vIndex < nPrimitives*3; vIndex++) {
triangleVertexIndices[vIndex]=mw.create();
}
for (int tIndex = 0; tIndex < nPrimitives; tIndex++) {
textureDescriptions[tIndex] = triangleAt(0, tIndex).texture
.get();
}
// Submit the GL task to set up the triangles.
if(tr.getTrConfig().isUsingNewTexturing()){
tr.getThreadManager().submitToGL(new Callable<Void>() {
@Override
public Void call() throws Exception {
for (int tIndex = 0; tIndex < nPrimitives; tIndex++) {
setupTriangle(tIndex,textureDescriptions[tIndex],triangleVertexIndices);}
return null;
}//end Call()
}).get();
}else{
Texture.executeInGLFollowingFinalization.add(new GLRunnable() {
@Override
public boolean run(GLAutoDrawable d){
for (int tIndex = 0; tIndex < nPrimitives; tIndex++) {
try{setupTriangle(tIndex,textureDescriptions[tIndex],triangleVertexIndices);}
catch(Exception e){throw new RuntimeException(e);}}
return true;
}//end run()
});
}//end legacy texturing enqueue later.
}// end allocateIndices(...)
@Override
public int getElementSizeInVec4s() {
return 3;
}
@Override
public int getGPUVerticesPerElement() {
return 3;
}
@Override
public org.jtrfp.trcl.PrimitiveList.RenderStyle getRenderStyle() {
return RenderStyle.OPAQUE;
}
public Vector3D getMaximumVertexDims() {
Vector3D result = Vector3D.ZERO;
Triangle[][] t = getPrimitives();
for (Triangle[] frame : t) {
for (Triangle tri : frame) {
for (int i = 0; i < 3; i++) {
double v;
final Vector3D pos = tri.getVertices()[i].getPosition();
v = pos.getX();
result = result.getX() < v ? new Vector3D(v, result.getY(),
result.getZ()) : result;
v = pos.getY();
result = result.getY() < v ? new Vector3D(result.getX(), v,
result.getZ()) : result;
v = pos.getZ();
result = result.getZ() < v ? new Vector3D(result.getX(),
result.getY(), v) : result;
}// end for(vertex)
}// end for(triangle)
}// end for(triangles)
return result;
}// end getMaximumVertexDims()
public Vector3D getMinimumVertexDims() {
Vector3D result = new Vector3D(Double.POSITIVE_INFINITY,
Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY);
Triangle[][] t = getPrimitives();
for (Triangle[] frame : t) {
for (Triangle tri : frame) {
for (int i = 0; i < 3; i++) {
double v;
final Vector3D pos = tri.getVertices()[i].getPosition();
v = pos.getX();
result = result.getX() > v ? new Vector3D(v, result.getY(),
result.getZ()) : result;
v = pos.getY();
result = result.getY() > v ? new Vector3D(result.getX(), v,
result.getZ()) : result;
v = pos.getZ();
result = result.getZ() > v ? new Vector3D(result.getX(),
result.getY(), v) : result;
}// end for(vertex)
}// end for(triangle)
}// end for(triangles)
return result;
}// end getMaximumVertexDims()
public double getMaximumVertexValue() {
double result = 0;
Triangle[][] t = getPrimitives();
for (Triangle[] frame : t) {
for (Triangle tri : frame) {
for (int i = 0; i < 3; i++) {
double v;
final Vector3D pos = tri.getVertices()[i].getPosition();
v = Math.abs(pos.getX());
result = result < v ? v : result;
v = Math.abs(pos.getY());
result = result < v ? v : result;
v = Math.abs(pos.getZ());
result = result < v ? v : result;
}// end for(vertex)
}// end for(triangle)
}// end for(triangles)
return result;
}// end getMaximumVertexValue()
/**
* @return the flatTVWindow
*/
private TriangleVertex2FlatDoubleWindow getFlatTVWindow() {
if (flatTVWindow == null)
flatTVWindow = new TriangleVertex2FlatDoubleWindow(
(TriangleVertexWindow) this.getMemoryWindow());
return flatTVWindow;
}
@Override
public byte getPrimitiveRenderMode() {
return PrimitiveRenderMode.RENDER_MODE_TRIANGLES;
}
@Override
public int getNumMemoryWindowIndicesPerElement() {
return 3;
}
}// end SingleTextureTriangleList |
package org.jtrfp.trcl.file;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import org.apache.commons.beanutils.BeanUtils;
import org.jtrfp.jfdt.ClassInclusion;
import org.jtrfp.jfdt.FailureBehavior;
import org.jtrfp.jfdt.Parser;
import org.jtrfp.jfdt.SelfParsingFile;
import org.jtrfp.jfdt.UnrecognizedFormatException;
import org.jtrfp.jtrfp.DataKey;
import org.jtrfp.jtrfp.lvl.ILvlData;
public class LVLFile extends SelfParsingFile implements ILvlData{
private static DataKey [] usedKeys; //jTRFP stuff.
LevelType levelType;
String briefingTextFile;
String heightMapOrTunnelFile;
String texturePlacementFile;
String globalPaletteFile;
String levelTextureListFile;
String qkeFile; // unknown
String powerupPlacementFile;
String textureAnimationFile;
String tunnelDefinitionFile;
String cloudTextureFile;
String backgroundGradientPaletteFile;
String enemyDefinitionAndPlacementFile;
String navigationFile;
String backgroundMusicFile;
String precalculatedFogFile;
String luminanceMapFile;
AbstractTriplet sunlightDirectionVector;
int ambientLight;
// Chamber light found by WDLMaster
AbstractTriplet chamberLightDirectionVector;
int chamberAmbientLight, unknownInt1;
// New Story stuff
String introVideoFile;
String levelEndVideoFile;
String transitionVideoFile;
String missionStartTextFile;
String missionEndTextFile;
enum LevelType {
UNKNOWN0, Tunnel, UNKNOWN2, UNKNOWN3, Overworld
}
@Override
public void describeFormat(Parser prs) throws UnrecognizedFormatException {
// REMEMBER: use \r\n because TR files use carriage-return-line-feed and
// not just the line-feed \n that java uses.
prs.stringEndingWith("\r\n",
prs.property("levelType", LevelType.class), false);
prs.stringEndingWith("\r\n",
prs.property("briefingTextFile", String.class), false);
prs.stringEndingWith("\r\n",
prs.property("heightMapOrTunnelFile", String.class), false);
prs.stringEndingWith("\r\n",
prs.property("texturePlacementFile", String.class), false);
prs.stringEndingWith("\r\n",
prs.property("globalPaletteFile", String.class), false);
prs.stringEndingWith("\r\n",
prs.property("levelTextureListFile", String.class), false);
prs.stringEndingWith("\r\n", prs.property("qkeFile", String.class),
false);
prs.stringEndingWith("\r\n",
prs.property("powerupPlacementFile", String.class), false);
prs.stringEndingWith("\r\n",
prs.property("textureAnimationFile", String.class), false);
prs.stringEndingWith("\r\n",
prs.property("tunnelDefinitionFile", String.class), false);
prs.stringEndingWith("\r\n",
prs.property("cloudTextureFile", String.class), false);
prs.stringEndingWith("\r\n",
prs.property("backgroundGradientPaletteFile", String.class),
false);
prs.stringEndingWith("\r\n",
prs.property("enemyDefinitionAndPlacementFile", String.class),
false);
prs.stringEndingWith("\r\n",
prs.property("navigationFile", String.class), false);
prs.stringEndingWith("\r\n",
prs.property("backgroundMusicFile", String.class), false);
prs.stringEndingWith("\r\n",
prs.property("precalculatedFogFile", String.class), false);
prs.stringEndingWith("\r\n",
prs.property("luminanceMapFile", String.class), false);
prs.subParseProposedClasses(
prs.property("sunlightDirectionVector", AbstractTriplet.class),
ClassInclusion.classOf(AbstractTriplet.class));
prs.stringEndingWith("\r\n",
prs.property("ambientLight", Integer.class), false);
prs.subParseProposedClasses(prs.property("chamberLightDirectionVector",
AbstractTriplet.class), ClassInclusion
.classOf(AbstractTriplet.class));
prs.stringEndingWith("\r\n",
prs.property("chamberAmbientLight", Integer.class), false);
prs.stringEndingWith("\r\n",
prs.property("unknownInt1", Integer.class), false);
prs.ignoreEOF(true);
prs.expectString(";New story stuff\r\n", FailureBehavior.IGNORE);
prs.stringEndingWith("\r\n",
prs.property("introVideoFile", String.class), false);
prs.stringEndingWith("\r\n",
prs.property("levelEndVideoFile", String.class), false);
prs.stringEndingWith("\r\n",
prs.property("transitionVideoFile", String.class), false);
prs.stringEndingWith("\r\n",
prs.property("missionStartTextFile", String.class), false);
prs.stringEndingWith("\r\n",
prs.property("missionEndTextFile", String.class), false);
// EOF
}
public LVLFile(InputStream is) throws IllegalAccessException, IOException {
super(is);
}
/**
* @return the levelEndVideoFile
*/
public String getLevelEndVideoFile() {
return levelEndVideoFile;
}
/**
* @param levelEndVideoFile
* the levelEndVideoFile to set
*/
public void setLevelEndVideoFile(String levelEndVideoFile) {
this.levelEndVideoFile = levelEndVideoFile;
}
/**
* @return the levelType
*/
public LevelType getLevelType() {
return levelType;
}
/**
* @param levelType
* the levelType to set
*/
public void setLevelType(LevelType levelType) {
this.levelType = levelType;
}
/**
* @return the briefingTextFile
*/
public String getBriefingTextFile() {
return briefingTextFile;
}
/**
* @param briefingTextFile
* the briefingTextFile to set
*/
public void setBriefingTextFile(String briefingTextFile) {
this.briefingTextFile = briefingTextFile;
}
/**
* @return the heightMapOrTunnelFile
*/
public String getHeightMapOrTunnelFile() {
return heightMapOrTunnelFile;
}
/**
* @param heightMapOrTunnelFile
* the heightMapOrTunnelFile to set
*/
public void setHeightMapOrTunnelFile(String heightMapOrTunnelFile) {
this.heightMapOrTunnelFile = heightMapOrTunnelFile;
}
/**
* CLR file stored in \DATA containing terrain texture indices to use.
*
* @return path to CLR file
*/
public String getTexturePlacementFile() {
return texturePlacementFile;
}
/**
* @param texturePlacementFile
* the texturePlacementFile to set
*/
public void setTexturePlacementFile(String texturePlacementFile) {
this.texturePlacementFile = texturePlacementFile;
}
/**
* @return the globalPaletteFile
*/
public String getGlobalPaletteFile() {
return globalPaletteFile;
}
/**
* @param globalPaletteFile
* the globalPaletteFile to set
*/
public void setGlobalPaletteFile(String globalPaletteFile) {
this.globalPaletteFile = globalPaletteFile;
}
/**
* @return the levelTextureListFile
*/
public String getLevelTextureListFile() {
return levelTextureListFile;
}
/**
* @param levelTextureListFile
* the levelTextureListFile to set
*/
public void setLevelTextureListFile(String levelTextureListFile) {
this.levelTextureListFile = levelTextureListFile;
}
/**
* @return the qkeFile
*/
public String getQkeFile() {
return qkeFile;
}
/**
* @param qkeFile
* the qkeFile to set
*/
public void setQkeFile(String qkeFile) {
this.qkeFile = qkeFile;
}
/**
* @return the powerupPlacementFile
*/
public String getPowerupPlacementFile() {
return powerupPlacementFile;
}
/**
* @param powerupPlacementFile
* the powerupPlacementFile to set
*/
public void setPowerupPlacementFile(String powerupPlacementFile) {
this.powerupPlacementFile = powerupPlacementFile;
}
/**
* @return the textureAnimationFile
*/
public String getTextureAnimationFile() {
return textureAnimationFile;
}
/**
* @param textureAnimationFile
* the textureAnimationFile to set
*/
public void setTextureAnimationFile(String textureAnimationFile) {
this.textureAnimationFile = textureAnimationFile;
}
/**
* @return the tunnelDefinitionFile
*/
public String getTunnelDefinitionFile() {
return tunnelDefinitionFile;
}
/**
* @param tunnelDefinitionFile
* the tunnelDefinitionFile to set
*/
public void setTunnelDefinitionFile(String tunnelDefinitionFile) {
this.tunnelDefinitionFile = tunnelDefinitionFile;
}
/**
* @return the cloudTextureFile
*/
public String getCloudTextureFile() {
return cloudTextureFile;
}
/**
* @param cloudTextureFile
* the cloudTextureFile to set
*/
public void setCloudTextureFile(String cloudTextureFile) {
this.cloudTextureFile = cloudTextureFile;
}
/**
* @return the backgroundGradientPaletteFile
*/
public String getBackgroundGradientPaletteFile() {
return backgroundGradientPaletteFile;
}
/**
* @param backgroundGradientPaletteFile
* the backgroundGradientPaletteFile to set
*/
public void setBackgroundGradientPaletteFile(
String backgroundGradientPaletteFile) {
this.backgroundGradientPaletteFile = backgroundGradientPaletteFile;
}
/**
* @return the enemyDefinitionAndPlacementFile
*/
public String getEnemyDefinitionAndPlacementFile() {
return enemyDefinitionAndPlacementFile;
}
/**
* @param enemyDefinitionAndPlacementFile
* the enemyDefinitionAndPlacementFile to set
*/
public void setEnemyDefinitionAndPlacementFile(
String enemyDefinitionAndPlacementFile) {
this.enemyDefinitionAndPlacementFile = enemyDefinitionAndPlacementFile;
}
/**
* @return the navigationFile
*/
public String getNavigationFile() {
return navigationFile;
}
/**
* @param navigationFile
* the navigationFile to set
*/
public void setNavigationFile(String navigationFile) {
this.navigationFile = navigationFile;
}
/**
* @return the backgroundMusicFile
*/
public String getBackgroundMusicFile() {
return backgroundMusicFile;
}
/**
* @param backgroundMusicFile
* the backgroundMusicFile to set
*/
public void setBackgroundMusicFile(String backgroundMusicFile) {
this.backgroundMusicFile = backgroundMusicFile;
}
/**
* @return the precalculatedFogFile
*/
public String getPrecalculatedFogFile() {
return precalculatedFogFile;
}
/**
* @param precalculatedFogFile
* the precalculatedFogFile to set
*/
public void setPrecalculatedFogFile(String precalculatedFogFile) {
this.precalculatedFogFile = precalculatedFogFile;
}
/**
* @return the luminanceMapFile
*/
public String getLuminanceMapFile() {
return luminanceMapFile;
}
/**
* @param luminanceMapFile
* the luminanceMapFile to set
*/
public void setLuminanceMapFile(String luminanceMapFile) {
this.luminanceMapFile = luminanceMapFile;
}
/**
* @return the sunlightDirectionVector
*/
public AbstractTriplet getSunlightDirectionVector() {
return sunlightDirectionVector;
}
/**
* @param sunlightDirectionVector
* the sunlightDirectionVector to set
*/
public void setSunlightDirectionVector(
AbstractTriplet sunlightDirectionVector) {
this.sunlightDirectionVector = sunlightDirectionVector;
}
/**
* @return the ambientLight
*/
public int getAmbientLight() {
return ambientLight;
}
/**
* @param ambientLight
* the ambientLight to set
*/
public void setAmbientLight(int ambientLight) {
this.ambientLight = ambientLight;
}
/**
* Found by WDLMaster
*
* @return the chamberLightDirectionVector
*/
public AbstractTriplet getChamberLightDirectionVector() {
return chamberLightDirectionVector;
}
/**
* Found by WDLMaster
*
* @return the chamberAmbientLight
*/
public int getChamberAmbientLight() {
return chamberAmbientLight;
}
/**
* Found by WDLMaster
*
* @param chamberAmbientLight
* the chamberAmbientLight to set
*/
public void setChamberAmbientLight(int chamberAmbientLight) {
this.chamberAmbientLight = chamberAmbientLight;
}
/**
* @return the unknownInt1
*/
public int getUnknownInt1() {
return unknownInt1;
}
/**
* @param unknownInt1
* the unknownInt1 to set
*/
public void setUnknownInt1(int unknownInt1) {
this.unknownInt1 = unknownInt1;
}
/**
* Found by WDLMaster
*
* @param chamberLightDirectionVector
* the chamberLightDirectionVector to set
*/
public void setChamberLightDirectionVector(
AbstractTriplet chamberLightDirectionVector) {
this.chamberLightDirectionVector = chamberLightDirectionVector;
}
/**
* @return the introVideoFile
*/
public String getIntroVideoFile() {
return introVideoFile;
}
/**
* @param introVideoFile
* the introVideoFile to set
*/
public void setIntroVideoFile(String introVideoFile) {
this.introVideoFile = introVideoFile;
}
/**
* @return the transitionVideoFile
*/
public String getTransitionVideoFile() {
return transitionVideoFile;
}
/**
* @param transitionVideoFile
* the transitionVideoFile to set
*/
public void setTransitionVideoFile(String transitionVideoFile) {
this.transitionVideoFile = transitionVideoFile;
}
/**
* @return the missionStartTextFile
*/
public String getMissionStartTextFile() {
return missionStartTextFile;
}
/**
* @param missionStartTextFile
* the missionStartTextFile to set
*/
public void setMissionStartTextFile(String missionStartTextFile) {
this.missionStartTextFile = missionStartTextFile;
}
/**
* @return the missionEndTextFile
*/
public String getMissionEndTextFile() {
return missionEndTextFile;
}
/**
* @param missionEndTextFile
* the missionEndTextFile to set
*/
public void setMissionEndTextFile(String missionEndTextFile) {
this.missionEndTextFile = missionEndTextFile;
}
//////// E X P E R I M E N T A L ///////////////////////////////////
@Override
public String getValue(DataKey key) {
try{return BeanUtils.getProperty(this, key.getIdentifier());}
catch(NoSuchMethodException e){return null;}
catch(InvocationTargetException e){return null;}
catch(IllegalAccessException e){return null;}
}//end getValue(...)
private static DataKey [] getUsedKeysSingleton(){
if(usedKeys==null)
usedKeys = generateUsedKeys();
return usedKeys;
}//end getUsedKeysSingleton()
private static DataKey [] generateUsedKeys(){
ArrayList<DataKey> result = new ArrayList<DataKey>();
try{for(PropertyDescriptor pd:Introspector.getBeanInfo(LVLFile.class).getPropertyDescriptors())
result.add(new DataKey(pd.getName(), pd.getDisplayName()));
}catch(Exception e){e.printStackTrace();}
return result.toArray(new DataKey[result.size()]);
}//end generateUsedKeys()
@Override
public DataKey[] getUsedKeys() {
return getUsedKeysSingleton();
}//end getUsedKeys()
}// end LVLFile |
package org.kitteh.irc;
import java.io.BufferedWriter;
import java.io.IOException;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
final class IRCBotOutput extends Thread {
private final Object wait = new Object();
private final BufferedWriter bufferedWriter;
private final int delay = 1200; // TODO customizable
private String quitReason;
private boolean handleLowPriority = false;
private final Queue<String> highPriorityQueue = new ConcurrentLinkedQueue<>();
private final Queue<String> lowPriorityQueue = new ConcurrentLinkedQueue<>();
IRCBotOutput(BufferedWriter bufferedWriter, String botName) {
this.setName("Kitteh IRCBot Output (" + botName + ")");
this.bufferedWriter = bufferedWriter;
}
@Override
public void run() {
while (!this.isInterrupted()) {
if ((!this.handleLowPriority || this.lowPriorityQueue.isEmpty()) && this.highPriorityQueue.isEmpty()) {
synchronized (this.wait) {
try {
this.wait.wait();
} catch (InterruptedException e) {
break;
}
}
}
String message = this.highPriorityQueue.poll();
if (message == null && this.handleLowPriority) {
message = this.lowPriorityQueue.poll();
}
if (message == null) {
continue;
}
try {
this.bufferedWriter.write(message + "\r\n");
this.bufferedWriter.flush();
} catch (final IOException ignored) {
}
try {
Thread.sleep(this.delay);
} catch (final InterruptedException e) {
break;
}
}
try {
this.bufferedWriter.write("QUIT :" + this.quitReason + "\r\n");
this.bufferedWriter.flush();
this.bufferedWriter.close();
} catch (final IOException e) {
e.printStackTrace();
}
}
void queueMessage(String message, boolean highPriority) {
(highPriority ? this.highPriorityQueue : this.lowPriorityQueue).add(message);
if (highPriority || this.handleLowPriority) {
synchronized (this.wait) {
this.wait.notify();
}
}
}
void readyForLowPriority() {
this.handleLowPriority = true;
}
void shutdown(String message) {
this.quitReason = message;
this.interrupt();
}
} |
package org.kohsuke.github;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
/**
* Common part of {@link GHUser} and {@link GHOrganization}.
*
* @author Kohsuke Kawaguchi
*/
public abstract class GHPerson {
/*package almost final*/ GitHub root;
// common
protected String login,location,blog,email,name,created_at,company;
protected int id;
protected String gravatar_id; // appears in V3 as well but presumably subsumed by avatar_url?
protected String avatar_url,html_url;
protected int followers,following,public_repos,public_gists;
/*package*/ GHPerson wrapUp(GitHub root) {
this.root = root;
return this;
}
/**
* Gets the repositories this user owns.
*/
public synchronized Map<String,GHRepository> getRepositories() throws IOException {
Map<String,GHRepository> repositories = new TreeMap<String, GHRepository>();
for (List<GHRepository> batch : iterateRepositories(100)) {
for (GHRepository r : batch)
repositories.put(r.getName(),r);
}
return Collections.unmodifiableMap(repositories);
}
/**
* Loads repository list in a pagenated fashion.
*
* <p>
* For a person with a lot of repositories, GitHub returns the list of repositories in a pagenated fashion.
* Unlike {@link #getRepositories()}, this method allows the caller to start processing data as it arrives.
*
* Every {@link Iterator#next()} call results in I/O. Exceptions that occur during the processing is wrapped
* into {@link Error}.
*/
public synchronized Iterable<List<GHRepository>> iterateRepositories(final int pageSize) {
return new Iterable<List<GHRepository>>() {
public Iterator<List<GHRepository>> iterator() {
final Iterator<GHRepository[]> pager = root.retrievePaged("/users/" + login + "/repos?per_page="+pageSize,GHRepository[].class,false);
return new Iterator<List<GHRepository>>() {
public boolean hasNext() {
return pager.hasNext();
}
public List<GHRepository> next() {
GHRepository[] batch = pager.next();
for (GHRepository r : batch)
r.root = root;
return Arrays.asList(batch);
}
public void remove() {
throw new UnsupportedOperationException();
}
};
}
};
}
/**
*
* @return
* null if the repository was not found
*/
public GHRepository getRepository(String name) throws IOException {
try {
return root.retrieveWithAuth("/repos/" + login + '/' + name, GHRepository.class).wrap(root);
} catch (FileNotFoundException e) {
return null;
}
}
/**
* Gravatar ID of this user, like 0cb9832a01c22c083390f3c5dcb64105
*
* @deprecated
* No longer available in the v3 API.
*/
public String getGravatarId() {
return gravatar_id;
}
public String getAvatarUrl() {
if (avatar_url!=null)
return avatar_url;
if (gravatar_id!=null)
return "https://secure.gravatar.com/avatar/"+gravatar_id;
return null;
}
/**
* Gets the login ID of this user, like 'kohsuke'
*/
public String getLogin() {
return login;
}
/**
* Gets the human-readable name of the user, like "Kohsuke Kawaguchi"
*/
public String getName() {
return name;
}
/**
* Gets the company name of this user, like "Sun Microsystems, Inc."
*/
public String getCompany() {
return company;
}
/**
* Gets the location of this user, like "Santa Clara, California"
*/
public String getLocation() {
return location;
}
public String getCreatedAt() {
return created_at;
}
/**
* Gets the blog URL of this user.
*/
public String getBlog() {
return blog;
}
/**
* Gets the e-mail address of the user.
*/
public String getEmail() {
return email;
}
public int getPublicGistCount() {
return public_gists;
}
public int getPublicRepoCount() {
return public_repos;
}
public int getFollowingCount() {
return following;
}
/**
* What appears to be a GitHub internal unique number that identifies this user.
*/
public int getId() {
return id;
}
public int getFollowersCount() {
return followers;
}
} |
package org.realrest.domain;
import lombok.Getter;
import lombok.Setter;
import java.time.LocalDate;
/**
* @author volodymyr.tsukur
*/
@Getter
@Setter
public final class Booking extends Identifiable {
private User user;
private Room room;
private LocalDate from;
private LocalDate to;
private boolean includeBreakfast;
private State state;
/**
* @author volodymyr.tsukur
*/
public enum State {
PENDING,
CONFIRMED,
CANCELLED,
SERVED,
REJECTED
}
} |
package org.testng.internal;
import static org.testng.internal.invokers.InvokedMethodListenerMethod.AFTER_INVOCATION;
import static org.testng.internal.invokers.InvokedMethodListenerMethod.BEFORE_INVOCATION;
import org.testng.IClass;
import org.testng.IConfigurable;
import org.testng.IConfigurationListener;
import org.testng.IConfigurationListener2;
import org.testng.IHookable;
import org.testng.IInvokedMethod;
import org.testng.IInvokedMethodListener;
import org.testng.IRetryAnalyzer;
import org.testng.ITestClass;
import org.testng.ITestContext;
import org.testng.ITestListener;
import org.testng.ITestNGMethod;
import org.testng.ITestResult;
import org.testng.Reporter;
import org.testng.SkipException;
import org.testng.SuiteRunState;
import org.testng.TestException;
import org.testng.TestNGException;
import org.testng.annotations.IConfigurationAnnotation;
import org.testng.annotations.NoInjection;
import org.testng.collections.Lists;
import org.testng.collections.Maps;
import org.testng.internal.InvokeMethodRunnable.TestNGRuntimeException;
import org.testng.internal.ParameterHolder.ParameterOrigin;
import org.testng.internal.annotations.AnnotationHelper;
import org.testng.internal.annotations.IAnnotationFinder;
import org.testng.internal.annotations.Sets;
import org.testng.internal.invokers.InvokedMethodListenerInvoker;
import org.testng.internal.invokers.InvokedMethodListenerMethod;
import org.testng.internal.thread.ThreadExecutionException;
import org.testng.internal.thread.ThreadUtil;
import org.testng.internal.thread.graph.IWorker;
import org.testng.xml.XmlClass;
import org.testng.xml.XmlSuite;
import org.testng.xml.XmlTest;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
/**
* This class is responsible for invoking methods:
* - test methods
* - configuration methods
* - possibly in a separate thread
* and then for notifying the result listeners.
*
* @author <a href="mailto:cedric@beust.com">Cedric Beust</a>
* @author <a href='mailto:the_mindstorm@evolva.ro'>Alexandru Popescu</a>
*/
public class Invoker implements IInvoker {
private final ITestContext m_testContext;
private final ITestResultNotifier m_notifier;
private final IAnnotationFinder m_annotationFinder;
private final SuiteRunState m_suiteState;
private final boolean m_skipFailedInvocationCounts;
private final List<IInvokedMethodListener> m_invokedMethodListeners;
private final boolean m_continueOnFailedConfiguration;
/** Group failures must be synced as the Invoker is accessed concurrently */
private Map<String, Boolean> m_beforegroupsFailures = Maps.newHashtable();
/** Class failures must be synced as the Invoker is accessed concurrently */
private Map<Class<?>, Set<Object>> m_classInvocationResults = Maps.newHashtable();
/** Test methods whose configuration methods have failed. */
private Map<ITestNGMethod, Set<Object>> m_methodInvocationResults = Maps.newHashtable();
private IConfiguration m_configuration;
/** Predicate to filter methods */
private static Predicate<ITestNGMethod, IClass> CAN_RUN_FROM_CLASS = new CanRunFromClassPredicate();
/** Predicate to filter methods */
private static final Predicate<ITestNGMethod, IClass> SAME_CLASS = new SameClassNamePredicate();
private void setClassInvocationFailure(Class<?> clazz, Object instance) {
Set<Object> instances = m_classInvocationResults.get( clazz );
if (instances == null) {
instances = Sets.newHashSet();
m_classInvocationResults.put(clazz, instances);
}
instances.add(instance);
}
private void setMethodInvocationFailure(ITestNGMethod method, Object instance) {
Set<Object> instances = m_methodInvocationResults.get(method);
if (instances == null) {
instances = Sets.newHashSet();
m_methodInvocationResults.put(method, instances);
}
instances.add(getMethodInvocationToken(method, instance));
}
public Invoker(IConfiguration configuration,
ITestContext testContext,
ITestResultNotifier notifier,
SuiteRunState state,
boolean skipFailedInvocationCounts,
List<IInvokedMethodListener> invokedMethodListeners) {
m_configuration = configuration;
m_testContext= testContext;
m_suiteState= state;
m_notifier= notifier;
m_annotationFinder= configuration.getAnnotationFinder();
m_skipFailedInvocationCounts = skipFailedInvocationCounts;
m_invokedMethodListeners = invokedMethodListeners;
m_continueOnFailedConfiguration = XmlSuite.CONTINUE.equals(testContext.getSuite().getXmlSuite().getConfigFailurePolicy());
}
/**
* Invoke configuration methods if they belong to the same TestClass passed
* in parameter.. <p/>TODO: Calculate ahead of time which methods should be
* invoked for each class. Might speed things up for users who invoke the
* same test class with different parameters in the same suite run.
*
* If instance is non-null, the configuration will be run on it. If it is null,
* the configuration methods will be run on all the instances retrieved
* from the ITestClass.
*/
@Override
public void invokeConfigurations(IClass testClass,
ITestNGMethod[] allMethods,
XmlSuite suite,
Map<String, String> params,
Object[] parameterValues,
Object instance)
{
invokeConfigurations(testClass, null, allMethods, suite, params, parameterValues, instance,
null);
}
private void invokeConfigurations(IClass testClass,
ITestNGMethod currentTestMethod,
ITestNGMethod[] allMethods,
XmlSuite suite,
Map<String, String> params,
Object[] parameterValues,
Object instance,
ITestResult testMethodResult)
{
if(null == allMethods) {
log(5, "No configuration methods found");
return;
}
ITestNGMethod[] methods= filterMethods(testClass, allMethods, SAME_CLASS);
for(ITestNGMethod tm : methods) {
if(null == testClass) {
testClass= tm.getTestClass();
}
ITestResult testResult= new TestResult(testClass,
instance,
tm,
null,
System.currentTimeMillis(),
System.currentTimeMillis(),
m_testContext);
IConfigurationAnnotation configurationAnnotation= null;
try {
Object inst = tm.getInstance();
if (inst == null) {
inst = instance;
}
Class<?> objectClass= inst.getClass();
Method method= tm.getMethod();
// Only run the configuration if
// - the test is enabled and
// - the Configuration method belongs to the same class or a parent
if(MethodHelper.isEnabled(objectClass, m_annotationFinder)) {
configurationAnnotation = AnnotationHelper.findConfiguration(m_annotationFinder, method);
if (MethodHelper.isEnabled(configurationAnnotation)) {
boolean isClassConfiguration = isClassConfiguration(configurationAnnotation);
boolean isSuiteConfiguration = isSuiteConfiguration(configurationAnnotation);
boolean alwaysRun= isAlwaysRun(configurationAnnotation);
if (!confInvocationPassed(tm, currentTestMethod, testClass, instance) && !alwaysRun) {
handleConfigurationSkip(tm, testResult, configurationAnnotation, currentTestMethod, instance, suite);
continue;
}
log(3, "Invoking " + Utils.detailedMethodName(tm, true));
Object[] parameters = Parameters.createConfigurationParameters(tm.getMethod(),
params,
parameterValues,
currentTestMethod,
m_annotationFinder,
suite,
m_testContext,
testMethodResult);
testResult.setParameters(parameters);
Object newInstance = null != instance ? instance: inst;
runConfigurationListeners(testResult, true /* before */);
invokeConfigurationMethod(newInstance, tm,
parameters, isClassConfiguration, isSuiteConfiguration, testResult);
// TODO: probably we should trigger the event for each instance???
testResult.setEndMillis(System.currentTimeMillis());
runConfigurationListeners(testResult, false /* after */);
}
else {
log(3,
"Skipping "
+ Utils.detailedMethodName(tm, true)
+ " because it is not enabled");
}
} // if is enabled
else {
log(3,
"Skipping "
+ Utils.detailedMethodName(tm, true)
+ " because "
+ objectClass.getName()
+ " is not enabled");
}
}
catch(InvocationTargetException ex) {
handleConfigurationFailure(ex, tm, testResult, configurationAnnotation, currentTestMethod, instance, suite);
}
catch(TestNGException ex) {
// Don't wrap TestNGExceptions, it could be a missing parameter on a
// @Configuration method
handleConfigurationFailure(ex, tm, testResult, configurationAnnotation, currentTestMethod, instance, suite);
}
catch(Throwable ex) { // covers the non-wrapper exceptions
handleConfigurationFailure(ex, tm, testResult, configurationAnnotation, currentTestMethod, instance, suite);
}
} // for methods
}
/**
* Marks the current <code>TestResult</code> as skipped and invokes the listeners.
*/
private void handleConfigurationSkip(ITestNGMethod tm,
ITestResult testResult,
IConfigurationAnnotation annotation,
ITestNGMethod currentTestMethod,
Object instance,
XmlSuite suite) {
recordConfigurationInvocationFailed(tm, testResult.getTestClass(), annotation, currentTestMethod, instance, suite);
testResult.setStatus(ITestResult.SKIP);
runConfigurationListeners(testResult, false /* after */);
}
/**
* Is the current <code>IConfiguration</code> a class-level method.
*/
private boolean isClassConfiguration(IConfigurationAnnotation configurationAnnotation) {
if (null == configurationAnnotation) {
return false;
}
boolean before = configurationAnnotation.getBeforeTestClass();
boolean after = configurationAnnotation.getAfterTestClass();
return before || after;
}
/**
* Is the current <code>IConfiguration</code> a suite level method.
*/
private boolean isSuiteConfiguration(IConfigurationAnnotation configurationAnnotation) {
if (null == configurationAnnotation) {
return false;
}
boolean before = configurationAnnotation.getBeforeSuite();
boolean after = configurationAnnotation.getAfterSuite();
return before || after;
}
/**
* Is the <code>IConfiguration</code> marked as alwaysRun.
*/
private boolean isAlwaysRun(IConfigurationAnnotation configurationAnnotation) {
if(null == configurationAnnotation) {
return false;
}
boolean alwaysRun= false;
if ((configurationAnnotation.getAfterSuite()
|| configurationAnnotation.getAfterTest()
|| configurationAnnotation.getAfterTestClass()
|| configurationAnnotation.getAfterTestMethod())
&& configurationAnnotation.getAlwaysRun())
{
alwaysRun= true;
}
return alwaysRun;
}
private void handleConfigurationFailure(Throwable ite,
ITestNGMethod tm,
ITestResult testResult,
IConfigurationAnnotation annotation,
ITestNGMethod currentTestMethod,
Object instance,
XmlSuite suite)
{
Throwable cause= ite.getCause() != null ? ite.getCause() : ite;
if(isSkipExceptionAndSkip(cause)) {
testResult.setThrowable(cause);
handleConfigurationSkip(tm, testResult, annotation, currentTestMethod, instance, suite);
return;
}
Utils.log("", 3, "Failed to invoke configuration method "
+ tm.getRealClass().getName() + "." + tm.getMethodName() + ":" + cause.getMessage());
handleException(cause, tm, testResult, 1);
runConfigurationListeners(testResult, false /* after */);
// If in TestNG mode, need to take a look at the annotation to figure out
// what kind of @Configuration method we're dealing with
if (null != annotation) {
recordConfigurationInvocationFailed(tm, testResult.getTestClass(), annotation, currentTestMethod, instance, suite);
}
}
/**
* @return All the classes that belong to the same <test> tag as @param cls
*/
private XmlClass[] findClassesInSameTest(Class<?> cls, XmlSuite suite) {
Map<String, XmlClass> vResult= Maps.newHashMap();
String className= cls.getName();
for(XmlTest test : suite.getTests()) {
for(XmlClass testClass : test.getXmlClasses()) {
if(testClass.getName().equals(className)) {
// Found it, add all the classes in this test in the result
for(XmlClass thisClass : test.getXmlClasses()) {
vResult.put(thisClass.getName(), thisClass);
}
// Note: we need to iterate through the entire suite since the same
// class might appear in several <test> tags
}
}
}
XmlClass[] result= vResult.values().toArray(new XmlClass[vResult.size()]);
return result;
}
/**
* Record internally the failure of a Configuration, so that we can determine
* later if @Test should be skipped.
*/
private void recordConfigurationInvocationFailed(ITestNGMethod tm,
IClass testClass,
IConfigurationAnnotation annotation,
ITestNGMethod currentTestMethod,
Object instance,
XmlSuite suite) {
// If beforeTestClass or afterTestClass failed, mark either the config method's
// entire class as failed, or the class under tests as failed, depending on
// the configuration failure policy
if (annotation.getBeforeTestClass() || annotation.getAfterTestClass()) {
// tm is the configuration method, and currentTestMethod is null for BeforeClass
// methods, so we need testClass
if (m_continueOnFailedConfiguration) {
setClassInvocationFailure(testClass.getRealClass(), instance);
} else {
setClassInvocationFailure(tm.getRealClass(), instance);
}
}
// If before/afterTestMethod failed, mark either the config method's entire
// class as failed, or just the current test method as failed, depending on
// the configuration failure policy
else if (annotation.getBeforeTestMethod() || annotation.getAfterTestMethod()) {
if (m_continueOnFailedConfiguration) {
setMethodInvocationFailure(currentTestMethod, instance);
} else {
setClassInvocationFailure(tm.getRealClass(), instance);
}
}
// If beforeSuite or afterSuite failed, mark *all* the classes as failed
// for configurations. At this point, the entire Suite is screwed
else if (annotation.getBeforeSuite() || annotation.getAfterSuite()) {
m_suiteState.failed();
}
// beforeTest or afterTest: mark all the classes in the same
// <test> stanza as failed for configuration
else if (annotation.getBeforeTest() || annotation.getAfterTest()) {
setClassInvocationFailure(tm.getRealClass(), instance);
XmlClass[] classes= findClassesInSameTest(tm.getRealClass(), suite);
for(XmlClass xmlClass : classes) {
setClassInvocationFailure(xmlClass.getSupportClass(), instance);
}
}
String[] beforeGroups= annotation.getBeforeGroups();
if(null != beforeGroups && beforeGroups.length > 0) {
for(String group: beforeGroups) {
m_beforegroupsFailures.put(group, Boolean.FALSE);
}
}
}
/**
* @return true if this class or a parent class failed to initialize.
*/
private boolean classConfigurationFailed(Class<?> cls) {
for (Class<?> c : m_classInvocationResults.keySet()) {
if (c == cls || cls.isAssignableFrom(c)) {
return true;
}
}
return false;
}
/**
* @return true if this class has successfully run all its @Configuration
* method or false if at least one of these methods failed.
*/
private boolean confInvocationPassed(ITestNGMethod method, ITestNGMethod currentTestMethod,
IClass testClass, Object instance) {
boolean result= true;
// If continuing on config failure, check invocation results for the class
// under test, otherwise use the method's declaring class
Class<?> cls = m_continueOnFailedConfiguration ?
testClass.getRealClass() : method.getMethod().getDeclaringClass();
if(m_suiteState.isFailed()) {
result= false;
}
else {
if (classConfigurationFailed(cls)) {
if (! m_continueOnFailedConfiguration) {
result = !classConfigurationFailed(cls);
} else {
result = !m_classInvocationResults.get(cls).contains(instance);
}
}
// if method is BeforeClass, currentTestMethod will be null
else if (m_continueOnFailedConfiguration &&
currentTestMethod != null &&
m_methodInvocationResults.containsKey(currentTestMethod)) {
result = !m_methodInvocationResults.get(currentTestMethod).contains(getMethodInvocationToken(currentTestMethod, instance));
}
else if (! m_continueOnFailedConfiguration) {
for(Class<?> clazz: m_classInvocationResults.keySet()) {
// if (clazz == cls) {
if(clazz.isAssignableFrom(cls)) {
result= false;
break;
}
}
}
}
// check if there are failed @BeforeGroups
String[] groups= method.getGroups();
if(null != groups && groups.length > 0) {
for(String group: groups) {
if(m_beforegroupsFailures.containsKey(group)) {
result= false;
break;
}
}
}
return result;
}
// Creates a token for tracking a unique invocation of a method on an instance.
// Is used when configFailurePolicy=continue.
private Object getMethodInvocationToken(ITestNGMethod method, Object instance) {
return String.format("%s+%d", instance.toString(), method.getCurrentInvocationCount());
}
private void invokeConfigurationMethod(Object targetInstance,
ITestNGMethod tm,
Object[] params,
boolean isClass,
boolean isSuite,
ITestResult testResult)
throws InvocationTargetException, IllegalAccessException
{
// Mark this method with the current thread id
tm.setId(ThreadUtil.currentThreadInfo());
{
InvokedMethod invokedMethod= new InvokedMethod(targetInstance,
tm,
params,
false, /* isTest */
isClass,
System.currentTimeMillis(),
testResult);
runInvokedMethodListeners(BEFORE_INVOCATION, invokedMethod, testResult);
m_notifier.addInvokedMethod(invokedMethod);
try {
Reporter.setCurrentTestResult(testResult);
Method method = tm.getMethod();
// If this method is a IConfigurable, invoke its run() method
IConfigurable configurableInstance =
IConfigurable.class.isAssignableFrom(tm.getMethod().getDeclaringClass()) ?
(IConfigurable) targetInstance : m_configuration.getConfigurable();
if (configurableInstance != null) {
MethodInvocationHelper.invokeConfigurable(targetInstance, params, configurableInstance, method,
testResult);
}
else {
// Not a IConfigurable, invoke directly
if (MethodHelper.calculateTimeOut(tm) <= 0) {
MethodInvocationHelper.invokeMethod(method, targetInstance, params);
}
else {
MethodInvocationHelper.invokeWithTimeout(tm, targetInstance, params, testResult);
if (!testResult.isSuccess()) {
// A time out happened
throwConfigurationFailure(testResult, testResult.getThrowable());
throw testResult.getThrowable();
}
}
}
}
catch (InvocationTargetException ex) {
throwConfigurationFailure(testResult, ex);
throw ex;
}
catch (IllegalAccessException ex) {
throwConfigurationFailure(testResult, ex);
throw ex;
}
catch (NoSuchMethodException ex) {
throwConfigurationFailure(testResult, ex);
throw new TestNGException(ex);
}
catch (Throwable ex) {
throwConfigurationFailure(testResult, ex);
throw new TestNGException(ex);
}
finally {
Reporter.setCurrentTestResult(testResult);
runInvokedMethodListeners(AFTER_INVOCATION, invokedMethod, testResult);
Reporter.setCurrentTestResult(null);
}
}
}
private void throwConfigurationFailure(ITestResult testResult, Throwable ex)
{
testResult.setStatus(ITestResult.FAILURE);;
testResult.setThrowable(ex.getCause() == null ? ex : ex.getCause());
}
private void runInvokedMethodListeners(InvokedMethodListenerMethod listenerMethod, IInvokedMethod invokedMethod,
ITestResult testResult)
{
if ( noListenersPresent() ) {
return;
}
InvokedMethodListenerInvoker invoker = new InvokedMethodListenerInvoker(listenerMethod, testResult, m_testContext);
for (IInvokedMethodListener currentListener : m_invokedMethodListeners) {
invoker.invokeListener(currentListener, invokedMethod);
}
}
private boolean noListenersPresent() {
return (m_invokedMethodListeners == null) || (m_invokedMethodListeners.size() == 0);
}
// pass both paramValues and paramIndex to be thread safe in case parallel=true + dataprovider.
private ITestResult invokeMethod(Object instance,
final ITestNGMethod tm,
Object[] parameterValues,
int parametersIndex,
XmlSuite suite,
Map<String, String> params,
ITestClass testClass,
ITestNGMethod[] beforeMethods,
ITestNGMethod[] afterMethods,
ConfigurationGroupMethods groupMethods,
FailureContext failureContext) {
TestResult testResult = new TestResult();
// Invoke beforeGroups configurations
invokeBeforeGroupsConfigurations(testClass, tm, groupMethods, suite, params,
instance);
// Invoke beforeMethods only if
// - firstTimeOnly is not set
// - firstTimeOnly is set, and we are reaching at the first invocationCount
invokeConfigurations(testClass, tm,
filterConfigurationMethods(tm, beforeMethods, true /* beforeMethods */),
suite, params, parameterValues,
instance, testResult);
// Create the ExtraOutput for this method
InvokedMethod invokedMethod = null;
try {
testResult.init(testClass, instance,
tm,
null,
System.currentTimeMillis(),
0,
m_testContext);
testResult.setParameters(parameterValues);
testResult.setHost(m_testContext.getHost());
testResult.setStatus(ITestResult.STARTED);
invokedMethod= new InvokedMethod(instance,
tm,
parameterValues,
true /* isTest */,
false /* isConfiguration */,
System.currentTimeMillis(),
testResult);
// Fix from ansgarkonermann
// invokedMethod is used in the finally, which can be invoked if
// any of the test listeners throws an exception, therefore,
// invokedMethod must have a value before we get here
runTestListeners(testResult);
runInvokedMethodListeners(BEFORE_INVOCATION, invokedMethod, testResult);
m_notifier.addInvokedMethod(invokedMethod);
Method thisMethod = tm.getConstructorOrMethod().getMethod();
if(confInvocationPassed(tm, tm, testClass, instance)) {
log(3, "Invoking " + tm.getRealClass().getName() + "." + tm.getMethodName());
// If no timeOut, just invoke the method
if (MethodHelper.calculateTimeOut(tm) <= 0) {
Reporter.setCurrentTestResult(testResult);
// If this method is a IHookable, invoke its run() method
IHookable hookableInstance =
IHookable.class.isAssignableFrom(tm.getRealClass()) ?
(IHookable) instance : m_configuration.getHookable();
if (hookableInstance != null) {
MethodInvocationHelper.invokeHookable(instance,
parameterValues, hookableInstance, thisMethod, testResult);
}
// Not a IHookable, invoke directly
else {
MethodInvocationHelper.invokeMethod(thisMethod, instance,
parameterValues);
}
testResult.setStatus(ITestResult.SUCCESS);
}
else {
// Method with a timeout
Reporter.setCurrentTestResult(testResult);
MethodInvocationHelper.invokeWithTimeout(tm, instance, parameterValues, testResult);
}
}
else {
testResult.setStatus(ITestResult.SKIP);
}
}
catch(InvocationTargetException ite) {
testResult.setThrowable(ite.getCause());
testResult.setStatus(ITestResult.FAILURE);
}
catch(ThreadExecutionException tee) { // wrapper for TestNGRuntimeException
Throwable cause= tee.getCause();
if(TestNGRuntimeException.class.equals(cause.getClass())) {
testResult.setThrowable(cause.getCause());
}
else {
testResult.setThrowable(cause);
}
testResult.setStatus(ITestResult.FAILURE);
}
catch(Throwable thr) { // covers the non-wrapper exceptions
testResult.setThrowable(thr);
testResult.setStatus(ITestResult.FAILURE);
}
finally {
// Set end time ASAP
testResult.setEndMillis(System.currentTimeMillis());
ExpectedExceptionsHolder expectedExceptionClasses
= MethodHelper.findExpectedExceptions(m_annotationFinder, tm.getMethod());
List<ITestResult> results = Lists.<ITestResult>newArrayList(testResult);
handleInvocationResults(tm, results, expectedExceptionClasses, false,
false /* collect results */, failureContext);
// If this method has a data provider and just failed, memorize the number
// at which it failed.
// Note: we're not exactly testing that this method has a data provider, just
// that it has parameters, so might have to revisit this if bugs get reported
// for the case where this method has parameters that don't come from a data
// provider
if (testResult.getThrowable() != null && parameterValues.length > 0) {
tm.addFailedInvocationNumber(parametersIndex);
}
// Increment the invocation count for this method
tm.incrementCurrentInvocationCount();
// Run invokedMethodListeners after updating TestResult
runInvokedMethodListeners(AFTER_INVOCATION, invokedMethod, testResult);
runTestListeners(testResult);
// Do not notify if will retry.
if (!results.isEmpty()) {
collectResults(tm, Collections.<ITestResult>singleton(testResult));
}
// Invoke afterMethods only if
// - lastTimeOnly is not set
// - lastTimeOnly is set, and we are reaching the last invocationCount
invokeConfigurations(testClass, tm,
filterConfigurationMethods(tm, afterMethods, false /* beforeMethods */),
suite, params, parameterValues,
instance,
testResult);
// Invoke afterGroups configurations
invokeAfterGroupsConfigurations(testClass, tm, groupMethods, suite,
params, instance);
// Reset the test result last. If we do this too early, Reporter.log()
// invocations from listeners will be discarded
Reporter.setCurrentTestResult(null);
}
return testResult;
}
void collectResults(ITestNGMethod testMethod, Collection<ITestResult> results) {
for (ITestResult result : results) {
// Collect the results
final int status = result.getStatus();
if(ITestResult.SUCCESS == status) {
m_notifier.addPassedTest(testMethod, result);
}
else if(ITestResult.SKIP == status) {
m_notifier.addSkippedTest(testMethod, result);
}
else if(ITestResult.FAILURE == status) {
m_notifier.addFailedTest(testMethod, result);
}
else if(ITestResult.SUCCESS_PERCENTAGE_FAILURE == status) {
m_notifier.addFailedButWithinSuccessPercentageTest(testMethod, result);
}
else {
assert false : "UNKNOWN STATUS:" + status;
}
}
}
/**
* The array of methods contains @BeforeMethods if isBefore if true, @AfterMethods
* otherwise. This function removes all the methods that should not be run at this
* point because they are either firstTimeOnly or lastTimeOnly and we haven't reached
* the current invocationCount yet
*/
private ITestNGMethod[] filterConfigurationMethods(ITestNGMethod tm,
ITestNGMethod[] methods, boolean isBefore)
{
List<ITestNGMethod> result = Lists.newArrayList();
for (ITestNGMethod m : methods) {
ConfigurationMethod cm = (ConfigurationMethod) m;
if (isBefore) {
if (! cm.isFirstTimeOnly() ||
(cm.isFirstTimeOnly() && tm.getCurrentInvocationCount() == 0))
{
result.add(m);
}
}
else {
int current = tm.getCurrentInvocationCount();
boolean isLast = false;
// If we have parameters, set the boolean if we are about to run
// the last invocation
if (tm.getParameterInvocationCount() > 0) {
isLast = current == tm.getParameterInvocationCount();
}
// If we have invocationCount > 1, set the boolean if we are about to
// run the last invocation
else if (tm.getInvocationCount() > 1) {
isLast = current == tm.getInvocationCount();
}
if (! cm.isLastTimeOnly() || (cm.isLastTimeOnly() && isLast)) {
result.add(m);
}
}
}
return result.toArray(new ITestNGMethod[result.size()]);
}
/**
* {@link #invokeTestMethods()} eventually converge here to invoke a single @Test method.
* <p/>
* This method is responsible for actually invoking the method. It decides if the invocation
* must be done:
* <ul>
* <li>through an <code>IHookable</code></li>
* <li>directly (through reflection)</li>
* <li>in a separate thread (in case it needs to timeout)
* </ul>
*
* <p/>
* This method is also responsible for invoking @BeforeGroup, @BeforeMethod, @AfterMethod, @AfterGroup
* if it is the case for the passed in @Test method.
*/
protected ITestResult invokeTestMethod(Object instance,
final ITestNGMethod tm,
Object[] parameterValues,
int parametersIndex,
XmlSuite suite,
Map<String, String> params,
ITestClass testClass,
ITestNGMethod[] beforeMethods,
ITestNGMethod[] afterMethods,
ConfigurationGroupMethods groupMethods,
FailureContext failureContext)
{
// Mark this method with the current thread id
tm.setId(ThreadUtil.currentThreadInfo());
ITestResult result = invokeMethod(instance, tm, parameterValues, parametersIndex, suite, params,
testClass, beforeMethods, afterMethods, groupMethods, failureContext);
return result;
}
/**
* Filter all the beforeGroups methods and invoke only those that apply
* to the current test method
*/
private void invokeBeforeGroupsConfigurations(ITestClass testClass,
ITestNGMethod currentTestMethod,
ConfigurationGroupMethods groupMethods,
XmlSuite suite,
Map<String, String> params,
Object instance)
{
synchronized(groupMethods) {
List<ITestNGMethod> filteredMethods = Lists.newArrayList();
String[] groups = currentTestMethod.getGroups();
Map<String, List<ITestNGMethod>> beforeGroupMap = groupMethods.getBeforeGroupsMap();
for (String group : groups) {
List<ITestNGMethod> methods = beforeGroupMap.get(group);
if (methods != null) {
filteredMethods.addAll(methods);
}
}
ITestNGMethod[] beforeMethodsArray = filteredMethods.toArray(new ITestNGMethod[filteredMethods.size()]);
// Invoke the right groups methods
if(beforeMethodsArray.length > 0) {
// don't pass the IClass or the instance as the method may be external
// the invocation must be similar to @BeforeTest/@BeforeSuite
invokeConfigurations(null, beforeMethodsArray, suite, params,
null, /* no parameter values */
null);
}
// Remove them so they don't get run again
groupMethods.removeBeforeGroups(groups);
}
}
private void invokeAfterGroupsConfigurations(ITestClass testClass,
ITestNGMethod currentTestMethod,
ConfigurationGroupMethods groupMethods,
XmlSuite suite,
Map<String, String> params,
Object instance)
{
// Skip this if the current method doesn't belong to any group
// (only a method that belongs to a group can trigger the invocation
// of afterGroups methods)
if (currentTestMethod.getGroups().length == 0) {
return;
}
// See if the currentMethod is the last method in any of the groups
// it belongs to
Map<String, String> filteredGroups = Maps.newHashMap();
String[] groups = currentTestMethod.getGroups();
synchronized(groupMethods) {
for (String group : groups) {
if (groupMethods.isLastMethodForGroup(group, currentTestMethod)) {
filteredGroups.put(group, group);
}
}
if(filteredGroups.isEmpty()) {
return;
}
// The list of afterMethods to run
Map<ITestNGMethod, ITestNGMethod> afterMethods = Maps.newHashMap();
// Now filteredGroups contains all the groups for which we need to run the afterGroups
// method. Find all the methods that correspond to these groups and invoke them.
Map<String, List<ITestNGMethod>> map = groupMethods.getAfterGroupsMap();
for (String g : filteredGroups.values()) {
List<ITestNGMethod> methods = map.get(g);
// Note: should put them in a map if we want to make sure the same afterGroups
// doesn't get run twice
if (methods != null) {
for (ITestNGMethod m : methods) {
afterMethods.put(m, m);
}
}
}
// Got our afterMethods, invoke them
ITestNGMethod[] afterMethodsArray = afterMethods.keySet().toArray(new ITestNGMethod[afterMethods.size()]);
// don't pass the IClass or the instance as the method may be external
// the invocation must be similar to @BeforeTest/@BeforeSuite
invokeConfigurations(null, afterMethodsArray, suite, params,
null, /* no parameter values */
null);
// Remove the groups so they don't get run again
groupMethods.removeAfterGroups(filteredGroups.keySet());
}
}
private Object[] getParametersFromIndex(Iterator<Object[]> parametersValues, int index) {
while (parametersValues.hasNext()) {
Object[] parameters = parametersValues.next();
if (index == 0) {
return parameters;
}
index
}
return null;
}
int retryFailed(Object instance,
final ITestNGMethod tm,
XmlSuite suite,
ITestClass testClass,
ITestNGMethod[] beforeMethods,
ITestNGMethod[] afterMethods,
ConfigurationGroupMethods groupMethods,
List<ITestResult> result,
int failureCount,
ExpectedExceptionsHolder expectedExceptionHolder,
ITestContext testContext,
Map<String, String> parameters,
int parametersIndex) {
final FailureContext failure = new FailureContext();
failure.count = failureCount;
do {
Map<String, String> allParameters = Maps.newHashMap();
/**
* TODO: This recreates all the parameters every time when we only need
* one specific set. Should optimize it by only recreating the set needed.
*/
ParameterBag bag = createParameters(tm, parameters,
allParameters, suite, testContext, null /* fedInstance */);
Object[] parameterValues =
getParametersFromIndex(bag.parameterHolder.parameters, parametersIndex);
result.add(invokeMethod(instance, tm, parameterValues, parametersIndex, suite,
allParameters, testClass, beforeMethods, afterMethods, groupMethods, failure));
// It's already handled inside 'invokeMethod' but results not collected
handleInvocationResults(tm, result, expectedExceptionHolder, true, true/* collect results */, failure);
}
while (!failure.instances.isEmpty());
return failure.count;
}
private ParameterBag createParameters(ITestNGMethod testMethod,
Map<String, String> parameters,
Map<String, String> allParameterNames,
XmlSuite suite,
ITestContext testContext,
Object fedInstance)
{
Object instance;
if (fedInstance != null) {
instance = fedInstance;
}
else {
instance = testMethod.getInstance();
}
ParameterBag bag = handleParameters(testMethod,
instance, allParameterNames, parameters, null, suite, testContext, fedInstance, null);
return bag;
}
/**
* Invoke all the test methods. Note the plural: the method passed in
* parameter might be invoked several times if the test class it belongs
* to has more than one instance (i.e., if an @Factory method has been
* declared somewhere that returns several instances of this TestClass).
* If no @Factory method was specified, testMethod will only be invoked
* once.
* <p/>
* Note that this method also takes care of invoking the beforeTestMethod
* and afterTestMethod, if any.
*
* Note (alex): this method can be refactored to use a SingleTestMethodWorker that
* directly invokes
* {@link #invokeTestMethod(Object[], ITestNGMethod, Object[], XmlSuite, Map, ITestClass, ITestNGMethod[], ITestNGMethod[], ConfigurationGroupMethods)}
* and this would simplify the implementation (see how DataTestMethodWorker is used)
*/
@Override
public List<ITestResult> invokeTestMethods(ITestNGMethod testMethod,
XmlSuite suite,
Map<String, String> testParameters,
ConfigurationGroupMethods groupMethods,
Object instance,
ITestContext testContext)
{
// Potential bug here if the test method was declared on a parent class
assert null != testMethod.getTestClass()
: "COULDN'T FIND TESTCLASS FOR " + testMethod.getRealClass();
if (!MethodHelper.isEnabled(testMethod.getMethod(), m_annotationFinder)) {
// return if the method is not enabled. No need to do any more calculations
return Collections.emptyList();
}
// By the time this testMethod to be invoked,
// all dependencies should be already run or we need to skip this method,
// so invocation count should not affect dependencies check
final String okToProceed = checkDependencies(testMethod, testContext.getAllTestMethods());
if (okToProceed != null) {
// Not okToProceed. Test is being skipped
ITestResult result = registerSkippedTestResult(testMethod, null, System.currentTimeMillis(),
new Throwable(okToProceed));
m_notifier.addSkippedTest(testMethod, result);
return Collections.singletonList(result);
}
final Map<String, String> parameters =
testMethod.findMethodParameters(testContext.getCurrentXmlTest());
// For invocationCount > 1 and threadPoolSize > 1 run this method in its own pool thread.
if (testMethod.getInvocationCount() > 1 && testMethod.getThreadPoolSize() > 1) {
return invokePooledTestMethods(testMethod, suite, parameters, groupMethods, testContext);
}
long timeOutInvocationCount = testMethod.getInvocationTimeOut();
//FIXME: Is this correct?
boolean onlyOne = testMethod.getThreadPoolSize() > 1 ||
timeOutInvocationCount > 0;
int invocationCount = onlyOne ? 1 : testMethod.getInvocationCount();
ExpectedExceptionsHolder expectedExceptionHolder =
MethodHelper.findExpectedExceptions(m_annotationFinder, testMethod.getMethod());
final ITestClass testClass= testMethod.getTestClass();
final List<ITestResult> result = Lists.newArrayList();
final FailureContext failure = new FailureContext();
final ITestNGMethod[] beforeMethods = filterMethods(testClass, testClass.getBeforeTestMethods(), CAN_RUN_FROM_CLASS);
final ITestNGMethod[] afterMethods = filterMethods(testClass, testClass.getAfterTestMethods(), CAN_RUN_FROM_CLASS);
while(invocationCount
if(false) {
// Prevent code formatting
}
// No threads, regular invocation
else {
// Used in catch statement
long start = System.currentTimeMillis();
Map<String, String> allParameterNames = Maps.newHashMap();
ParameterBag bag = createParameters(testMethod,
parameters, allParameterNames, suite, testContext, instance);
if (bag.hasErrors()) {
handleInvocationResults(testMethod,
Lists.newArrayList(bag.errorResult), expectedExceptionHolder, true,
true /* collect results */, failure);
ITestResult tr = registerSkippedTestResult(testMethod, instance,
System.currentTimeMillis(),
bag.errorResult.getThrowable());
result.add(tr);
continue;
}
Iterator<Object[]> allParameterValues = bag.parameterHolder.parameters;
int parametersIndex = 0;
try {
List<TestMethodWithDataProviderMethodWorker> workers = Lists.newArrayList();
if (bag.parameterHolder.origin == ParameterOrigin.ORIGIN_DATA_PROVIDER &&
bag.parameterHolder.dataProviderHolder.annotation.isParallel()) {
while (allParameterValues.hasNext()) {
Object[] parameterValues = injectParameters(allParameterValues.next(),
testMethod.getMethod(), testContext, null /* test result */);
TestMethodWithDataProviderMethodWorker w =
new TestMethodWithDataProviderMethodWorker(this,
testMethod, parametersIndex,
parameterValues, instance, suite, parameters, testClass,
beforeMethods, afterMethods, groupMethods,
expectedExceptionHolder, testContext, m_skipFailedInvocationCounts,
invocationCount, failure.count, m_notifier);
workers.add(w);
// testng387: increment the param index in the bag.
parametersIndex++;
}
PoolService<List<ITestResult>> ps =
new PoolService<List<ITestResult>>(suite.getDataProviderThreadCount());
List<List<ITestResult>> r = ps.submitTasksAndWait(workers);
for (List<ITestResult> l2 : r) {
result.addAll(l2);
}
} else {
while (allParameterValues.hasNext()) {
Object[] parameterValues = injectParameters(allParameterValues.next(),
testMethod.getMethod(), testContext, null /* test result */);
List<ITestResult> tmpResults = Lists.newArrayList();
try {
tmpResults.add(invokeTestMethod(instance,
testMethod,
parameterValues,
parametersIndex,
suite,
parameters,
testClass,
beforeMethods,
afterMethods,
groupMethods, failure));
}
finally {
if (failure.instances.isEmpty()) {
result.addAll(tmpResults);
} else {
for (Object failedInstance : failure.instances) {
List<ITestResult> retryResults = Lists.newArrayList();
failure.count = retryFailed(
failedInstance, testMethod, suite, testClass, beforeMethods,
afterMethods, groupMethods, retryResults,
failure.count, expectedExceptionHolder,
testContext, parameters, parametersIndex);
result.addAll(retryResults);
}
}
// If we have a failure, skip all the
// other invocationCounts
if (failure.count > 0
&& (m_skipFailedInvocationCounts
|| testMethod.skipFailedInvocations())) {
while (invocationCount
result.add(registerSkippedTestResult(testMethod, instance, System.currentTimeMillis(), null));
}
break;
}
}// end finally
parametersIndex++;
}
}
}
catch (Throwable cause) {
ITestResult r =
new TestResult(testMethod.getTestClass(),
instance,
testMethod,
cause,
start,
System.currentTimeMillis(),
m_testContext);
r.setStatus(TestResult.FAILURE);
result.add(r);
runTestListeners(r);
m_notifier.addFailedTest(testMethod, r);
} // catch
}
}
return result;
} // invokeTestMethod
private ITestResult registerSkippedTestResult(ITestNGMethod testMethod, Object instance,
long start, Throwable throwable) {
ITestResult result =
new TestResult(testMethod.getTestClass(),
instance,
testMethod,
throwable,
start,
System.currentTimeMillis(),
m_testContext);
result.setStatus(TestResult.SKIP);
runTestListeners(result);
return result;
}
/**
* Gets an array of parameter values returned by data provider or the ones that
* are injected based on parameter type. The method also checks for {@code NoInjection}
* annotation
* @param parameterValues parameter values from a data provider
* @param method method to be invoked
* @param context test context
* @param testResult test result
* @return
*/
private Object[] injectParameters(Object[] parameterValues, Method method,
ITestContext context, ITestResult testResult)
throws TestNGException {
List<Object> vResult = Lists.newArrayList();
int i = 0;
int numValues = parameterValues.length;
int numParams = method.getParameterTypes().length;
if (numValues > numParams && ! method.isVarArgs()) {
throw new TestNGException("The data provider is trying to pass " + numValues
+ " parameters but the method "
+ method.getDeclaringClass().getName() + "#" + method.getName()
+ " takes " + numParams);
}
// beyond this, numValues <= numParams
for (Class<?> cls : method.getParameterTypes()) {
Annotation[] annotations = method.getParameterAnnotations()[i];
boolean noInjection = false;
for (Annotation a : annotations) {
if (a instanceof NoInjection) {
noInjection = true;
break;
}
}
Object injected = Parameters.getInjectedParameter(cls, method, context, testResult);
if (injected != null && ! noInjection) {
vResult.add(injected);
} else {
try {
if (method.isVarArgs()) vResult.add(parameterValues);
else vResult.add(parameterValues[i++]);
} catch (ArrayIndexOutOfBoundsException ex) {
throw new TestNGException("The data provider is trying to pass " + numValues
+ " parameters but the method "
+ method.getDeclaringClass().getName() + "#" + method.getName()
+ " takes " + numParams
+ " and TestNG is unable in inject a suitable object", ex);
}
}
}
return vResult.toArray(new Object[vResult.size()]);
}
private ParameterBag handleParameters(ITestNGMethod testMethod,
Object instance,
Map<String, String> allParameterNames,
Map<String, String> parameters,
Object[] parameterValues,
XmlSuite suite,
ITestContext testContext,
Object fedInstance,
ITestResult testResult)
{
try {
return new ParameterBag(
Parameters.handleParameters(testMethod,
allParameterNames,
instance,
new Parameters.MethodParameters(parameters,
testMethod.findMethodParameters(testContext.getCurrentXmlTest()),
parameterValues,
testMethod.getMethod(), testContext, testResult),
suite,
m_annotationFinder,
fedInstance));
}
// catch(TestNGException ex) {
// throw ex;
catch(Throwable cause) {
return new ParameterBag(
new TestResult(
testMethod.getTestClass(),
instance,
testMethod,
cause,
System.currentTimeMillis(),
System.currentTimeMillis(),
m_testContext));
}
}
/**
* Invokes a method that has a specified threadPoolSize.
*/
private List<ITestResult> invokePooledTestMethods(ITestNGMethod testMethod,
XmlSuite suite,
Map<String, String> parameters,
ConfigurationGroupMethods groupMethods,
ITestContext testContext)
{
// Create the workers
List<IWorker<ITestNGMethod>> workers = Lists.newArrayList();
// Create one worker per invocationCount
for (int i = 0; i < testMethod.getInvocationCount(); i++) {
// we use clones for reporting purposes
ITestNGMethod clonedMethod= testMethod.clone();
clonedMethod.setInvocationCount(1);
clonedMethod.setThreadPoolSize(1);
MethodInstance mi = new MethodInstance(clonedMethod);
workers.add(new SingleTestMethodWorker(this,
mi,
suite,
parameters,
testContext));
}
return runWorkers(testMethod, workers, testMethod.getThreadPoolSize(), groupMethods, suite, parameters);
}
static class FailureContext {
int count = 0;
List<Object> instances = Lists.newArrayList();
}
/**
* @param testMethod
* @param result
* @param expectedExceptionsHolder
* @param failure
* @return
*/
void handleInvocationResults(ITestNGMethod testMethod,
List<ITestResult> result,
ExpectedExceptionsHolder expectedExceptionsHolder,
boolean triggerListeners,
boolean collectResults,
FailureContext failure)
{
// Go through all the results and create a TestResult for each of them
List<ITestResult> resultsToRetry = Lists.newArrayList();
for (ITestResult testResult : result) {
Throwable ite= testResult.getThrowable();
int status= testResult.getStatus();
boolean handled = false;
// Exception thrown?
if (ite != null) {
// Invocation caused an exception, see if the method was annotated with @ExpectedException
if (isExpectedException(ite, expectedExceptionsHolder)) {
if (messageRegExpMatches(expectedExceptionsHolder.messageRegExp, ite)) {
testResult.setStatus(ITestResult.SUCCESS);
status= ITestResult.SUCCESS;
}
else {
testResult.setThrowable(
new TestException("The exception was thrown with the wrong message:" +
" expected \"" + expectedExceptionsHolder.messageRegExp + "\"" +
" but got \"" + ite.getMessage() + "\"", ite));
status= ITestResult.FAILURE;
}
} else if (isSkipExceptionAndSkip(ite)){
status = ITestResult.SKIP;
} else if (expectedExceptionsHolder != null) {
testResult.setThrowable(
new TestException("Expected exception of " +
getExpectedExceptionsPluralize(expectedExceptionsHolder)
+ " but got " + ite, ite));
status= ITestResult.FAILURE;
} else {
handleException(ite, testMethod, testResult, failure.count++);
handled = true;
status = testResult.getStatus();
}
}
// No exception thrown, make sure we weren't expecting one
else if(status != ITestResult.SKIP && expectedExceptionsHolder != null) {
Class<?>[] classes = expectedExceptionsHolder.expectedClasses;
if (classes != null && classes.length > 0) {
testResult.setThrowable(
new TestException("Method " + testMethod + " should have thrown an exception of "
+ getExpectedExceptionsPluralize(expectedExceptionsHolder)));
status= ITestResult.FAILURE;
}
}
testResult.setStatus(status);
if (status == ITestResult.FAILURE && !handled) {
handleException(ite, testMethod, testResult, failure.count++);
status = testResult.getStatus();
}
if (status == ITestResult.FAILURE) {
IRetryAnalyzer retryAnalyzer = testMethod.getRetryAnalyzer();
if (retryAnalyzer != null && failure.instances != null && retryAnalyzer.retry(testResult)) {
resultsToRetry.add(testResult);
failure.instances.add(testResult.getInstance());
}
}
if (collectResults) {
// Collect the results
collectResults(testMethod, Collections.singleton(testResult));
// if (triggerListeners && status != ITestResult.SUCCESS) {
// runTestListeners(testResult);
}
} // for results
removeResultsToRetryFromResult(resultsToRetry, result, failure);
}
private String getExpectedExceptionsPluralize(final ExpectedExceptionsHolder holder) {
StringBuilder sb = new StringBuilder();
if (holder.expectedClasses.length > 1) {
sb.append("any of types ");
sb.append(Arrays.toString(holder.expectedClasses));
} else {
sb.append("type ");
sb.append(holder.expectedClasses[0]);
}
return sb.toString();
}
private boolean isSkipExceptionAndSkip(Throwable ite) {
return SkipException.class.isAssignableFrom(ite.getClass()) && ((SkipException) ite).isSkip();
}
/**
* message / regEx .* other
* null true false
* non-null true match
*/
private boolean messageRegExpMatches(String messageRegExp, Throwable ite) {
if (".*".equals(messageRegExp)) {
return true;
} else {
final String message = ite.getMessage();
return message != null && Pattern.matches(messageRegExp, message);
}
}
private void removeResultsToRetryFromResult(List<ITestResult> resultsToRetry,
List<ITestResult> result, FailureContext failure) {
if (resultsToRetry != null) {
for (ITestResult res : resultsToRetry) {
result.remove(res);
failure.count
}
}
}
/**
* To reduce thread contention and also to correctly handle thread-confinement
* this method invokes the @BeforeGroups and @AfterGroups corresponding to the current @Test method.
*/
private List<ITestResult> runWorkers(ITestNGMethod testMethod,
List<IWorker<ITestNGMethod>> workers,
int threadPoolSize,
ConfigurationGroupMethods groupMethods,
XmlSuite suite,
Map<String, String> parameters)
{
// Invoke @BeforeGroups on the original method (reduce thread contention,
// and also solve thread confinement)
ITestClass testClass= testMethod.getTestClass();
Object[] instances = testClass.getInstances(true);
for(Object instance: instances) {
invokeBeforeGroupsConfigurations(testClass, testMethod, groupMethods, suite, parameters, instance);
}
long maxTimeOut= -1; // 10 seconds
for(IWorker<ITestNGMethod> tmw : workers) {
long mt= tmw.getTimeOut();
if(mt > maxTimeOut) {
maxTimeOut= mt;
}
}
ThreadUtil.execute(workers, threadPoolSize, maxTimeOut, true);
// Collect all the TestResults
List<ITestResult> result = Lists.newArrayList();
for (IWorker<ITestNGMethod> tmw : workers) {
if (tmw instanceof TestMethodWorker) {
result.addAll(((TestMethodWorker)tmw).getTestResults());
}
}
for(Object instance: instances) {
invokeAfterGroupsConfigurations(testClass, testMethod, groupMethods, suite, parameters, instance);
}
return result;
}
/**
* Checks to see of the test method has certain dependencies that prevents
* TestNG from executing it
* @param testMethod test method being checked for
* @return error message or null if dependencies have been run successfully
*/
private String checkDependencies(ITestNGMethod testMethod,
ITestNGMethod[] allTestMethods)
{
// If this method is marked alwaysRun, no need to check for its dependencies
if (testMethod.isAlwaysRun()) {
return null;
}
// Any missing group?
if (testMethod.getMissingGroup() != null
&& !testMethod.ignoreMissingDependencies()) {
return "Method " + testMethod + " depends on nonexistent group \"" + testMethod.getMissingGroup() + "\"";
}
// If this method depends on groups, collect all the methods that
// belong to these groups and make sure they have been run successfully
final String[] groups = testMethod.getGroupsDependedUpon();
if (null != groups && groups.length > 0) {
// Get all the methods that belong to the group depended upon
for (String element : groups) {
ITestNGMethod[] methods =
MethodGroupsHelper.findMethodsThatBelongToGroup(testMethod,
m_testContext.getAllTestMethods(),
element);
if (methods.length == 0 && !testMethod.ignoreMissingDependencies()) {
// Group is missing
return "Method " + testMethod + " depends on nonexistent group \"" + element + "\"";
}
if (!haveBeenRunSuccessfully(testMethod, methods)) {
return "Method " + testMethod +
" depends on not successfully finished methods in group \"" + element + "\"";
}
}
} // depends on groups
// If this method depends on other methods, make sure all these other
// methods have been run successfully
if (dependsOnMethods(testMethod)) {
ITestNGMethod[] methods =
MethodHelper.findDependedUponMethods(testMethod, allTestMethods);
if (!haveBeenRunSuccessfully(testMethod, methods)) {
return "Method " + testMethod + " depends on not successfully finished methods";
}
}
return null;
}
/**
* @return the test results that apply to one of the instances of the testMethod.
*/
private Set<ITestResult> keepSameInstances(ITestNGMethod method, Set<ITestResult> results) {
Set<ITestResult> result = Sets.newHashSet();
for (ITestResult r : results) {
final Object o = method.getInstance();
// Keep this instance if 1) It's on a different class or 2) It's on the same class
// and on the same instance
Object instance = r.getInstance() != null
? r.getInstance() : r.getMethod().getInstance();
if (r.getTestClass() != method.getTestClass() || instance == o) result.add(r);
}
return result;
}
/**
* @return true if all the methods have been run successfully
*/
private boolean haveBeenRunSuccessfully(ITestNGMethod testMethod, ITestNGMethod[] methods) {
// Make sure the method has been run successfully
for (ITestNGMethod method : methods) {
Set<ITestResult> results = keepSameInstances(testMethod, m_notifier.getPassedTests(method));
Set<ITestResult> failedAndSkippedMethods = Sets.newHashSet();
failedAndSkippedMethods.addAll(m_notifier.getFailedTests(method));
failedAndSkippedMethods.addAll(m_notifier.getSkippedTests(method));
Set<ITestResult> failedresults = keepSameInstances(testMethod, failedAndSkippedMethods);
// If failed results were returned on the same instance, then these tests didn't pass
if (failedresults != null && failedresults.size() > 0) {
return false;
}
for (ITestResult result : results) {
if(!result.isSuccess()) {
return false;
}
}
}
return true;
}
// private boolean containsInstance(Set<ITestResult> failedresults, Object[] instances) {
// for (ITestResult tr : failedresults) {
// for (Object o : instances) {
// if (o == tr.getInstance()) {
// return true;
// return false;
/**
* An exception was thrown by the test, determine if this method
* should be marked as a failure or as failure_but_within_successPercentage
*/
private void handleException(Throwable throwable,
ITestNGMethod testMethod,
ITestResult testResult,
int failureCount) {
if (throwable != null) {
testResult.setThrowable(throwable);
}
int successPercentage= testMethod.getSuccessPercentage();
int invocationCount= testMethod.getInvocationCount();
float numberOfTestsThatCanFail= ((100 - successPercentage) * invocationCount) / 100f;
if(failureCount < numberOfTestsThatCanFail) {
testResult.setStatus(ITestResult.SUCCESS_PERCENTAGE_FAILURE);
}
else {
testResult.setStatus(ITestResult.FAILURE);
}
}
/**
* @param ite The exception that was just thrown
* @param exceptionHolder Expected exceptions holder for this
* test method
* @return true if the exception that was just thrown is part of the
* expected exceptions
*/
private boolean isExpectedException(Throwable ite, ExpectedExceptionsHolder exceptionHolder) {
if (exceptionHolder == null || exceptionHolder.expectedClasses == null) {
return false;
}
// TestException is the wrapper exception that TestNG will be throwing when an exception was
// expected but not thrown
if (ite.getClass() == TestException.class) {
return false;
}
Class<?>[] exceptions = exceptionHolder.expectedClasses;
Class<?> realExceptionClass= ite.getClass();
for (Class<?> exception : exceptions) {
if (exception.isAssignableFrom(realExceptionClass)) {
return true;
}
}
return false;
}
static interface Predicate<K, T> {
boolean isTrue(K k, T v);
}
static class CanRunFromClassPredicate implements Predicate <ITestNGMethod, IClass> {
@Override
public boolean isTrue(ITestNGMethod m, IClass v) {
return m.canRunFromClass(v);
}
}
static class SameClassNamePredicate implements Predicate<ITestNGMethod, IClass> {
@Override
public boolean isTrue(ITestNGMethod m, IClass c) {
return c == null || m.getTestClass().getName().equals(c.getName());
}
}
/**
* @return Only the ITestNGMethods applicable for this testClass
*/
private ITestNGMethod[] filterMethods(IClass testClass, ITestNGMethod[] methods,
Predicate<ITestNGMethod, IClass> predicate) {
List<ITestNGMethod> vResult= Lists.newArrayList();
for(ITestNGMethod tm : methods) {
if (predicate.isTrue(tm, testClass)) {
log(10, "Keeping method " + tm + " for class " + testClass);
vResult.add(tm);
} else {
log(10, "Filtering out method " + tm + " for class " + testClass);
}
}
ITestNGMethod[] result= vResult.toArray(new ITestNGMethod[vResult.size()]);
return result;
}
/**
* @return true if this method depends on certain methods.
*/
private boolean dependsOnMethods(ITestNGMethod tm) {
String[] methods = tm.getMethodsDependedUpon();
return null != methods && methods.length > 0;
}
private void runConfigurationListeners(ITestResult tr, boolean before) {
if (before) {
for(IConfigurationListener icl: m_notifier.getConfigurationListeners()) {
if (icl instanceof IConfigurationListener2) {
((IConfigurationListener2) icl).beforeConfiguration(tr);
}
}
} else {
for(IConfigurationListener icl: m_notifier.getConfigurationListeners()) {
switch(tr.getStatus()) {
case ITestResult.SKIP:
icl.onConfigurationSkip(tr);
break;
case ITestResult.FAILURE:
icl.onConfigurationFailure(tr);
break;
case ITestResult.SUCCESS:
icl.onConfigurationSuccess(tr);
break;
}
}
}
}
void runTestListeners(ITestResult tr) {
runTestListeners(tr, m_notifier.getTestListeners());
}
// TODO: move this from here as it is directly called from TestNG
public static void runTestListeners(ITestResult tr, List<ITestListener> listeners) {
for (ITestListener itl : listeners) {
switch(tr.getStatus()) {
case ITestResult.SKIP: {
itl.onTestSkipped(tr);
break;
}
case ITestResult.SUCCESS_PERCENTAGE_FAILURE: {
itl.onTestFailedButWithinSuccessPercentage(tr);
break;
}
case ITestResult.FAILURE: {
itl.onTestFailure(tr);
break;
}
case ITestResult.SUCCESS: {
itl.onTestSuccess(tr);
break;
}
case ITestResult.STARTED: {
itl.onTestStart(tr);
break;
}
default: {
assert false : "UNKNOWN STATUS:" + tr;
}
}
}
}
private void log(int level, String s) {
Utils.log("Invoker " + Thread.currentThread().hashCode(), level, s);
}
/**
* This class holds a {@code ParameterHolder} or in case of an error, a non-null
* {@code TestResult} containing the cause
*/
private static class ParameterBag {
final ParameterHolder parameterHolder;
final ITestResult errorResult;
public ParameterBag(ParameterHolder parameterHolder) {
this.parameterHolder = parameterHolder;
this.errorResult = null;
}
public ParameterBag(ITestResult errorResult) {
this.parameterHolder = null;
this.errorResult = errorResult;
}
public boolean hasErrors() {
return errorResult != null;
}
}
} |
package pipeline;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class PipelineController {
@RequestMapping("/pipelines")
public String pipeline(@RequestParam(value="name", required=false, defaultValue="Pipeline IT Magix") String name, Model model) {
model.addAttribute("name", name);
return "pipeline";
}
} |
package main.java.player.panels;
import java.util.List;
import javax.swing.JTextArea;
@SuppressWarnings("serial")
public class UnitInfoPanel extends ObservingPanel{
public static final String TIME = "Time";
private JTextArea unitInfoArea;
public UnitInfoPanel() {
unitInfoArea = new JTextArea(5, 5);
unitInfoArea.setEditable(false);
unitInfoArea.setLineWrap(true);
unitInfoArea.setWrapStyleWord(true);
add(unitInfoArea);
}
@Override
public void update() {
List<String> unitInfoList = engine.getCurrentDescription();
String unitInfo = "";
for(String s: unitInfoList){
unitInfo += s + "\n";
}
unitInfoArea.setText(unitInfo);
}
} |
package robertbosch.utils;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.TimeoutException;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import com.google.protobuf.util.JsonFormat;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
//import com.protoTest.smartcity.Actuated;
import com.rabbitmq.client.Consumer;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;
public class Testproto {
static int ctr=0;
public static void main(String[] args) throws IOException {
// System.out.println("start...");
// writeProtodata();
// System.out.println("stop...");
// readProtoData();
// dynamicCompile();
// readInRemoteMode();
// ProcessBuilder builder = new ProcessBuilder("/Users/sahiltyagi/Downloads/apache-maven-3.5.2/bin/mvn", "clean", "compile", "assembly:single");
// builder.directory(new File("/Users/sahiltyagi/Documents/IISc/protoschema"));
// Process compile = builder.start();
// try {
// int complete = compile.waitFor();
// } catch(InterruptedException in) {
// in.printStackTrace();
// System.out.println("done waiting for compiling");
// checkprotoJAR();
// System.out.println("test rabbitmq subscriber...");
// subscriberabbitMQ(1000);
// System.out.println("done with test proto code...");
String url = "https://raw.githubusercontent.com/mukuntharun/flowsensor/master/protos/sensed.proto";
System.out.println(RobertBoschUtils.protofiles + url.split("/")[url.split("/").length -1]);
}
private static void subscriberabbitMQ(int datapoint) {
String subscribefile = "/Users/sahiltyagi/Desktop/subscribe.txt";
JSONParser parser = new JSONParser();
RobertBoschUtils rb = new RobertBoschUtils();
try {
final BufferedWriter subscriber = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(subscribefile)));
ConnectionFactory factory = new ConnectionFactory();
factory.setHost(RobertBoschUtils.props.getProperty("host"));
factory.setPort(Integer.parseInt(RobertBoschUtils.props.getProperty("port")));
factory.setUsername(RobertBoschUtils.props.getProperty("username"));
factory.setPassword(RobertBoschUtils.props.getProperty("password"));
factory.setVirtualHost(RobertBoschUtils.props.getProperty("virtualhost"));
Connection conn = factory.newConnection();
Channel channel = conn.createChannel();
channel.queueDeclare("sahil", false, false, false, null);
Consumer consumer = new DefaultConsumer(channel) {
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
//RabbitMQSpout.nbqueue.add(body);
String message = new String(body, "UTF-8");
System.out.println(" [x] Received '" + message + "'");
try {
Object ob = parser.parse(message);
JSONObject jsonob = (JSONObject)ob;
System.out.println(jsonob.get("devEUI"));
subscriber.write(System.currentTimeMillis() + "," + jsonob.get("devEUI") + "\n");
ctr++;
if(ctr == datapoint) {
subscriber.close();
}
} catch (ParseException e) {
e.printStackTrace();
}
}
};
channel.basicConsume("sahil", true, consumer);
} catch(IOException e) {
e.printStackTrace();
} catch(TimeoutException t) {
t.printStackTrace();
}
}
private static void checkprotoJAR() {
try {
Class cls = Class.forName("com.protoTest.smartcity.Prototest");
Class[] arr2 = {};
Method m2 = cls.getDeclaredMethod("start", arr2);
Object printer = m2.invoke(cls, null);
System.out.println("end");
} catch(ClassNotFoundException cl) {
cl.printStackTrace();
} catch(NoSuchMethodException nomethod) {
nomethod.printStackTrace();
} catch(InvocationTargetException invoke) {
invoke.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
}
private static void readProtoData() {
// try {
// Actuated.targetConfigurations confs = Actuated.targetConfigurations.parseFrom(new FileInputStream("/Users/sahiltyagi/Desktop/out1.txt"));
//// Actuated.targetConfigurations confs = Actuated.targetConfigurations.parseFrom(data)
//// System.out.println(confs.getPowerState().getTargetPowerState());
//// System.out.println(confs.getControlPolicy().getControlPolicy());
//// System.out.println(confs.getManualControlParams().getTargetBrightnessLevel());
// Object ob = Actuated.targetConfigurations.parseFrom(new FileInputStream("/Users/sahiltyagi/Desktop/out1.txt"));
// String packet=JsonFormat.printer().print((Actuated.targetConfigurations)ob);
// System.out.println(packet);
// } catch(IOException e) {
// e.printStackTrace();
}
private static void dynamicCompile() {
try {
String urlstr = "https://raw.githubusercontent.com/rbccps-iisc/applications-streetlight/master/proto_stm/rxmsg/actuated.proto";
URL url = new URL(urlstr);
BufferedReader rdr = new BufferedReader(new InputStreamReader(url.openStream()));
String schema="";
String proto;
BufferedWriter bfrwrtr = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("/Users/sahiltyagi/Desktop/actuated3.proto")));
while((proto = rdr.readLine()) != null) {
schema += proto;
bfrwrtr.write(proto+"\n");
if(proto.equals("syntax = \"proto2\";")) {
bfrwrtr.write("option java_package= \"com.protoTest.smartcity\";");
}
}
rdr.close();
System.out.println(schema);
bfrwrtr.close();
// one variable to set location of generated .proto files, another variable to specify the package to place generated java class into it
String[] command = {"/usr/local/bin/protoc", "--proto_path=/Users/sahiltyagi/Desktop",
"--java_out=/Users/sahiltyagi/Documents/IISc/protoschema/src/main/java", "actuated5.proto"};
Process proc = Runtime.getRuntime().exec(command);
int protogen = proc.waitFor();
ProcessBuilder builder = new ProcessBuilder("/Users/sahiltyagi/Downloads/apache-maven-3.5.2/bin/mvn", "clean", "compile", "assembly:single");
builder.directory(new File("/Users/sahiltyagi/Documents/IISc/protoschema"));
Process compile = builder.start();
int wait = compile.waitFor();
System.out.println("done");
} catch(MalformedURLException urlex) {
urlex.printStackTrace();
} catch(IOException e) {
e.printStackTrace();
} catch(InterruptedException in) {
in.printStackTrace();
}
}
private static void readInRemoteMode() {
try {
Class cls = Class.forName("com.protoTest.smartcity.Actuated5$targetConfigurations");
// for(Method method : cls.getMethods()) {
// System.out.println(method.getName());
Class[] arr = {InputStream.class};
Method method = cls.getDeclaredMethod("parseFrom", arr);
Object packet = method.invoke(cls, new FileInputStream("/Users/sahiltyagi/Desktop/out2.txt"));
//System.out.println(packet.toString());
Class format = Class.forName("com.google.protobuf.util.JsonFormat");
Class[] arr2 = {};
Method m2 = format.getDeclaredMethod("printer", arr2);
Object printer = m2.invoke(format, null);
// System.out.println(printer.getClass());
// com.google.protobuf.MessageOrBuilder
// for(Method m : printer.getClass().getMethods()) {
// System.out.println(m.getName());
// for(Parameter param : m.getParameters()) {
// System.out.println(param.getParameterizedType().getTypeName());
Class[] arr3 = {Class.forName("com.google.protobuf.MessageOrBuilder")};
Method m3 = printer.getClass().getDeclaredMethod("print", arr3);
Object data = m3.invoke(printer, packet);
System.out.println(data.toString());
System.out.println("done.");
} catch(ClassNotFoundException c) {
c.printStackTrace();
} catch(NoSuchMethodException method) {
method.printStackTrace();
} catch(FileNotFoundException f) {
f.printStackTrace();
} catch(IllegalAccessException acc) {
acc.printStackTrace();
} catch(InvocationTargetException invoke) {
invoke.printStackTrace();
}
}
private static void writeProtodata() {
//// Actuated.targetPowerStateParams.Builder powerstate = Actuated.targetPowerStateParams.newBuilder();
//// powerstate.setTargetPowerState(true);
//// Actuated.targetControlPolicy.Builder ctrlpolicy = Actuated.targetControlPolicy.newBuilder();
//// ctrlpolicy.setControlPolicy(Actuated.ctrlPolicy.AUTO_LUX);
//// Actuated.targetManualControlParams.Builder manualparams = Actuated.targetManualControlParams.newBuilder();
//// manualparams.setTargetBrightnessLevel(99);
// Actuated.targetAutoTimerParams.Builder autotimers = Actuated.targetAutoTimerParams.newBuilder();
// autotimers.setTargetOnTime(60000);
// autotimers.setTargetOffTime(120000);
//// Actuated.targetAutoLuxParams.Builder autolux = Actuated.targetAutoLuxParams.newBuilder();
//// autolux.setTargetOnLux(199);
//// autolux.setTargetOffLux(299);
// Actuated.targetConfigurations.Builder confs = Actuated.targetConfigurations.newBuilder();
//// confs.setPowerState(powerstate);
//// confs.setControlPolicy(ctrlpolicy);
//// confs.setManualControlParams(manualparams);
// confs.setAutoTimerParams(autotimers);
//// confs.setAutoLuxParams(autolux);
// Actuated.targetConfigurations finalconf = confs.build();
// try {
// finalconf.writeTo(new FileOutputStream("/Users/sahiltyagi/Desktop/out1.txt"));
// } catch(IOException e) {
// e.printStackTrace();
// System.out.println("done writing proto data to file");
}
} |
package sc.fiji.threed;
import cleargl.GLMatrix;
import cleargl.GLVector;
import com.jogamp.opengl.GLAutoDrawable;
import ij.ImagePlus;
import net.imagej.ImageJ;
import net.imglib2.RealLocalizable;
import sc.fiji.threed.process.MeshConverter;
import org.scijava.ui.behaviour.ClickBehaviour;
import scenery.*;
import scenery.controls.behaviours.ArcballCameraControl;
import scenery.controls.behaviours.FPSCameraControl;
import scenery.backends.Renderer;
import scenery.backends.opengl.OpenGLRenderer;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.FloatBuffer;
import java.util.concurrent.CopyOnWriteArrayList;
public class ThreeDViewer extends SceneryDefaultApplication {
static ImageJ ij;
static ThreeDViewer viewer;
static Thread animationThread;
static Mesh aMesh = null;
static Boolean defaultArcBall = true;
public ThreeDViewer() {
super("ThreeDViewer", 800, 600);
}
public ThreeDViewer(String applicationName, int windowWidth, int windowHeight) {
super(applicationName, windowWidth, windowHeight);
}
public void init() {
setRenderer( Renderer.Companion.createRenderer( getApplicationName(), getScene(), 512, 512));
getHub().add(SceneryElement.RENDERER, getRenderer());
PointLight[] lights = new PointLight[2];
for( int i = 0; i < lights.length; i++ ) {
lights[i] = new PointLight();
lights[i].setPosition( new GLVector(2.0f * i, 2.0f * i, 2.0f * i) );
lights[i].setEmissionColor( new GLVector(1.0f, 0.0f, 1.0f) );
lights[i].setIntensity( 0.2f*(i+1) );
getScene().addChild( lights[i] );
}
Camera cam = new DetachedHeadCamera();
cam.setPosition( new GLVector(0.0f, 0.0f, -5.0f) );
cam.setView( new GLMatrix().setCamera(cam.getPosition(), cam.getPosition().plus(cam.getForward()), cam.getUp()) );
cam.setProjection( new GLMatrix().setPerspectiveProjectionMatrix( (float) (70.0f / 180.0f * java.lang.Math.PI), 1024f / 1024f, 0.1f, 2000.0f) );
cam.setActive( true );
getScene().addChild(cam);
viewer = this;
}
public void inputSetup() {
//setInputHandler((ClearGLInputHandler) viewer.getHub().get(SceneryElement.INPUT));
ClickBehaviour objectSelector = new ClickBehaviour() {
public void click( int x, int y ) {
System.out.println( "Clicked at x=" + x + " y=" + y );
}
};
viewer.getInputHandler().useDefaultBindings("");
viewer.getInputHandler().addBehaviour("object_selection_mode", objectSelector);
enableArcBallControl();
}
public static void addBox() {
addBox( new GLVector(0.0f, 0.0f, 0.0f) );
}
public static void addBox( GLVector position ) {
addBox( position, new GLVector(10.0f, 10.0f, 10.0f) );
}
public static void addBox( GLVector position, GLVector size ) {
addBox( position, size, new GLVector( 0.9f, 0.9f, 0.9f ) );
}
public static void addBox( GLVector position, GLVector size, GLVector color ) {
Material boxmaterial = new Material();
boxmaterial.setAmbient( new GLVector(1.0f, 0.0f, 0.0f) );
boxmaterial.setDiffuse( color );
boxmaterial.setSpecular( new GLVector(1.0f, 1.0f, 1.0f) );
boxmaterial.setDoubleSided(true);
//boxmaterial.getTextures().put("diffuse", SceneViewer3D.class.getResource("textures/helix.png").getFile() );
final Box box = new Box( size );
box.setMaterial( boxmaterial );
box.setPosition( position );
//System.err.println( "Num elements in scene: " + viewer.getSceneNodes().size() );
viewer.getScene().addChild(box);
if( defaultArcBall ) enableArcBallControl();
//System.err.println( "Num elements in scene: " + viewer.getSceneNodes().size() );
}
public static void addSphere() {
addSphere( new GLVector(0.0f, 0.0f, 0.0f), 1 );
}
public static void addSphere( GLVector position, float radius ) {
addSphere( position, radius, new GLVector( 0.9f, 0.9f, 0.9f ) );
}
public static void addSphere( GLVector position, float radius, GLVector color ) {
Material material = new Material();
material.setAmbient( new GLVector(1.0f, 0.0f, 0.0f) );
material.setDiffuse( color );
material.setSpecular( new GLVector(1.0f, 1.0f, 1.0f) );
//boxmaterial.getTextures().put("diffuse", SceneViewer3D.class.getResource("textures/helix.png").getFile() );
final Sphere sphere = new Sphere( radius, 20 );
sphere.setMaterial( material );
sphere.setPosition( position );
viewer.getScene().addChild(sphere);
if( defaultArcBall ) enableArcBallControl();
}
public static void addPointLight() {
Material material = new Material();
material.setAmbient( new GLVector(1.0f, 0.0f, 0.0f) );
material.setDiffuse( new GLVector(0.0f, 1.0f, 0.0f) );
material.setSpecular( new GLVector(1.0f, 1.0f, 1.0f) );
//boxmaterial.getTextures().put("diffuse", SceneViewer3D.class.getResource("textures/helix.png").getFile() );
final PointLight light = new PointLight();
light.setMaterial( material );
light.setPosition( new GLVector(0.0f, 0.0f, 0.0f) );
viewer.getScene().addChild(light);
}
/* java.nio.FloatBuffer.array version
public static void writeSCMesh( String filename, Mesh scMesh ) {
File f = new File( filename );
BufferedOutputStream out;
try {
out = new BufferedOutputStream( new FileOutputStream( f ) );
out.write( "solid STL generated by FIJI\n".getBytes() );
float[] verts = scMesh.getVertices().array();
float[] norms = scMesh.getNormals().array();
for( int k = 0; k < verts.length/9; k++ ) {
int offset = k * 9;
out.write( ("facet normal " + norms[offset] + " " + norms[offset+1] + " " + norms[offset+2] + "\n").getBytes() );
out.write( "outer loop\n".getBytes() );
for( int v = 0; v < 3; v++ ) {
int voff = v*3;
out.write( ( "vertex\t" + verts[offset+voff] + " " + verts[offset+voff+1] + " " + verts[offset+voff+2] + "\n" ).getBytes() );
}
out.write( "endloop\n".getBytes() );
out.write( "endfacet\n".getBytes() );
}
out.write( "endsolid vcg\n".getBytes() );
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
*/
public static void writeSCMesh( String filename, Mesh scMesh ) {
File f = new File( filename );
BufferedOutputStream out;
try {
out = new BufferedOutputStream( new FileOutputStream( f ) );
out.write( "solid STL generated by FIJI\n".getBytes() );
FloatBuffer normalsFB = scMesh.getNormals();
FloatBuffer verticesFB = scMesh.getVertices();
while( verticesFB.hasRemaining() && normalsFB.hasRemaining() ) {
out.write( ("facet normal " + normalsFB.get() + " " + normalsFB.get() + " " + normalsFB.get() + "\n").getBytes() );
out.write( "outer loop\n".getBytes() );
for( int v = 0; v < 3; v++ ) {
out.write( ( "vertex\t" + verticesFB.get() + " " + verticesFB.get() + " " + verticesFB.get() + "\n" ).getBytes() );
}
out.write( "endloop\n".getBytes() );
out.write( "endfacet\n".getBytes() );
}
out.write( "endsolid vcg\n".getBytes() );
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void addSTL( String filename ) {
Mesh scMesh = new Mesh();
scMesh.readFromSTL( filename );
scMesh.generateBoundingBox();
System.out.println( "Read STL: " + scMesh.getBoundingBox() );
net.imagej.ops.geom.geom3d.mesh.Mesh opsMesh = MeshConverter.getOpsMesh( scMesh );
System.out.println( "Loaded and converted mesh: " + opsMesh.getVertices().size() );
//((DefaultMesh) opsMesh).centerMesh();
addMesh( opsMesh );
}
public static void addObj( String filename ) {
Mesh scMesh = new Mesh();
scMesh.readFromOBJ( filename, false );// Could check if there is a MTL to use to toggle flag
net.imagej.ops.geom.geom3d.mesh.Mesh opsMesh = MeshConverter.getOpsMesh( scMesh );
//((DefaultMesh) opsMesh).centerMesh();
addMesh( opsMesh );
}
public static void addMesh( net.imagej.ops.geom.geom3d.mesh.Mesh mesh ) {
Mesh scMesh = MeshConverter.getSceneryMesh( mesh );
Material material = new Material();
material.setAmbient( new GLVector(1.0f, 0.0f, 0.0f) );
material.setDiffuse( new GLVector(0.0f, 1.0f, 0.0f) );
material.setSpecular( new GLVector(1.0f, 1.0f, 1.0f) );
material.setDoubleSided(true);
scMesh.setMaterial( material );
scMesh.setPosition( new GLVector(1.0f, 1.0f, 1.0f) );
aMesh = scMesh;
viewer.getScene().addChild( scMesh );
if( defaultArcBall ) enableArcBallControl();
// System.err.println( "Number of nodes in scene: " + ThreeDViewer.getSceneNodes().size() );
}
public static void removeMesh( Mesh scMesh ) {
viewer.getScene().removeChild( scMesh );
}
public static Mesh getSelectedMesh() {
return aMesh;
}
public static Thread getAnimationThread() {
return ThreeDViewer.animationThread;
}
public static void setAnimationThread( Thread newAnimator ) {
ThreeDViewer.animationThread = newAnimator;
}
public static void takeScreenshot() {
float[] bounds = viewer.getRenderer().getWindow().getClearglWindow().getBounds();
// if we're in a jpanel, this isn't the way to get bounds
try {
Robot robot = new Robot();
BufferedImage screenshot = robot.createScreenCapture( new Rectangle( (int)bounds[0], (int)bounds[1], (int)bounds[2], (int)bounds[3] ) );
ImagePlus imp = new ImagePlus( "ThreeDViewer_Screenshot", screenshot );
imp.show();
} catch (AWTException e) {
e.printStackTrace();
}
}
public static void enableArcBallControl() {
GLVector target;
if( getSelectedMesh() == null ) {
target = new GLVector( 0, 0, 0 );
} else {
net.imagej.ops.geom.geom3d.mesh.Mesh opsMesh = MeshConverter.getOpsMesh( getSelectedMesh() );
RealLocalizable center = MeshUtils.getCenter(opsMesh);
target = new GLVector( center.getFloatPosition(0), center.getFloatPosition(1), center.getFloatPosition(2) );
}
ArcballCameraControl targetArcball = new ArcballCameraControl("mouse_control", viewer.getScene().findObserver(),
viewer.getRenderer().getWindow().getClearglWindow().getWidth(),
viewer.getRenderer().getWindow().getClearglWindow().getHeight(), target);
targetArcball.setMaximumDistance(Float.MAX_VALUE);
viewer.getInputHandler().addBehaviour("mouse_control", targetArcball);
viewer.getInputHandler().addBehaviour("scroll_arcball", targetArcball);
viewer.getInputHandler().addKeyBinding("scroll_arcball", "scroll");
}
public static void enableFPSControl() {
FPSCameraControl fpsControl = new FPSCameraControl("mouse_control", viewer.getScene().findObserver(),
viewer.getRenderer().getWindow().getClearglWindow().getWidth(),
viewer.getRenderer().getWindow().getClearglWindow().getHeight());
viewer.getInputHandler().addBehaviour("mouse_control", fpsControl);
viewer.getInputHandler().removeBehaviour("scroll_arcball");
}
public static ThreeDViewer getViewer() {
return viewer;
}
public static Node[] getSceneNodes() {
CopyOnWriteArrayList<Node> children = viewer.getScene().getChildren();
return viewer.getScene().getChildren().toArray( new Node[children.size()] );
}
public static void deleteSelectedMesh() {
viewer.getScene().removeChild( ThreeDViewer.getSelectedMesh() );
}
public static void main(String... args)
{
if( ij == null )
ij = new ImageJ();
if( !ij.ui().isVisible() )
ij.ui().showUI();
ThreeDViewer viewer = new ThreeDViewer( "ThreeDViewer", 800, 600 );
viewer.main();
}
} |
package seedu.address.ui;
import java.io.File;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.Scene;
import javafx.scene.control.MenuItem;
import javafx.scene.control.TextInputControl;
import javafx.scene.input.KeyCombination;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.Region;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import seedu.address.commons.core.Config;
import seedu.address.commons.core.GuiSettings;
import seedu.address.commons.events.ui.ExitAppRequestEvent;
import seedu.address.commons.util.FxViewUtil;
import seedu.address.logic.Logic;
import seedu.address.logic.commands.CommandResult;
import seedu.address.logic.commands.exceptions.CommandException;
import seedu.address.model.UserPrefs;
import seedu.address.model.task.ReadOnlyTask;
/**
* The Main Window. Provides the basic application layout containing
* a menu bar and space where other JavaFX elements can be placed.
*/
public class MainWindow extends UiPart<Region> {
private static final String MESSAGE_SUCCESS_SAVE = "File location saved at";
private static final String MESSAGE_SUCCESS_OPEN = " sucessfully loaded!";
private static final String COMMAND_OPEN = "open ";
private static final String COMMAND_SAVE = "save ";
private static final String ICON = "/images/address_book_32.png";
private static final String FXML = "MainWindow.fxml";
private static final int MIN_HEIGHT = 600;
private static final int MIN_WIDTH = 450;
private Stage primaryStage;
private Logic logic;
// Independent Ui parts residing in this Ui container
private TaskListPanel taskListPanel;
private Config config;
private TaskDescription taskDescription;
private TaskDetail taskDetail;
@FXML
private AnchorPane commandBoxPlaceholder;
@FXML
private MenuItem helpMenuItem;
@FXML
private AnchorPane taskListPanelPlaceholder;
@FXML
private AnchorPane resultDisplayPlaceholder;
@FXML
private AnchorPane statusbarPlaceholder;
@FXML
private AnchorPane taskDescriptionPlaceholder;
@FXML
private AnchorPane taskDetailsPlaceholder;
public MainWindow(Stage primaryStage, Config config, UserPrefs prefs, Logic logic) {
super(FXML);
// Set dependencies
this.primaryStage = primaryStage;
this.logic = logic;
this.config = config;
// Configure the UI
setTitle(config.getAppTitle());
setIcon(ICON);
setWindowMinSize();
setWindowDefaultSize(prefs);
Scene scene = new Scene(getRoot());
primaryStage.setScene(scene);
setAccelerators();
}
public Stage getPrimaryStage() {
return primaryStage;
}
private void setAccelerators() {
setAccelerator(helpMenuItem, KeyCombination.valueOf("F1"));
}
/**
* Sets the accelerator of a MenuItem.
* @param keyCombination the KeyCombination value of the accelerator
*/
private void setAccelerator(MenuItem menuItem, KeyCombination keyCombination) {
menuItem.setAccelerator(keyCombination);
getRoot().addEventFilter(KeyEvent.KEY_PRESSED, event -> {
if (event.getTarget() instanceof TextInputControl && keyCombination.match(event)) {
menuItem.getOnAction().handle(new ActionEvent());
event.consume();
}
});
}
public void fillInnerParts() {
taskDescription = new TaskDescription(getTaskDescriptionPlaceholder(), logic);
taskDetail = new TaskDetail(getTaskDetailsPlaceholder(), logic);
taskListPanel = new TaskListPanel(getTaskListPlaceholder(), logic.getFilteredTaskList());
new ResultDisplay(getResultDisplayPlaceholder());
new StatusBarFooter(getStatusbarPlaceholder(), config.getAddressBookFilePath());
new CommandBox(getCommandBoxPlaceholder(), logic);
}
private AnchorPane getCommandBoxPlaceholder() {
return commandBoxPlaceholder;
}
private AnchorPane getStatusbarPlaceholder() {
return statusbarPlaceholder;
}
private AnchorPane getResultDisplayPlaceholder() {
return resultDisplayPlaceholder;
}
private AnchorPane getTaskListPlaceholder() {
return taskListPanelPlaceholder;
}
private AnchorPane getTaskDescriptionPlaceholder() {
return taskDescriptionPlaceholder;
}
private AnchorPane getTaskDetailsPlaceholder() {
return taskDetailsPlaceholder;
}
void hide() {
primaryStage.hide();
}
private void setTitle(String appTitle) {
primaryStage.setTitle(appTitle);
}
/**
* Sets the given image as the icon of the main window.
* @param iconSource e.g. {@code "/images/help_icon.png"}
*/
private void setIcon(String iconSource) {
FxViewUtil.setStageIcon(primaryStage, iconSource);
}
/**
* Sets the default size based on user preferences.
*/
private void setWindowDefaultSize(UserPrefs prefs) {
primaryStage.setHeight(prefs.getGuiSettings().getWindowHeight());
primaryStage.setWidth(prefs.getGuiSettings().getWindowWidth());
if (prefs.getGuiSettings().getWindowCoordinates() != null) {
primaryStage.setX(prefs.getGuiSettings().getWindowCoordinates().getX());
primaryStage.setY(prefs.getGuiSettings().getWindowCoordinates().getY());
}
}
private void setWindowMinSize() {
primaryStage.setMinHeight(MIN_HEIGHT);
primaryStage.setMinWidth(MIN_WIDTH);
}
/**
* Returns the current size and the position of the main Window.
*/
public GuiSettings getCurrentGuiSetting() {
return new GuiSettings(primaryStage.getWidth(), primaryStage.getHeight(),
(int) primaryStage.getX(), (int) primaryStage.getY());
}
@FXML
public void handleHelp() {
HelpWindow helpWindow = new HelpWindow();
helpWindow.show();
}
public void show() {
primaryStage.show();
}
//@@author A0135807A
/**
* Allows the user to select/create a file to save to.
*/
@FXML
public CommandResult handleSaveAs() throws CommandException {
FileChooser fileChooser = new FileChooser();
FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter(
"XML files (*.xml)", "*.xml");
fileChooser.getExtensionFilters().add(extFilter);
File file = fileChooser.showSaveDialog(primaryStage);
logic.execute(COMMAND_SAVE + file.getAbsolutePath());
updateStatusBarFooter();
return new CommandResult(MESSAGE_SUCCESS_SAVE + file.getName());
}
@FXML
public CommandResult handleOpen() throws CommandException {
FileChooser fileChooser = new FileChooser();
FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter(
"XML files (*.xml)", "*.xml");
fileChooser.getExtensionFilters().add(extFilter);
File file = fileChooser.showOpenDialog(primaryStage);
logic.execute(COMMAND_OPEN + file.getAbsolutePath());
updateStatusBarFooter();
return new CommandResult(file.getName() + MESSAGE_SUCCESS_OPEN);
}
public void updateStatusBarFooter() {
new StatusBarFooter(getStatusbarPlaceholder(), config.getAddressBookFilePath());
}
//author
/**
* Closes the application.
*/
@FXML
private void handleExit() {
raise(new ExitAppRequestEvent());
}
public TaskListPanel getTaskListPanel() {
return this.taskListPanel;
}
//@@author A0135807A
public void loadTaskPage(ReadOnlyTask task) {
taskDescription = new TaskDescription(getTaskDescriptionPlaceholder(), logic);
taskDetail = new TaskDetail(getTaskDetailsPlaceholder(), logic);
taskDescription.loadTaskPage(task);
taskDetail.loadTaskPage(task);
}
} |
package starfish.type;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import starfish.helper.Util;
public class TableMetadata implements Serializable {
private static final long serialVersionUID = 1L;
public final String tableName, keyColname, valueColname, versionColname, timestampColname;
public TableMetadata(Map<String, String> names) {
this.tableName = Util.notNull(names.get("tableName"), "tableName must not be null");
this.keyColname = Util.notNull(names.get("keyColname"), "keyColname must not be null");
this.valueColname = Util.notNull(names.get("valueColname"), "valueColname must not be null");
this.versionColname = Util.notNull(names.get("versionColname"), "versionColname must not be null");
this.timestampColname = Util.notNull(names.get("timestampColname"), "timestampColname must not be null");
}
public static TableMetadata create(String tableName) {
Map<String, String> names = new HashMap<String, String>();
names.put("tableName", tableName);
names.put("keyColname", "key");
names.put("valueColname", "value");
names.put("versionColname", "version");
names.put("timestampColname", "updated");
return new TableMetadata(names);
}
public static TableMetadata create(String tableName, String keyColname, String valueColname, String versionColname,
String timestampColname) {
Map<String, String> names = new HashMap<String, String>();
names.put("tableName", tableName);
names.put("keyColname", keyColname);
names.put("valueColname", valueColname);
names.put("versionColname", versionColname);
names.put("timestampColname", timestampColname);
return new TableMetadata(names);
}
public String groovyReplace(String format) {
return Util.groovyReplace(format, toMap(), true);
}
public String groovyReplaceKeep(String format) {
return Util.groovyReplace(format, toMap(), false);
}
public Map<String, String> toMap() {
Map<String, String> result = new HashMap<String, String>();
result.put("tableName", tableName);
result.put("keyColname", keyColname);
result.put("valueColname", valueColname);
result.put("versionColname", versionColname);
result.put("timestampColname", timestampColname);
return result;
}
@Override
public String toString() {
return String.format("tableName=%s, keyColname=%s, valueColname=%s, versionColname=%s, timestampColname=%s",
tableName, keyColname, valueColname, versionColname, timestampColname);
}
@Override
public int hashCode() {
return (tableName + '|' + keyColname + '|' + valueColname + '|' + versionColname + '|' + timestampColname)
.toLowerCase().hashCode();
}
@Override
public boolean equals(Object obj) {
if (obj == null || !(obj instanceof TableMetadata)) {
return false;
}
TableMetadata that = (TableMetadata) obj;
return tableName.equalsIgnoreCase(that.tableName) &&
keyColname.equalsIgnoreCase(that.keyColname) &&
valueColname.equalsIgnoreCase(that.valueColname) &&
versionColname.equalsIgnoreCase(that.versionColname) &&
timestampColname.equalsIgnoreCase(that.timestampColname);
}
} |
package teamasm.moh.block;
import codechicken.lib.tile.IDisplayTickTile;
import codechicken.lib.tile.IGuiTile;
import codechicken.lib.tile.IHarvestTile;
import codechicken.lib.tile.IRotatableTile;
import codechicken.lib.util.ItemUtils;
import codechicken.lib.util.RotationUtils;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import javax.annotation.Nullable;
import java.util.Random;
public class BaseBlock extends Block {
public BaseBlock(Material material) {
super(material);
}
@Override
public void onBlockPlacedBy(World worldIn, BlockPos pos, IBlockState state, EntityLivingBase placer, ItemStack stack) {
TileEntity tileEntity = worldIn.getTileEntity(pos);
if (tileEntity instanceof IRotatableTile) {
IRotatableTile tile = (IRotatableTile) tileEntity;
tile.setRotation(RotationUtils.getPlacedRotationHorizontal(placer));
}
}
@Override
public boolean canSilkHarvest(World world, BlockPos pos, IBlockState state, EntityPlayer player) {
return false;
}
@Override
public void harvestBlock(World worldIn, EntityPlayer player, BlockPos pos, IBlockState state, @Nullable TileEntity te, @Nullable ItemStack stack) {
super.harvestBlock(worldIn, player, pos, state, te, stack);
if (te instanceof IHarvestTile) {
IHarvestTile harvestTile = (IHarvestTile) te;
if (harvestTile.getHarvestItems() != null) {
for (ItemStack harvestStack : harvestTile.getHarvestItems()) {
if (harvestStack != null) {
ItemUtils.dropItem(worldIn, pos, harvestStack);
}
}
}
}
}
@Override
public boolean onBlockActivated(World worldIn, BlockPos pos, IBlockState state, EntityPlayer playerIn, EnumHand hand, @Nullable ItemStack heldItem, EnumFacing side, float hitX, float hitY, float hitZ) {
if (worldIn.isRemote) {
return true;
}
if (!playerIn.isSneaking()) {
TileEntity tileEntity = worldIn.getTileEntity(pos);
if (tileEntity instanceof IGuiTile) {
IGuiTile tile = (IGuiTile) tileEntity;
tile.openGui(worldIn, pos, playerIn);
return true;
}
}
return false;
}
@Override
public void randomDisplayTick(IBlockState state, World worldIn, BlockPos pos, Random rand) {
TileEntity te = worldIn.getTileEntity(pos);
if (te instanceof IDisplayTickTile) {
IDisplayTickTile tile = (IDisplayTickTile) te;
tile.randomDisplayTick(worldIn, pos, state, rand);
}
}
} |
package xpress.storage;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Expression;
import org.hibernate.criterion.Restrictions;
import org.hibernate.impl.SessionImpl;
import org.joda.time.Interval;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import xpress.storage.entity.VoteEntity;
import java.util.List;
/**
* @author sechelc
*/
@Component
@Transactional
public class DBRepository implements Repository {
@Autowired
private SessionFactory sessionFactory;
@Override
public void saveVote(VoteEntity voteEntity) {
Session currentSession = sessionFactory.getCurrentSession();
currentSession.persist(voteEntity);
currentSession.flush();
}
@Override
public List<VoteEntity> getVotes(Filter queryVote) {
Session currentSession = sessionFactory.getCurrentSession();
Criteria criteria = currentSession.createCriteria(VoteEntity.class);
if(!isEmpty(queryVote)){
if (queryVote.getTag() != null) {
criteria.add(Expression.eq("tag", queryVote.getTag()));
}
if (queryVote.getMood() != null) {
criteria.add(Expression.eq("mood", queryVote.getMood()));
}
if (queryVote.getTime() != null) {
Interval interval = Utils.getIntervalFormTimeEnum(queryVote.getTime());
criteria.add(Restrictions.between("time", interval.getStartMillis(), interval.getEndMillis()));
}
return criteria.list();
}else{
return ((SessionImpl)currentSession).find("from VoteEntity");
}
}
private boolean isEmpty(Filter queryVote) {
return queryVote == null? true : !hasTagSet(queryVote) && !hasMoodSet(queryVote) && !hasTimeSet(queryVote);
}
private boolean hasTagSet(Filter queryVote) {
return (queryVote.getTag() != null);
}
private boolean hasMoodSet(Filter queryVote) {
return (queryVote.getMood() != null);
}
private boolean hasTimeSet(Filter queryVote) {
return (queryVote.getTime() != null);
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
} |
package mondrian.olap;
import mondrian.util.PropertiesPlus;
import org.apache.log4j.Logger;
import javax.servlet.ServletContext;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.ref.WeakReference;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Enumeration;
import java.util.Collections;
import java.util.Map;
import java.util.HashMap;
import java.util.Properties;
import java.util.ArrayList;
import java.util.ListIterator;
import java.util.Iterator;
import java.util.List;
/**
* <code>MondrianProperties</code> contains the properties which determine the
* behavior of a mondrian instance.
*
* <p>There is a method for property valid in a
* <code>mondrian.properties</code> file. Although it is possible to retrieve
* properties using the inherited {@link Properties#getProperty(String)}
* method, we recommend that you use methods in this class.
*
* <p>If you wish to be notified of changes to properties, use
* {@link #addTrigger(mondrian.olap.MondrianProperties.Trigger, String)}
* method to register a callback.
*
* @author jhyde
* @since 22 December, 2002
* @version $Id$
**/
public class MondrianProperties extends PropertiesPlus {
private static final Logger LOGGER =
Logger.getLogger(MondrianProperties.class);
/**
* Properties, drawn from {@link System#getProperties}, plus the contents
* of "mondrian.properties" if it exists. A singleton.
*/
private static MondrianProperties instance;
private static final String mondrianDotProperties = "mondrian.properties";
private static final String buildDotProperties = "build.properties";
public static synchronized MondrianProperties instance() {
if (instance == null) {
instance = new MondrianProperties();
instance.populate(null);
}
return instance;
}
/**
* A Trigger is a callback which allows a subscriber to be notified
* when a property value changes.
*
* <p>If the user wishes to be able to remove a Trigger at some time after
* it has been added, then either 1) the user has to keep the instance of
* the Trigger that was added and use it when calling the remove method or
* 2) the Trigger must implement the equals method and the Trigger used
* during the call to the remove method must be equal to the original
* Trigger added.
* <p>
* Each non-persistent Trigger is wrapped in a {@link WeakReference}, so
* that is can be garbage-collected. But this means that
* the user had better keep a reference to the Trigger, otherwise
* it will be removed (garbage collected) without the user knowing.
* <p>
* Persistent Triggers (those that refer to objects in their
* {@link #executeTrigger} method that will never be garbage-collected) are
* not wrapped in a WeakReference.
* <p>
* What does all this mean, well, objects that might be garbage collected
* that create a Trigger must keep a reference to the Trigger (otherwise the
* Trigger will be garbage-collected out from under the object). A common
* usage pattern is to implement the Trigger interface using an anonymous
* class - anonymous classes are non-static classes when created in an
* instance object. But, remember, the anonymous class instance holds a
* reference to the outer instance object but not the other way around; the
* instance object does not have an implicit reference to the anonymous
* class instance - the reference must be explicit. And, if the anonymous
* Trigger is created with the isPersistent method returning true, then,
* surprise, the outer instance object will never be garbage collected!!!
* <p>
* Note that it is up to the creator of MondrianProperties Triggers to make
* sure that they are ordered correctly. This is done by either having
* order independent Triggers (they all have the same phase) or by
* assigning phases to the Triggers where primaries execute before
* secondary which execute before tertiary.
* <p>
* If a finer level of execution order granularity is needed, then the
* implementation should be changed so that the {@link #phase} method
* returns just some integer and it's up to the users to coordinate their
* values.
*/
public interface Trigger {
int PRIMARY_PHASE = 1;
int SECONDARY_PHASE = 2;
int TERTIARY_PHASE = 3;
public static class VetoRT extends RuntimeException {
public VetoRT(String msg) {
super(msg);
}
public VetoRT(Exception ex) {
super(ex);
}
}
/**
* An Entry is associated with a property key. Each Entry can have one
* or more Triggers. Each Trigger is stored in a WeakReference so that
* when the the Trigger is only reachable via weak referencs the Trigger
* will be be collected and the contents of the WeakReference
* will be set to null.
*/
public static class Entry {
private ArrayList triggerList;
Entry() {
triggerList = new ArrayList();
}
/**
* Add a Trigger wrapping it in a WeakReference.
*
* @param trigger
*/
void add(final Trigger trigger) {
// this is the object to add to list
Object o = (trigger.isPersistent())
? trigger : (Object) new WeakReference(trigger);
// Add a Trigger in the correct group of phases in the list
for (ListIterator it = triggerList.listIterator();
it.hasNext(); ) {
Trigger t = convert(it.next());
if (t == null) {
it.remove();
} else if (trigger.phase() < t.phase()) {
// add it before
it.hasPrevious();
it.add(o);
return;
} else if (trigger.phase() == t.phase()) {
// add it after
it.add(o);
return;
}
}
triggerList.add(o);
}
/**
* Remove the given Trigger.
* In addition, any WeakReference that is empty are removed.
*
* @param trigger
*/
void remove(final Trigger trigger) {
for (Iterator it = triggerList.iterator(); it.hasNext(); ) {
Trigger t = convert(it.next());
if (t == null) {
it.remove();
} else if (t.equals(trigger)) {
it.remove();
}
}
}
/**
* Returns true if there are no Trigger in this Entry.
*
* @return true it there are no Triggers.
*/
boolean isEmpty() {
return triggerList.isEmpty();
}
/**
* Execute all Triggers in this Entry passing in the property
* key whose change was the casue.
* In addition, any WeakReference that is empty are removed.
*
* @param key
*/
void execute(final String key,
final String value) throws VetoRT {
// Make a copy so that if during the execution of a trigger a
// Trigger is added or removed, we do not get a concurrent
// modification exception. We do an explicit copy (rather than
// a clone) so that we can remove any WeakReference whose
// content has become null.
List l = new ArrayList();
for (Iterator it = triggerList.iterator(); it.hasNext(); ) {
Trigger t = convert(it.next());
if (t == null) {
it.remove();
} else {
l.add(t);
}
}
for (Iterator it = l.iterator(); it.hasNext(); ) {
Trigger t = (Trigger) it.next();
t.executeTrigger(key, value);
}
}
private Trigger convert(Object o) {
if (o instanceof WeakReference) {
o = ((WeakReference) o).get();
}
return (Trigger) o;
}
}
/**
* If a Trigger is associated with a class or singleton, then it should
* return true because its associated object is not subject to garbage
* collection. On the other hand, if a Trigger is associated with an
* object which will be garbage collected, then this method must return
* false so that the Trigger will be wrapped in a WeakReference and
* thus can itself be garbage collected.
*
* @return
*/
boolean isPersistent();
/**
* Which phase does this Trigger belong to.
*
* @return
*/
int phase();
/**
* Execute the Trigger passing in the key of the property whose change
* triggered the execution.
*
* @param key
*/
void executeTrigger(final String key, final String value) throws VetoRT;
}
private int populateCount;
private Map triggers;
public MondrianProperties() {
triggers = Collections.EMPTY_MAP;
}
/**
* Add a {@link Trigger} associating it with the parameter property key.
*
* @param trigger
* @param key
*/
public void addTrigger(Trigger trigger, String key) {
if (triggers == Collections.EMPTY_MAP) {
triggers = new HashMap();
}
Trigger.Entry e = (Trigger.Entry) triggers.get(key);
if (e == null) {
e = new Trigger.Entry();
triggers.put(key, e);
}
e.add(trigger);
}
/**
* Removes the {@link Trigger}, if any, that is associated with property
* key.
*
* @param trigger
* @param key
*/
public void removeTrigger(Trigger trigger, String key) {
Trigger.Entry e = (Trigger.Entry) triggers.get(key);
if (e != null) {
e.remove(trigger);
if (e.isEmpty()) {
triggers.remove(key);
}
}
}
/**
* Sets the value of a property.
*
* <p>If the previous value does not equal the new value, executes any
* {@link Trigger}s associated with the property, in order of their
* {@link mondrian.olap.MondrianProperties.Trigger#phase() phase}.
*
* @param key
* @param value
* @return the old value
*/
public synchronized Object setProperty(
final String key, final String value) {
String oldValue = getPropertyValueReflect(key);
Object object = super.setProperty(key, value);
if (oldValue == null) {
oldValue = (object == null) ? null : object.toString();
}
// If we have changed the value of a property, then call all of the
// property's associated Triggers (if any).
if (! Util.equals(oldValue, value) && getEnableTriggers()) {
Trigger.Entry e = (Trigger.Entry) triggers.get(key);
if (e != null) {
try {
e.execute(key, value);
} catch (Trigger.VetoRT vex) {
// Reset to the old value, do not call setProperty
// unless you want to run out of stack space
superSetProperty(key, oldValue);
try {
e.execute(key, oldValue);
} catch (Trigger.VetoRT ex) {
// ignore during reset
}
throw vex;
}
}
}
return oldValue;
}
/**
* This is ONLY called during a veto
* operation. It calls the super class {@link #setProperty}.
*
* @param key
* @param oldValue
*/
private void superSetProperty(String key, String oldValue) {
if (oldValue != null) {
super.setProperty(key, oldValue);
}
}
/**
* Gets property value for given propertyName parameter by using reflection
* on the {@link MondrianProperties} class. Returns null if there are any
* exceptions or the field name prepended with "get" does not match the
* method name.
*
* @param propertyName
* @return
*/
public String getPropertyValueReflect(String propertyName) {
try {
String fieldName = null;
Field[] fields = MondrianProperties.class.getFields();
for (int i = 0; i < fields.length; i++) {
Field field = fields[i];
if (field.getType() != String.class) {
continue;
}
String v = (String) field.get(MondrianProperties.class);
if (Util.equals(v, propertyName)) {
fieldName = field.getName();
break;
}
}
if (fieldName != null) {
String methodName = "get" + fieldName;
Method m = MondrianProperties.class.getMethod(methodName, null);
if (m != null) {
Object o =
m.invoke(MondrianProperties.instance(), new Object[0]);
if (o != null) {
return o.toString();
}
}
}
} catch (Exception ex) {
// ignore
}
return null;
}
/**
* Loads this property set from: the file "mondrian.properties" (if it
* exists); the "mondrian.properties" in the JAR (if we're in a servlet);
* and from the system properties.
*
* @param servletContext May be null
*/
public void populate(ServletContext servletContext) {
// Read properties file "mondrian.properties", if it exists.
File file = new File(mondrianDotProperties);
if (file.exists()) {
try {
URL url = Util.toURL(file);
load(url);
// For file-based installations (i.e. testing), load any overrides from
// build.properties.
file = new File(buildDotProperties);
if (file.exists()) {
url = Util.toURL(file);
load(url);
}
} catch (MalformedURLException e) {
LOGGER.error("Mondrian: file '"
+ file.getAbsolutePath()
+ "' could not be loaded ("
+ e
+ ")");
}
} else if (populateCount == 0 && false) {
LOGGER.warn("Mondrian: Warning: file '"
+ file.getAbsolutePath()
+ "' not found");
}
// If we're in a servlet, read "mondrian.properties" from WEB-INF
// directory.
if (servletContext != null) {
try {
final URL resourceUrl = servletContext.getResource(
"/WEB-INF/" + mondrianDotProperties);
if (resourceUrl != null) {
load(resourceUrl);
}
else if (populateCount == 0 && false) {
LOGGER.warn("Mondrian: Warning: servlet resource '"
+ mondrianDotProperties
+ "' not found");
}
} catch (MalformedURLException e) {
LOGGER.error("Mondrian: '" + mondrianDotProperties
+ "' could not be loaded from servlet context ("
+ e
+ ")");
}
}
// copy in all system properties which start with "mondrian."
int count = 0;
for (Enumeration keys = System.getProperties().keys();
keys.hasMoreElements(); ) {
String key = (String) keys.nextElement();
String value = System.getProperty(key);
if (key.startsWith("mondrian.")) {
// NOTE: the super allows us to bybase calling triggers
// Is this the correct behavior?
super.setProperty(key, value);
count++;
}
}
if (populateCount++ == 0) {
LOGGER.info("Mondrian: loaded "
+ count
+ " system properties");
}
}
/**
* Tries to load properties from a URL. Does not fail, just prints success
* or failure to {@link System#out}.
*/
private void load(final URL url) {
try {
load(url.openStream());
if (populateCount == 0) {
LOGGER.info("Mondrian: properties loaded from '"
+ url
+ "'");
}
} catch (IOException e) {
LOGGER.error("Mondrian: error while loading properties "
+ "from '"
+ url
+ "' ("
+ e
+ ")");
}
}
/**
* Retrieves the value of the {@link #QueryLimit} property,
* default value {@link #QueryLimit_Default}.
*/
public int getQueryLimit() {
return getIntProperty(QueryLimit, QueryLimit_Default);
}
/** Property {@value}. */
public static final String QueryLimit = "mondrian.query.limit";
/** Value is {@value}. */
public static final int QueryLimit_Default = 40;
/** Retrieves the value of the {@link #TraceLevel} property. */
public int getTraceLevel() {
return getIntProperty(TraceLevel);
}
/** Property {@value}. */
public static final String TraceLevel = "mondrian.trace.level";
/** Property {@value}. */
public static final String DebugOutFile = "mondrian.debug.out.file";
/** Retrieves the value of the {@link #JdbcDrivers} property,
* default value {@link #JdbcDrivers_Default}. */
public String getJdbcDrivers() {
return getProperty(JdbcDrivers, JdbcDrivers_Default);
}
/** Property {@value}. */
public static final String JdbcDrivers = "mondrian.jdbcDrivers";
/** Values is {@value}. */
public static final String JdbcDrivers_Default =
"sun.jdbc.odbc.JdbcOdbcDriver,"
+ "org.hsqldb.jdbcDriver,"
+ "oracle.jdbc.OracleDriver,"
+ "com.mysql.jdbc.Driver";
/** Retrieves the value of the {@link #ResultLimit} property. */
public int getResultLimit() {
return getIntProperty(ResultLimit, 0);
}
/** Property {@value}. */
public static final String ResultLimit = "mondrian.result.limit";
// mondrian.rolap properties
/** Retrieves the value of the {@link #CachePoolCostLimit} property,
* default value {@link #CachePoolCostLimit_Default}. */
public int getCachePoolCostLimit() {
return getIntProperty(CachePoolCostLimit, CachePoolCostLimit_Default);
}
/** Property {@value}. */
public static final String CachePoolCostLimit = "mondrian.rolap.CachePool.costLimit";
/** Value is {@value}. */
public static final int CachePoolCostLimit_Default = 10000;
/** Retrieves the value of the {@link #PrintCacheablesAfterQuery} property. */
public boolean getPrintCacheablesAfterQuery() {
return getBooleanProperty(PrintCacheablesAfterQuery);
}
/** Property {@value}. */
public static final String PrintCacheablesAfterQuery =
"mondrian.rolap.RolapResult.printCacheables";
/** Retrieves the value of the {@link #FlushAfterQuery} property. */
public boolean getFlushAfterQuery() {
return getBooleanProperty(FlushAfterQuery);
}
/** Property {@value}. */
public static final String FlushAfterQuery =
"mondrian.rolap.RolapResult.flushAfterEachQuery";
// mondrian.test properties
/**
* Retrieves the value of the {@link #TestName} property.
* This is a regular expression as defined by
* {@link java.util.regex.Pattern}.
* If this property is specified, only tests whose names match the pattern
* in its entirety will be run.
*
* @see #getTestClass
*/
public String getTestName() {
return getProperty(TestName);
}
/** Property {@value}. */
public static final String TestName = "mondrian.test.Name";
/**
* Retrieves the value of the {@link #TestClass} property. This is the
* name of the class which either implements {@link junit.framework.Test},
* or has a method <code>public [static] {@link junit.framework.Test}
* suite()</code>.
* @see #getTestName
*/
public String getTestClass() {
return getProperty(TestClass);
}
/** Property {@value}. */
public static final String TestClass = "mondrian.test.Class";
/** Retrieves the value of the {@link #TestConnectString} property. */
public String getTestConnectString() {
return getProperty(TestConnectString);
}
/** Property {@value} */
public static final String TestConnectString =
"mondrian.test.connectString";
// miscellaneous
/**
* Retrieves the value of the {@link #JdbcURL} property.
* The {@link #JdbcURL_Default default value} connects to an ODBC data
* source.
*/
public String getFoodmartJdbcURL() {
return getProperty(JdbcURL, JdbcURL_Default);
}
/** Property {@value}. */
public static final String JdbcURL = "mondrian.foodmart.jdbcURL";
/** Value is {@value}. */
public static final String JdbcURL_Default = "jdbc:odbc:MondrianFoodMart";
/**
* Retrieves the value of the {@link #LargeDimensionThreshold} property.
* If a dimension has more than this number of members, use a
* smart member reader (see {@link mondrian.rolap.SmartMemberReader}).
* Default is {@link #LargeDimensionThreshold_Default}.
*/
public int getLargeDimensionThreshold() {
return getIntProperty(LargeDimensionThreshold, LargeDimensionThreshold_Default);
}
/** Property {@value}. */
public static final String LargeDimensionThreshold =
"mondrian.rolap.LargeDimensionThreshold";
/** Value is {@value}. */
public static final int LargeDimensionThreshold_Default = 100;
/**
* Retrieves the value of the {@link #SparseSegmentCountThreshold} property.
* When storing collections of cell values, we have to choose between a
* sparse and a dense representation, based upon the <code>possible</code>
* and <code>actual</code> number of values.
* The <code>density</code> is <code>actual / possible</code>.
* We use a sparse representation if
* <code>possible -
* {@link #getSparseSegmentCountThreshold countThreshold} *
* actual >
* {@link #getSparseSegmentDensityThreshold densityThreshold}</code>
*
* <p>The default values are
* {@link #SparseSegmentCountThreshold countThreshold} =
* {@link #SparseSegmentCountThreshold_Default},
* {@link #SparseSegmentDensityThreshold} =
* {@link #SparseSegmentDensityThreshold_Default}.
*
* <p>At these default values, we use a dense representation
* for (1000 possible, 0 actual), or (2000 possible, 500 actual), or
* (3000 possible, 1000 actual). Any fewer actual values, or any more
* possible values, and we will use a sparse representation.
*/
public int getSparseSegmentCountThreshold() {
return getIntProperty(SparseSegmentCountThreshold, SparseSegmentCountThreshold_Default);
}
/** Property {@value}. */
public static final String SparseSegmentCountThreshold =
"mondrian.rolap.SparseSegmentValueThreshold";
/** Value is {@value}. */
public static final int SparseSegmentCountThreshold_Default = 1000;
/** Retrieves the value of the {@link #SparseSegmentDensityThreshold} property.
* @see #getSparseSegmentCountThreshold */
public double getSparseSegmentDensityThreshold() {
return getDoubleProperty(SparseSegmentDensityThreshold, SparseSegmentDensityThreshold_Default);
}
/** Property {@value}. */
public static final String SparseSegmentDensityThreshold =
"mondrian.rolap.SparseSegmentDensityThreshold";
/** Value is {@value}. */
public static final double SparseSegmentDensityThreshold_Default = 0.5;
public static final String QueryFilePattern =
"mondrian.test.QueryFilePattern";
public String getQueryFilePattern() {
return getProperty(QueryFilePattern);
}
public static final String QueryFileDirectory =
"mondrian.test.QueryFileDirectory";
public String getQueryFileDirectory() {
return getProperty(QueryFileDirectory);
}
public static final String Iterations = "mondrian.test.Iterations";
public static final int Iterations_Default = 1;
public int getIterations() {
return getIntProperty(Iterations, Iterations_Default);
}
public static final String VUsers = "mondrian.test.VUsers";
public static final int VUsers_Default = 1;
public int getVUsers() {
return getIntProperty(VUsers, VUsers_Default);
}
public static final String TimeLimit = "mondrian.test.TimeLimit";
public static final int TimeLimit_Default = 0;
/** Returns the time limit for the test run in seconds. If the test is
* running after that time, it is terminated. */
public int getTimeLimit() {
return getIntProperty(TimeLimit, TimeLimit_Default);
}
public static final String Warmup = "mondrian.test.Warmup";
public boolean getWarmup() {
return getBooleanProperty(Warmup);
}
/**
* Retrieves the URL of the catalog to be used by
* {@link mondrian.tui.CmdRunner} and XML/A Test.
*/
public String getCatalogURL() {
return getProperty("mondrian.catalogURL");
}
/**
* Sets the catalog URL. Writes to {@link System#getProperties()}.
*/
public void setCatalogURL() {
}
/** Property {@value}. */
public static final String CatalogUrl = "mondrian.catalogURL";
// properties relating to aggregates
/**
* Name of boolean property that controls whether or not aggregates
* should be used. If true, then aggregates are used. This property is
* queried prior to each aggregate query so that changing the value of this
* property dynamically (not just at startup) is meaningful.
*/
public static final String UseAggregates = "mondrian.rolap.aggregates.Use";
/**
* Should aggregates be used.
*
* @return true if aggregates are to be used.
*/
public boolean getUseAggregates() {
return getBooleanProperty(UseAggregates);
}
/**
* Name of boolean property that controls whether or not aggregate tables
* are ordered by their volume or row count.
*/
public static final String ChooseAggregateByVolume
= "mondrian.rolap.aggregates.ChooseByVolume";
/**
* Should aggregate tables be ordered by volume.
*
* @return true if aggregate tables are to be ordered by volume.
*/
public boolean getChooseAggregateByVolume() {
return getBooleanProperty(ChooseAggregateByVolume);
}
/**
* This is a String property which can be either a resource in the
* Mondrian jar or a URL.
*/
public static final String AggregateRules
= "mondrian.rolap.aggregates.rules";
/**
* The default value of the AggRules property, a resource in Mondrian jar.
* DefaultRules.xml is in mondrian.rolap.aggmatcher
*
*/
public static final String AggregateRules_Default = "DefaultRules.xml";
/**
* Get the value of the AggregateRules property which returns the
* default value, AggregateRules_Default, if not set.
* <p>
* Normally, this property is not set by a user.
*
* @return
*/
public String getAggregateRules() {
return getProperty(AggregateRules, AggregateRules_Default);
}
/**
* This is a String property which is the AggRule element's tag value.
*/
public static final String AggregateRuleTag
= "mondrian.rolap.aggregates.rule.tag";
/**
* The default value of the AggRule element tag value.
*/
public static final String AggregateRuleTag_Default = "default";
/**
* Get the value of the AggRule element tag property which returns the
* default value, AggregateRuleTag_Default, if not set.
* <p>
* Normally, this property is not set by a user.
*
* @return
*/
public String getAggregateRuleTag() {
return getProperty(AggregateRuleTag, AggregateRuleTag_Default);
}
/**
* This is the boolean property that controls whether or not triggers are
* executed when a MondrianProperty changes.
*/
public static final String EnableTriggers = "mondrian.olap.triggers.enable";
/**
* Returns true means that MondrianProperties Triggers are enabled.
*
* @return
*/
public boolean getEnableTriggers() {
return getBooleanProperty(EnableTriggers);
}
/**
* This is a boolean property if set to true, the all SqlQuery sql string
* will be generated in pretty-print mode, formatted for ease of reading.
*/
public static final String GenerateFormattedSql =
"mondrian.rolap.generate.formatted.sql";
public boolean getGenerateFormattedSql() {
return getBooleanProperty(GenerateFormattedSql);
}
}
// End MondrianProperties.java |
package net.hillsdon.svnwiki.vc;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import junit.framework.AssertionFailedError;
import org.tmatesoft.svn.core.SVNException;
import org.tmatesoft.svn.core.SVNProperty;
import org.tmatesoft.svn.core.io.ISVNEditor;
import org.tmatesoft.svn.core.io.SVNRepository;
import org.tmatesoft.svn.core.io.diff.SVNDeltaGenerator;
import org.tmatesoft.svn.core.wc.SVNRevision;
/**
* Stores pages in an SVN repository.
*
* @author mth
*/
public class SVNPageStore implements PageStore {
/**
* The assumed encoding of files from the repository.
*/
private static final String UTF8 = "UTF8";
private final SVNRepository _repository;
/**
* Note the repository URL can be deep, it need not refer to
* the root of the repository itself. We put pages in the root
* of what we're given.
*/
public SVNPageStore(final SVNRepository repository) {
_repository = repository;
}
public PageInfo get(final String path) throws PageStoreException {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
HashMap<String, String> properties = new HashMap<String, String>();
_repository.getFile(path, SVNRevision.HEAD.getNumber(), properties, baos);
long revision = Long.parseLong(properties.get(SVNProperty.REVISION));
return new PageInfo(toUTF8(baos.toByteArray()), revision);
}
catch (SVNException ex) {
throw new PageStoreException(ex);
}
}
public void set(final String path, final long baseRevision, final String content) throws PageStoreException {
try {
ISVNEditor commitEditor = _repository.getCommitEditor("[automated commit]", null);
modifyFile(commitEditor, path, baseRevision, fromUTF8(content));
commitEditor.closeEdit();
}
catch (SVNException ex) {
throw new PageStoreException(ex);
}
}
private void modifyFile(final ISVNEditor commitEditor, final String filePath, final long baseRevision, final byte[] newData) throws SVNException {
commitEditor.openRoot(-1);
commitEditor.openFile(filePath, baseRevision);
commitEditor.applyTextDelta(filePath, null);
SVNDeltaGenerator deltaGenerator = new SVNDeltaGenerator();
// We don't keep the base around so we can't provide it here.
String checksum = deltaGenerator.sendDelta(filePath, new ByteArrayInputStream(newData), commitEditor, true);
commitEditor.closeFile(filePath, checksum);
commitEditor.closeDir();
}
private static String toUTF8(byte[] bytes) {
try {
return new String(bytes, UTF8);
}
catch (UnsupportedEncodingException e) {
throw new AssertionFailedError("Java supports UTF8.");
}
}
private static byte[] fromUTF8(String string) {
try {
return string.getBytes(UTF8);
}
catch (UnsupportedEncodingException e) {
throw new AssertionFailedError("Java supports UTF8.");
}
}
} |
package com.arover.moment;
import java.security.InvalidParameterException;
import java.util.Calendar;
/**
* @author arover
* created at 8/26/16 23:32
*/
public class Editor {
private Moment mMoment;
private Calendar mCalendar;
public Editor(Moment moment) {
mMoment = moment;
mCalendar = moment.getCalendar();
}
/**
* add x unit to moment.
*
* @param x 0-n
* @param unit time unit
*/
private void set(int x, int unit) {
switch (unit) {
case MomentUnit.YEAR: {
int year = mCalendar.get(Calendar.YEAR);
mCalendar.set(Calendar.YEAR, year + x);
break;
}
case MomentUnit.MONTH: {
int months = x % 12;
int year = x / 12;
int month = mCalendar.get(Calendar.MONTH);
if (month + x > Calendar.DECEMBER) {
mCalendar.set(Calendar.YEAR, mCalendar.get(Calendar.YEAR) + 1);
mCalendar.set(Calendar.MONTH, (month + x) % 11);
} else if (month + x < Calendar.JANUARY) {
mCalendar.set(Calendar.YEAR, mCalendar.get(Calendar.YEAR) - 1);
mCalendar.set(Calendar.MONTH, (month + x) % 11);
} else {
mCalendar.set(Calendar.MONTH, (month + x));
}
break;
}
case MomentUnit.DAY:
mCalendar.add(Calendar.DAY_OF_YEAR, x);
break;
case MomentUnit.HOUR:
mCalendar.add(Calendar.HOUR, x);
break;
case MomentUnit.MINUTE:
mCalendar.add(Calendar.MINUTE, x);
break;
case MomentUnit.SECOND:
mCalendar.add(Calendar.SECOND, x);
break;
case MomentUnit.MILISECOND:
mCalendar.add(Calendar.MILLISECOND, x);
break;
}
}
public void add(int n, int unit) {
set(n, unit);
}
/**
* minux x int time unit.
*
* @param n the amount to minus to the field
* @param unit time field/unit.
*/
public void minus(int n, int unit) {
set(-n, unit);
}
public void setFirstDayOfWeek(DayOfWeek dayOfWeek) {
// mFirstDayOfWeek = dayOfWeek;
}
public void setMillisecond(long timeInMillis) {
if (timeInMillis < 0)
throw new InvalidParameterException("can't millisecond to " + timeInMillis);
mCalendar.setTimeInMillis(timeInMillis);
}
public void setSecond(int sec) {
if (sec < 0 || sec > 59)
throw new InvalidParameterException("can't sec second to " + sec);
mCalendar.set(Calendar.SECOND, sec);
}
public void setMinute(int min) {
if (min < 0 || min > 59)
throw new InvalidParameterException("can't sec minute to " + min);
mCalendar.set(Calendar.MINUTE, min);
}
/**
* @param hour [0,23]
*/
public void setHour(int hour) {
if (hour < 0 || hour > 23)
throw new InvalidParameterException("can't sec hour to " + hour);
mCalendar.set(Calendar.HOUR_OF_DAY, hour);
}
public void setDayOfMonth(int day) {
if (day < 0 || day > 23)
throw new InvalidParameterException("can't sec minute to " + day);
mCalendar.set(Calendar.DAY_OF_MONTH, day);
}
public void setMonth(Month month) {
mCalendar.set(Calendar.MONTH, month.ordinal());
}
/**
* @param month [Calendar.JANUARY,Calendar.DECEMBER]
*/
public void setMonth(int month) {
mCalendar.set(Calendar.MONTH, month);
}
public Moment setBeginningOfDay() {
Util.setTimeToBeginningOfDay(mCalendar);
return mMoment;
}
public Moment setEndOfDay() {
Util.setTimeToEndOfDay(mCalendar);
return mMoment;
}
} |
// S i g R e d u c e r //
// <editor-fold defaultstate="collapsed" desc="hdr">
// This program is free software: you can redistribute it and/or modify it under the terms of the
// </editor-fold>
package org.audiveris.omr.sig;
import org.audiveris.omr.constant.ConstantSet;
import org.audiveris.omr.glyph.Shape;
import org.audiveris.omr.glyph.ShapeSet;
import static org.audiveris.omr.glyph.ShapeSet.Accidentals;
import static org.audiveris.omr.glyph.ShapeSet.CoreBarlines;
import static org.audiveris.omr.glyph.ShapeSet.Flags;
import org.audiveris.omr.math.GeoOrder;
import org.audiveris.omr.math.GeoUtil;
import org.audiveris.omr.sheet.Part;
import org.audiveris.omr.sheet.Scale;
import org.audiveris.omr.sheet.Staff;
import org.audiveris.omr.sheet.SystemInfo;
import org.audiveris.omr.sheet.header.StaffHeader;
import org.audiveris.omr.sheet.rhythm.Measure;
import org.audiveris.omr.sheet.rhythm.SystemBackup;
import org.audiveris.omr.sig.inter.AbstractBeamInter;
import org.audiveris.omr.sig.inter.AbstractChordInter;
import org.audiveris.omr.sig.inter.AbstractNoteInter;
import org.audiveris.omr.sig.inter.AbstractTimeInter;
import org.audiveris.omr.sig.inter.AlterInter;
import org.audiveris.omr.sig.inter.AugmentationDotInter;
import org.audiveris.omr.sig.inter.BarlineInter;
import org.audiveris.omr.sig.inter.BeamHookInter;
import org.audiveris.omr.sig.inter.BeamInter;
import org.audiveris.omr.sig.inter.DeletedInterException;
import org.audiveris.omr.sig.inter.HeadInter;
import org.audiveris.omr.sig.inter.Inter;
import org.audiveris.omr.sig.inter.InterEnsemble;
import org.audiveris.omr.sig.inter.KeyAlterInter;
import org.audiveris.omr.sig.inter.LedgerInter;
import org.audiveris.omr.sig.inter.SlurInter;
import org.audiveris.omr.sig.inter.SmallBeamInter;
import org.audiveris.omr.sig.inter.StemInter;
import org.audiveris.omr.sig.inter.StringSymbolInter;
import org.audiveris.omr.sig.inter.TimeNumberInter;
import org.audiveris.omr.sig.inter.TupletInter;
import org.audiveris.omr.sig.inter.WordInter;
import org.audiveris.omr.sig.relation.AbstractConnection;
import org.audiveris.omr.sig.relation.AlterHeadRelation;
import org.audiveris.omr.sig.relation.AugmentationRelation;
import org.audiveris.omr.sig.relation.BeamHeadRelation;
import org.audiveris.omr.sig.relation.BeamPortion;
import org.audiveris.omr.sig.relation.BeamStemRelation;
import org.audiveris.omr.sig.relation.DoubleDotRelation;
import org.audiveris.omr.sig.relation.Exclusion;
import org.audiveris.omr.sig.relation.HeadHeadRelation;
import org.audiveris.omr.sig.relation.HeadStemRelation;
import org.audiveris.omr.sig.relation.Relation;
import org.audiveris.omr.sig.relation.StemPortion;
import static org.audiveris.omr.sig.relation.StemPortion.*;
import org.audiveris.omr.sig.relation.TimeTopBottomRelation;
import org.audiveris.omr.util.HorizontalSide;
import static org.audiveris.omr.util.HorizontalSide.*;
import org.audiveris.omr.util.Navigable;
import org.audiveris.omr.util.Predicate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.geom.Line2D;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.EnumMap;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.SortedMap;
public class SigReducer
{
private static final Constants constants = new Constants();
private static final Logger logger = LoggerFactory.getLogger(SigReducer.class);
/** Shapes for which overlap detection is (currently) disabled. */
private static final EnumSet<Shape> disabledShapes = EnumSet.copyOf(
Arrays.asList(Shape.LEDGER, Shape.CRESCENDO, Shape.DIMINUENDO));
/** Predicate for non-disabled overlap. */
private static final Predicate<Inter> overlapPredicate = new Predicate<Inter>()
{
@Override
public boolean check (Inter inter)
{
// Take all non-disabled shapes
// Excluding inters within headers
return !disabledShapes.contains(inter.getShape());
}
};
/** Shapes that can overlap with a beam. */
private static final EnumSet<Shape> beamCompShapes = EnumSet.copyOf(CoreBarlines);
/** Shapes that can overlap with a slur. */
private static final EnumSet<Shape> slurCompShapes = EnumSet.noneOf(Shape.class);
static {
slurCompShapes.addAll(Accidentals.getShapes());
slurCompShapes.addAll(CoreBarlines);
slurCompShapes.addAll(Flags.getShapes());
}
/** Shapes that can overlap with a stem. */
private static final EnumSet<Shape> stemCompShapes = EnumSet.copyOf(
Arrays.asList(Shape.SLUR, Shape.CRESCENDO, Shape.DIMINUENDO));
/** Standard vs Small size. */
private static enum Size
{
STANDARD,
SMALL;
}
/** The dedicated system. */
@Navigable(false)
private final SystemInfo system;
/** Scale. */
@Navigable(false)
private final Scale scale;
/** The related SIG. */
private final SIGraph sig;
/** Should we purge weak inter instances?. */
private final boolean purgeWeaks;
/**
* Creates a new {@code SigReducer} object.
*
* @param system the related system
* @param purgeWeaks true for purging weak inters
*/
public SigReducer (SystemInfo system,
boolean purgeWeaks)
{
this.system = system;
this.purgeWeaks = purgeWeaks;
sig = system.getSig();
scale = system.getSheet().getScale();
}
// reduceFoundations //
/**
* Reduce all the interpretations and relations of the SIG, on the founding inters
* (Heads, Stems and Beams).
* This is meant for the REDUCTION step.
*/
public void reduceFoundations ()
{
reduce(new AdapterForFoundations());
}
// reduceLinks //
/**
* Final global reduction.
* This is meant for the LINKS step.
*/
public void reduceLinks ()
{
reduce(new AdapterForLinks());
}
// reduceRhythms //
/**
* NOT USED!
* Reduce interpretations while saving reduced rhythm data.
* This is meant for the RHYTHMS step.
*
* @param systemPoorFrats (output) where selected inters must be backed up
* @param classes FRAT classes
*/
@Deprecated
public void reduceRhythms (SystemBackup systemPoorFrats,
Class<?>... classes)
{
AdapterForRhythms adapter = new AdapterForRhythms(systemPoorFrats, classes);
Set<Inter> allRemoved = reduce(adapter);
allRemoved.retainAll(adapter.selected);
systemPoorFrats.setSeeds(allRemoved);
}
// analyzeChords //
/**
* Analyze consistency of note heads & beams attached to a (good) stem.
* <ul>
* <li>All (standard) black, all (standard) void, all small black or all small void.
* <li>All (standard) beams or all small beams.
* <li>(standard) beams with (standard) heads only.
* <li>Small beams with small heads only.
* </ul>
*/
private void analyzeChords ()
{
// All stems of the sig
List<Inter> stems = sig.inters(Shape.STEM);
// Heads organized by shape (black, void, and small versions)
Map<Shape, Set<Inter>> heads = new HashMap<Shape, Set<Inter>>();
// Beams organized by size (standard vs small versions)
Map<Size, Set<Inter>> beams = new EnumMap<Size, Set<Inter>>(Size.class);
for (Inter stem : stems) {
if (stem.isVip()) {
logger.info("VIP analyzeChords with {}", stem);
}
// Consider only good stems
if (!stem.isGood()) {
continue;
}
heads.clear();
beams.clear();
// Populate the various head & beam classes around this stem
for (Relation rel : sig.edgesOf(stem)) {
if (rel instanceof HeadStemRelation) {
Inter head = sig.getEdgeSource(rel);
Shape shape = head.getShape();
Set<Inter> set = heads.get(shape);
if (set == null) {
heads.put(shape, set = new LinkedHashSet<Inter>());
}
set.add(head);
} else if (rel instanceof BeamStemRelation) {
Inter beam = sig.getEdgeSource(rel);
Size size = (beam instanceof SmallBeamInter) ? Size.SMALL : Size.STANDARD;
Set<Inter> set = beams.get(size);
if (set == null) {
beams.put(size, set = new LinkedHashSet<Inter>());
}
set.add(beam);
}
}
// Mutual head exclusion based on head shape
// But perhaps the joining stem is the problem, so check the two conflicting heads
// are not linked to any other stem than the one at hand.
List<Shape> headShapes = new ArrayList<Shape>(heads.keySet());
for (int ic = 0; ic < (headShapes.size() - 1); ic++) {
Shape c1 = headShapes.get(ic);
Set<Inter> set1 = heads.get(c1);
for (Inter h1 : set1) {
HeadInter head1 = (HeadInter) h1;
if (head1.getStems().size() == 1) {
for (Shape c2 : headShapes.subList(ic + 1, headShapes.size())) {
Set<Inter> set2 = heads.get(c2);
for (Inter h2 : set2) {
HeadInter head2 = (HeadInter) h2;
if (head2.getStems().size() == 1) {
sig.insertExclusion(h1, h2, Exclusion.Cause.INCOMPATIBLE);
}
}
}
}
}
}
// Mutual head support within same shape
for (Shape shape : heads.keySet()) {
List<Inter> list = new ArrayList<Inter>(heads.get(shape));
for (int i = 0; i < list.size(); i++) {
HeadInter h1 = (HeadInter) list.get(i);
for (Inter other : list.subList(i + 1, list.size())) {
HeadInter h2 = (HeadInter) other;
sig.insertSupport(h1, h2, HeadHeadRelation.class);
}
}
}
// Mutual beam exclusion based on beam size
List<Size> beamSizes = new ArrayList<Size>(beams.keySet());
for (int ic = 0; ic < (beamSizes.size() - 1); ic++) {
Size c1 = beamSizes.get(ic);
Set<Inter> set1 = beams.get(c1);
for (Size c2 : beamSizes.subList(ic + 1, beamSizes.size())) {
Set<Inter> set2 = beams.get(c2);
exclude(set1, set2);
}
}
// Head/Beam support or exclusion based on size
for (Entry<Size, Set<Inter>> entry : beams.entrySet()) {
Size size = entry.getKey();
Set<Inter> beamSet = entry.getValue();
if (size == Size.SMALL) {
// Small beams exclude standard heads
for (Shape shape : new Shape[]{Shape.NOTEHEAD_BLACK, Shape.NOTEHEAD_VOID}) {
Set<Inter> headSet = heads.get(shape);
if (headSet != null) {
exclude(beamSet, headSet);
}
}
// Small beams support small black heads
Set<Inter> smallHeadSet = heads.get(Shape.NOTEHEAD_BLACK_SMALL);
if (smallHeadSet != null) {
for (Inter smallBeam : beamSet) {
BeamStemRelation bs = (BeamStemRelation) sig.getRelation(
smallBeam,
stem,
BeamStemRelation.class);
for (Inter smallHead : smallHeadSet) {
if (sig.getRelation(smallBeam, smallHead, BeamHeadRelation.class) == null) {
// Use average of beam-stem and head-stem relation grades
HeadStemRelation hs = (HeadStemRelation) sig.getRelation(
smallHead,
stem,
HeadStemRelation.class);
double grade = (bs.getGrade() + hs.getGrade()) / 2;
sig.addEdge(smallBeam, smallHead, new BeamHeadRelation(grade));
}
}
}
}
} else {
// Standard beams exclude small heads
Set<Inter> smallHeadSet = heads.get(Shape.NOTEHEAD_BLACK_SMALL);
if (smallHeadSet != null) {
exclude(beamSet, smallHeadSet);
}
// Standard beams support black heads (not void)
Set<Inter> blackHeadSet = heads.get(Shape.NOTEHEAD_BLACK);
if (blackHeadSet != null) {
for (Inter beam : beamSet) {
BeamStemRelation bs = (BeamStemRelation) sig.getRelation(
beam,
stem,
BeamStemRelation.class);
for (Inter head : blackHeadSet) {
if (sig.getRelation(beam, head, BeamHeadRelation.class) == null) {
// Use average of beam-stem and head-stem relation grades
HeadStemRelation hs = (HeadStemRelation) sig.getRelation(
head,
stem,
HeadStemRelation.class);
double grade = (bs.getGrade() + hs.getGrade()) / 2;
sig.addEdge(beam, head, new BeamHeadRelation(grade));
}
}
}
}
}
}
}
}
// analyzeFrozenInters //
/**
* Browse all the frozen inters and simply delete any inter that conflicts with them.
*/
private void analyzeFrozenInters ()
{
Set<Inter> toDelete = new LinkedHashSet<Inter>();
for (Inter inter : sig.vertexSet()) {
if (inter.isFrozen()) {
for (Relation rel : sig.getRelations(inter, Exclusion.class)) {
Inter other = sig.getOppositeInter(inter, rel);
if (other.isFrozen()) {
logger.error("Conflicting frozen inters {} & {}", inter, other);
} else {
toDelete.add(other);
if (other.isVip()) {
logger.info("VIP deleting {} conflicting with frozen {}", other, inter);
}
}
}
}
}
sig.deleteInters(toDelete);
}
// analyzeHeadStems //
/**
* Check any head has at most one stem on left side and one stem on right side.
* If not, the various stems on a same side are mutually exclusive.
*/
private void analyzeHeadStems ()
{
final List<Inter> heads = sig.inters(ShapeSet.StemHeads);
for (Inter hi : heads) {
HeadInter head = (HeadInter) hi;
// Retrieve connected stems into left and right sides
Map<HorizontalSide, Set<StemInter>> map = head.getSideStems();
// Check each side
for (Entry<HorizontalSide, Set<StemInter>> entry : map.entrySet()) {
Set<StemInter> set = entry.getValue();
if (set.size() > 1) {
//////////////////////////////////////////////////HB sig.insertExclusions(set, Exclusion.Cause.OVERLAP);
//TODO:
// Instead of stem exclusion, we should disconnect head from some of these stems
// Either all the stems above or all the stems below
}
}
}
}
// beamHasBothStems //
private boolean beamHasBothStems (BeamInter beam)
{
boolean hasLeft = false;
boolean hasRight = false;
// if (beam.isVip()) {
// logger.info("VIP beamHasBothStems for {}", beam);
for (Relation rel : sig.edgesOf(beam)) {
if (rel instanceof BeamStemRelation) {
BeamStemRelation bsRel = (BeamStemRelation) rel;
BeamPortion portion = bsRel.getBeamPortion();
if (portion == BeamPortion.LEFT) {
hasLeft = true;
} else if (portion == BeamPortion.RIGHT) {
hasRight = true;
}
}
}
return hasLeft && hasRight;
}
// checkAugmentationDots //
/**
* Perform checks on augmentation dots.
* <p>
* An augmentation dot needs a target to augment (note, rest or another augmentation dot).
*
* @return the count of modifications done
*/
private int checkAugmentationDots ()
{
int modifs = 0;
final List<Inter> dots = sig.inters(AugmentationDotInter.class);
DotLoop:
for (Inter inter : dots) {
final AugmentationDotInter dot = (AugmentationDotInter) inter;
// Look for a target head or rest
if (sig.hasRelation(dot, AugmentationRelation.class)) {
continue;
}
// Look for a target dot on left side
final int dotCenterX = dot.getCenter().x;
for (Relation rel : sig.getRelations(dot, DoubleDotRelation.class)) {
Inter opposite = sig.getOppositeInter(dot, rel);
if (opposite.getCenter().x < dotCenterX) {
continue DotLoop;
}
}
if (dot.isVip() || logger.isDebugEnabled()) {
logger.info("Deleting {} lacking target", dot);
}
dot.delete();
modifs++;
}
return modifs;
}
// checkAugmented //
/**
* Perform checks on augmented entities.
* <p>
* An entity (note, rest or augmentation dot) can have at most one augmentation dot.
* <p>
* NOTA: This is OK for rests but not always for heads.
* TODO: We could address head-chords rather than individual heads and handle the chord
* augmentation dots as a whole (in parallel with chord heads) and link each chord head with its
* 'facing' dot.
*
* @return the count of modifications done
*/
private int checkAugmented ()
{
int modifs = 0;
List<Inter> entities = sig.inters(AbstractNoteInter.class);
for (Inter entity : entities) {
Set<Relation> rels = sig.getRelations(entity, AugmentationRelation.class);
if (rels.size() > 1) {
modifs += reduceAugmentations(rels);
if (entity.isVip() || logger.isDebugEnabled()) {
logger.info("Reduced augmentations for {}", entity);
}
}
}
return modifs;
}
// checkBeams //
/**
* Perform checks on beams.
*
* @return the count of modifications done
*/
private int checkBeams ()
{
int modifs = 0;
final List<Inter> beams = sig.inters(BeamInter.class);
for (Inter inter : beams) {
final BeamInter beam = (BeamInter) inter;
if (!beamHasBothStems(beam)) {
if (beam.isVip() || logger.isDebugEnabled()) {
logger.info("VIP deleting beam lacking stem {}", beam);
}
beam.delete();
modifs++;
}
}
return modifs;
}
// checkDoubleAlters //
/**
* Perform checks on double alterations (double sharp or double flat).
* They need a note head nearby.
*
* @return the count of modifications done
*/
private int checkDoubleAlters ()
{
int modifs = 0;
final List<Inter> doubles = sig.inters(
Arrays.asList(Shape.DOUBLE_FLAT, Shape.DOUBLE_SHARP));
for (Inter inter : doubles) {
final AlterInter alter = (AlterInter) inter;
// Check whether the double-alter is connected to a note head
if (!sig.hasRelation(alter, AlterHeadRelation.class)) {
if (alter.isVip() || logger.isDebugEnabled()) {
logger.info("VIP deleting {} lacking note head", alter);
}
alter.delete();
modifs++;
}
}
return modifs;
}
// checkHeadSide //
/**
* If head is on the wrong side of the stem, check if there is a head on the other
* side, located one or two step(s) further.
* <p>
* If the side is wrong and there is no head on the other side, simply remove this head-stem
* relation and insert exclusion instead.
*
* @param head the head inter (black or void)
* @return the number of modifications done
*/
private int checkHeadSide (Inter head)
{
if (head.isVip()) {
logger.info("VIP checkHeadSide for {}", head);
}
int modifs = 0;
// Check all connected stems
Set<Relation> stemRels = sig.getRelations(head, HeadStemRelation.class);
RelsLoop:
for (Relation relation : stemRels) {
HeadStemRelation rel = (HeadStemRelation) relation;
StemInter stem = (StemInter) sig.getEdgeTarget(rel);
// What is the stem direction? (up: dir < 0, down: dir > 0, unknown: 0)
int dir = stem.computeDirection();
if (dir == 0) {
if (stem.isVip()) {
logger.info("VIP deleting {} with no correct head on either end", stem);
}
stem.delete();
modifs++;
continue;
}
// Side is normal?
HorizontalSide headSide = rel.getHeadSide();
if (((headSide == LEFT) && (dir > 0)) || ((headSide == RIGHT) && (dir < 0))) {
continue; // It's OK
}
// Pitch of the note head
int pitch = ((HeadInter) head).getIntegerPitch();
// Target side and target pitches of other head
// Look for presence of head on other side with target pitch
HorizontalSide targetSide = headSide.opposite();
for (int targetPitch = pitch - 1; targetPitch <= (pitch + 1); targetPitch++) {
if (stem.lookupHead(targetSide, targetPitch) != null) {
continue RelsLoop;
}
}
// We have a bad head+stem couple, so let's remove the relationship
if (head.isVip() || logger.isDebugEnabled()) {
logger.info("VIP wrong side for {} on {}", head, stem);
}
sig.removeEdge(rel);
sig.insertExclusion(head, stem, Exclusion.Cause.INCOMPATIBLE);
modifs++;
}
return modifs;
}
// checkHeads //
/**
* Perform checks on heads.
*
* @return the count of modifications done
*/
private int checkHeads ()
{
int modifs = 0;
final List<Inter> heads = sig.inters(ShapeSet.StemHeads);
for (Inter head : heads) {
if (head.isVip()) {
logger.info("VIP checkheads for {}", head);
}
// Check if the head has a stem relation
if (!sig.hasRelation(head, HeadStemRelation.class)) {
if (head.isVip() || logger.isDebugEnabled()) {
logger.info("VIP no stem for {}", head);
}
head.delete();
modifs++;
continue;
}
// Check head location relative to stem
modifs += checkHeadSide(head);
}
return modifs;
}
// checkHooks //
/**
* Perform checks on hooks.
*
* @return the count of modifications done
*/
private int checkHooks ()
{
int modifs = 0;
final List<Inter> inters = sig.inters(BeamHookInter.class);
for (Inter inter : inters) {
// Check if the hook has a stem relation
if (!sig.hasRelation(inter, BeamStemRelation.class)) {
if (inter.isVip() || logger.isDebugEnabled()) {
logger.info("VIP no stem for {}", inter);
}
inter.delete();
}
}
return modifs;
}
// checkIsolatedAlters //
/**
* Perform checks on isolated alterations.
* <p>
* An isolated (not head-related) alter should be allowed only in some cases:
* <ul>
* <li>turn sign
* <li>part of stand-alone key signature
* <li>key signature cancel in cautionary measure
* </ul>
* They are discarded if there is no relation with a nearby head (or ).
* TODO: rework this when stand-alone key signatures are supported.
*
* @return the count of modifications done
*/
private int checkIsolatedAlters ()
{
int modifs = 0;
final List<Inter> alters = sig.inters(ShapeSet.Accidentals.getShapes());
for (Inter inter : alters) {
if (inter instanceof KeyAlterInter) {
continue; // Don't consider alters within a key-sig
}
final AlterInter alter = (AlterInter) inter;
// Connected to a note head?
if (sig.hasRelation(alter, AlterHeadRelation.class)) {
continue;
}
// Within a cautionary measure?
Point center = inter.getCenter();
Staff staff = alter.getStaff();
if (staff == null) {
List<Staff> stavesAround = system.getStavesAround(center); // 1 or 2 staves
staff = stavesAround.get(0);
}
Part part = staff.getPart();
Measure measure = part.getMeasureAt(center);
if ((measure != null)
&& (measure == part.getLastMeasure())
&& (measure.getBarline(HorizontalSide.RIGHT) == null)) {
// Empty measure?
// Measure width?
continue;
}
if (alter.isVip() || logger.isDebugEnabled()) {
logger.info("VIP deleting isolated {}", alter);
}
alter.delete();
modifs++;
}
return modifs;
}
// checkLedgers //
/**
* Perform checks on ledger.
*
* @return the count of modifications done
*/
private int checkLedgers ()
{
// All system note heads, sorted by abscissa
List<Inter> allHeads = sig.inters(ShapeSet.Heads);
Collections.sort(allHeads, Inter.byAbscissa);
final List<LedgerInter> toDelete = new ArrayList<LedgerInter>();
boolean modified;
do {
modified = false;
for (Staff staff : system.getStaves()) {
SortedMap<Integer, List<LedgerInter>> map = staff.getLedgerMap();
// Need a set copy to avoid concurrent modifications
Set<Entry<Integer, List<LedgerInter>>> setCopy;
setCopy = new LinkedHashSet<Entry<Integer, List<LedgerInter>>>(map.entrySet());
for (Entry<Integer, List<LedgerInter>> entry : setCopy) {
int index = entry.getKey();
// Need a list copy to avoid concurrent modifications
List<LedgerInter> ledgersCopy = new ArrayList<LedgerInter>(entry.getValue());
for (LedgerInter ledger : ledgersCopy) {
if (!ledgerHasHeadOrLedger(staff, index, ledger, allHeads)) {
if (ledger.isVip() || logger.isDebugEnabled()) {
logger.info("VIP deleting orphan ledger {}", ledger);
}
ledger.delete();
modified = true;
}
}
}
}
} while (modified);
if (!toDelete.isEmpty()) {
for (LedgerInter ledger : toDelete) {
ledger.delete(); // This updates the ledgerMap in relevant staves
}
}
return toDelete.size();
}
// checkSlurOnTuplet //
/**
* Detect and remove a small slur around a tuplet sign.
*
* @return the slurs removed
*/
private Set<Inter> checkSlurOnTuplet ()
{
Set<Inter> deleted = new LinkedHashSet<Inter>();
final int maxSlurWidth = scale.toPixels(constants.maxTupletSlurWidth);
final List<Inter> slurs = sig.inters(
new Predicate<Inter>()
{
@Override
public boolean check (Inter inter)
{
return !inter.isDeleted() && (inter instanceof SlurInter)
&& (inter.getBounds().width <= maxSlurWidth);
}
});
final List<Inter> tuplets = sig.inters(
new Predicate<Inter>()
{
@Override
public boolean check (Inter inter)
{
return !inter.isDeleted() && (inter instanceof TupletInter)
&& (inter.isContextuallyGood());
}
});
for (Inter slurInter : slurs) {
final SlurInter slur = (SlurInter) slurInter;
// Look for a tuplet sign embraced
final int above = slur.isAbove() ? 1 : (-1);
Rectangle box = slur.getBounds();
box.translate(0, above * box.height);
for (Inter tuplet : tuplets) {
if (box.intersects(tuplet.getBounds())) {
if (slur.isVip() || logger.isDebugEnabled()) {
logger.info("VIP deleting tuplet-slur {}", slur);
}
slur.delete();
deleted.add(slur);
break;
}
}
}
return deleted;
}
// checkStemEndingHeads //
/**
* Perform checks on correct side for ending heads of stems.
*
* @return the count of modifications done
*/
private int checkStemEndingHeads ()
{
int modifs = 0;
final List<Inter> stems = sig.inters(Shape.STEM);
for (Inter inter : stems) {
final StemInter stem = (StemInter) inter;
// Cut links to ending heads on wrong stem side
if (pruneStemHeads(stem)) {
modifs++;
}
}
return modifs;
}
// checkStemLengths //
/**
* Perform checks on stem length from tail to closest head anchor.
*
* @return the count of modifications done
*/
private int checkStemLengths ()
{
final int minStemExtension = scale.toPixels(constants.minStemExtension);
final List<Inter> stems = sig.inters(Shape.STEM);
int modifs = 0;
for (Inter inter : stems) {
final StemInter stem = (StemInter) inter;
final Rectangle stemBox = stem.getBounds();
Rectangle headsBox = null;
for (Relation rel : sig.getRelations(stem, HeadStemRelation.class)) {
final HeadInter head = (HeadInter) sig.getOppositeInter(stem, rel);
final Rectangle headBox = head.getBounds();
if (headsBox == null) {
headsBox = headBox;
} else {
headsBox.add(headBox);
}
}
if (headsBox == null) {
stem.delete();
modifs++;
} else {
final int above = headsBox.y - stemBox.y;
final int below = (stemBox.y + stemBox.height) - (headsBox.y + headsBox.height);
final int extension = Math.max(above, below);
if (extension < minStemExtension) {
stem.delete();
modifs++;
}
}
}
return modifs;
}
// checkStems //
/**
* Perform checks on stems.
*
* @return the count of modifications done
*/
private int checkStems ()
{
int modifs = 0;
final List<Inter> stems = sig.inters(Shape.STEM);
for (Inter inter : stems) {
final StemInter stem = (StemInter) inter;
if (!stemHasHeadAtEnd(stem)) {
if (stem.isVip() || logger.isDebugEnabled()) {
logger.info("VIP deleting stem lacking starting head {}", stem);
}
stem.delete();
modifs++;
continue;
}
if (!stemHasSingleHeadEnd(stem)) {
modifs++;
}
}
return modifs;
}
// checkTimeNumbers //
/**
* Perform checks on time numbers.
*
* @return the count of modifications done
*/
private int checkTimeNumbers ()
{
int modifs = 0;
final List<Inter> numbers = sig.inters(TimeNumberInter.class);
for (Inter inter : numbers) {
final TimeNumberInter number = (TimeNumberInter) inter;
// Check this number has a sibling number
if (!sig.hasRelation(number, TimeTopBottomRelation.class)) {
if (number.isVip() || logger.isDebugEnabled()) {
logger.info("VIP deleting time number lacking sibling {}", number);
}
number.delete();
modifs++;
}
}
return modifs;
}
// checkTimeSignatures //
/**
* Perform checks on time signatures.
* <p>
* Check there is no note between measure start and time signature, otherwise insert exclusion.
*/
private void checkTimeSignatures ()
{
List<Inter> systemNotes = sig.inters(AbstractNoteInter.class);
if (systemNotes.isEmpty()) {
return;
}
final List<Inter> systemTimes = sig.inters(AbstractTimeInter.class);
Collections.sort(systemNotes, Inter.byAbscissa);
for (Staff staff : system.getStaves()) {
List<Inter> staffTimes = SIGraph.inters(staff, systemTimes);
if (staffTimes.isEmpty()) {
continue;
}
List<Inter> notes = SIGraph.inters(staff, systemNotes);
for (Inter inter : staffTimes) {
AbstractTimeInter timeSig = (AbstractTimeInter) inter;
// Position WRT Notes in staff
int notePrev = -2 - Collections.binarySearch(notes, timeSig, Inter.byAbscissa);
if (notePrev != -1) {
// Position WRT Bars in staff
List<BarlineInter> bars = staff.getBars();
int barPrev = -2
- Collections.binarySearch(
bars,
timeSig,
Inter.byAbscissa);
int xMin = (barPrev != -1) ? bars.get(barPrev).getCenter().x : 0;
for (int i = notePrev; i >= 0; i
Inter note = notes.get(i);
if (note.getCenter().x < xMin) {
break;
}
if (timeSig.isVip() || note.isVip() || logger.isDebugEnabled()) {
logger.info("VIP {} preceding {}", note, timeSig);
}
sig.insertExclusion(note, timeSig, Exclusion.Cause.INCOMPATIBLE);
}
}
}
}
}
// compatible //
/**
* Check whether the two provided Inter instance can overlap.
*
* @param inters array of exactly 2 instances
* @return true if overlap is accepted, false otherwise
*/
private static boolean compatible (Inter[] inters)
{
for (int i = 0; i <= 1; i++) {
Inter inter = inters[i];
Inter other = inters[1 - i];
if (inter instanceof AbstractBeamInter) {
if (other instanceof AbstractBeamInter) {
return true;
}
if (beamCompShapes.contains(other.getShape())) {
return true;
}
} else if (inter instanceof SlurInter) {
if (slurCompShapes.contains(other.getShape())) {
return true;
}
} else if (inter instanceof StemInter) {
if (stemCompShapes.contains(other.getShape())) {
return true;
}
}
}
return false;
}
// wordMatchesSymbol //
/**
* Check whether the word and the symbol might represent the same thing, after all.
*
* @param wordInter text word
* @param symbol symbol
*/
private static boolean wordMatchesSymbol (WordInter wordInter,
StringSymbolInter symbol)
{
logger.debug("Comparing {} and {}", wordInter, symbol);
final String symbolString = symbol.getSymbolString();
if (wordInter.getValue().equalsIgnoreCase(symbolString)) {
logger.debug("Math found");
//TODO: Perhaps more checks on word/sentence?
return true;
}
return false;
}
// detectOverlaps //
/**
* Detect all cases where 2 Inters actually overlap and, if there is no support
* relation between them, insert a mutual exclusion.
* <p>
* This method is key!
*
* @param inters the collection of inters to process
*/
private void detectOverlaps (List<Inter> inters,
Adapter adapter)
{
Collections.sort(inters, Inter.byAbscissa);
NextLeft:
for (int i = 0, iBreak = inters.size() - 1; i < iBreak; i++) {
Inter left = inters.get(i);
if (left.isDeleted()) {
continue;
}
final Rectangle leftBox = left.getBounds();
Set<Inter> mirrors = null;
final Inter leftMirror = left.getMirror();
if (leftMirror != null) {
mirrors = new LinkedHashSet<Inter>();
mirrors.add(leftMirror);
if (left.getEnsemble() != null) {
AbstractChordInter leftChord = (AbstractChordInter) left.getEnsemble();
Inter leftChordMirror = leftChord.getMirror();
if (leftChordMirror != null) {
mirrors.add(leftChordMirror);
mirrors.addAll(((AbstractChordInter) leftChordMirror).getNotes());
}
} else if (leftMirror instanceof AbstractChordInter) {
mirrors.addAll(((AbstractChordInter) leftMirror).getNotes());
}
}
final double xMax = leftBox.getMaxX();
for (Inter right : inters.subList(i + 1, inters.size())) {
if (right.isDeleted()) {
continue;
}
// Mirror entities do not exclude one another
if ((mirrors != null) && mirrors.contains(right)) {
continue;
}
// Overlap is accepted in some cases
if (compatible(new Inter[]{left, right})) {
continue;
}
Rectangle rightBox = right.getBounds();
if (leftBox.intersects(rightBox)) {
// Have a more precise look
if (left.isVip() && right.isVip()) {
logger.info("VIP check overlap {} vs {}", left, right);
}
try {
if (left.overlaps(right) && right.overlaps(left)) {
// Specific case: Word vs "string" Symbol
if (left instanceof WordInter && right instanceof StringSymbolInter) {
if (wordMatchesSymbol((WordInter) left, (StringSymbolInter) right)) {
left.decrease(0.5);
}
} else if (left instanceof StringSymbolInter
&& right instanceof WordInter) {
if (wordMatchesSymbol((WordInter) right, (StringSymbolInter) left)) {
right.decrease(0.5);
}
}
exclude(left, right);
}
} catch (DeletedInterException diex) {
if (diex.inter == left) {
continue NextLeft;
}
}
} else if (rightBox.x > xMax) {
break; // Since inters list is sorted by abscissa
}
}
}
}
// exclude //
/**
* Insert exclusion between (the members of) the 2 sets.
*
* @param set1 one set
* @param set2 the other set
*/
private void exclude (Set<Inter> set1,
Set<Inter> set2)
{
for (Inter i1 : set1) {
for (Inter i2 : set2) {
sig.insertExclusion(i1, i2, Exclusion.Cause.INCOMPATIBLE);
}
}
}
// exclude //
private void exclude (Inter left,
Inter right)
{
// Special overlap case between a stem and a standard-size note head
if ((left instanceof StemInter && right instanceof HeadInter
&& !right.getShape().isSmall())
|| (right instanceof StemInter && left instanceof HeadInter && !left.getShape().isSmall())) {
return;
}
// If there is no support between left & right, insert an exclusion
final SIGraph leftSig = left.getSig();
if (leftSig.noSupport(left, right)) {
leftSig.insertExclusion(left, right, Exclusion.Cause.OVERLAP);
}
}
// getHeadersInters //
/**
* Collect inters that belong to staff headers in this system.
*
* @return the headers inters
*/
private List<Inter> getHeadersInters ()
{
List<Inter> inters = new ArrayList<Inter>();
for (Staff staff : system.getStaves()) {
StaffHeader header = staff.getHeader();
if (header.clef != null) {
inters.add(header.clef);
}
if (header.key != null) {
inters.add(header.key);
inters.addAll(header.key.getMembers());
}
if (header.time != null) {
inters.add(header.time);
if (header.time instanceof InterEnsemble) {
inters.addAll(((InterEnsemble) header.time).getMembers());
}
}
}
logger.debug("S#{} headers inters: {}", system.getId(), inters);
return inters;
}
// ledgerHasHeadOrLedger //
/**
* Check if the provided ledger has either a note head centered on it
* (or one step further) or another ledger just further.
*
* @param staff the containing staff
* @param index the ledger line index
* @param ledger the ledger to check
* @param allHeads the abscissa-ordered list of heads in the system
* @return true if OK
*/
private boolean ledgerHasHeadOrLedger (Staff staff,
int index,
LedgerInter ledger,
List<Inter> allHeads)
{
Rectangle ledgerBox = ledger.getBounds();
ledgerBox.grow(0, scale.getInterline()); // Very high box, but that's OK
// Check for another ledger on next line
int nextIndex = index + Integer.signum(index);
List<LedgerInter> nextLedgers = staff.getLedgers(nextIndex);
if (nextLedgers != null) {
for (LedgerInter nextLedger : nextLedgers) {
// Check abscissa compatibility
if (GeoUtil.xOverlap(ledgerBox, nextLedger.getBounds()) > 0) {
return true;
}
}
}
// Else, check for a note centered on ledger, or just on next pitch
final int ledgerPitch = Staff.getLedgerPitchPosition(index);
final int nextPitch = ledgerPitch + Integer.signum(index);
final List<Inter> heads = sig.intersectedInters(allHeads, GeoOrder.BY_ABSCISSA, ledgerBox);
for (Inter inter : heads) {
final HeadInter head = (HeadInter) inter;
final int notePitch = head.getIntegerPitch();
if ((notePitch == ledgerPitch) || (notePitch == nextPitch)) {
return true;
}
}
return false;
}
// pruneStemHeads //
/**
* Cut links between the provided stem and its ending head(s) on wrong side.
*
* @param stem the stem to process
* @return true if one or several heads were pruned from the stem
*/
private boolean pruneStemHeads (StemInter stem)
{
if (stem.isVip()) {
// logger.info("VIP pruneStemHeads for {}", stem);
}
final Set<Relation> links = sig.getRelations(stem, HeadStemRelation.class);
int modifs = 0;
boolean modified;
StemGeometryScan:
do {
modified = false;
final Line2D stemLine = stem.computeExtendedLine(); // Update geometry
for (Relation rel : links) {
// Retrieve the stem portion for this Head -> Stem link
HeadInter head = (HeadInter) sig.getEdgeSource(rel);
HeadStemRelation link = (HeadStemRelation) rel;
StemPortion portion = link.getStemPortion(head, stemLine, scale);
HorizontalSide headSide = link.getHeadSide();
if (((portion == STEM_BOTTOM) && (headSide != RIGHT))
|| ((portion == STEM_TOP) && (headSide != LEFT))) {
sig.removeEdge(rel);
links.remove(rel);
modifs++;
modified = true;
if (stem.isVip() || head.isVip() || logger.isDebugEnabled()) {
logger.info("VIP pruned {} from {}", head, stem);
}
continue StemGeometryScan;
}
}
} while (modified);
return modifs > 0;
}
// reduce //
/**
* Reduce all the interpretations and relations of the SIG.
*
* @return the collection of removed inters
*/
private Set<Inter> reduce (Adapter adapter)
{
final Set<Inter> allRemoved = new LinkedHashSet<Inter>();
logger.debug("S#{} reducing sig ...", system.getId());
// General exclusions based on overlap
List<Inter> inters = sig.inters(overlapPredicate);
inters.removeAll(getHeadersInters());
detectOverlaps(inters, adapter);
// Inters that conflict with frozen inters must be deleted
adapter.checkFrozens();
// Make sure all inters have their contextual grade up-to-date
sig.contextualize();
adapter.prolog();
Set<Inter> reduced = new LinkedHashSet<Inter>(); // Reduced inters
Set<Inter> deleted = new LinkedHashSet<Inter>(); // Deleted inters
do {
reduced.clear();
deleted.clear();
// First, remove all inters with too low contextual grade
deleted.addAll(updateAndPurge());
deleted.addAll(adapter.checkSlurs());
allRemoved.addAll(deleted);
int modifs; // modifications done in current iteration
while ((modifs = adapter.checkConsistencies()) > 0) {
logger.debug("S#{} modifs: {}", system.getId(), modifs);
}
// Remaining exclusions
reduced.addAll(sig.reduceExclusions());
allRemoved.addAll(reduced);
while ((modifs = adapter.checkLateConsistencies()) > 0) {
logger.debug("S#{} late modifs: {}", system.getId(), modifs);
}
logger.debug("S#{} reductions: {}", system.getId(), reduced);
} while (!reduced.isEmpty() || !deleted.isEmpty());
return allRemoved;
}
// reduceAugmentations //
/**
* Reduce the number of augmentation relations to one.
*
* @param rels the augmentation links for the same entity
* @return the number of relation deleted
*/
private int reduceAugmentations (Set<Relation> rels)
{
int modifs = 0;
// Simply select the relation with best grade
double bestGrade = 0;
AbstractConnection bestLink = null;
for (Relation rel : rels) {
AbstractConnection link = (AbstractConnection) rel;
double grade = link.getGrade();
if (grade > bestGrade) {
bestGrade = grade;
bestLink = link;
}
}
for (Relation rel : rels) {
if (rel != bestLink) {
sig.removeEdge(rel);
modifs++;
}
}
return modifs;
}
// stemHasHeadAtEnd //
/**
* Check if the stem has at least a head at some end.
*
* @param stem the stem inter
* @return true if OK
*/
private boolean stemHasHeadAtEnd (StemInter stem)
{
if (stem.isVip()) {
// logger.info("VIP stemHasHeadAtEnd for {}", stem);
}
final Line2D stemLine = stem.computeExtendedLine();
for (Relation rel : sig.getRelations(stem, HeadStemRelation.class)) {
// Check stem portion
HeadStemRelation hsRel = (HeadStemRelation) rel;
Inter head = sig.getOppositeInter(stem, rel);
if (hsRel.getStemPortion(head, stemLine, scale) != STEM_MIDDLE) {
return true;
}
}
return false;
}
// stemHasSingleHeadEnd //
/**
* Check if the stem does not have heads at both ends.
* <p>
* If heads are found at the "tail side" of the stem, their relations to the stem are removed.
*
* @param stem the stem inter
* @return true if OK
*/
private boolean stemHasSingleHeadEnd (StemInter stem)
{
final Line2D stemLine = stem.computeExtendedLine();
final int stemDir = stem.computeDirection();
if (stemDir == 0) {
return true; // We cannot decide
}
final StemPortion forbidden = (stemDir > 0) ? STEM_BOTTOM : STEM_TOP;
final List<Relation> toRemove = new ArrayList<Relation>();
for (Relation rel : sig.getRelations(stem, HeadStemRelation.class)) {
// Check stem portion
HeadStemRelation hsRel = (HeadStemRelation) rel;
Inter head = sig.getOppositeInter(stem, rel);
StemPortion portion = hsRel.getStemPortion(head, stemLine, scale);
if (portion == forbidden) {
if (stem.isVip() || logger.isDebugEnabled()) {
logger.info(
"VIP cutting relation between {} and {}",
stem,
sig.getEdgeSource(rel));
}
toRemove.add(rel);
}
}
if (!toRemove.isEmpty()) {
sig.removeAllEdges(toRemove);
}
return toRemove.isEmpty();
}
// updateAndPurge //
/**
* Update the contextual grade of each Inter in SIG, and remove the weak ones if so
* desired.
*
* @return the set of inters removed
*/
private Set<Inter> updateAndPurge ()
{
sig.contextualize();
if (purgeWeaks) {
return sig.deleteWeakInters();
}
return Collections.emptySet();
}
// Adapter //
private abstract static class Adapter
{
Set<Inter> deleted = new LinkedHashSet<Inter>();
Set<Inter> reduced = new LinkedHashSet<Inter>();
public int checkConsistencies ()
{
return 0; // Void by default
}
public void checkFrozens ()
{
// Void by default
}
public int checkLateConsistencies ()
{
return 0; // Void by default
}
public Set<Inter> checkSlurs ()
{
return Collections.emptySet();
}
public void prolog ()
{
// Void by default
}
}
// AdapterForFoundations //
private class AdapterForFoundations
extends Adapter
{
@Override
public int checkConsistencies ()
{
int modifs = 0;
modifs += checkStemEndingHeads();
deleted.addAll(updateAndPurge());
modifs += checkHeads();
deleted.addAll(updateAndPurge());
modifs += checkHooks();
deleted.addAll(updateAndPurge());
modifs += checkBeams();
deleted.addAll(updateAndPurge());
modifs += checkLedgers();
deleted.addAll(updateAndPurge());
modifs += checkStems();
deleted.addAll(updateAndPurge());
return modifs;
}
@Override
public int checkLateConsistencies ()
{
int modifs = 0;
modifs += checkStemLengths();
deleted.addAll(updateAndPurge());
return modifs;
}
@Override
public void prolog ()
{
analyzeHeadStems(); // Check there is at most one stem on each side of any head
analyzeChords(); // Heads & beams compatibility
}
}
// AdapterForLinks //
private class AdapterForLinks
extends Adapter
{
@Override
public int checkConsistencies ()
{
int modifs = 0;
modifs += checkStemEndingHeads();
deleted.addAll(updateAndPurge());
modifs += checkHeads();
deleted.addAll(updateAndPurge());
modifs += checkDoubleAlters();
deleted.addAll(updateAndPurge());
modifs += checkTimeNumbers();
checkTimeSignatures();
deleted.addAll(updateAndPurge());
modifs += checkAugmentationDots();
modifs += checkAugmented();
deleted.addAll(updateAndPurge());
modifs += checkIsolatedAlters();
deleted.addAll(updateAndPurge());
return modifs;
}
@Override
public void checkFrozens ()
{
analyzeFrozenInters();
}
@Override
public Set<Inter> checkSlurs ()
{
return checkSlurOnTuplet();
}
@Override
public void prolog ()
{
// Still needed because of cue beams
analyzeChords();
}
}
// AdapterForRhythms //
/**
* NOT USED.
* Adapter meant for RHYTHMS step.
*
* @deprecated no longer used
*/
@Deprecated
private class AdapterForRhythms
extends Adapter
{
private final SystemBackup systemPoorFrats;
private final Class[] classes;
public List<Inter> selected;
public AdapterForRhythms (SystemBackup systemPoorFrats,
Class[] classes)
{
this.systemPoorFrats = systemPoorFrats;
this.classes = classes;
}
@Override
public int checkConsistencies ()
{
int modifs = 0;
modifs += checkDoubleAlters();
deleted.addAll(updateAndPurge());
modifs += checkTimeNumbers();
checkTimeSignatures();
deleted.addAll(updateAndPurge());
modifs += checkAugmentationDots();
modifs += checkAugmented();
deleted.addAll(updateAndPurge());
return modifs;
}
@Override
public Set<Inter> checkSlurs ()
{
return checkSlurOnTuplet();
}
@Override
public void prolog ()
{
// Still needed because of cue beams
analyzeChords();
// All inters of selected classes (with all their relations)
selected = sig.inters(classes);
systemPoorFrats.save(selected);
}
}
// Constants //
private static final class Constants
extends ConstantSet
{
private final Scale.Fraction maxTupletSlurWidth = new Scale.Fraction(
3,
"Maximum width for slur around tuplet");
private final Scale.Fraction minStemExtension = new Scale.Fraction(
1.5,
"Minimum vertical extension of a stem beyond last head");
}
} |
package net.ohloh.ohcount4j;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import net.ohloh.ohcount4j.detect.SimpleDetector;
import net.ohloh.ohcount4j.io.FileBlob;
import net.ohloh.ohcount4j.scan.LineHandler;
import net.ohloh.ohcount4j.scan.Scanner;
import org.apache.commons.io.DirectoryWalker;
public class DirectoryScanner extends DirectoryWalker<Object> {
protected LineHandler lineHandler;
public DirectoryScanner(LineHandler handler) {
super();
this.lineHandler = handler;
}
public void scan(File startPath) throws IOException {
if (startPath.isDirectory()) {
this.walk(startPath, new ArrayList<Object>());
} else {
scanFile(startPath);
}
}
@Override
protected void handleFile(File file, int depth, Collection<Object> results) throws IOException {
scanFile(file);
}
protected void scanFile(File file) throws IOException {
FileBlob blob = new FileBlob(file);
Scanner scanner = SimpleDetector.detect(blob);
if (scanner != null) {
scanner.scan(blob, this.lineHandler);
}
}
} |
package net.oschina.concurrency;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.Thread.State;
public class TestPriority {
public static void main(String[] args) {
// Thread priority infomation
System.out.printf("Minimum Priority: %s\n",Thread.MIN_PRIORITY);
System.out.printf("Normal Priority: %s\n",Thread.NORM_PRIORITY);
System.out.printf("Maximun Priority: %s\n",Thread.MAX_PRIORITY);
Thread threads[];
Thread.State status[];
threads=new Thread[10];
status=new Thread.State[10];
for (int i=0; i<10; i++){
threads[i]=new Thread(new Calculator(i));
if ((i%2)==0){
threads[i].setPriority(Thread.MAX_PRIORITY);
} else {
threads[i].setPriority(Thread.MIN_PRIORITY);
}
threads[i].setName("Thread "+i);
}
try (FileWriter file = new FileWriter("log.txt");PrintWriter pw = new PrintWriter(file);){
for (int i=0; i<10; i++){
pw.println("Main : Status of Thread "+i+" : "+threads[i].getState());
status[i]=threads[i].getState();
}
for (int i=0; i<10; i++){
threads[i].start();
}
boolean finish=false;
while (!finish) {
for (int i=0; i<10; i++){
if (threads[i].getState()!=status[i]) {
writeThreadInfo(pw, threads[i],status[i]);
status[i]=threads[i].getState();
}
}
finish=true;
for (int i=0; i<10; i++){
finish=finish &&(threads[i].getState()==State.TERMINATED);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
private static void writeThreadInfo(PrintWriter pw, Thread thread, State state) {
pw.printf("Main : Id %d - %s\n",thread.getId(),thread.getName());
pw.printf("Main : Priority: %d\n",thread.getPriority());
pw.printf("Main : Old State: %s\n",state);
pw.printf("Main : New State: %s\n",thread.getState());
pw.printf("Main : ************************************\n");
}
} |
package soliddomino.game.dominos;
import soliddomino.game.managers.Dealer;
import soliddomino.game.boards.Board;
import soliddomino.game.components.Piece;
import soliddomino.game.components.Player;
import soliddomino.game.movement.Turn;
import soliddomino.game.movement.Movement;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import soliddomino.game.boards.ConsoleBoard;
import soliddomino.game.exceptions.NoPiecesToTakeException;
import soliddomino.game.managers.PieceChain;
import soliddomino.game.movement.MovementBuilder;
public abstract class Domino {
private List<Piece> pieces;
private Board board;
private List<Player> players = new ArrayList<>();
public static int PIECES_PER_PLAYER = 7;
public static int MAX_PIECE_VALUE = 6;
private Dealer dealer;
private Turn turn;
public Domino(Board board, MovementBuilder movementBuilder){
this.board = board;
pieces = board.loadPieces(MAX_PIECE_VALUE);
board.shuffle(pieces);
dealer = new Dealer(players);
dealer.setMovementBuilder(movementBuilder);
this.turn = new Turn();
}
public void init(){
createPlayers(2);
try {
dealer.distributePiecesToPlayers(pieces);
} catch (NoPiecesToTakeException ex) {
System.out.println(ex.getMessage());
}
}
public String play(){
Player currentPlayer = dealer.chooseStartingPlayer();
board.applyFirstMove(currentPlayer);
dealer.setStartingPieceUsed((board).getPieceChain().getStartingPiece());
boolean isDrawedGame = false;
do {
currentPlayer = dealer.nextPlayerTakingTurn(currentPlayer);
getMovementFromPlayer(currentPlayer);
isDrawedGame = dealer.gameIsDrawed();
}while(!isDrawedGame && !(turn.hasWon(currentPlayer)));
return isDrawedGame ? getDrawWinner() : currentPlayer.getName() ;
}
private void getMovementFromPlayer(Player currentPlayer) {
Movement currentMove = dealer.getPlayerMovement(currentPlayer, board);
if(currentMove.isPass())
dealer.addPieceToPlayer(currentPlayer, pieces);
else
board.applyMove(currentMove);
PieceChain pieceChain = board.getPieceChain();
dealer.setPiecesStatues(
pieceChain.getLeftmostValue(),
pieceChain.getRightmostValue());
}
private void createPlayers(int numberOfPlayers) {
for(int i = 1; i <= numberOfPlayers; i++)
players.add(new Player("Player " + i));
}
private String getDrawWinner() {
Collections.sort(players);
Player drawWinner = players.get(0);
return drawWinner.getName() + " with " + drawWinner.getSumOfPiecesValues();
}
} |
package net.sf.cglib;
import java.io.Serializable;
import java.util.*;
import java.lang.reflect.*;
/**
* This class is meant to be used as a drop-in replacement for
* <code>java.lang.reflect.Proxy</code>.
* There are some known subtle differences:
* <ul>
* <li>The exceptions returned by invoking <code>getExceptionTypes</code>
* on the <code>Method</code> passed to the <code>invoke</code> method
* <b>are</b> the exact set that can be thrown without resulting in an
* <code>UndeclaredThrowableException</code> being thrown.
* <li>There is no protected constructor which accepts an
* <code>InvocationHandler</code>. Instead, use the more convenient
* <code>newProxyInstance</code> static method.
* <li><code>net.sf.cglib.UndeclaredThrowableException</code> is used instead
* of <code>java.lang.reflect.UndeclaredThrowableException</code>.
* </ul>
* @author Chris Nokleberg <a href="mailto:chris@nokleberg.com">chris@nokleberg.com</a>
* @version $Id: JdkCompatibleProxy.java,v 1.5 2002-12-06 19:39:51 herbyderby Exp $
*/
public class JdkCompatibleProxy implements Serializable {
private static final Class thisClass = JdkCompatibleProxy.class;
private static final HandlerAdapter nullInterceptor = new HandlerAdapter(null);
private static class HandlerAdapter implements MethodInterceptor {
private InvocationHandler handler;
public HandlerAdapter(InvocationHandler handler) {
this.handler = handler;
}
public Object aroundAdvice(Object obj, Method method, Object[] args,
MethodProxy proxy) throws Throwable {
return handler.invoke(obj, method, args);
}
}
protected InvocationHandler h;
protected JdkCompatibleProxy(MethodInterceptor mi) {
HandlerAdapter adapter = (HandlerAdapter)mi;
if (adapter != null)
h = adapter.handler;
}
public static InvocationHandler getInvocationHandler(Object proxy) {
return ((HandlerAdapter)((Factory)proxy).getInterceptor()).handler;
}
public static Class getProxyClass(ClassLoader loader, Class[] interfaces) {
return Enhancer.enhance(thisClass, interfaces, nullInterceptor, loader).getClass();
}
public static boolean isProxyClass(Class cl) {
return cl.getSuperclass().getName().equals(thisClass.getName());
}
public static Object newProxyInstance(ClassLoader loader, Class[] interfaces, InvocationHandler h) {
return Enhancer.enhance(thisClass, interfaces, new HandlerAdapter(h), loader);
}
} |
package org.adligo.cl;
import org.adligo.i.adig.client.BaseGInvoker;
import org.adligo.i.adig.client.I_GInvoker;
public class MockConsoleInputReader extends BaseGInvoker implements I_GInvoker<Object, String> {
public static final MockConsoleInputReader INSTANCE = new MockConsoleInputReader();
private String nextInput;
private MockConsoleInputReader() {
super(Object.class, String.class);
}
@Override
public String invoke(Object valueObject) {
return nextInput;
}
public String getNextInput() {
return nextInput;
}
public void setNextInput(String nextInput) {
this.nextInput = nextInput;
}
} |
package org.bouncycastle.crypto.tls;
import org.bouncycastle.crypto.Digest;
import org.bouncycastle.crypto.digests.MD5Digest;
import org.bouncycastle.crypto.digests.SHA1Digest;
import org.bouncycastle.crypto.macs.HMac;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.util.Strings;
import org.bouncycastle.util.io.Streams;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* Some helper fuctions for MicroTLS.
*/
public class TlsUtils
{
protected static void writeUint8(short i, OutputStream os) throws IOException
{
os.write(i);
}
protected static void writeUint8(short i, byte[] buf, int offset)
{
buf[offset] = (byte)i;
}
protected static void writeUint16(int i, OutputStream os) throws IOException
{
os.write(i >> 8);
os.write(i);
}
protected static void writeUint16(int i, byte[] buf, int offset)
{
buf[offset] = (byte)(i >> 8);
buf[offset + 1] = (byte)i;
}
protected static void writeUint24(int i, OutputStream os) throws IOException
{
os.write(i >> 16);
os.write(i >> 8);
os.write(i);
}
protected static void writeUint24(int i, byte[] buf, int offset)
{
buf[offset] = (byte)(i >> 16);
buf[offset + 1] = (byte)(i >> 8);
buf[offset + 2] = (byte)(i);
}
protected static void writeUint32(long i, OutputStream os) throws IOException
{
os.write((int)(i >> 24));
os.write((int)(i >> 16));
os.write((int)(i >> 8));
os.write((int)(i));
}
protected static void writeUint32(long i, byte[] buf, int offset)
{
buf[offset] = (byte)(i >> 24);
buf[offset + 1] = (byte)(i >> 16);
buf[offset + 2] = (byte)(i >> 8);
buf[offset + 3] = (byte)(i);
}
protected static void writeUint64(long i, OutputStream os) throws IOException
{
os.write((int)(i >> 56));
os.write((int)(i >> 48));
os.write((int)(i >> 40));
os.write((int)(i >> 32));
os.write((int)(i >> 24));
os.write((int)(i >> 16));
os.write((int)(i >> 8));
os.write((int)(i));
}
protected static void writeUint64(long i, byte[] buf, int offset)
{
buf[offset] = (byte)(i >> 56);
buf[offset + 1] = (byte)(i >> 48);
buf[offset + 2] = (byte)(i >> 40);
buf[offset + 3] = (byte)(i >> 32);
buf[offset + 4] = (byte)(i >> 24);
buf[offset + 5] = (byte)(i >> 16);
buf[offset + 6] = (byte)(i >> 8);
buf[offset + 7] = (byte)(i);
}
protected static void writeOpaque8(byte[] buf, OutputStream os) throws IOException
{
writeUint8((short)buf.length, os);
os.write(buf);
}
protected static void writeOpaque16(byte[] buf, OutputStream os) throws IOException
{
writeUint16(buf.length, os);
os.write(buf);
}
protected static void writeOpaque24(byte[] buf, OutputStream os) throws IOException
{
writeUint24(buf.length, os);
os.write(buf);
}
protected static short readUint8(InputStream is) throws IOException
{
int i = is.read();
if (i == -1)
{
throw new EOFException();
}
return (short)i;
}
protected static int readUint16(InputStream is) throws IOException
{
int i1 = is.read();
int i2 = is.read();
if ((i1 | i2) < 0)
{
throw new EOFException();
}
return i1 << 8 | i2;
}
protected static int readUint24(InputStream is) throws IOException
{
int i1 = is.read();
int i2 = is.read();
int i3 = is.read();
if ((i1 | i2 | i3) < 0)
{
throw new EOFException();
}
return (i1 << 16) | (i2 << 8) | i3;
}
protected static long readUint32(InputStream is) throws IOException
{
int i1 = is.read();
int i2 = is.read();
int i3 = is.read();
int i4 = is.read();
if ((i1 | i2 | i3 | i4) < 0)
{
throw new EOFException();
}
return (((long)i1) << 24) | (((long)i2) << 16) | (((long)i3) << 8) | ((long)i4);
}
protected static void readFully(byte[] buf, InputStream is) throws IOException
{
if (Streams.readFully(is, buf) != buf.length)
{
throw new EOFException();
}
}
protected static byte[] readOpaque8(InputStream is) throws IOException
{
short length = readUint8(is);
byte[] value = new byte[length];
readFully(value, is);
return value;
}
protected static byte[] readOpaque16(InputStream is) throws IOException
{
int length = readUint16(is);
byte[] value = new byte[length];
readFully(value, is);
return value;
}
protected static void checkVersion(byte[] readVersion, TlsProtocolHandler handler) throws IOException
{
if ((readVersion[0] != 3) || (readVersion[1] != 1))
{
handler.failWithError(TlsProtocolHandler.AL_fatal, TlsProtocolHandler.AP_protocol_version);
}
}
protected static void checkVersion(InputStream is, TlsProtocolHandler handler) throws IOException
{
int i1 = is.read();
int i2 = is.read();
if ((i1 != 3) || (i2 != 1))
{
handler.failWithError(TlsProtocolHandler.AL_fatal, TlsProtocolHandler.AP_protocol_version);
}
}
protected static void writeVersion(OutputStream os) throws IOException
{
os.write(3);
os.write(1);
}
private static void hmac_hash(Digest digest, byte[] secret, byte[] seed, byte[] out)
{
HMac mac = new HMac(digest);
KeyParameter param = new KeyParameter(secret);
byte[] a = seed;
int size = digest.getDigestSize();
int iterations = (out.length + size - 1) / size;
byte[] buf = new byte[mac.getMacSize()];
byte[] buf2 = new byte[mac.getMacSize()];
for (int i = 0; i < iterations; i++)
{
mac.init(param);
mac.update(a, 0, a.length);
mac.doFinal(buf, 0);
a = buf;
mac.init(param);
mac.update(a, 0, a.length);
mac.update(seed, 0, seed.length);
mac.doFinal(buf2, 0);
System.arraycopy(buf2, 0, out, (size * i), Math.min(size, out.length - (size * i)));
}
}
protected static void PRF(byte[] secret, String asciiLabel, byte[] seed, byte[] buf)
{
byte[] label = Strings.toByteArray(asciiLabel);
int s_half = (secret.length + 1) / 2;
byte[] s1 = new byte[s_half];
byte[] s2 = new byte[s_half];
System.arraycopy(secret, 0, s1, 0, s_half);
System.arraycopy(secret, secret.length - s_half, s2, 0, s_half);
byte[] ls = new byte[label.length + seed.length];
System.arraycopy(label, 0, ls, 0, label.length);
System.arraycopy(seed, 0, ls, label.length, seed.length);
byte[] prf = new byte[buf.length];
hmac_hash(new MD5Digest(), s1, ls, prf);
hmac_hash(new SHA1Digest(), s2, ls, buf);
for (int i = 0; i < buf.length; i++)
{
buf[i] ^= prf[i];
}
}
} |
package org.encog.util.math;
public class GaussianFunction {
private double center;
private double peak;
private double width;
public GaussianFunction(double center,double peak,double width)
{
this.center = center;
this.peak = peak;
this.width = width;
}
public double gaussian(double x)
{
return (this.peak*MathConst.EULERS_NUMBER)*(-(Math.pow(x-this.center, 2.0)/2.0*Math.pow(this.width, 2.0)));
}
public double gaussianDerivative(double x) {
return ((-x)*Math.pow(this.width, -2))+(this.center*Math.pow(this.width, -2));
}
public double getCenter() {
return center;
}
public double getPeak() {
return peak;
}
public double getWidth() {
return width;
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.