answer
stringlengths 17
10.2M
|
|---|
// RMG - Reaction Mechanism Generator
// RMG Team ([email protected])
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
// all copies or substantial portions of the Software.
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
package jing.rxn;
import java.io.*;
import jing.chem.*;
import java.util.*;
import jing.param.*;
import jing.mathTool.*;
import jing.chemParser.*;
import jing.chem.Species;
import jing.param.Temperature;
import jing.rxnSys.Logger;
import jing.rxnSys.NegativeConcentrationException;
import jing.rxnSys.ReactionModelGenerator;
import jing.rxnSys.SystemSnapshot;
//## package jing::rxn
//jing\rxn\Reaction.java
/**
Immutable objects.
*/
//## class Reaction
public class Reaction {
protected static double TRIMOLECULAR_RATE_UPPER = 1.0E100;
protected static double BIMOLECULAR_RATE_UPPER = 1.0E100; //## attribute BIMOLECULAR_RATE_UPPER
protected static double UNIMOLECULAR_RATE_UPPER = 1.0E100; //## attribute UNIMOLECULAR_RATE_UPPER
protected String comments = "No comment"; //## attribute comments
protected Kinetics[] fittedReverseKinetics = null; //## attribute fittedReverseKinetics
protected double rateConstant;
protected Reaction reverseReaction = null; //## attribute reverseReaction
protected Kinetics[] kinetics;
protected Structure structure;
protected double UpperBoundRate;//svp
protected double LowerBoundRate;//svp
protected boolean finalized = false;
protected String ChemkinString = null;
protected boolean kineticsFromPrimaryKineticLibrary = false;
protected boolean expectDuplicate = false;
// Constructors
//## operation Reaction()
public Reaction() {
//#[ operation Reaction()
//
}
//## operation Reaction(Structure,RateConstant)
private Reaction(Structure p_structure, Kinetics[] p_kinetics) {
//#[ operation Reaction(Structure,RateConstant)
structure = p_structure;
kinetics = p_kinetics;
//rateConstant = calculateTotalRate(Global.temperature);
//
}
//## operation allProductsIncluded(HashSet)
public boolean allProductsIncluded(HashSet p_speciesSet) {
//#[ operation allProductsIncluded(HashSet)
Iterator iter = getProducts();
while (iter.hasNext()) {
Species spe = ((Species)iter.next());
if (!p_speciesSet.contains(spe)) return false;
}
return true;
//
}
//## operation allReactantsIncluded(HashSet)
public boolean allReactantsIncluded(HashSet p_speciesSet) {
//#[ operation allReactantsIncluded(HashSet)
if (p_speciesSet == null) throw new NullPointerException();
Iterator iter = getReactants();
while (iter.hasNext()) {
Species spe = ((Species)iter.next());
if (!p_speciesSet.contains(spe)) return false;
}
return true;
//
}
/**
Calculate this reaction's thermo parameter. Basically, make addition of the thermo parameters of all the reactants and products.
*/
//## operation calculateHrxn(Temperature)
public double calculateHrxn(Temperature p_temperature) {
//#[ operation calculateHrxn(Temperature)
return structure.calculateHrxn(p_temperature);
//
}
//## operation calculateKeq(Temperature)
public double calculateKeq(Temperature p_temperature) {
//#[ operation calculateKeq(Temperature)
return structure.calculateKeq(p_temperature);
//
}
//## operation calculateKeqUpperBound(Temperature)
//svp
public double calculateKeqUpperBound(Temperature p_temperature) {
//#[ operation calculateKeqUpperBound(Temperature)
return structure.calculateKeqUpperBound(p_temperature);
//
}
//## operation calculateKeqLowerBound(Temperature)
//svp
public double calculateKeqLowerBound(Temperature p_temperature) {
//#[ operation calculateKeqLowerBound(Temperature)
return structure.calculateKeqLowerBound(p_temperature);
//
}
public double calculateTotalRate(Temperature p_temperature){
double rate =0;
Temperature stdtemp = new Temperature(298,"K");
double Hrxn = calculateHrxn(stdtemp);
Temperature sys_temp = ReactionModelGenerator.getTemp4BestKinetics();
/* AJ 12JULY2010:
* Added diffusive limits from previous RMG version by replacing function calculateTotalRate
* Checks the exothermicity and molecularity of reaction to determine the diffusive rate limit
*/
/*
* 29Jun2009-MRH: Added a kinetics from PRL check
* If the kinetics for this reaction is from a PRL, use those numbers
* to compute the rate. Else, proceed as before.
*/
/*
* MRH 18MAR2010:
* Changing the structure of a reaction's kinetics
* If the kinetics are from a primary kinetic library, we assume the user
* has supplied the total pre-exponential factor for the reaction (and
* not the per-event pre-exponential facor).
* If the kinetics were estimated by RMG, the pre-exponential factor must
* be multiplied by the "redundancy" (# of events)
*/
if (kineticsFromPrimaryKineticLibrary) {
Kinetics[] k_All = kinetics;
for (int numKinetics=0; numKinetics<kinetics.length; numKinetics++) {
Kinetics k = k_All[numKinetics];
rate += k.calculateRate(p_temperature,Hrxn);
}
return rate;
}
else if (isForward()){
Kinetics[] k_All = kinetics;
for (int numKinetics=0; numKinetics<kinetics.length; numKinetics++) {
Kinetics k = k_All[numKinetics];
if ((int)structure.redundancy != 1){
k = k.multiply(structure.redundancy);
}
rate += k.calculateRate(p_temperature,Hrxn);
}
/* Diffusion limits added by AJ on July 12, 2010
* Requires correction in the forward direction only, reverse reaction corrects itself
* If ReactionModelGenerator.useDiffusion is true (solvation is on)
* compute kd and return keff
*/
if (ReactionModelGenerator.getUseDiffusion()) {
int numReacts = structure.getReactantNumber();
int numProds = structure.getProductNumber();
double keff = 0.0;
double DiffFactor = 0.0;
if (numReacts == 1 && numProds == 1) {
keff = rate;
rate = keff;
DiffFactor = 1;
}
else if (numReacts == 1 && numProds == 2) {
double k_back = rate / calculateKeq(p_temperature);
LinkedList reactantsInBackRxn = structure.products;
double k_back_diff= calculatediff(reactantsInBackRxn);
double k_back_eff= k_back*k_back_diff/(k_back + k_back_diff);
keff = k_back_eff*calculateKeq(p_temperature);
DiffFactor = keff/rate;
rate = keff;
}
else if (numReacts == 2 && numProds == 1) {
double k_forw = rate;
LinkedList reactantsInForwRxn = structure.reactants;
double k_forw_diff = calculatediff(reactantsInForwRxn);
double k_forw_eff = k_forw*k_forw_diff/(k_forw + k_forw_diff);
keff = k_forw_eff;
DiffFactor = keff/rate;
rate = keff;
}
else if (numReacts == 2 && numProds == 2) {
double rxn_Keq = structure.calculateKeq(p_temperature);
double deltaHrxn = structure.calculateHrxn(p_temperature);
if (rxn_Keq>1){ // Forward reaction is exothermic hence the corresponding diffusion limit applies
double k_forw = rate;
LinkedList reactantsInForwRxn = structure.reactants;
double k_forw_diff = calculatediff(reactantsInForwRxn);
double k_forw_eff = k_forw*k_forw_diff/(k_forw + k_forw_diff);
keff = k_forw_eff;
DiffFactor = keff/rate;
rate = keff;
}
else if (rxn_Keq<1){ // Reverse reaction is exothermic and the corresponding diffusion limit should be used
double k_back = rate / calculateKeq(p_temperature);
LinkedList reactantsInBackRxn = structure.products;
double k_back_diff = calculatediff(reactantsInBackRxn);
double k_back_eff = k_back*k_back_diff/(k_back + k_back_diff);
keff = k_back_eff * calculateKeq(p_temperature);
DiffFactor = keff/rate;
rate = keff;
}
}
else if (numReacts == 2 && numProds == 3) {
double k_forw = rate;
LinkedList reactantsInForwRxn = structure.reactants;
double k_forw_diff = calculatediff(reactantsInForwRxn);
double k_forw_eff = k_forw*k_forw_diff/(k_forw + k_forw_diff);
keff = k_forw_eff;
DiffFactor = keff/rate;
rate = keff;
}
// Add comments only if the temperature at which the function has been called corresponds to the system temperature specified in the condition file
// And if they haven't already been added
if (p_temperature.getK()==sys_temp.getK()){
String oldComments = k_All[0].getComment();
if (!oldComments.contains("Diffusion")) {
if (numReacts == 1 && numProds == 1)
oldComments += " Unimolecular: no diffusion limitation.";
String newComments = oldComments + String.format(" Diffusion factor=%.3g, rate=%.3g, Keq=%.3g, at T=%.0fK.", DiffFactor, rate, calculateKeq(p_temperature), p_temperature.getK());
setKineticsComments(newComments,0);
}
}
}
return rate;
}
else if (isBackward()){
Reaction r = getReverseReaction();
rate = r.calculateTotalRate(p_temperature);
return rate*calculateKeq(p_temperature);
}
else {
throw new InvalidReactionDirectionException();
}
}
//## operation calculatediff(LinkedList)
public double calculatediff(LinkedList p_struct) {
if (p_struct.size()!=2){
Logger.warning("Cannot compute diffusive limit if number of reactants is not equal to 2");
}
// Array containing the radii of the two species passed in p_struct
double[] r;
double[] d;
r = new double[2];
d = new double[2];
int i= 0;
for (Iterator iter = p_struct.iterator(); iter.hasNext();) {
Species sp = (Species)iter.next();
ChemGraph cg = sp.getChemGraph();
r[i] = cg.getRadius();
d[i] = cg.getDiffusivity();
i = i+1;
}
double kdiff;
kdiff = (88/7)*(d[0] + d[1])*(r[0] + r[1]) * 6.023e29; // units of r[i]=m; d[1]=m2/sec; kdiff=cm3/mole sec
return kdiff;
}
//## operation calculateUpperBoundRate(Temperature)
//svp
public double calculateUpperBoundRate(Temperature p_temperature){
//#[ operation calculateUpperBoundRate(Temperature)
if (isForward()){
double A;
double E;
double n;
for (int numKinetics=0; numKinetics<kinetics.length; numKinetics++) {
A = kinetics[numKinetics].getA().getUpperBound();
E = kinetics[numKinetics].getE().getLowerBound();
n = kinetics[numKinetics].getN().getUpperBound();
if (A > 1E300) {
A = kinetics[numKinetics].getA().getValue()*1.2;
}
//Kinetics kinetics = getRateConstant().getKinetics();
if (kinetics[numKinetics] instanceof ArrheniusEPKinetics){
ArrheniusEPKinetics arrhenius = (ArrheniusEPKinetics)kinetics[numKinetics];
double H = calculateHrxn(p_temperature);
if (H < 0) {
if (arrhenius.getAlpha().getValue() > 0){
double alpha = arrhenius.getAlpha().getUpperBound();
E = E + alpha * H;
}
else{
double alpha = arrhenius.getAlpha().getLowerBound();
E = E + alpha*H;
}
}
else {
if (arrhenius.getAlpha().getValue() > 0){
double alpha = arrhenius.getAlpha().getLowerBound();
E = E + alpha * H;
}
else{
double alpha = arrhenius.getAlpha().getUpperBound();
E = E + alpha*H;
}
}
}
if (E < 0){
E = 0;
}
double indiv_k = 0.0;
indiv_k = A*Math.pow(p_temperature.getK(),n)*Math.exp(-E/GasConstant.getKcalMolK()/p_temperature.getK());
indiv_k *= getStructure().getRedundancy();
UpperBoundRate += indiv_k;
}
return UpperBoundRate;
}
else if (isBackward()) {
Reaction r = getReverseReaction();
if (r == null) throw new NullPointerException("Reverse reaction is null.\n" + structure.toString());
if (!r.isForward()) throw new InvalidReactionDirectionException();
for (int numKinetics=0; numKinetics<kinetics.length; numKinetics++) {
double A = kinetics[numKinetics].getA().getUpperBound();
double E = kinetics[numKinetics].getE().getLowerBound();
double n = kinetics[numKinetics].getN().getUpperBound();
if (A > 1E300) {
A = kinetics[numKinetics].getA().getValue()*1.2;
}
//Kinetics kinetics = getRateConstant().getKinetics();
if (kinetics[numKinetics] instanceof ArrheniusEPKinetics){
ArrheniusEPKinetics arrhenius = (ArrheniusEPKinetics)kinetics[numKinetics];
double H = calculateHrxn(p_temperature);
if (H < 0) {
if (arrhenius.getAlpha().getValue() > 0){
double alpha = arrhenius.getAlpha().getUpperBound();
E = E + alpha * H;
}
else{
double alpha = arrhenius.getAlpha().getLowerBound();
E = E + alpha*H;
}
}
else {
if (arrhenius.getAlpha().getValue() > 0){
double alpha = arrhenius.getAlpha().getLowerBound();
E = E + alpha * H;
}
else{
double alpha = arrhenius.getAlpha().getUpperBound();
E = E + alpha*H;
}
}
}
if (E < 0){
E = 0;
}
double indiv_k = 0.0;
indiv_k = A*Math.pow(p_temperature.getK(),n)*Math.exp(-E/GasConstant.getKcalMolK()/p_temperature.getK());
indiv_k *= getStructure().getRedundancy();
UpperBoundRate += indiv_k*calculateKeqUpperBound(p_temperature);
}
return UpperBoundRate;
}
else{
throw new InvalidReactionDirectionException();
}
//
}
//## operation calculateLowerBoundRate(Temperature)
//svp
public double calculateLowerBoundRate(Temperature p_temperature){
//#[ operation calculateLowerBoundRate(Temperature)
if (isForward()){
for (int numKinetics=0; numKinetics<kinetics.length; ++numKinetics) {
double A = kinetics[numKinetics].getA().getLowerBound();
double E = kinetics[numKinetics].getE().getUpperBound();
double n = kinetics[numKinetics].getN().getLowerBound();
if (A > 1E300 || A <= 0) {
A = kinetics[numKinetics].getA().getValue()/1.2;
}
//Kinetics kinetics = getRateConstant().getKinetics();
if (kinetics[numKinetics] instanceof ArrheniusEPKinetics){
ArrheniusEPKinetics arrhenius = (ArrheniusEPKinetics)kinetics[numKinetics];
double H = calculateHrxn(p_temperature);
if (H < 0) {
if (arrhenius.getAlpha().getValue()>0){
double alpha = arrhenius.getAlpha().getLowerBound();
E = E + alpha * H;
}
else{
double alpha = arrhenius.getAlpha().getUpperBound();
E = E + alpha*H;
}
}
else {
if (arrhenius.getAlpha().getValue()>0){
double alpha = arrhenius.getAlpha().getUpperBound();
E = E + alpha * H;
}
else{
double alpha = arrhenius.getAlpha().getLowerBound();
E = E + alpha*H;
}
}
}
double indiv_k = 0.0;
indiv_k = A*Math.pow(p_temperature.getK(),n)*Math.exp(-E/GasConstant.getKcalMolK()/p_temperature.getK());
indiv_k *= getStructure().getRedundancy();
LowerBoundRate += indiv_k;
}
return LowerBoundRate;
}
else if (isBackward()) {
Reaction r = getReverseReaction();
if (r == null) throw new NullPointerException("Reverse reaction is null.\n" + structure.toString());
if (!r.isForward()) throw new InvalidReactionDirectionException();
for (int numKinetics=0; numKinetics<kinetics.length; ++numKinetics) {
double A = kinetics[numKinetics].getA().getLowerBound();
double E = kinetics[numKinetics].getE().getUpperBound();
double n = kinetics[numKinetics].getN().getLowerBound();
if (A > 1E300) {
A = kinetics[numKinetics].getA().getValue()/1.2;
}
if (kinetics[numKinetics] instanceof ArrheniusEPKinetics){
ArrheniusEPKinetics arrhenius = (ArrheniusEPKinetics)kinetics[numKinetics];
double H = calculateHrxn(p_temperature);
if (H < 0) {
if (arrhenius.getAlpha().getValue() > 0){
double alpha = arrhenius.getAlpha().getLowerBound();
E = E + alpha * H;
}
else{
double alpha = arrhenius.getAlpha().getUpperBound();
E = E + alpha*H;
}
}
else {
if (arrhenius.getAlpha().getValue() > 0){
double alpha = arrhenius.getAlpha().getUpperBound();
E = E + alpha * H;
}
else{
double alpha = arrhenius.getAlpha().getLowerBound();
E = E + alpha*H;
}
}
}
double indiv_k = 0.0;
indiv_k = A*Math.pow(p_temperature.getK(),n)*Math.exp(-E/GasConstant.getKcalMolK()/p_temperature.getK());
indiv_k *= getStructure().getRedundancy();
LowerBoundRate += indiv_k*calculateKeqLowerBound(p_temperature);
}
return LowerBoundRate;
}
else{
throw new InvalidReactionDirectionException();
}
//
}
//## operation calculateSrxn(Temperature)
public double calculateSrxn(Temperature p_temperature) {
//#[ operation calculateSrxn(Temperature)
return structure.calculateSrxn(p_temperature);
//
}
//## operation calculateThirdBodyCoefficient(SystemSnapshot)
public double calculateThirdBodyCoefficient(SystemSnapshot p_presentStatus) {
//#[ operation calculateThirdBodyCoefficient(SystemSnapshot)
if (!(this instanceof ThirdBodyReaction)) return 1;
else {
return ((ThirdBodyReaction)this).calculateThirdBodyCoefficient(p_presentStatus);
}
//
}
//## operation checkRateRange()
public boolean checkRateRange() {
//#[ operation checkRateRange()
Temperature t = new Temperature(1500,"K");
double rate = calculateTotalRate(t);
if (getReactantNumber() == 2) {
if (rate > BIMOLECULAR_RATE_UPPER) return false;
}
else if (getReactantNumber() == 1) {
if (rate > UNIMOLECULAR_RATE_UPPER) return false;
}
else if (getReactantNumber() == 3) {
if (rate > TRIMOLECULAR_RATE_UPPER) return false;
}
else throw new InvalidReactantNumberException();
return true;
//
}
//## operation contains(Species)
public boolean contains(Species p_species) {
//#[ operation contains(Species)
if (containsAsReactant(p_species) || containsAsProduct(p_species)) return true;
else return false;
//
}
//## operation containsAsProduct(Species)
public boolean containsAsProduct(Species p_species) {
//#[ operation containsAsProduct(Species)
Iterator iter = getProducts();
while (iter.hasNext()) {
//ChemGraph cg = (ChemGraph)iter.next();
Species spe = (Species)iter.next();
if (spe.equals(p_species)) return true;
}
return false;
//
}
//## operation containsAsReactant(Species)
public boolean containsAsReactant(Species p_species) {
//#[ operation containsAsReactant(Species)
Iterator iter = getReactants();
while (iter.hasNext()) {
//ChemGraph cg = (ChemGraph)iter.next();
Species spe = (Species)iter.next();
if (spe.equals(p_species)) return true;
}
return false;
//
}
/**
* Checks if the structure of the reaction is the same. Does not check the rate constant.
* Two reactions with the same structure but different rate constants will be equal.
*/
//## operation equals(Object)
public boolean equals(Object p_reaction) {
//#[ operation equals(Object)
if (this == p_reaction) return true;
if (!(p_reaction instanceof Reaction)) return false;
Reaction r = (Reaction)p_reaction;
if (!getStructure().equals(r.getStructure())) return false;
return true;
}
/*
// fitReverseKineticsPrecisely and getPreciseReverseKinetics
// are not used, not maintained, and we have clue what they do,
// so we're commenting them out so we don't keep looking at them.
// (oh, and they look pretty similar to each other!)
// - RWest & JWAllen, June 2009
//## operation fitReverseKineticsPrecisely()
public void fitReverseKineticsPrecisely() {
//#[ operation fitReverseKineticsPrecisely()
if (isForward()) {
fittedReverseKinetics = null;
}
else {
String result = "";
for (double t = 300.0; t<1500.0; t+=50.0) {
double rate = calculateTotalRate(new Temperature(t,"K"));
result += String.valueOf(t) + '\t' + String.valueOf(rate) + '\n';
}
// run fit3p
String dir = System.getProperty("RMG.workingDirectory");
File fit3p_input;
try {
// prepare fit3p input file, "input.dat" is the input file name
fit3p_input = new File("fit3p/input.dat");
FileWriter fw = new FileWriter(fit3p_input);
fw.write(result);
fw.close();
}
catch (IOException e) {
System.out.println("Wrong input file for fit3p!");
System.out.println(e.getMessage());
System.exit(0);
}
try {
// system call for fit3p
String[] command = {dir+ "/bin/fit3pbnd.exe"};
File runningDir = new File("fit3p");
Process fit = Runtime.getRuntime().exec(command, null, runningDir);
int exitValue = fit.waitFor();
}
catch (Exception e) {
System.out.println("Error in run fit3p!");
System.out.println(e.getMessage());
System.exit(0);
}
// parse the output file from chemdis
try {
String fit3p_output = "fit3p/output.dat";
FileReader in = new FileReader(fit3p_output);
BufferedReader data = new BufferedReader(in);
String line = ChemParser.readMeaningfulLine(data);
line = line.trim();
StringTokenizer st = new StringTokenizer(line);
String A = st.nextToken();
String temp = st.nextToken();
temp = st.nextToken();
temp = st.nextToken();
double Ar = Double.parseDouble(temp);
line = ChemParser.readMeaningfulLine(data);
line = line.trim();
st = new StringTokenizer(line);
String n = st.nextToken();
temp = st.nextToken();
temp = st.nextToken();
double nr = Double.parseDouble(temp);
line = ChemParser.readMeaningfulLine(data);
line = line.trim();
st = new StringTokenizer(line);
String E = st.nextToken();
temp = st.nextToken();
temp = st.nextToken();
temp = st.nextToken();
double Er = Double.parseDouble(temp);
if (Er < 0) {
System.err.println(getStructure().toString());
System.err.println("fitted Er < 0: "+Double.toString(Er));
double increase = Math.exp(-Er/GasConstant.getKcalMolK()/715.0);
double deltan = Math.log(increase)/Math.log(715.0);
System.err.println("n enlarged by factor of: " + Double.toString(deltan));
nr += deltan;
Er = 0;
}
UncertainDouble udAr = new UncertainDouble(Ar, 0, "Adder");
UncertainDouble udnr = new UncertainDouble(nr, 0, "Adder");
UncertainDouble udEr = new UncertainDouble(Er, 0, "Adder");
fittedReverseKinetics = new ArrheniusKinetics(udAr, udnr , udEr, "300-1500", 1, "fitting from forward and thermal",null);
in.close();
}
catch (Exception e) {
System.out.println("Error in read output.dat from fit3p!");
System.out.println(e.getMessage());
System.exit(0);
}
}
return;
//#]
}
//## operation fitReverseKineticsPrecisely()
public Kinetics getPreciseReverseKinetics() {
//#[ operation fitReverseKineticsPrecisely()
Kinetics fittedReverseKinetics =null;
String result = "";
for (double t = 300.0; t<1500.0; t+=50.0) {
double rate = calculateTotalRate(new Temperature(t,"K"));
result += String.valueOf(t) + '\t' + String.valueOf(rate) + '\n';
}
// run fit3p
String dir = System.getProperty("RMG.workingDirectory");
File fit3p_input;
try {
// prepare fit3p input file, "input.dat" is the input file name
fit3p_input = new File("fit3p/input.dat");
FileWriter fw = new FileWriter(fit3p_input);
fw.write(result);
fw.close();
}
catch (IOException e) {
System.out.println("Wrong input file for fit3p!");
System.out.println(e.getMessage());
System.exit(0);
}
try {
// system call for fit3p
String[] command = {dir+ "/bin/fit3pbnd.exe"};
File runningDir = new File("fit3p");
Process fit = Runtime.getRuntime().exec(command, null, runningDir);
int exitValue = fit.waitFor();
}
catch (Exception e) {
System.out.println("Error in run fit3p!");
System.out.println(e.getMessage());
System.exit(0);
}
// parse the output file from chemdis
try {
String fit3p_output = "fit3p/output.dat";
FileReader in = new FileReader(fit3p_output);
BufferedReader data = new BufferedReader(in);
String line = ChemParser.readMeaningfulLine(data);
line = line.trim();
StringTokenizer st = new StringTokenizer(line);
String A = st.nextToken();
String temp = st.nextToken();
temp = st.nextToken();
temp = st.nextToken();
double Ar = Double.parseDouble(temp);
line = ChemParser.readMeaningfulLine(data);
line = line.trim();
st = new StringTokenizer(line);
String n = st.nextToken();
temp = st.nextToken();
temp = st.nextToken();
double nr = Double.parseDouble(temp);
line = ChemParser.readMeaningfulLine(data);
line = line.trim();
st = new StringTokenizer(line);
String E = st.nextToken();
temp = st.nextToken();
temp = st.nextToken();
temp = st.nextToken();
double Er = Double.parseDouble(temp);
if (Er < 0) {
System.err.println(getStructure().toString());
System.err.println("fitted Er < 0: "+Double.toString(Er));
double increase = Math.exp(-Er/GasConstant.getKcalMolK()/715.0);
double deltan = Math.log(increase)/Math.log(715.0);
System.err.println("n enlarged by factor of: " + Double.toString(deltan));
nr += deltan;
Er = 0;
}
UncertainDouble udAr = new UncertainDouble(Ar, 0, "Adder");
UncertainDouble udnr = new UncertainDouble(nr, 0, "Adder");
UncertainDouble udEr = new UncertainDouble(Er, 0, "Adder");
fittedReverseKinetics = new ArrheniusKinetics(udAr, udnr , udEr, "300-1500", 1, "fitting from forward and thermal",null);
in.close();
}
catch (Exception e) {
System.out.println("Error in read output.dat from fit3p!");
System.out.println(e.getMessage());
System.exit(0);
}
return fittedReverseKinetics;
//#]
}
// */
//## operation fitReverseKineticsRoughly()
public void fitReverseKineticsRoughly() {
//#[ operation fitReverseKineticsRoughly()
// now is a rough fitting
if (isForward()) {
fittedReverseKinetics = null;
}
else {
//double temp = 715;
double temp = 298.15; //11/9/07 gmagoon: restored use of 298.15 per discussion with Sandeep
//double temp = Global.temperature.getK();
Kinetics[] k = getKinetics();
fittedReverseKinetics = new Kinetics[k.length];
double doubleAlpha;
for (int numKinetics=0; numKinetics<k.length; numKinetics++) {
if (k[numKinetics] instanceof ArrheniusEPKinetics) doubleAlpha = ((ArrheniusEPKinetics)k[numKinetics]).getAlphaValue();
else doubleAlpha = 0;
double Hrxn = calculateHrxn(new Temperature(temp,"K"));
double Srxn = calculateSrxn(new Temperature(temp, "K"));
// for EvansPolyani kinetics (Ea = Eo + alpha * Hrxn) remember that k.getEValue() gets Eo not Ea
// this Hrxn is for the reverse reaction (ie. -Hrxn_forward)
double doubleEr = k[numKinetics].getEValue() - (doubleAlpha-1)*Hrxn;
if (doubleEr < 0) {
Logger.warning("fitted Er < 0: "+Double.toString(doubleEr));
Logger.warning(getStructure().toString());
//doubleEr = 0;
}
UncertainDouble Er = new UncertainDouble(doubleEr, k[numKinetics].getE().getUncertainty(), k[numKinetics].getE().getType());
UncertainDouble n = new UncertainDouble(0,0, "Adder");
double doubleA = k[numKinetics].getAValue()* Math.pow(temp, k[numKinetics].getNValue())* Math.exp(Srxn/GasConstant.getCalMolK());
doubleA *= Math.pow(GasConstant.getCCAtmMolK()*temp, -getStructure().getDeltaN()); // assumes Ideal gas law concentration and 1 Atm reference state
fittedReverseKinetics[numKinetics] = new ArrheniusKinetics(new UncertainDouble(doubleA, 0, "Adder"), n , Er, "300-1500", 1, "fitting from forward and thermal",null);
}
}
return;
//
}
/**
* Generates a reaction whose structure is opposite to that of the present reaction.
* Just appends the rate constant of this reaction to the reverse reaction.
*
*/
//## operation generateReverseReaction()
public void generateReverseReaction() {
//#[ operation generateReverseReaction()
Structure s = getStructure();
//Kinetics k = getKinetics();
Kinetics[] k = kinetics;
if (kinetics == null)
throw new NullPointerException();
Structure newS = s.generateReverseStructure();
newS.setRedundancy(s.getRedundancy());
Reaction r = new Reaction(newS, k);
// if (hasAdditionalKinetics()){
// r.addAdditionalKinetics(additionalKinetics,1);
r.setReverseReaction(this);
this.setReverseReaction(r);
return;
//
}
public String getComments() {
return comments;
}
//## operation getDirection()
public int getDirection() {
//#[ operation getDirection()
return getStructure().getDirection();
//
}
//## operation getFittedReverseKinetics()
public Kinetics[] getFittedReverseKinetics() {
//#[ operation getFittedReverseKinetics()
if (fittedReverseKinetics == null) fitReverseKineticsRoughly();
return fittedReverseKinetics;
//
}
/*//## operation getForwardRateConstant()
public Kinetics getForwardRateConstant() {
//#[ operation getForwardRateConstant()
if (isForward()) return kinetics;
else return null;
//
}
*/
//## operation getKinetics()
public Kinetics[] getKinetics() {
//#[ operation getKinetics()
// returns the kinetics OF THE FORWARD REACTION
// ie. if THIS is reverse, it calls this.getReverseReaction().getKinetics()
/*
* 29Jun2009-MRH:
* When getting kinetics, check whether it comes from a PRL or not.
* If so, return the kinetics. We are not worried about the redundancy
* because I assume the user inputs the Arrhenius kinetics for the overall
* reaction A = B + C
*
* E.g. CH4 = CH3 + H A n E
* The Arrhenius parameters would be for the overall decomposition of CH4,
* not for each carbon-hydrogen bond fission
*/
if (isFromPrimaryKineticLibrary()) {
return kinetics;
}
if (isForward()) {
int red = structure.getRedundancy();
if (red==1) return kinetics; // Don't waste time multiplying by 1
Kinetics[] kinetics2return = new Kinetics[kinetics.length];
for (int numKinetics=0; numKinetics<kinetics.length; ++numKinetics) {
kinetics2return[numKinetics] = kinetics[numKinetics].multiply(red);
}
return kinetics2return;
}
else if (isBackward()) {
Reaction rr = getReverseReaction();
// Added by MRH on 7/Sept/2009
// Required when reading in the restart files
if (rr == null) {
generateReverseReaction();
rr = getReverseReaction();
}
if (rr == null) throw new NullPointerException("Reverse reaction is null.\n" + structure.toString());
if (!rr.isForward()) throw new InvalidReactionDirectionException(structure.toString());
return rr.getKinetics();
}
else
throw new InvalidReactionDirectionException(structure.toString());
}
public void setKineticsComments(String p_string, int num_k){
kinetics[num_k].setComments(p_string);
}
// shamel: Added this function 6/10/2010, to get Kinetics Source to identify duplicates
// in Reaction Library, Seed Mech and Template Reaction with Library Reaction feature
public String getKineticsSource(int num_k){
// The num_k is the number for different kinetics stored for one type of reaction but formed due to different families
// Returns Source as null when there are no Kinetics at all!
if (kinetics == null) {
return null;
}
String source = null;
if(kinetics[num_k] != null){
source = kinetics[num_k].getSource();
}
// This is mostly done for case of H Abstraction where forward kinetic source may be null
if (source == null){
try {
source = this.reverseReaction.kinetics[num_k].getSource();
}
catch (NullPointerException e) {
// this catches several possibilities:
// this.reverseReaction == null
// this.reverseReaction.kinetics == null
// this.reverseReaction.kinetics[num_k] == null
source = null;
}
}
return source;
}
public void setKineticsSource(String p_string, int num_k){
kinetics[num_k].setSource(p_string);
}
//## operation getUpperBoundRate(Temperature)
public double getUpperBoundRate(Temperature p_temperature){//svp
//#[ operation getUpperBoundRate(Temperature)
if (UpperBoundRate == 0.0){
calculateUpperBoundRate(p_temperature);
}
return UpperBoundRate;
//
}
//## operation getLowerBoundRate(Temperature)
public double getLowerBoundRate(Temperature p_temperature){//svp
//#[ operation getLowerBoundRate(Temperature)
if (LowerBoundRate == 0.0){
calculateLowerBoundRate(p_temperature);
}
return LowerBoundRate;
//
}
//## operation getProductList()
public LinkedList getProductList() {
//#[ operation getProductList()
return structure.getProductList();
//
}
//## operation getProductNumber()
public int getProductNumber() {
//#[ operation getProductNumber()
return getStructure().getProductNumber();
//
}
//## operation getProducts()
public ListIterator getProducts() {
//#[ operation getProducts()
return structure.getProducts();
//
}
//## operation getReactantList()
public LinkedList getReactantList() {
//#[ operation getReactantList()
return structure.getReactantList();
//
}
//## operation getReactantNumber()
public int getReactantNumber() {
//#[ operation getReactantNumber()
return getStructure().getReactantNumber();
//
}
//## operation getReactants()
public ListIterator getReactants() {
//#[ operation getReactants()
return structure.getReactants();
//
}
//## operation getRedundancy()
public int getRedundancy() {
//#[ operation getRedundancy()
return getStructure().getRedundancy();
//
}
public boolean hasResonanceIsomer() {
//#[ operation hasResonanceIsomer()
return (hasResonanceIsomerAsReactant() || hasResonanceIsomerAsProduct());
//
}
//## operation hasResonanceIsomerAsProduct()
public boolean hasResonanceIsomerAsProduct() {
//#[ operation hasResonanceIsomerAsProduct()
for (Iterator iter = getProducts(); iter.hasNext();) {
Species spe = ((Species)iter.next());
if (spe.hasResonanceIsomers()) return true;
}
return false;
//
}
//## operation hasResonanceIsomerAsReactant()
public boolean hasResonanceIsomerAsReactant() {
//#[ operation hasResonanceIsomerAsReactant()
for (Iterator iter = getReactants(); iter.hasNext();) {
Species spe = ((Species)iter.next());
if (spe.hasResonanceIsomers()) return true;
}
return false;
//
}
//## operation hasReverseReaction()
public boolean hasReverseReaction() {
//#[ operation hasReverseReaction()
return reverseReaction != null;
//
}
//## operation hashCode()
public int hashCode() {
//#[ operation hashCode()
// just use the structure's hashcode
return structure.hashCode();
//
}
//## operation isDuplicated(Reaction)
/*public boolean isDuplicated(Reaction p_reaction) {
//#[ operation isDuplicated(Reaction)
// the same structure, return true
Structure str1 = getStructure();
Structure str2 = p_reaction.getStructure();
//if (str1.isDuplicate(str2)) return true;
// if not the same structure, check the resonance isomers
if (!hasResonanceIsomer()) return false;
if (str1.equals(str2)) return true;
else return false;
//#]
}*/
//## operation isBackward()
public boolean isBackward() {
//#[ operation isBackward()
return structure.isBackward();
//
}
//## operation isForward()
public boolean isForward() {
//#[ operation isForward()
return structure.isForward();
//
}
//## operation isIncluded(HashSet)
public boolean isIncluded(HashSet p_speciesSet) {
//#[ operation isIncluded(HashSet)
return (allReactantsIncluded(p_speciesSet) && allProductsIncluded(p_speciesSet));
//
}
//## operation makeReaction(Structure,Kinetics,boolean)
public static Reaction makeReaction(Structure p_structure, Kinetics[] p_kinetics, boolean p_generateReverse) {
//#[ operation makeReaction(Structure,Kinetics,boolean)
if (!p_structure.repOk()) throw new InvalidStructureException(p_structure.toChemkinString(false).toString());
for (int numKinetics=0; numKinetics<p_kinetics.length; numKinetics++) {
if (!p_kinetics[numKinetics].repOk()) throw new InvalidKineticsException(p_kinetics[numKinetics].toString());
}
Reaction r = new Reaction(p_structure, p_kinetics);
if (p_generateReverse) {
r.generateReverseReaction();
}
else {
r.setReverseReaction(null);
}
return r;
//
}
//## operation reactantEqualsProduct()
public boolean reactantEqualsProduct() {
//#[ operation reactantEqualsProduct()
return getStructure().reactantEqualsProduct();
//
}
//## operation repOk()
public boolean repOk() {
//#[ operation repOk()
if (!structure.repOk()) {
Logger.error("Invalid Reaction Structure:" + structure.toString());
return false;
}
if (!isForward() && !isBackward()) {
Logger.error("Invalid Reaction Direction: " + String.valueOf(getDirection()));
return false;
}
if (isBackward() && reverseReaction == null) {
Logger.error("Backward Reaction without a reversed reaction defined!");
return false;
}
/*if (!getRateConstant().repOk()) {
Logger.error("Invalid Rate Constant: " + getRateConstant().toString());
return false;
}*/
Kinetics[] allKinetics = getKinetics();
for (int numKinetics=0; numKinetics<allKinetics.length; ++numKinetics) {
if (!allKinetics[numKinetics].repOk()) {
Logger.error("Invalid Kinetics: " + allKinetics[numKinetics].toString());
return false;
}
}
if (!checkRateRange()) {
Logger.error("reaction rate is higher than the upper rate limit!");
Logger.info(getStructure().toString());
Temperature tup = new Temperature(1500,"K");
if (isForward()) {
Logger.info("k(T=1500) = " + String.valueOf(calculateTotalRate(tup)));
}
else {
Logger.info("k(T=1500) = " + String.valueOf(calculateTotalRate(tup)));
Logger.info("Keq(T=1500) = " + String.valueOf(calculateKeq(tup)));
Logger.info("krev(T=1500) = " + String.valueOf(getReverseReaction().calculateTotalRate(tup)));
}
Logger.info(getKinetics().toString());
return false;
}
return true;
//
}
//## operation setReverseReaction(Reaction)
public void setReverseReaction(Reaction p_reverseReaction) {
//#[ operation setReverseReaction(Reaction)
reverseReaction = p_reverseReaction;
if (p_reverseReaction != null) reverseReaction.reverseReaction = this;
//
}
//## operation toChemkinString()
public String toChemkinString(Temperature p_temperature) {
//#[ operation toChemkinString()
if (ChemkinString != null)
return ChemkinString;
StringBuilder result = new StringBuilder();
String strucString = String.format("%-52s",getStructure().toChemkinString(hasReverseReaction()));
Temperature stdtemp = new Temperature(298,"K");
double Hrxn = calculateHrxn(stdtemp);
Kinetics[] allKinetics = getKinetics();
for (int numKinetics=0; numKinetics<allKinetics.length; ++numKinetics) {
String k = allKinetics[numKinetics].toChemkinString(Hrxn,p_temperature,true);
if (allKinetics.length == 1)
result.append(strucString + " " + k);
else
result.append(strucString + " " + k + "\nDUP\n");
}
if (result.charAt(result.length()-1)=='\n')
result.deleteCharAt(result.length()-1);
ChemkinString = result.toString();
return result.toString();
}
public String toChemkinString(Temperature p_temperature, Pressure p_pressure) {
// For certain PDep cases it's helpful to be able to call this with a temperature and pressure
// but usually (and in this case) the pressure is irrelevant, so we just call the above toChemkinString(Temperature) method:
return toChemkinString(p_temperature);
}
public String toRestartString(Temperature p_temperature, boolean pathReaction) {
/*
* Edited by MRH on 18Jan2010
*
* Writing restart files was causing a bug in the RMG-generated chem.inp file
* For example, H+CH4=CH3+H2 in input file w/HXD13, CH4, and H2
* RMG would correctly multiply the A factor by the structure's redundancy
* when calculating the rate to place in the ODEsolver input file. However,
* the A reported in the chem.inp file would be the "per event" A. This was
* due to the reaction.toChemkinString() method being called when writing the
* Restart coreReactions.txt and edgeReactions.txt files. At the first point of
* writing the chemkinString for this reaction (when it is still an edge reaction),
* RMG had not yet computed the redundancy of the structure (as H was not a core
* species at the time, but CH3 and H2 were). When RMG tried to write the chemkinString
* for the above reaction, using the correct redundancy, the chemkinString already existed
* and thus the toChemkinString() method was exited immediately.
* MRH is replacing the reaction.toChemkinString() call with reaction.toRestartString()
* when writing the Restart files, to account for this bug.
*/
String result = String.format("%-52s",getStructure().toRestartString(hasReverseReaction())); //+ " "+getStructure().direction + " "+getStructure().redundancy;
// MRH 18Jan2010: Restart files do not look for direction/redundancy
/*
* MRH 14Feb2010: Handle reactions with multiple kinetics
*/
String totalResult = "";
Kinetics[] allKinetics = getKinetics();
for (int numKinetics=0; numKinetics<allKinetics.length; ++numKinetics) {
totalResult += result + " " + allKinetics[numKinetics].toChemkinString(calculateHrxn(p_temperature),p_temperature,true);
if (allKinetics.length != 1) {
if (pathReaction) {
totalResult += "\n";
if (numKinetics != allKinetics.length-1) totalResult += getStructure().direction + "\t";
}
else totalResult += "\n\tDUP\n";
}
}
return totalResult;
}
/*
* MRH 23MAR2010:
* Method not used in RMG
*/
// //## operation toFullString()
// public String toFullString() {
// //#[ operation toFullString()
// return getStructure().toString() + getKinetics().toString() + getComments().toString();
// //
//## operation toString()
public String toString(Temperature p_temperature) {
//#[ operation toString()
String string2return = "";
Kinetics[] k = getKinetics();
for (int numKinetics=0; numKinetics<k.length; ++numKinetics) {
string2return += getStructure().toString() + "\t";
string2return += k[numKinetics].toChemkinString(calculateHrxn(p_temperature),p_temperature,false);
if (k.length > 1) string2return += "\n";
}
return string2return;
}
/*
* MRH 23MAR2010:
* This method is redundant to toString()
*/
//10/26/07 gmagoon: changed to take temperature as parameter (required changing function name from toString to reactionToString
// public String reactionToString(Temperature p_temperature) {
// // public String toString() {
// //#[ operation toString()
// // Temperature p_temperature = Global.temperature;
// Kinetics k = getKinetics();
// String kString = k.toChemkinString(calculateHrxn(p_temperature),p_temperature,false);
// return getStructure().toString() + '\t' + kString;
// //
public static double getBIMOLECULAR_RATE_UPPER() {
return BIMOLECULAR_RATE_UPPER;
}
public static double getUNIMOLECULAR_RATE_UPPER() {
return UNIMOLECULAR_RATE_UPPER;
}
public void setComments(String p_comments) {
comments = p_comments;
}
/**
* Returns the reverse reaction of this reaction. If there is no reverse reaction present
* then a null object is returned.
* @return
*/
public Reaction getReverseReaction() {
return reverseReaction;
}
public void setKinetics(Kinetics p_kinetics, int k_index) {
if (p_kinetics == null) {
kinetics = null;
}
else {
kinetics[k_index] = p_kinetics;
}
}
public void addAdditionalKinetics(Kinetics p_kinetics, int red, boolean readingFromUserLibrary) {
if (finalized)
return;
if (p_kinetics == null)
return;
if (kinetics == null){
kinetics = new Kinetics[1];
kinetics[0] = p_kinetics;
structure.redundancy = 1;
}
else if (readingFromUserLibrary || (!readingFromUserLibrary && !p_kinetics.isFromPrimaryKineticLibrary())) {
boolean kineticsAlreadyPresent = false;
for (int i=0; i<kinetics.length; i++) {
Kinetics old_kinetics = kinetics[i];
if (!( old_kinetics instanceof ArrheniusKinetics))
continue; // we can't compare or increment
if ( ((ArrheniusKinetics)old_kinetics).equalNESource(p_kinetics) )
{
((ArrheniusKinetics)old_kinetics).addToA( p_kinetics.getA().multiply((double)red) );
kineticsAlreadyPresent = true;
}
}
if (!kineticsAlreadyPresent) {
Kinetics[] tempKinetics = kinetics;
kinetics = new Kinetics[tempKinetics.length+1];
for (int i=0; i<tempKinetics.length; i++) {
kinetics[i] = tempKinetics[i];
}
kinetics[kinetics.length-1] = p_kinetics;
structure.redundancy = 1;
}
}
}
public void setFinalized(boolean p_finalized) {
finalized = p_finalized;
return;
}
public Structure getStructure() {
return structure;
}
public void setStructure(Structure p_Structure) {
structure = p_Structure;
}
/**
* Returns the reaction as an ASCII string.
* @return A string representing the reaction equation in ASCII test.
*/
@Override
public String toString() {
if (getReactantNumber() == 0 || getProductNumber() == 0)
return "";
String rxn = "";
Species species = (Species) structure.getReactantList().get(0);
rxn = rxn + species.getFullName() ;
for (int i = 1; i < getReactantNumber(); i++) {
species = (Species) structure.getReactantList().get(i);
rxn += " + " + species.getFullName() ;
}
rxn += "
species = (Species) structure.getProductList().get(0);
rxn = rxn + species.getFullName() ;
for (int i = 1; i < getProductNumber(); i++) {
species = (Species) structure.getProductList().get(i);
rxn += " + " + species.getFullName() ;
}
return rxn;
}
public String toInChIString() {
if (getReactantNumber() == 0 || getProductNumber() == 0)
return "";
String rxn = "";
Species species = (Species) structure.getReactantList().get(0);
rxn = rxn + species.getInChI();
for (int i = 1; i < getReactantNumber(); i++) {
species = (Species) structure.getReactantList().get(i);
rxn += " + " + species.getInChI();
}
rxn += "
species = (Species) structure.getProductList().get(0);
rxn = rxn + species.getInChI();
for (int i = 1; i < getProductNumber(); i++) {
species = (Species) structure.getProductList().get(i);
rxn += " + " + species.getInChI();
}
return rxn;
}
/**
* Calculates the flux of this reaction given the provided system snapshot.
* The system snapshot contains the temperature, pressure, and
* concentrations of each core species.
* @param ss The system snapshot at which to determine the reaction flux
* @return The determined reaction flux
*/
public double calculateFlux(SystemSnapshot ss) {
return calculateForwardFlux(ss) - calculateReverseFlux(ss);
}
/**
* Calculates the forward flux of this reaction given the provided system snapshot.
* The system snapshot contains the temperature, pressure, and
* concentrations of each core species.
* @param ss The system snapshot at which to determine the reaction flux
* @return The determined reaction flux
*/
public double calculateForwardFlux(SystemSnapshot ss) {
Temperature T = ss.getTemperature();
double forwardFlux = calculateTotalRate(T);
for (ListIterator<Species> iter = getReactants(); iter.hasNext(); ) {
Species spe = iter.next();
double conc = 0.0;
if (ss.getSpeciesStatus(spe) != null)
conc = ss.getSpeciesStatus(spe).getConcentration();
if (conc < 0) {
double aTol = ReactionModelGenerator.getAtol();
//if (Math.abs(conc) < aTol) conc = 0;
//else throw new NegativeConcentrationException(spe.getFullName() + ": " + String.valueOf(conc));
if (conc < -100.0 * aTol)
throw new NegativeConcentrationException("Species " + spe.getFullName() + " has negative concentration: " + String.valueOf(conc));
}
forwardFlux *= conc;
}
return forwardFlux;
}
/**
* Calculates the flux of this reaction given the provided system snapshot.
* The system snapshot contains the temperature, pressure, and
* concentrations of each core species.
* @param ss The system snapshot at which to determine the reaction flux
* @return The determined reaction flux
*/
public double calculateReverseFlux(SystemSnapshot ss) {
if (hasReverseReaction())
return reverseReaction.calculateForwardFlux(ss);
else
return 0.0;
}
public boolean isFromPrimaryKineticLibrary() {
return kineticsFromPrimaryKineticLibrary;
}
public void setIsFromPrimaryKineticLibrary(boolean p_boolean) {
kineticsFromPrimaryKineticLibrary = p_boolean;
}
public boolean hasMultipleKinetics() {
if (getKinetics().length > 1) return true;
else return false;
}
public void setExpectDuplicate(boolean b) {
expectDuplicate = b;
}
public boolean getExpectDuplicate() {
return expectDuplicate;
}
public void prune() {
// Do what's necessary to prune the reaction
// Also clears the reverse, so don't expect to be able to get it back
// Do santy check on the isFromPrimaryKineticLibrary() method we rely on.
// (This shouldn't be necessary, but we have no unit test framework so I'm building one in here!)
if (!isFromPrimaryKineticLibrary())
{
if (isForward())
if (getKineticsSource(0) != null)
if (getKineticsSource(0).contains("Library"))
throw new RuntimeException(String.format(
"Reaction %s kinetics source contains 'Library' but isFromPrimaryKineticLibrary() returned false.",this));
if (isBackward())
if (getReverseReaction().getKineticsSource(0) != null)
if (getReverseReaction().getKineticsSource(0).contains("Library"))
throw new RuntimeException(String.format(
"Reverse of reaction %s kinetics source contains 'Library' but isFromPrimaryKineticLibrary() returned false.",this));
// I'm not sure why we can't clear the reverse anyway - as long as the direction WITH kinetics still has a Structure we should be ok.
}
// Use isFromPrimaryKineticLibrary() to decide if it's safe to clear the reaction structure
if (!isFromPrimaryKineticLibrary()){
setStructure(null);
setReverseReaction(null);
}
}
}
|
package org.jboss.hal.testsuite.test.deployment;
import java.io.OutputStreamWriter;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.dmr.ModelNode;
import org.jboss.hal.meta.token.NameTokens;
import org.jboss.hal.resources.Ids;
import org.jboss.hal.testsuite.Random;
import org.jboss.hal.testsuite.creaper.ResourceVerifier;
import org.jboss.hal.testsuite.fragment.DialogFragment;
import org.jboss.hal.testsuite.fragment.FormFragment;
import org.jboss.hal.testsuite.fragment.UploadFormFragment;
import org.jboss.hal.testsuite.fragment.WizardFragment;
import org.jboss.hal.testsuite.fragment.finder.ColumnFragment;
import org.jboss.hal.testsuite.fragment.finder.FinderFragment;
import org.jboss.hal.testsuite.tooling.deployment.Deployment;
import org.jboss.hal.testsuite.util.Library;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.wildfly.extras.creaper.core.online.ModelNodeResult;
import org.wildfly.extras.creaper.core.online.operations.Address;
import org.wildfly.extras.creaper.core.online.operations.Operations;
import static org.jboss.hal.dmr.ModelDescriptionConstants.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
@RunWith(Arquillian.class)
public class StandaloneDeploymentTest extends AbstractDeploymentTest {
@Test
public void uploadDeployment() throws Exception {
deploymentPage.navigate();
Deployment deployment = createSimpleDeployment();
WizardFragment wizard = deploymentPage.uploadStandaloneDeployment();
wizard.getUploadForm().uploadFile(deployment.getDeploymentFile());
wizard.next(Ids.UPLOAD_NAMES_FORM);
wizard.finishStayOpen();
wizard.verifySuccess();
wizard.close();
new ResourceVerifier(deployment.getAddress(), client).verifyExists();
assertTrue("The deployment does not contain expected " + INDEX_HTML + " file.",
deploymentOps.deploymentContainsPath(deployment.getName(), INDEX_HTML));
}
@Test
public void verifyHash() throws Exception {
deploymentPage.navigate();
Deployment deployment = createSimpleDeployment();
WizardFragment wizard = deploymentPage.uploadStandaloneDeployment();
wizard.getUploadForm().uploadFile(deployment.getDeploymentFile());
wizard.next(Ids.UPLOAD_NAMES_FORM);
wizard.finishStayOpen();
wizard.verifySuccess();
wizard.close();
FinderFragment finder = console.finder(NameTokens.DEPLOYMENTS);
finder.column(Ids.DEPLOYMENT).selectItem(Ids.deployment(deployment.getName()));
String expected = finder.preview().getMainAttributes().get("Hash");
Operations ops = new Operations(client);
ModelNode content = ops.readAttribute(deployment.getAddress(), CONTENT).value();
byte[] hash = content.get(0).get(HASH).asBytes();
StringBuilder actual = new StringBuilder();
for (byte b : hash) {
int i = b;
if (i < 0) {
i = i & 0xff;
}
String hex = Integer.toHexString(i);
if (hex.length() == 1) {
actual.append('0');
}
actual.append(hex);
}
assertEquals(expected, actual.toString());
}
@Test
public void addUnmanagedDeployment() throws Exception {
deploymentPage.navigate();
Deployment deployment = createSimpleDeployment();
String
nameValue = deployment.getName(),
runtimeNameValue = Random.name(),
pathValue = deployment.getDeploymentFile().getAbsolutePath();
DialogFragment dialog = deploymentPage.addUnmanagedStandaloneDeployment();
FormFragment form = dialog.getForm(Ids.UNMANAGED_FORM);
form.text(NAME, nameValue);
form.text(RUNTIME_NAME, runtimeNameValue);
form.text(PATH, pathValue);
form.flip(ARCHIVE, true);
Library.letsSleep(500);
dialog.primaryButton();
new ResourceVerifier(deployment.getAddress(), client).verifyExists()
.verifyAttribute(NAME, nameValue)
.verifyAttribute(RUNTIME_NAME, runtimeNameValue);
assertEquals(pathValue, deploymentOps.getDeploymentPath(nameValue));
assertFalse(deploymentOps.deploymentIsExploded(nameValue));
}
@Test
public void enableDeployment() throws Exception {
String enableActionName = "Enable";
Deployment deployment = createSimpleDeployment();
ResourceVerifier deploymentVerifier = new ResourceVerifier(deployment.getAddress(), client);
client.apply(deployment.deployEnabledCommand());
deploymentVerifier.verifyExists().verifyAttribute(ENABLED, true);
deploymentPage.navigate();
assertFalse(enableActionName + " action should not be available for already enabled deployment.",
deploymentPage.isActionOnStandaloneDeploymentAvailable(deployment.getName(), enableActionName));
client.apply(deployment.disableCommand());
deploymentVerifier.verifyExists().verifyAttribute(ENABLED, false);
deploymentPage.navigate();
deploymentPage.callActionOnStandaloneDeployment(deployment.getName(), "Enable");
deploymentVerifier.verifyAttribute(ENABLED, true);
}
@Test
public void disableDeployment() throws Exception {
String disableActionName = "Disable";
Deployment deployment = createSimpleDeployment();
ResourceVerifier deploymentVerifier = new ResourceVerifier(deployment.getAddress(), client);
client.apply(deployment.deployEnabledCommand());
deploymentVerifier.verifyExists().verifyAttribute(ENABLED, true);
deploymentPage.navigate();
deploymentPage.callActionOnStandaloneDeployment(deployment.getName(), disableActionName);
deploymentVerifier.verifyAttribute(ENABLED, false);
deploymentPage.navigate();
assertFalse(disableActionName + " action should not be available for already disabled deployment.",
deploymentPage.isActionOnStandaloneDeploymentAvailable(deployment.getName(), disableActionName));
}
@Test
public void explodeDeployment() throws Exception {
String explodeActionName = "Explode";
Deployment deployment = createSimpleDeployment();
client.apply(deployment.deployEnabledCommand());
new ResourceVerifier(deployment.getAddress(), client).verifyExists();
deploymentPage.navigate();
assertFalse(explodeActionName + " action should not be available for enabled deployment.",
deploymentPage.isActionOnStandaloneDeploymentAvailable(deployment.getName(), explodeActionName));
client.apply(deployment.disableCommand());
assertFalse("Deployment should not be exploded yet.", deploymentOps.deploymentIsExploded(deployment.getName()));
deploymentPage.navigate();
deploymentPage.callActionOnStandaloneDeployment(deployment.getName(), explodeActionName);
Library.letsSleep(500);
assertTrue("Deployment should be exploded.", deploymentOps.deploymentIsExploded(deployment.getName()));
deploymentPage.navigate();
assertFalse(explodeActionName + " action should not be available for already exploded deployment.",
deploymentPage.isActionOnStandaloneDeploymentAvailable(deployment.getName(), explodeActionName));
}
@Test
public void replaceDeployment() throws Exception {
Deployment
originalDeployment = createSimpleDeployment(),
modifiedDeployment = createAnotherDeployment();
client.apply(originalDeployment.deployEnabledCommand());
new ResourceVerifier(originalDeployment.getAddress(), client).verifyExists();
assertTrue("The deployment does not contain expected " + INDEX_HTML + " original file.",
deploymentOps.deploymentContainsPath(originalDeployment.getName(), INDEX_HTML));
assertFalse("The deployment should not yet contain " + OTHER_HTML + " file.",
deploymentOps.deploymentContainsPath(originalDeployment.getName(), OTHER_HTML));
deploymentPage.navigate();
deploymentPage.callActionOnStandaloneDeployment(originalDeployment.getName(), "Replace");
DialogFragment uploadDialog = console.dialog();
UploadFormFragment.getUploadForm(uploadDialog.getRoot()).uploadFile(modifiedDeployment.getDeploymentFile());
uploadDialog.primaryButton();
Library.letsSleep(500);
assertFalse("The deployment should not any more contain " + INDEX_HTML + " file from original deployment.",
deploymentOps.deploymentContainsPath(originalDeployment.getName(), INDEX_HTML));
assertTrue("The deployment does not contain expected " + OTHER_HTML + " file.",
deploymentOps.deploymentContainsPath(originalDeployment.getName(), OTHER_HTML));
}
@Test
public void undeploy() throws Exception {
Deployment deployment = createSimpleDeployment();
ResourceVerifier deploymentVerifier = new ResourceVerifier(deployment.getAddress(), client);
client.apply(deployment.deployEnabledCommand());
deploymentVerifier.verifyExists();
deploymentPage.navigate();
deploymentPage.callActionOnStandaloneDeployment(deployment.getName(), "Undeploy");
console.confirmationDialog().confirm();
deploymentVerifier.verifyDoesNotExist();
}
@Test
public void createEmptyDeployment() throws Exception {
String deploymentName = createSimpleDeployment().getName();
deploymentPage.navigate();
DialogFragment dialog = deploymentPage.addEmptyStandaloneDeployment();
dialog.getForm(Ids.DEPLOYMENT_EMPTY_FORM).text(NAME, deploymentName);
Library.letsSleep(500);
dialog.primaryButton();
new ResourceVerifier(Address.deployment(deploymentName), client).verifyExists();
}
}
|
package com.linkedin.thirdeye.auto.onboard;
import com.fasterxml.jackson.databind.JsonNode;
import com.google.common.collect.Collections2;
import com.google.common.collect.Lists;
import com.linkedin.pinot.common.data.MetricFieldSpec;
import com.linkedin.pinot.common.data.Schema;
import com.linkedin.thirdeye.datalayer.bao.DatasetConfigManager;
import com.linkedin.thirdeye.datalayer.bao.MetricConfigManager;
import com.linkedin.thirdeye.datalayer.dto.DatasetConfigDTO;
import com.linkedin.thirdeye.datalayer.dto.MetricConfigDTO;
import com.linkedin.thirdeye.datalayer.pojo.MetricConfigBean;
import com.linkedin.thirdeye.datalayer.pojo.MetricConfigBean.DimensionAsMetricProperties;
import com.linkedin.thirdeye.datalayer.util.Predicate;
import com.linkedin.thirdeye.datasource.DAORegistry;
import com.linkedin.thirdeye.datasource.DataSourceConfig;
import com.linkedin.thirdeye.datasource.pinot.PinotThirdEyeDataSource;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.Nullable;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This is a service to onboard datasets automatically to thirdeye from pinot
* The run method is invoked periodically by the AutoOnboardService, and it checks for new tables in pinot, to add to thirdeye
* It also looks for any changes in dimensions or metrics to the existing tables
*/
public class AutoOnboardPinotDataSource extends AutoOnboard {
private static final Logger LOG = LoggerFactory.getLogger(AutoOnboardPinotDataSource.class);
private static final DAORegistry DAO_REGISTRY = DAORegistry.getInstance();
private final DatasetConfigManager datasetDAO;
private final MetricConfigManager metricDAO;
private AutoOnboardPinotMetricsUtils autoLoadPinotMetricsUtils;
public AutoOnboardPinotDataSource(DataSourceConfig dataSourceConfig)
throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
super(dataSourceConfig);
try {
autoLoadPinotMetricsUtils = new AutoOnboardPinotMetricsUtils(dataSourceConfig);
LOG.info("Created {}", AutoOnboardPinotDataSource.class.getName());
} catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
throw e;
}
this.datasetDAO = DAO_REGISTRY.getDatasetConfigDAO();
this.metricDAO = DAO_REGISTRY.getMetricConfigDAO();
}
public AutoOnboardPinotDataSource(DataSourceConfig dataSourceConfig, AutoOnboardPinotMetricsUtils utils) {
super(dataSourceConfig);
autoLoadPinotMetricsUtils = utils;
this.datasetDAO = DAO_REGISTRY.getDatasetConfigDAO();
this.metricDAO = DAO_REGISTRY.getMetricConfigDAO();
}
public void run() {
LOG.info("Running auto load for {}", AutoOnboardPinotDataSource.class.getSimpleName());
try {
List<String> allDatasets = new ArrayList<>();
Map<String, Schema> allSchemas = new HashMap<>();
Map<String, Map<String, String>> allCustomConfigs = new HashMap<>();
loadDatasets(allDatasets, allSchemas, allCustomConfigs);
LOG.info("Checking all datasets");
removeDeletedDataset(allDatasets);
for (String dataset : allDatasets) {
LOG.info("Checking dataset {}", dataset);
Schema schema = allSchemas.get(dataset);
Map<String, String> customConfigs = allCustomConfigs.get(dataset);
DatasetConfigDTO datasetConfig = datasetDAO.findByDataset(dataset);
addPinotDataset(dataset, schema, customConfigs, datasetConfig);
}
} catch (Exception e) {
LOG.error("Exception in loading datasets", e);
}
}
void removeDeletedDataset(List<String> allDatasets) {
LOG.info("Removing deleted Pinot datasets");
List<DatasetConfigDTO> allExsistingDataset = this.datasetDAO.findAll();
Set<String> datasets = new HashSet<>(allDatasets);
Collection<DatasetConfigDTO> filtered = Collections2.filter(allExsistingDataset, new com.google.common.base.Predicate<DatasetConfigDTO>() {
@Override
public boolean apply(@Nullable DatasetConfigDTO datasetConfigDTO) {
return datasetConfigDTO.getDataSource().equals(PinotThirdEyeDataSource.DATA_SOURCE_NAME);
}
});
for (DatasetConfigDTO datasetConfigDTO : filtered) {
if (shouldRemoveDataset(datasetConfigDTO, datasets)) {
datasetDAO.deleteByPredicate(Predicate.EQ("dataset", datasetConfigDTO.getDataset()));
}
}
}
private boolean shouldRemoveDataset(DatasetConfigDTO datasetConfigDTO, Set<String> datasets) {
if (!datasets.contains(datasetConfigDTO.getDataset())) {
List<MetricConfigDTO> metrics = metricDAO.findByDataset(datasetConfigDTO.getDataset());
int metricCount = metrics.size();
for (MetricConfigDTO metric : metrics) {
if (!metric.isDerived()) {
metricDAO.delete(metric);
metricCount
}
}
return metricCount == 0;
} else {
return false;
}
}
/**
* Adds a dataset to the thirdeye database
* @param dataset
* @param schema
* @param datasetConfig
*/
public void addPinotDataset(String dataset, Schema schema, Map<String, String> customConfigs,
DatasetConfigDTO datasetConfig) throws Exception {
if (datasetConfig == null) {
LOG.info("Dataset {} is new, adding it to thirdeye", dataset);
addNewDataset(dataset, schema, customConfigs);
} else {
LOG.info("Dataset {} already exists, checking for updates", dataset);
refreshOldDataset(dataset, schema, customConfigs, datasetConfig);
}
}
/**
* Adds a new dataset to the thirdeye database
* @param dataset
* @param schema
*/
private void addNewDataset(String dataset, Schema schema, Map<String, String> customConfigs) throws Exception {
List<MetricFieldSpec> metricSpecs = schema.getMetricFieldSpecs();
// Create DatasetConfig
DatasetConfigDTO datasetConfigDTO = ConfigGenerator.generateDatasetConfig(dataset, schema, customConfigs);
LOG.info("Creating dataset for {}", dataset);
this.datasetDAO.save(datasetConfigDTO);
// Create MetricConfig
for (MetricFieldSpec metricFieldSpec : metricSpecs) {
MetricConfigDTO metricConfigDTO = ConfigGenerator.generateMetricConfig(metricFieldSpec, dataset);
LOG.info("Creating metric {} for {}", metricConfigDTO.getName(), dataset);
this.metricDAO.save(metricConfigDTO);
}
}
/**
* Refreshes an existing dataset in the thirdeye database
* with any dimension/metric changes from pinot schema
* @param dataset
* @param schema
* @param datasetConfig
*/
private void refreshOldDataset(String dataset, Schema schema, Map<String, String> customConfigs,
DatasetConfigDTO datasetConfig) throws Exception {
checkDimensionChanges(dataset, datasetConfig, schema);
checkMetricChanges(dataset, datasetConfig, schema);
appendNewCustomConfigs(datasetConfig, customConfigs);
}
private void checkDimensionChanges(String dataset, DatasetConfigDTO datasetConfig, Schema schema) {
LOG.info("Checking for dimensions changes in {}", dataset);
List<String> schemaDimensions = schema.getDimensionNames();
List<String> datasetDimensions = datasetConfig.getDimensions();
// in dimensionAsMetric case, the dimension name will be used in the METRIC_NAMES_COLUMNS property of the metric
List<String> dimensionsAsMetrics = new ArrayList<>();
List<MetricConfigDTO> metricConfigs = DAO_REGISTRY.getMetricConfigDAO().findByDataset(dataset);
for (MetricConfigDTO metricConfig : metricConfigs) {
if (metricConfig.isDimensionAsMetric()) {
Map<String, String> metricProperties = metricConfig.getMetricProperties();
if (MapUtils.isNotEmpty(metricProperties)) {
String metricNames = metricProperties.get(DimensionAsMetricProperties.METRIC_NAMES_COLUMNS.toString());
if (StringUtils.isNotBlank(metricNames)) {
dimensionsAsMetrics.addAll(Lists.newArrayList(metricNames.split(MetricConfigBean.METRIC_PROPERTIES_SEPARATOR)));
}
}
}
}
List<String> dimensionsToAdd = new ArrayList<>();
List<String> dimensionsToRemove = new ArrayList<>();
// dimensions which are new in the pinot schema
for (String dimensionName : schemaDimensions) {
if (!datasetDimensions.contains(dimensionName) && !dimensionsAsMetrics.contains(dimensionName)) {
dimensionsToAdd.add(dimensionName);
}
}
// dimensions which are removed from pinot schema
for (String dimensionName : datasetDimensions) {
if (!schemaDimensions.contains(dimensionName)) {
dimensionsToRemove.add(dimensionName);
}
}
if (CollectionUtils.isNotEmpty(dimensionsToAdd) || CollectionUtils.isNotEmpty(dimensionsToRemove)) {
datasetDimensions.addAll(dimensionsToAdd);
datasetDimensions.removeAll(dimensionsToRemove);
datasetConfig.setDimensions(datasetDimensions);
if (!datasetConfig.isAdditive()
&& CollectionUtils.isNotEmpty(datasetConfig.getDimensionsHaveNoPreAggregation())) {
List<String> dimensionsHaveNoPreAggregation = datasetConfig.getDimensionsHaveNoPreAggregation();
dimensionsHaveNoPreAggregation.removeAll(dimensionsToRemove);
datasetConfig.setDimensionsHaveNoPreAggregation(dimensionsHaveNoPreAggregation);
}
LOG.info("Added dimensions {}, removed {}", dimensionsToAdd, dimensionsToRemove);
DAO_REGISTRY.getDatasetConfigDAO().update(datasetConfig);
}
}
private void checkMetricChanges(String dataset, DatasetConfigDTO datasetConfig, Schema schema) {
LOG.info("Checking for metric changes in {}", dataset);
List<MetricFieldSpec> schemaMetricSpecs = schema.getMetricFieldSpecs();
List<MetricConfigDTO> datasetMetricConfigs = DAO_REGISTRY.getMetricConfigDAO().findByDataset(dataset);
Set<String> datasetMetricNames = new HashSet<>();
for (MetricConfigDTO metricConfig : datasetMetricConfigs) {
// In dimensionAsMetric case, the metric name will be used in the METRIC_VALUES_COLUMN property of the metric
if (metricConfig.isDimensionAsMetric()) {
Map<String, String> metricProperties = metricConfig.getMetricProperties();
if (MapUtils.isNotEmpty(metricProperties)) {
String metricValuesColumn = metricProperties.get(DimensionAsMetricProperties.METRIC_VALUES_COLUMN.toString());
datasetMetricNames.add(metricValuesColumn);
}
} else {
datasetMetricNames.add(metricConfig.getName());
}
}
List<Long> metricsToAdd = new ArrayList<>();
for (MetricFieldSpec metricSpec : schemaMetricSpecs) {
// metrics which are new in pinot schema, create them
String metricName = metricSpec.getName();
if (!datasetMetricNames.contains(metricName)) {
MetricConfigDTO metricConfigDTO = ConfigGenerator.generateMetricConfig(metricSpec, dataset);
LOG.info("Creating metric {} for {}", metricName, dataset);
metricsToAdd.add(DAO_REGISTRY.getMetricConfigDAO().save(metricConfigDTO));
}
}
// TODO: write a tool, which given a metric id, erases all traces of that metric from the database
// This will include:
// 1) delete the metric from metricConfigs
// 2) remove any derived metrics which use the deleted metric
// 3) remove the metric, and derived metrics from all dashboards
// 4) remove any anomaly functions associated with the metric
// 5) remove any alerts associated with these anomaly functions
}
/**
* This method ensures that the given custom configs exist in the dataset config and their value are the same.
*
* @param datasetConfig the current dataset config to be appended with new custom config.
* @param customConfigs the custom config to be matched with that from dataset config.
*
* TODO: Remove out-of-date Pinot custom config from dataset config.
*/
private void appendNewCustomConfigs(DatasetConfigDTO datasetConfig, Map<String, String> customConfigs) {
if (MapUtils.isNotEmpty(customConfigs)) {
Map<String, String> properties = datasetConfig.getProperties();
boolean hasUpdate = false;
if (MapUtils.isEmpty(properties)) {
properties = customConfigs;
hasUpdate = true;
} else {
for (Map.Entry<String, String> customConfig : customConfigs.entrySet()) {
String configKey = customConfig.getKey();
String configValue = customConfig.getValue();
if (!properties.containsKey(configKey)) {
properties.put(configKey, configValue);
hasUpdate = true;
}
}
}
if (hasUpdate) {
datasetConfig.setProperties(properties);
DAO_REGISTRY.getDatasetConfigDAO().update(datasetConfig);
}
}
}
/**
* Reads all table names in pinot, and loads their schema
* @param allSchemas
* @param allDatasets
* @throws IOException
*/
private void loadDatasets(List<String> allDatasets, Map<String, Schema> allSchemas,
Map<String, Map<String, String>> allCustomConfigs) throws IOException {
JsonNode tables = autoLoadPinotMetricsUtils.getAllTablesFromPinot();
LOG.info("Getting all schemas");
for (JsonNode table : tables) {
String dataset = table.asText();
Map<String, String> pinotCustomProperty = autoLoadPinotMetricsUtils.getCustomConfigsFromPinotEndpoint(dataset);
Schema schema = autoLoadPinotMetricsUtils.getSchemaFromPinot(dataset);
if (schema != null) {
if (!autoLoadPinotMetricsUtils.verifySchemaCorrectness(schema)) {
LOG.info("Skipping {} due to incorrect schema", dataset);
} else {
allDatasets.add(dataset);
allSchemas.put(dataset, schema);
allCustomConfigs.put(dataset, pinotCustomProperty);
}
}
}
}
@Override
public void runAdhoc() {
LOG.info("Triggering adhoc run for AutoOnboard Pinot data source");
run();
}
}
|
package org.sagebionetworks.tool.migration.v3;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.Callable;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.sagebionetworks.client.SynapseAdministrationInt;
import org.sagebionetworks.client.exceptions.SynapseException;
import org.sagebionetworks.repo.model.DaemonStatusUtil;
import org.sagebionetworks.repo.model.daemon.BackupRestoreStatus;
import org.sagebionetworks.repo.model.daemon.DaemonStatus;
import org.sagebionetworks.repo.model.daemon.RestoreSubmission;
import org.sagebionetworks.repo.model.migration.IdList;
import org.sagebionetworks.repo.model.migration.ListBucketProvider;
import org.sagebionetworks.repo.model.migration.MigrationType;
import org.sagebionetworks.repo.model.migration.MigrationUtils;
import org.sagebionetworks.repo.model.migration.RowMetadata;
import org.sagebionetworks.schema.adapter.JSONObjectAdapterException;
import org.sagebionetworks.tool.migration.Progress.BasicProgress;
public class CreateUpdateWorker implements Callable<Long>, BatchWorker {
static private Log log = LogFactory.getLog(CreateUpdateWorker.class);
// Restore takes takes up 75% of the time
private static final float RESTORE_FRACTION = 75.0f/100.0f;
// Backup takes 25% of the time.
private static final float BAKUP_FRACTION = 1.0f-RESTORE_FRACTION;
MigrationType type;
long count;
Iterator<RowMetadata> iterator;
BasicProgress progress;
SynapseAdministrationInt destClient;
SynapseAdministrationInt sourceClient;
long batchSize;
long timeoutMS;
int retryDenominator;
/**
*
* @param type - The type to be migrated.
* @param count - The number of items in the iterator to be migrated.
* @param iterator - Abstraction for iterating over the objects to be migrated.
* @param progress - The worker will update the progress objects so its progress can be monitored externally.
* @param destClient - A handle to the destination SynapseAdministration client. Data will be pushed to the destination.
* @param sourceClient - A handle to the source SynapseAdministration client. Data will be pulled from the source.
* @param batchSize - Data is migrated in batches. This controls the size of the batches.
* @param timeout - How long should the worker wait for Daemon job to finish its task before timing out in milliseconds.
* @param retryDenominator - If a daemon fails to backup or restore a single batch, the worker will divide the batch into sub-batches
* using this number as the denominator. An attempt will then be made to retry the migration of each sub-batch in an attempt to isolate the problem.
* If this is set to less than 2, then no re-try will be attempted.
*/
public CreateUpdateWorker(MigrationType type, long count, Iterator<RowMetadata> iterator, BasicProgress progress,
SynapseAdministrationInt destClient,
SynapseAdministrationInt sourceClient, long batchSize, long timeoutMS, int retryDenominator) {
super();
this.type = type;
this.count = count;
this.iterator = iterator;
this.progress = progress;
this.progress.setCurrent(0);
this.progress.setTotal(count);
this.destClient = destClient;
this.sourceClient = sourceClient;
this.batchSize = batchSize;
this.timeoutMS = timeoutMS;
this.retryDenominator = retryDenominator;
}
@Override
public Long call() throws Exception {
// First we need to calculate the required buckets.
ListBucketProvider provider = new ListBucketProvider();
// This utility will guarantee that all parents are in buckets that proceed their children
// so as long as we create the buckets in order, all parents and their children can be created
// without foreign key constraint violations.
progress.setMessage("Bucketing by tree level...");
MigrationUtils.bucketByTreeLevel(this.iterator, provider);
List<List<Long>> listOfBuckets = provider.getListOfBuckets();
// Send each bucket batched.
long updateCount = 0;
for(List<Long> bucket: listOfBuckets){
updateCount += backupBucketAsBatch(bucket.iterator());
}
progress.setDone();
return updateCount;
}
/**
* Backup a single bucket
* @param bucketIt
* @return
* @throws Exception
*/
private long backupBucketAsBatch(Iterator<Long> bucketIt) throws Exception{
// Iterate and create batches.
Long id = null;
List<Long> batch = new LinkedList<Long>();
long updateCount = 0;
while(bucketIt.hasNext()){
id = bucketIt.next();
if(id != null){
batch.add(id);
if(batch.size() >= batchSize){
migrateBatch(batch);
updateCount += batch.size();
batch.clear();
}
}
}
// If there is any data left in the batch send it
if(batch.size() > 0){
migrateBatch(batch);
updateCount += batch.size();
batch.clear();
}
return updateCount;
}
/**
* Migrate the batches
* @param ids
* @throws Exception
*/
protected void migrateBatch(List<Long> ids) throws Exception {
// This utility will first attempt to execute the batch.
// If there are failures it will break the batch into sub-batches and attempt to execute eatch sub-batch.
BatchUtility.attemptBatchWithRetry(this.retryDenominator, this, ids);
}
/**
* Attempt to migrate a single batch.
* @param ids
* @throws JSONObjectAdapterException
* @throws SynapseException
* @throws InterruptedException
*/
public boolean attemptBatch(List<Long> ids) throws JSONObjectAdapterException, SynapseException, InterruptedException {
int listSize = ids.size();
progress.setMessage("Starting backup daemon for "+listSize+" objects");
// Start a backup.
IdList request = new IdList();
request.setList(ids);
BackupRestoreStatus status = this.sourceClient.startBackup(type, request);
// Wait for the backup to complete
status = waitForDaemon(status.getId(), this.sourceClient);
// Now restore this to the destination
String backupFileName = getFileNameFromUrl(status.getBackupUrl());
RestoreSubmission restoreSub = new RestoreSubmission();
restoreSub.setFileName(backupFileName);
status = this.destClient.startRestore(type, restoreSub);
// Wait for the backup to complete
status = waitForDaemon(status.getId(), this.destClient);
// Update the progress
progress.setMessage("Finished restore for "+listSize+" objects");
progress.setCurrent(progress.getCurrent()+listSize);
return true;
}
/**
* Wait for a daemon to finish.
* @param daemonId
* @param client
* @return
* @throws SynapseException
* @throws JSONObjectAdapterException
* @throws InterruptedException
*/
public BackupRestoreStatus waitForDaemon(String daemonId, SynapseAdministrationInt client)
throws SynapseException, JSONObjectAdapterException,
InterruptedException {
// Wait for the daemon to finish.
long start = System.currentTimeMillis();
while (true) {
long now = System.currentTimeMillis();
if(now-start > timeoutMS){
log.debug("Timeout waiting for daemon to complete");
throw new InterruptedException("Timed out waiting for the daemon to complete");
}
BackupRestoreStatus status = client.getStatus(daemonId);
progress.setMessage(String.format("\t Waiting for daemon: %1$s id: %2$s", status.getType().name(), status.getId()));
// Check to see if we failed.
if(DaemonStatus.FAILED == status.getStatus()){
log.debug("Daemon failure");
throw new DaemonFailedException("Failed: "+status.getType()+" message:"+status.getErrorMessage());
}
// Are we done?
if (DaemonStatus.COMPLETED == status.getStatus()) {
logStatus(status);
return status;
} else {
logStatus(status);
}
// Wait.
Thread.sleep(2000);
}
}
/**
* Log the status if trace is enabled.
* @param status
*/
public void logStatus(BackupRestoreStatus status) {
if (log.isTraceEnabled()) {
String format = "Worker: %1$-10d : %2$s";
String statString = DaemonStatusUtil.printStatus(status);
log.trace(String.format(format, Thread.currentThread().getId(), statString));
}
}
/**
* Extract the filename from the full url.
* @param fullUrl
* @return
*/
public String getFileNameFromUrl(String fullUrl){;
int index = fullUrl.lastIndexOf("/");
return fullUrl.substring(index+1, fullUrl.length());
}
}
|
package won.protocol.highlevel;
import java.util.function.Function;
import org.apache.jena.query.Dataset;
import org.apache.jena.rdf.model.Model;
import won.protocol.util.DatasetSelectionBySparqlFunction;
public class HighlevelProtocols {
/**
* Calculates all agreements present in the specified conversation dataset.
*/
public static Dataset getAgreements(Dataset conversationDataset) {
DatasetSelectionBySparqlFunction acknowledgedSelection = HighlevelFunctionFactory.getAcknowledgedSelection();
DatasetSelectionBySparqlFunction modifiedSelection = HighlevelFunctionFactory.getModifiedSelection();
Function<Dataset, Dataset> agreementFunction = HighlevelFunctionFactory.getAgreementFunction();
Dataset acknowledged = acknowledgedSelection.apply(conversationDataset);
Dataset modified = modifiedSelection.apply(acknowledged);
Dataset agreed = agreementFunction.apply(modified);
return agreed;
}
/**
* Calculates all open proposals present in the specified conversation dataset.
* Returns the envelope graph of the proposal with the contents of the proposed
* message inside.
* @param conversationDataset
* @return
*/
public static Dataset getProposals(Dataset conversationDataset) {
DatasetSelectionBySparqlFunction acknowledgedSelection = HighlevelFunctionFactory.getAcknowledgedSelection();
DatasetSelectionBySparqlFunction modifiedSelection = HighlevelFunctionFactory.getModifiedSelection();
Function<Dataset, Dataset> proposalFunction = HighlevelFunctionFactory.getProposalFunction();
// Try something like:
// proposed -> acknowledgedSelection.andThen(modifiedSelection).andThen(proposalFunction).apply(proposed)
Dataset acknowledged = acknowledgedSelection.apply(conversationDataset);
Dataset modified = modifiedSelection.apply(acknowledged);
Dataset proposed = proposalFunction.apply(modified);
return proposed;
}
/** reveiw and rewrite the JavaDoc descriptions below **/
/**
* Calculates all open proposals to cancel present in the specified conversation dataset.
* returns envelope graph of the proposaltocancel with the contents of the target agreement to
* cancel inside.
* @param conversationDataset
* @return
*/
public static Dataset getProposalsToCancel(Dataset conversationDataset) {
Function<Dataset, Dataset> acknowledgedSelection = HighlevelFunctionFactory.getAcknowledgedSelection();
DatasetSelectionBySparqlFunction modifiedSelection = HighlevelFunctionFactory.getModifiedSelection();
Function<Dataset, Dataset> proposalToCancelFunction = HighlevelFunctionFactory.getProposalToCancelFunction();
Dataset acknowledged = acknowledgedSelection.apply(conversationDataset);
Dataset modified = modifiedSelection.apply(acknowledged);
Dataset proposedtocancel = proposalToCancelFunction.apply(modified);
return proposedtocancel;
}
/**
* Returns ?openprop agr:proposes ?openclause .
* ?openprop == unaccepted propsal
* ?openclause == proposed clause that is unaccepted
* @param conversationDataset
* @return
*/
public static Model getPendingProposes(Dataset conversationDataset) {
Model pendingproposes = HighlevelFunctionFactory.getPendingProposesFunction().apply(conversationDataset);
return pendingproposes;
}
/**
* Returns ?openprop agr:proposesToCancel ?acc .
* ?openprop == unaccepted proposal to cancel
* ?acc == agreement proposed for cancellation
* @param conversationDataset
* @return
*/
public static Model getPendingProposesToCancel(Dataset conversationDataset) {
Model pendingproposestocancel = HighlevelFunctionFactory.getPendingProposesToCancelFunction().apply(conversationDataset);
return pendingproposestocancel;
}
/**
* Returns ?prop agr:proposes ?clause .
* ?prop == accepted proposal in an agreement
* ?clause == accepted clause in an agreement
* @param conversationDataset
* @return
*/
public static Model getAcceptedProposes(Dataset conversationDataset) {
Model acceptedproposes = HighlevelFunctionFactory.getAcceptedProposesFunction().apply(conversationDataset);
return acceptedproposes;
}
/**
* Returns ?acc agr:accepts ?prop .
* ?prop == accepted proposal in an agreement
* ?acc == agreement
* @param conversationDataset
* @return
*/
public static Model getAcceptsProposes(Dataset conversationDataset) {
Model acceptsproposes = HighlevelFunctionFactory.getAcceptsProposesFunction().apply(conversationDataset);
return acceptsproposes;
}
/**
* Returns ?cancelProp2 agr:proposesToCancel ?acc .
* ?cancelProp2 == accepted proposal to cancel
* ?acc == agreement proposed for cancellation
* @param conversationDataset
* @return
*/
public static Model getAcceptedProposesToCancel(Dataset conversationDataset) {
Model acceptedproposestocancel = HighlevelFunctionFactory.getAcceptedProposesToCancelFunction().apply(conversationDataset);
return acceptedproposestocancel;
}
/**
* Returns ?cancelAcc2 agr:accepts ?cancelProp2 .
* ?cancelProp2 . == accepted proposal to cancel
* ?cancelAcc2 == cancallation agreement
* @param conversationDataset
* @return
*/
public static Model getAcceptsProposesToCancel(Dataset conversationDataset) {
Model acceptsproposestocancel = HighlevelFunctionFactory.getAcceptsProposesToCancelFunction().apply(conversationDataset);
return acceptsproposestocancel;
}
/**
* Returns ?prop agr:proposes ?clause .
* ?prop == accepted proposal in agreement that was cancelled
* ?clause == accepted clause in an agreement that was cancelled
* @param conversationDataset
* @return
*/
public static Model getProposesInCancelledAgreement(Dataset conversationDataset) {
Model proposesincancelledagreement = HighlevelFunctionFactory.getProposesInCancelledAgreementFunction().apply(conversationDataset);
return proposesincancelledagreement;
}
/**
* Returns ?acc agr:accepts ?prop .
* ?acc == agreement that was cancelled
* ?prop == accepted proposal in agreement that was cancelled
* @param conversationDataset
* @return
*/
public static Model getAcceptsInCancelledAgreement(Dataset conversationDataset) {
Model acceptscancelledagreement = HighlevelFunctionFactory.getAcceptsInCancelledAgreementFunction().apply(conversationDataset);
return acceptscancelledagreement;
}
/**
* Returns ?retractingMsg mod:retracts ?retractedMsg .
* ?retractingMsg == message containing mod:retracts
* ?retractedMsg == message that was retracted
* @param conversationDataset
* @return
*/
public static Model getAcceptedRetracts(Dataset conversationDataset) {
Model acceptedretracts = HighlevelFunctionFactory.getAcceptedRetractsFunction().apply(conversationDataset);
return acceptedretracts;
}
}
|
package buildingblock.sorting.merge.lc350_intersectionoftwoarrays2;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
/**
* Given two arrays, write a function to compute their intersection.
* Example: Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2, 2].
* Note: Each element in the result should appear as many times as it shows in both arrays.
* The result can be in any order.
* Follow up:
* What if the given array is already sorted? How would you optimize your algorithm?
* What if nums1's size is small compared to nums2's size? Which algorithm is better?
* What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?
*/
public class Solution {
// My 2nd
// Why lambda is very slow...
public int[] intersection_lambda(int[] nums1, int[] nums2) {
Set<Integer> set = Arrays.stream(nums2).boxed().collect(Collectors.toSet());
return Arrays.stream(nums1).distinct().filter(set::contains).toArray();
}
public int[] intersection(int[] nums1, int[] nums2) {
Arrays.sort(nums1);
Arrays.sort(nums2);
Set<Integer> intersect = new HashSet<>();
for (int i = 0, j = 0; i < nums1.length && j < nums2.length; ) {
if (nums1[i] > nums2[j]) j++;
else if (nums1[i] < nums2[j]) i++;
else {
intersect.add(nums1[i]);
i++;
j++;
}
}
int[] result = new int[intersect.size()];
int i = 0;
for (int num : intersect) result[i++] = num;
return result;
}
// Solution2: faster
public int[] intersect2(int[] nums1, int[] nums2) {
Map<Integer,Integer> map2 = toMap(nums2);
// Compute retailAll() manually
List<Integer> list = new ArrayList<>();
for (int n : nums1) {
Integer count = map2.get(n);
if (count == null) {
continue;
}
if (count == 1) {
map2.remove(n);
} else {
map2.put(n, count - 1);
}
list.add(n);
}
// Conver to primitive array
int[] result = new int[list.size()];
for (int i = 0; i < result.length; i++) {
result[i] = list.get(i);
}
return result;
}
// Solution3: Correct but a little slow, since one Map is enough!
public int[] intersect3(int[] nums1, int[] nums2) {
Map<Integer,Integer> map1 = toMap(nums1);
Map<Integer,Integer> map2 = toMap(nums2);
//map1.retainAll(map2); // unaccessible in Map interface
return toArray(map1, map2);
}
private Map<Integer,Integer> toMap(int[] nums) {
Map<Integer,Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
Integer cnt = map.get(nums[i]);
if (cnt == null) {
cnt = 0;
}
map.put(nums[i], cnt + 1);
}
return map;
}
private int[] toArray(Map<Integer,Integer> map1, Map<Integer,Integer> map2) {
// Compute retailAll() manually
List<Integer> list = new ArrayList<>();
for (Map.Entry<Integer,Integer> e : map1.entrySet()) {
if (!map2.containsKey(e.getKey())) {
continue;
}
//int count = e.getValue() + map2.get(e.getKey());
int count = Math.min(e.getValue(), map2.get(e.getKey())); // "as it shows in both arrays" doesn't mean total
while (count
list.add(e.getKey());
}
}
// Conver to primitive array
int[] result = new int[list.size()];
for (int i = 0; i < result.length; i++) {
result[i] = list.get(i);
}
return result;
}
}
|
package com.radish.choiceview;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.ServletConfig;
import java.util.concurrent.*;
import java.util.*;
import org.apache.log4j.*;
import com.radishsystems.choiceview.webapi.*;
import java.io.*;
import java.text.*;
/**
* @author Derek Teuscher
*/
public class ChoiceViewServlet extends HttpServlet {
/* Instantiate a logger named ServletLogger */
private static Logger mylogger = null;
private static Properties logProperties = null;
private static ServletConfig cfg = null;
private static boolean loggedMessage = false;
private static Map <String, Thread>cvThreads;
public ChoiceViewServlet() {
}
/* (non-Javadoc)
* @see javax.servlet.GenericServlet#init()
*/
@Override
public void init() throws ServletException {
super.init();
cfg = getServletConfig();
if(cfg == null){
System.out.println("*** The ServletConfig is null");
}
initLogger();
cvThreads = new HashMap();
mylogger.debug("Starting ChoiceView Servlet");
}
public static boolean addSession(String sessionID, ChoiceViewSession cvs, String sessionURL, String basicHttpID){
if(cvThreads.containsKey(sessionID)){
mylogger.warn("Session " + sessionID + " already exists");
return false;
}else{
ChoiceViewPollingThread checker = new ChoiceViewPollingThread(sessionID, cvs, sessionURL, basicHttpID);
checker.setLogger(mylogger);
Thread t = new Thread(checker);
t.start();
cvThreads.put(sessionID, t);
mylogger.debug("Started new ChoiceView Polling Thread; SessionID: " + sessionID + ". ThreadID: " + t.getId());
}
return true;
}
public static boolean removeSession(String sessionID){
if(cvThreads.containsKey(sessionID)){
Thread cvThread = cvThreads.get(sessionID);
mylogger.debug("Stopping ChoiceView Polling Thread; SessionID: " + sessionID + ". ThreadID: " + cvThread.getId());
while(cvThread != null && cvThread.isAlive()){
cvThread.interrupt();
try{
cvThread.join();
}catch(InterruptedException ie){
mylogger.debug("shut down thread: " + cvThread.getId());
}
}
mylogger.debug("ChoiceView Polling Thread Stopped; SessionID: " + sessionID + ". ThreadID: " + cvThread.getId());
cvThreads.remove(sessionID);
}else{
mylogger.warn("Session " + sessionID + " does not exist. Can't remove session.");
return false;
}
return true;
}
/**
* Initialize the log 4j stuff
*/
private static void initLogger(){
logProperties = new Properties();
try{
String ddHome;
if(cfg != null){
ddHome = cfg.getInitParameter("DDAppHome");
}else{
System.out.println("*** The ServletConfig is null. Using default for DDAppHome.");
ddHome = "/usr/share/tomcat6/webapps/VoxeoRadishDemo";
}
String log4jFile = ddHome + "/data/ddlog4j.properties";
File logDir = new File( ddHome + "/data/log");
if(logDir.exists() == false){
logDir.mkdir();
}
logProperties.load(new FileInputStream(log4jFile));
logProperties.setProperty("dd.apphome", ddHome);
PropertyConfigurator.configure(logProperties);
mylogger = Logger.getLogger("Servlet");
mylogger.debug("Initialized ChoiceViewServlet logger.");
}catch(Exception e){
BasicConfigurator.configure();
mylogger = Logger.getRootLogger();
mylogger.error("Couldn't load the log4j properties. Using StdOut.", e);
}
}
/* (non-Javadoc)
* @see javax.servlet.GenericServlet#destroy()
*/
@Override
public void destroy() {
mylogger.debug("Stopping ChoiceViewServlet servlet");
//if Tomcat shuts down, we need to stop all of our threads if any;
Set keys = cvThreads.keySet();
for(Iterator it =keys.iterator(); it.hasNext();){
String key = (String) it.next();
Thread t = (Thread) cvThreads.get(key);
while (t.isAlive()) {
t.interrupt();
try{
t.join();
}catch(InterruptedException ie){
mylogger.debug("shut down thread: " + t.getId());
}
}
//now that all of the treads have stopped, then remove them from the map.
cvThreads.remove(key);
}
super.destroy();
}
/**
* @param args
*/
public static void main(String[] args) {
ChoiceViewServlet servlet = new ChoiceViewServlet();
try{
servlet.init();
}catch(Exception e){
e.printStackTrace();
}finally{
servlet.destroy();
}
}
}
|
package de.uka.ipd.sdq.beagle.core.judge;
import de.uka.ipd.sdq.beagle.core.BlackboardStorer;
import de.uka.ipd.sdq.beagle.core.ExternalCallParameter;
import de.uka.ipd.sdq.beagle.core.ResourceDemandingInternalAction;
import de.uka.ipd.sdq.beagle.core.SeffBranch;
import de.uka.ipd.sdq.beagle.core.SeffLoop;
import de.uka.ipd.sdq.beagle.core.measurement.BranchDecisionMeasurementResult;
import de.uka.ipd.sdq.beagle.core.measurement.ParameterChangeMeasurementResult;
import de.uka.ipd.sdq.beagle.core.measurement.ResourceDemandMeasurementResult;
import java.io.Serializable;
import java.util.Set;
/**
* Interface for Blackboard views designed to be passed to an
* {@link EvaluableExpressionFitnessFunction}. Provides reading and writing access for
* custom data on the Blackboard as well as access to the {@code getMeasurementResultsFor}
* methods.
*
* @author Christoph Michelbach
* @author Joshua Gleitze
*/
public interface EvaluableExpressionFitnessFunctionBlackboardView {
/**
* Delegates to
* {@link de.uka.ipd.sdq.beagle.core.Blackboard#getMeasurementResultsFor(ResourceDemandingInternalAction)}
* .
*
* @param rdia An resource demanding internal action to get the measurement results
* of. Must not be {@code null}.
* @return All measurement results reported for {@code rdia}. Changes to the returned
* set will not modify the blackboard content. Is never {@code null}.
* @see de.uka.ipd.sdq.beagle.core.Blackboard#getMeasurementResultsFor(ResourceDemandingInternalAction)
*/
Set<ResourceDemandMeasurementResult> getMeasurementResultsFor(ResourceDemandingInternalAction rdia);
/**
* Delegates to
* {@link de.uka.ipd.sdq.beagle.core.Blackboard#getMeasurementResultsFor(SeffBranch)}.
*
* @param branch A SEFF Branch to get the measurement results of. Must not be
* {@code null}.
* @return All measurement results reported for {@code branch}. Changes to the
* returned set will not modify the blackboard content. Is never {@code null}.
* @see de.uka.ipd.sdq.beagle.core.Blackboard#getMeasurementResultsFor(SeffBranch)
*/
Set<BranchDecisionMeasurementResult> getMeasurementResultsFor(SeffBranch branch);
/**
* Delegates to
* {@link de.uka.ipd.sdq.beagle.core.Blackboard#getMeasurementResultsFor(SeffLoop)}.
*
* @param loop A SEFF Loop to get the measurement results of. Must not be {@code null}
* .
* @return All measurement results reported for {@code loop}. Changes to the returned
* set will not modify the blackboard content. Is never {@code null}.
* @see de.uka.ipd.sdq.beagle.core.Blackboard#getMeasurementResultsFor(SeffLoop)
*/
Set<ResourceDemandMeasurementResult> getMeasurementResultsFor(SeffLoop loop);
/**
* Delegates to
* {@link de.uka.ipd.sdq.beagle.core.Blackboard#getMeasurementResultsFor(ExternalCallParameter)}
* .
*
* @param externalCallParameter An external parameter to get the measurement results
* of. Must not be {@code null}.
* @return All measurement results reported for {@code loexternalCallParameterop}.
* Changes to the returned set will not modify the blackboard content. Is
* never {@code null}.
* @see de.uka.ipd.sdq.beagle.core.Blackboard#getMeasurementResultsFor(ExternalCallParameter)
*/
Set<ParameterChangeMeasurementResult> getMeasurementResultsFor(ExternalCallParameter externalCallParameter);
/**
* Delegates to {@link de.uka.ipd.sdq.beagle.core.Blackboard#readFor(Class)} .
*
* @param writer The class the desired data was written for. Must not be {@code null}.
* @param <WRITTEN_TYPE> The type of the data to be read.
* @return The data written in the last call to
* {@linkplain de.uka.ipd.sdq.beagle.core.Blackboard#writeFor(Class, Serializable)}
* for {@code writer}. {@code null} if no data has been written for
* {@code writer} yet.
* @see de.uka.ipd.sdq.beagle.core.Blackboard#readFor(Class)
*/
<WRITTEN_TYPE extends Serializable> WRITTEN_TYPE readFor(Class<? extends BlackboardStorer<WRITTEN_TYPE>> writer);
<WRITTEN_TYPE extends Serializable> void writeFor(Class<? extends BlackboardStorer<WRITTEN_TYPE>> writer,
WRITTEN_TYPE written);
}
|
package alien4cloud.deployment;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import javax.annotation.Resource;
import javax.inject.Inject;
import org.alien4cloud.tosca.model.templates.ServiceNodeTemplate;
import org.alien4cloud.tosca.normative.constants.NormativeWorkflowNameConstants;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.stereotype.Service;
import com.google.common.collect.Maps;
import alien4cloud.application.ApplicationEnvironmentService;
import alien4cloud.application.ApplicationService;
import alien4cloud.dao.IGenericSearchDAO;
import alien4cloud.dao.model.FacetedSearchResult;
import alien4cloud.deployment.matching.services.location.TopologyLocationUtils;
import alien4cloud.events.DeploymentCreatedEvent;
import alien4cloud.model.application.Application;
import alien4cloud.model.application.ApplicationEnvironment;
import alien4cloud.model.common.MetaPropConfiguration;
import alien4cloud.model.deployment.Deployment;
import alien4cloud.model.deployment.DeploymentSourceType;
import alien4cloud.model.deployment.DeploymentTopology;
import alien4cloud.model.deployment.IDeploymentSource;
import alien4cloud.model.orchestrators.Orchestrator;
import alien4cloud.model.orchestrators.locations.Location;
import alien4cloud.orchestrators.plugin.IOrchestratorPlugin;
import alien4cloud.orchestrators.services.OrchestratorService;
import alien4cloud.paas.IPaaSCallback;
import alien4cloud.paas.OrchestratorPluginService;
import alien4cloud.paas.exception.EmptyMetaPropertyException;
import alien4cloud.paas.exception.OrchestratorDeploymentIdConflictException;
import alien4cloud.paas.model.PaaSDeploymentLog;
import alien4cloud.paas.model.PaaSDeploymentLogLevel;
import alien4cloud.paas.model.PaaSMessageMonitorEvent;
import alien4cloud.paas.model.PaaSTopologyDeploymentContext;
import alien4cloud.utils.PropertyUtil;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
/**
* Service responsible for deployment of an application.
*/
@Slf4j
@Service
public class DeployService {
@Resource(name = "alien-monitor-es-dao")
private IGenericSearchDAO alienMonitorDao;
@Resource(name = "alien-es-dao")
private IGenericSearchDAO alienDao;
@Inject
private ApplicationService applicationService;
@Inject
private ApplicationEnvironmentService applicationEnvironmentService;
@Inject
private OrchestratorService orchestratorService;
@Inject
private DeploymentService deploymentService;
@Inject
private OrchestratorPluginService orchestratorPluginService;
@Inject
private DeploymentContextService deploymentContextService;
@Inject
private DeploymentTopologyService deploymentTopologyService;
@Inject
private ArtifactProcessorService artifactProcessorService;
@Inject
private ApplicationEventPublisher eventPublisher;
@Inject
private DeploymentLockService deploymentLockService;
@Inject
private DeploymentLoggingService deploymentLoggingService;
@Inject
private ServiceResourceRelationshipService serviceResourceRelationshipService;
/**
* Deploy a topology and return the deployment ID.
*
* @param deploymentTopology Location aware and matched topology.
* @param deploymentSource Application to be deployed or the Csar that contains test toplogy to be deployed
* @return The id of the generated deployment.
*/
public String deploy(final DeploymentTopology deploymentTopology, IDeploymentSource deploymentSource) {
Map<String, String> locationIds = TopologyLocationUtils.getLocationIds(deploymentTopology);
Map<String, Location> locations = deploymentTopologyService.getLocations(locationIds);
final Location firstLocation = locations.values().iterator().next();
String deploymentPaaSId = generateOrchestratorDeploymentId(deploymentTopology.getEnvironmentId(), firstLocation.getOrchestratorId());
return deploymentLockService.doWithDeploymentWriteLock(deploymentPaaSId, () -> {
// Get the orchestrator that will perform the deployment
IOrchestratorPlugin orchestratorPlugin = orchestratorPluginService.getOrFail(firstLocation.getOrchestratorId());
// Create a deployment object to be kept in ES.
final Deployment deployment = new Deployment();
deployment.setId(UUID.randomUUID().toString());
deployment.setOrchestratorId(firstLocation.getOrchestratorId());
deployment.setLocationIds(locationIds.values().toArray(new String[locationIds.size()]));
deployment.setOrchestratorDeploymentId(deploymentPaaSId);
deployment.setSourceId(deploymentSource.getId());
String sourceName;
if (deploymentSource.getName() == null) {
sourceName = UUID.randomUUID().toString();
} else {
sourceName = deploymentSource.getName();
}
deployment.setSourceName(sourceName);
deployment.setSourceType(DeploymentSourceType.fromSourceType(deploymentSource.getClass()));
// mandatory for the moment since we could have deployment with no environment (csar test)
deployment.setEnvironmentId(deploymentTopology.getEnvironmentId());
deployment.setVersionId(deploymentTopology.getVersionId());
deployment.setStartDate(new Date());
setUsedServicesResourcesIds(deploymentTopology, deployment);
alienDao.save(deployment);
// publish an event for the eventual managed service
eventPublisher.publishEvent(new DeploymentCreatedEvent(this, deployment.getId()));
PaaSTopologyDeploymentContext deploymentContext = saveDeploymentTopologyAndGenerateDeploymentContext(deploymentTopology, deployment, locations);
// Build the context for deployment and deploy
orchestratorPlugin.deploy(deploymentContext, new IPaaSCallback<Object>() {
@Override
public void onSuccess(Object data) {
log.debug("Deployed topology [{}] on location [{}], generated deployment with id [{}]", deploymentTopology.getInitialTopologyId(),
firstLocation.getId(), deployment.getId());
}
@Override
public void onFailure(Throwable t) {
log.error("Deployment failed with cause", t);
log(deployment, t);
}
});
log.debug("Triggered deployment of topology [{}] on location [{}], generated deployment with id [{}]", deploymentTopology.getInitialTopologyId(),
firstLocation.getId(), deployment.getId());
return deployment.getId();
});
}
public void update(final DeploymentTopology deploymentTopology, final IDeploymentSource deploymentSource, final Deployment existingDeployment,
final IPaaSCallback<Object> callback) {
Map<String, String> locationIds = TopologyLocationUtils.getLocationIds(deploymentTopology);
Map<String, Location> locations = deploymentTopologyService.getLocations(locationIds);
final Location firstLocation = locations.values().iterator().next();
deploymentLockService.doWithDeploymentWriteLock(existingDeployment.getOrchestratorDeploymentId(), () -> {
// Get the orchestrator that will perform the deployment
IOrchestratorPlugin orchestratorPlugin = orchestratorPluginService.getOrFail(firstLocation.getOrchestratorId());
PaaSTopologyDeploymentContext deploymentContext = saveDeploymentTopologyAndGenerateDeploymentContext(deploymentTopology, existingDeployment,
locations);
// After update we allow running a post_update workflow automatically, however as adding workflow in update depends on orchestrator we have to check
// if such option is possible on the selected orchestrator.
final DeploymentTopology deployedTopology = alienMonitorDao.findById(DeploymentTopology.class, existingDeployment.getId());
// enrich the callback
IPaaSCallback<Object> callbackWrapper = new IPaaSCallback<Object>() {
@Override
public void onSuccess(Object data) {
existingDeployment.setVersionId(deploymentTopology.getVersionId());
alienDao.save(existingDeployment);
callback.onSuccess(data);
}
@Override
public void onFailure(Throwable throwable) {
log(existingDeployment, throwable);
callback.onFailure(throwable);
}
};
// Build the context for deployment and deploy
orchestratorPlugin.update(deploymentContext, callbackWrapper);
log.debug("Triggered deployment of topology [{}] on location [{}], generated deployment with id [{}]", deploymentTopology.getInitialTopologyId(),
firstLocation.getId(), existingDeployment.getId());
return null;
});
}
private void log(Deployment deployment, Throwable throwable) {
log(deployment, throwable.getMessage(), ExceptionUtils.getStackTrace(throwable), PaaSDeploymentLogLevel.ERROR);
}
private void log(Deployment deployment, String message, String stack, PaaSDeploymentLogLevel level) {
PaaSDeploymentLog deploymentLog = new PaaSDeploymentLog();
deploymentLog.setDeploymentId(deployment.getId());
deploymentLog.setDeploymentPaaSId(deployment.getOrchestratorDeploymentId());
String content = stack == null ? message : message + "\n" + stack;
deploymentLog.setContent(content);
deploymentLog.setLevel(level);
deploymentLog.setTimestamp(new Date());
deploymentLoggingService.save(deploymentLog);
PaaSMessageMonitorEvent messageMonitorEvent = new PaaSMessageMonitorEvent();
messageMonitorEvent.setDeploymentId(deploymentLog.getDeploymentId());
messageMonitorEvent.setOrchestratorId(deploymentLog.getDeploymentPaaSId());
messageMonitorEvent.setMessage(message);
messageMonitorEvent.setDate(deploymentLog.getTimestamp().getTime());
alienMonitorDao.save(messageMonitorEvent);
}
private PaaSTopologyDeploymentContext saveDeploymentTopologyAndGenerateDeploymentContext(final DeploymentTopology deploymentTopology,
final Deployment deployment, final Map<String, Location> locations) {
String deploymentTopologyId = deploymentTopology.getId();
// save the topology as a deployed topology.
// change the Id before saving
deploymentTopology.setId(deployment.getId());
deploymentTopology.setDeployed(true);
alienMonitorDao.save(deploymentTopology);
// put back the old Id for deployment
deploymentTopology.setId(deploymentTopologyId);
PaaSTopologyDeploymentContext deploymentContext = deploymentContextService.buildTopologyDeploymentContext(deployment, locations, deploymentTopology);
// Process services relationships to inject the service side based on the service resource.
serviceResourceRelationshipService.process(deploymentContext);
// Download and process all remote artifacts before deployment
artifactProcessorService.processArtifacts(deploymentContext);
return deploymentContext;
}
/**
* From the substitutedNodes values, find out which are services and populate the {@link Deployment#serviceResourceIds}
*
* @param deployment
* @param deploymentTopology
*/
private void setUsedServicesResourcesIds(DeploymentTopology deploymentTopology, Deployment deployment) {
String[] serviceResourcesIds = deploymentTopology.getSubstitutedNodes().entrySet().stream()
.filter(entry -> deploymentTopology.getNodeTemplates().get(entry.getKey()) instanceof ServiceNodeTemplate).map(entry -> entry.getValue())
.toArray(String[]::new);
if (ArrayUtils.isNotEmpty(serviceResourcesIds)) {
deployment.setServiceResourceIds(serviceResourcesIds);
}
}
/**
* Generate the human readable deployment id for the orchestrator.
*
* @param envId Id of the deployed environment.
* @param orchestratorId Id of the orchestrator on which the deployment is performed.
* @return The orchestrator deployment id.
* @throws alien4cloud.paas.exception.OrchestratorDeploymentIdConflictException
*/
private String generateOrchestratorDeploymentId(String envId, String orchestratorId) throws OrchestratorDeploymentIdConflictException {
log.debug("Generating deployment paaS Id...");
log.debug("All spaces will be replaced by an \"_\" charactr. You might consider it while naming your applications.");
ApplicationEnvironment env = applicationEnvironmentService.getOrFail(envId);
Orchestrator orchestrator = orchestratorService.getOrFail(orchestratorId);
String namePattern = orchestrator.getDeploymentNamePattern();
ExpressionParser parser = new SpelExpressionParser();
Expression exp = parser.parseExpression(namePattern);
String orchestratorDeploymentId = (String) exp
.getValue(new OrchestratorIdContext(env, applicationService.getOrFail(env.getApplicationId()), namePattern.contains("metaProperties[")));
// ensure that the id is not used by another deployment.
if (deploymentService.isActiveDeployment(orchestratorId, orchestratorDeploymentId)) {
throw new OrchestratorDeploymentIdConflictException("Conflict detected with the generated paasId <" + orchestratorDeploymentId + ">.");
}
return orchestratorDeploymentId;
}
// Inner class used to build context for generation of the orchestrator id.
@Getter
class OrchestratorIdContext {
private ApplicationEnvironment environment;
private Application application;
private Map<String, String> metaProperties;
private String time;
private Map<String, String> constructMapOfMetaProperties(final Application app) {
Map<String, String[]> filters = new HashMap<String, String[]>();
filters.put("target", new String[] { "application" }); // get all meta properties configuration for applications.
FacetedSearchResult result = alienDao.facetedSearch(MetaPropConfiguration.class, null, filters, null, 0, 20);
MetaPropConfiguration metaProp;
Map<String, String> metaProperties = Maps.newHashMap();
for (int i = 0; i < result.getData().length; i++) {
metaProp = (MetaPropConfiguration) result.getData()[i];
if (app.getMetaProperties().get(metaProp.getId()) != null) {
metaProperties.put(metaProp.getName(), app.getMetaProperties().get(metaProp.getId()));
} else if (!PropertyUtil.setScalarDefaultValueIfNotNull(metaProperties, metaProp.getName(), metaProp.getDefault())) {
throw new EmptyMetaPropertyException("The meta property " + metaProp.getName() + " is null and don't have a default value.");
}
}
return metaProperties;
}
public OrchestratorIdContext(ApplicationEnvironment env, Application app, boolean hasMetaProperties) {
this.environment = env;
this.application = app;
SimpleDateFormat ft = new SimpleDateFormat("yyyyMMddHHmm");
this.time = ft.format(new Date());
if (hasMetaProperties) {
this.metaProperties = constructMapOfMetaProperties(app);
}
}
}
}
|
package com.medium.reactnative.appsee;
import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.JavaScriptModule;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import com.appsee.*;
public class RNAppseePackage implements ReactPackage {
private String mApiKey;
public RNAppseePackage(String apiKey) {
mApiKey = apiKey;
Appsee.addAppseeListener(new AppseeListener() {
@Override
public void onAppseeScreenDetected(AppseeScreenDetectedInfo screenInfo)
{
//Ignore "Main" screen that auto detect by appsee sdk.
if(screenInfo.getScreenName().equals("MainActivity")){
screenInfo.setScreenName(null);
}
}
@Override
public void onAppseeSessionStarting(AppseeSessionStartingInfo startingInfo)
{
}
@Override
public void onAppseeSessionStarted(AppseeSessionStartedInfo sessionInfo)
{
}
@Override
public void onAppseeSessionEnding(AppseeSessionEndingInfo sessionInfo)
{
}
@Override
public void onAppseeSessionEnded(AppseeSessionEndedInfo sessionInfo)
{
}
});
}
/**
* according to appsee sdk, this is only allowed to be called within onCreate or onResume
*/
public void start() {
Appsee.start(mApiKey);
}
@Override
public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
return Arrays.<NativeModule>asList(new AppseeNativeModule(reactContext));
}
@Override
public List<Class<? extends JavaScriptModule>> createJSModules() {
return Collections.emptyList();
}
@Override
public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
return Collections.emptyList();
}
}
|
package com.groupon.seleniumgridextras.grid.servlets;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.openqa.grid.common.exception.GridException;
import org.openqa.grid.internal.ProxySet;
import org.openqa.grid.internal.Registry;
import org.openqa.grid.internal.RemoteProxy;
import org.openqa.grid.internal.TestSlot;
import org.openqa.grid.web.servlet.RegistryBasedServlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Iterator;
public class ProxyStatusJsonServlet extends RegistryBasedServlet {
private static final long serialVersionUID = -1975392591408983229L;
public ProxyStatusJsonServlet() {
this(null);
}
public ProxyStatusJsonServlet(Registry registry) {
super(registry);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
process(req, resp);
}
protected void process(HttpServletRequest request, HttpServletResponse response)
throws IOException {
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.setStatus(200);
JSONObject res;
try {
res = getResponse();
response.getWriter().print(res.toString(4));
response.getWriter().close();
} catch (JSONException e) {
throw new GridException(e.getMessage());
}
}
private JSONObject getResponse() throws IOException, JSONException {
JSONObject requestJSON = new JSONObject();
ProxySet proxies = this.getRegistry().getAllProxies();
Iterator<RemoteProxy> iterator = proxies.iterator();
JSONArray Proxies = new JSONArray();
JSONArray ProxyStatus = new JSONArray();
while (iterator.hasNext()) {
RemoteProxy eachProxy = iterator.next();
Iterator<TestSlot> proxyIterator = eachProxy.getTestSlots().iterator();
while (proxyIterator.hasNext()) {
JSONObject TestMachine = new JSONObject();
TestSlot eachSlot = proxyIterator.next();
//getSession is null if not being used
if (eachSlot.getSession() == null) {
//System.out.println(eachSlot.getCapabilities().get("browserName").toString());
TestMachine.put("browserName", eachSlot.getCapabilities().get("browserName").toString());
String version = "null";
if (eachSlot.getCapabilities().containsKey("version")) {
version = eachSlot.getCapabilities().get("version").toString();
}
TestMachine.put("version", version);
}
ProxyStatus.put(TestMachine);
}
Proxies.put(eachProxy.getOriginalRegistrationRequest().getAssociatedJSON());
}
requestJSON.put("Proxies", ProxyStatus);
requestJSON.put("TotalProxies", Proxies);
return requestJSON;
}
}
|
package com.google.ads.mediation.pangle.rtb;
import static com.google.ads.mediation.pangle.PangleConstants.ERROR_INVALID_BID_RESPONSE;
import static com.google.ads.mediation.pangle.PangleConstants.ERROR_INVALID_SERVER_PARAMETERS;
import static com.google.ads.mediation.pangle.PangleMediationAdapter.TAG;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.TTAdConstant;
import com.bytedance.sdk.openadsdk.TTAdManager;
import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.TTFeedAd;
import com.bytedance.sdk.openadsdk.TTImage;
import com.bytedance.sdk.openadsdk.TTNativeAd;
import com.bytedance.sdk.openadsdk.adapter.MediaView;
import com.bytedance.sdk.openadsdk.adapter.MediationAdapterUtil;
import com.google.ads.mediation.pangle.PangleConstants;
import com.google.ads.mediation.pangle.PangleMediationAdapter;
import com.google.android.gms.ads.AdError;
import com.google.android.gms.ads.formats.NativeAd.Image;
import com.google.android.gms.ads.mediation.MediationAdLoadCallback;
import com.google.android.gms.ads.mediation.MediationNativeAdCallback;
import com.google.android.gms.ads.mediation.MediationNativeAdConfiguration;
import com.google.android.gms.ads.mediation.UnifiedNativeAdMapper;
import com.google.android.gms.ads.nativead.NativeAdAssetNames;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class PangleRtbNativeAd extends UnifiedNativeAdMapper {
private static final double PANGLE_SDK_IMAGE_SCALE = 1.0;
private final MediationNativeAdConfiguration adConfiguration;
private final MediationAdLoadCallback<UnifiedNativeAdMapper, MediationNativeAdCallback> adLoadCallback;
private MediationNativeAdCallback callback;
private TTFeedAd ttFeedAd;
public PangleRtbNativeAd(@NonNull MediationNativeAdConfiguration mediationNativeAdConfiguration,
@NonNull MediationAdLoadCallback<UnifiedNativeAdMapper, MediationNativeAdCallback> mediationAdLoadCallback) {
adConfiguration = mediationNativeAdConfiguration;
adLoadCallback = mediationAdLoadCallback;
}
public void render() {
PangleMediationAdapter.setCoppa(adConfiguration.taggedForChildDirectedTreatment());
String placementId = adConfiguration.getServerParameters()
.getString(PangleConstants.PLACEMENT_ID);
if (TextUtils.isEmpty(placementId)) {
AdError error =
PangleConstants.createAdapterError(
ERROR_INVALID_SERVER_PARAMETERS,
"Failed to load native ad from Pangle. Missing or invalid Placement ID.");
Log.w(TAG, error.toString());
adLoadCallback.onFailure(error);
return;
}
String bidResponse = adConfiguration.getBidResponse();
if (TextUtils.isEmpty(bidResponse)) {
AdError error =
PangleConstants.createAdapterError(
ERROR_INVALID_BID_RESPONSE,
"Failed to load native ad from Pangle. Missing or invalid bid response.");
Log.w(TAG, error.toString());
adLoadCallback.onFailure(error);
return;
}
TTAdManager mTTAdManager = PangleMediationAdapter.getPangleSdkManager();
TTAdNative mTTAdNative = mTTAdManager
.createAdNative(adConfiguration.getContext().getApplicationContext());
AdSlot adSlot = new AdSlot.Builder()
.setCodeId(placementId)
.setAdCount(1)
.withBid(bidResponse)
.build();
mTTAdNative.loadFeedAd(adSlot, new TTAdNative.FeedAdListener() {
@Override
public void onError(int errorCode, String message) {
AdError error = PangleConstants.createSdkError(errorCode, message);
Log.w(TAG, error.toString());
adLoadCallback.onFailure(error);
}
@Override
public void onFeedAdLoad(List<TTFeedAd> ads) {
mapNativeAd(ads.get(0));
callback = adLoadCallback.onSuccess(PangleRtbNativeAd.this);
}
});
}
private void mapNativeAd(TTFeedAd ad) {
this.ttFeedAd = ad;
// Set data.
setHeadline(ttFeedAd.getTitle());
setBody(ttFeedAd.getDescription());
setCallToAction(ttFeedAd.getButtonText());
if (ttFeedAd.getIcon() != null && ttFeedAd.getIcon().isValid()) {
setIcon(new PangleNativeMappedImage(null, Uri.parse(ttFeedAd.getIcon().getImageUrl()),
PANGLE_SDK_IMAGE_SCALE));
}
// Set ad image.
if (ttFeedAd.getImageList() != null && ttFeedAd.getImageList().size() != 0) {
List<Image> imagesList = new ArrayList<>();
for (TTImage ttImage : ttFeedAd.getImageList()) {
if (ttImage.isValid()) {
imagesList.add(new PangleNativeMappedImage(null, Uri.parse(ttImage.getImageUrl()),
PANGLE_SDK_IMAGE_SCALE));
}
}
setImages(imagesList);
}
// Pangle does its own show event handling and click event handling.
setOverrideImpressionRecording(true);
setOverrideClickHandling(true);
// Add Native Feed Main View.
MediaView mediaView = new MediaView(adConfiguration.getContext());
MediationAdapterUtil
.addNativeFeedMainView(adConfiguration.getContext(), ttFeedAd.getImageMode(), mediaView,
ttFeedAd.getAdView(), ttFeedAd.getImageList());
setMediaView(mediaView);
// Set logo.
setAdChoicesContent(ttFeedAd.getAdLogoView());
if (ttFeedAd.getImageMode() == TTAdConstant.IMAGE_MODE_VIDEO ||
ttFeedAd.getImageMode() == TTAdConstant.IMAGE_MODE_VIDEO_VERTICAL ||
ttFeedAd.getImageMode() == TTAdConstant.IMAGE_MODE_VIDEO_SQUARE) {
setHasVideoContent(true);
ttFeedAd.setVideoAdListener(new TTFeedAd.VideoAdListener() {
@Override
public void onVideoLoad(TTFeedAd ad) {
// No-op, will be deprecated in the next version.
}
@Override
public void onVideoError(int errorCode, int extraCode) {
String errorMessage = String.format("Native ad video playback error," +
" errorCode: %s, extraCode: %s.", errorCode, extraCode);
Log.d(TAG, errorMessage);
}
@Override
public void onVideoAdStartPlay(TTFeedAd ad) {
// No-op, will be deprecated in the next version.
}
@Override
public void onVideoAdPaused(TTFeedAd ad) {
// No-op, will be deprecated in the next version.
}
@Override
public void onVideoAdContinuePlay(TTFeedAd ad) {
// No-op, will be deprecated in the next version.
}
@Override
public void onProgressUpdate(long current, long duration) {
// No-op, will be deprecated in the next version.
}
@Override
public void onVideoAdComplete(TTFeedAd ad) {
// No-op, will be deprecated in the next version.
}
});
}
}
@Override
public void trackViews(@NonNull View containerView,
@NonNull Map<String, View> clickableAssetViews,
@NonNull Map<String, View> nonClickableAssetViews) {
// Set click interaction.
HashMap<String, View> copyClickableAssetViews = new HashMap<>(clickableAssetViews);
copyClickableAssetViews.remove(NativeAdAssetNames.ASSET_ADCHOICES_CONTAINER_VIEW);
// Exclude fragments view containing ad choices to avoid ad choices click listener failure.
copyClickableAssetViews.remove("3012");
ArrayList<View> assetViews = new ArrayList<>(copyClickableAssetViews.values());
View creativeBtn = copyClickableAssetViews.get(NativeAdAssetNames.ASSET_CALL_TO_ACTION);
ArrayList<View> creativeViews = new ArrayList<>();
if (creativeBtn != null) {
creativeViews.add(creativeBtn);
}
ttFeedAd.registerViewForInteraction((ViewGroup) containerView, assetViews, creativeViews,
new TTNativeAd.AdInteractionListener() {
@Override
public void onAdClicked(View view, TTNativeAd ad) {
// No-op.
}
@Override
public void onAdCreativeClick(View view, TTNativeAd ad) {
if (callback != null) {
callback.reportAdClicked();
}
}
@Override
public void onAdShow(TTNativeAd ad) {
if (callback != null) {
callback.reportAdImpression();
}
}
});
// Set ad choices click listener.
getAdChoicesContent().setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
ttFeedAd.showPrivacyActivity();
}
});
}
public class PangleNativeMappedImage extends Image {
private final Drawable drawable;
private final Uri imageUri;
private final double scale;
private PangleNativeMappedImage(Drawable drawable, Uri imageUri, double scale) {
this.drawable = drawable;
this.imageUri = imageUri;
this.scale = scale;
}
@NonNull
@Override
public Drawable getDrawable() {
return drawable;
}
@NonNull
@Override
public Uri getUri() {
return imageUri;
}
@Override
public double getScale() {
return scale;
}
}
}
|
package org.headsupdev.agile.app.milestones;
import org.headsupdev.agile.api.User;
import org.headsupdev.agile.storage.StoredProject;
import org.headsupdev.agile.storage.issues.Duration;
import org.headsupdev.agile.storage.issues.DurationWorked;
import org.headsupdev.agile.storage.issues.Issue;
import org.headsupdev.agile.storage.issues.Milestone;
import org.headsupdev.agile.web.components.StripedListView;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.panel.Panel;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
/**
* A tabular layout of the duration worked for a milestone
*
* @author Andrew Williams
* @version $Id$
* @since 1.0
*/
public class WorkRemainingTable
extends Panel
{
public WorkRemainingTable( String id, final Milestone milestone )
{
super( id );
final boolean burndown = Boolean.parseBoolean( milestone.getProject().getConfigurationValue(
StoredProject.CONFIGURATION_TIMETRACKING_BURNDOWN ) );
List<User> users = new LinkedList<User>();
for ( Issue issue : milestone.getIssues() )
{
if ( issue.getAssignee() != null && !users.contains( issue.getAssignee() ) )
{
users.add( issue.getAssignee() );
}
for ( DurationWorked worked : issue.getTimeWorked() )
{
if ( worked.getUser() != null && !users.contains( worked.getUser() ) )
{
users.add( worked.getUser() );
}
}
}
List<Issue> issues = new LinkedList<Issue>( milestone.getIssues() );
Collections.sort( issues, new IssueComparator() );
add( new StripedListView<User>( "person", users )
{
@Override
protected void populateItem( ListItem<User> listItem )
{
super.populateItem( listItem );
final User user = listItem.getModelObject();
if ( user.isHiddenInTimeTracking() )
{
listItem.setVisible( false );
return;
}
listItem.add( new Label( "user", user.getFullnameOrUsername() ) );
int estimate = 0;
int worked = 0;
int remaining = 0;
for ( Issue issue : milestone.getIssues() )
{
if ( issue.getAssignee() != null && issue.getAssignee().equals( user ) )
{
if ( issue.getTimeEstimate() != null && issue.getTimeEstimate().getHours() > 0 )
{
double e = issue.getTimeEstimate().getHours();
estimate += e;
if ( burndown )
{
if (issue.getTimeRequired() != null)
{
remaining += issue.getTimeRequired().getHours();
}
}
else
{
if ( issue.getTimeRequired() != null )
{
double r = issue.getTimeRequired().getHours();
double delta = e - r;
if ( delta > 0 )
{
remaining += delta;
}
}
}
}
}
for ( DurationWorked dur : issue.getTimeWorked() )
{
if ( user.equals( dur.getUser() ) && dur.getWorked() != null )
{
worked += dur.getWorked().getHours();
}
}
}
listItem.add( new Label( "estimate", new Duration( estimate ).toString()) );
listItem.add( new Label( "worked", new Duration( worked ).toString()) );
listItem.add( new Label( "remaining", new Duration( remaining ).toString()) );
}
} );
}
}
|
package ru.yandex.qatools.allure.testng;
import org.testng.ITestContext;
import org.testng.ITestListener;
import org.testng.ITestResult;
import ru.yandex.qatools.allure.Allure;
import ru.yandex.qatools.allure.events.*;
import java.lang.annotation.Annotation;
import java.util.Arrays;
import java.util.Collections;
import java.util.UUID;
@SuppressWarnings("unused")
public class AllureTestListener implements ITestListener {
private String runUid;
public AllureTestListener() {
runUid = UUID.randomUUID().toString();
}
@Override
public void onTestStart(ITestResult iTestResult) {
Allure.LIFECYCLE.fire(new TestStartedEvent(
Thread.currentThread().getName(),
iTestResult.getName(),
Arrays.asList(iTestResult.getMethod().getConstructorOrMethod().getMethod().getAnnotations())
));
}
@Override
public void onTestSuccess(ITestResult iTestResult) {
Allure.LIFECYCLE.fire(new TestFinishedEvent(
runUid,
Thread.currentThread().getName()
));
}
@Override
public void onTestFailure(ITestResult iTestResult) {
Allure.LIFECYCLE.fire(new TestFailureEvent(
Thread.currentThread().getName(),
iTestResult.getThrowable()
));
}
@Override
public void onTestSkipped(ITestResult iTestResult) {
Allure.LIFECYCLE.fire(new TestAssumptionFailureEvent(
Thread.currentThread().getName(),
iTestResult.getThrowable()
));
}
@Override
public void onTestFailedButWithinSuccessPercentage(ITestResult iTestResult) {
Allure.LIFECYCLE.fire(new TestFailureEvent(
Thread.currentThread().getName(),
iTestResult.getThrowable()
));
}
@Override
public void onStart(ITestContext iTestContext) {
Allure.LIFECYCLE.fire(new TestRunStartedEvent(
runUid,
iTestContext.getCurrentXmlTest().getSuite().getName(),
Collections.<Annotation>emptyList()
));
}
@Override
public void onFinish(ITestContext iTestContext) {
Allure.LIFECYCLE.fire(new TestRunFinishedEvent(
runUid
));
}
}
|
package com.plusonelabs.calendar;
import android.content.Context;
import android.text.format.DateUtils;
import org.joda.time.DateTime;
import java.text.DateFormat;
import java.text.ParseException;
import java.util.Date;
import java.util.Locale;
public class DateUtil {
private static final String TWELVE = "12";
private static final String NOON_AM = "12:00 AM";
private static final String EMPTY_STRING = "";
private static final String COMMA_SPACE = ", ";
public static boolean isMidnight(DateTime date) {
return date.isEqual(date.withTimeAtStartOfDay());
}
public static boolean hasAmPmClock(Locale locale) {
DateFormat stdFormat = DateFormat.getTimeInstance(DateFormat.SHORT, Locale.US);
DateFormat localeFormat = DateFormat.getTimeInstance(DateFormat.LONG, locale);
String midnight = EMPTY_STRING;
try {
midnight = localeFormat.format(stdFormat.parse(NOON_AM));
} catch (ParseException ignore) {
// we ignore this exception deliberately
}
return midnight.contains(TWELVE);
}
public static String createDateString(Context context, DateTime dateTime) {
DateTime timeAtStartOfToday = DateTime.now().withTimeAtStartOfDay();
if (dateTime.withTimeAtStartOfDay().isEqual(timeAtStartOfToday)) {
return createDateString(context, dateTime.toDate(), context.getString(R.string.today));
} else if (dateTime.withTimeAtStartOfDay().isEqual(timeAtStartOfToday.plusDays(1))) {
return createDateString(context, dateTime.toDate(), context.getString(R.string.tomorrow));
}
return DateUtils.formatDateTime(context, dateTime.toDate().getTime(),
DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY);
}
private static String createDateString(Context context, Date date, String prefix) {
return prefix + COMMA_SPACE + DateUtils.formatDateTime(context, date.getTime(), DateUtils.FORMAT_SHOW_DATE);
}
}
|
package jsettlers.logic.algorithms.path;
import jsettlers.common.position.ISPosition2D;
public class Path {
private final ISPosition2D[] path;
private short walkIdx = 1;
public Path(int length) {
path = new ISPosition2D[length + 1];
}
/**
* sets the given position to the given index of the path
*
* @param idx
* NOTE: this must be in the integer interval [0, pathlength -1]!
* @param step
* NOTE: this mustn't be null!
*/
public void insertAt(int idx, ISPosition2D step) {
assert step != null : "PATH POINT == NULL";
path[idx] = step;
}
/**
* returns the next step and increases the steps counter
*
* @return null if {@link #isFinished()} returns true<br>
* otherwise the next step
*/
public ISPosition2D nextStep() {
if (isFinished()) {
return null;
} else {
return path[walkIdx++];
}
}
public boolean isFinished() {
return walkIdx >= path.length;// || walkIdx >= insertIdx;
}
@Override
public String toString() {
StringBuffer res = new StringBuffer();
for (ISPosition2D curr : path) {
res.append(curr.toString());
}
return res.toString();
}
public ISPosition2D getFirst() {
return path[1];
}
public ISPosition2D getTargetPos() {
return path[path.length - 1];
}
}
|
package cgeo.geocaching.maps;
import cgeo.geocaching.R;
import cgeo.geocaching.activity.ActivityMixin;
import cgeo.geocaching.export.IndividualRouteExport;
import cgeo.geocaching.files.GPXIndividualRouteImporter;
import cgeo.geocaching.files.GPXTrackOrRouteImporter;
import cgeo.geocaching.location.Geopoint;
import cgeo.geocaching.maps.routing.RouteSortActivity;
import cgeo.geocaching.models.IndividualRoute;
import cgeo.geocaching.models.Route;
import cgeo.geocaching.settings.Settings;
import cgeo.geocaching.storage.ContentStorageActivityHelper;
import cgeo.geocaching.storage.PersistableFolder;
import cgeo.geocaching.storage.extension.Trackfiles;
import cgeo.geocaching.ui.TextParam;
import cgeo.geocaching.ui.dialog.Dialogs;
import cgeo.geocaching.ui.dialog.SimpleDialog;
import cgeo.geocaching.utils.functions.Action2;
import cgeo.geocaching.utils.functions.Func0;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.widget.TooltipCompat;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import com.google.android.material.bottomsheet.BottomSheetDialog;
public class RouteTrackUtils {
private static final int REQUEST_SORT_INDIVIDUAL_ROUTE = 4712;
private static final String STATE_CSAH_ROUTE = "csah_route";
private static final String STATE_CSAH_TRACK = "csah_track";
private final Activity activity;
private final ContentStorageActivityHelper fileSelectorRoute;
private final ContentStorageActivityHelper fileSelectorTrack;
private View popup = null;
private Tracks tracks = null;
private final Runnable reloadIndividualRoute;
private final Runnable clearIndividualRoute;
private final Tracks.UpdateTrack updateTrack;
private final Route.CenterOnPosition centerOnPosition;
private final Func0<Boolean> isTargetSet;
public RouteTrackUtils(final Activity activity, final Bundle savedState, final Route.CenterOnPosition centerOnPosition, final Runnable clearIndividualRoute, final Runnable reloadIndividualRoute, final Tracks.UpdateTrack updateTrack, final Func0<Boolean> isTargetSet) {
this.activity = activity;
this.centerOnPosition = centerOnPosition;
this.clearIndividualRoute = clearIndividualRoute;
this.reloadIndividualRoute = reloadIndividualRoute;
this.updateTrack = updateTrack;
this.isTargetSet = isTargetSet;
this.fileSelectorRoute = new ContentStorageActivityHelper(activity, savedState == null ? null : savedState.getBundle(STATE_CSAH_ROUTE))
.addSelectActionCallback(ContentStorageActivityHelper.SelectAction.SELECT_FILE, Uri.class, this::importIndividualRoute);
this.fileSelectorTrack = new ContentStorageActivityHelper(activity, savedState == null ? null : savedState.getBundle(STATE_CSAH_TRACK))
.addSelectActionCallback(ContentStorageActivityHelper.SelectAction.SELECT_FILE_MULTIPLE, List.class, this::importTracks);
}
private void importIndividualRoute(final Uri uri) {
if (uri != null) {
GPXIndividualRouteImporter.doImport(activity, uri);
reloadIndividualRoute.run();
}
}
private void importTracks(final List<Uri> uris) {
if (uris != null && this.updateTrack != null) {
for (Uri uri : uris) {
GPXTrackOrRouteImporter.doImport(activity, uri, (route) -> {
final String key = tracks.add(activity, uri, updateTrack);
tracks.setRoute(key, route);
updateTrack.updateRoute(key, route);
updateDialogTracks(popup, tracks);
});
}
}
}
public void setTracks(final Tracks tracks) {
this.tracks = tracks;
}
/**
* Shows a popup menu for individual route related items
*
*/
public void showPopup(final IndividualRoute individualRoute, final Action2<Geopoint, String> setTarget) {
this.popup = activity.getLayoutInflater().inflate(R.layout.routes_tracks_dialog, null);
updateDialog(this.popup, individualRoute, tracks, setTarget);
final BottomSheetDialog dialog = Dialogs.bottomSheetDialogWithActionbar(activity, this.popup, R.string.routes_tracks_dialog_title);
dialog.setOnDismissListener(dialog1 -> popup = null);
dialog.show();
}
private void updateDialog(final View dialog, final IndividualRoute individualRoute, final Tracks tracks, final Action2<Geopoint, String> setTarget) {
updateDialogIndividualRoute(dialog, individualRoute, setTarget);
updateDialogTracks(dialog, tracks);
updateDialogClearTargets(dialog, individualRoute, setTarget);
}
private void startFileSelectorIndividualRoute() {
fileSelectorRoute.selectFile(null, PersistableFolder.GPX.getUri());
}
private void updateDialogIndividualRoute(final View dialog, final IndividualRoute individualRoute, final Action2<Geopoint, String> setTarget) {
if (dialog == null) {
return;
}
dialog.findViewById(R.id.indivroute_load).setOnClickListener(v1 -> {
if (null == individualRoute || individualRoute.getNumSegments() == 0) {
startFileSelectorIndividualRoute();
} else {
SimpleDialog.of(activity).setTitle(R.string.map_load_individual_route).setMessage(R.string.map_load_individual_route_confirm).confirm(
(d, w) -> startFileSelectorIndividualRoute());
}
});
if (isRouteNonEmpty(individualRoute)) {
dialog.findViewById(R.id.indivroute).setVisibility(View.VISIBLE);
final View vSort = dialog.findViewById(R.id.item_sort);
vSort.setVisibility(View.VISIBLE);
vSort.setOnClickListener(v1 -> activity.startActivityForResult(new Intent(activity, RouteSortActivity.class), REQUEST_SORT_INDIVIDUAL_ROUTE));
dialog.findViewById(R.id.item_center).setOnClickListener(v1 -> individualRoute.setCenter(centerOnPosition));
final ImageButton vVisibility = dialog.findViewById(R.id.item_visibility);
vVisibility.setVisibility(View.VISIBLE);
setVisibilityInfo(vVisibility, individualRoute.isHidden());
vVisibility.setOnClickListener(v -> {
final boolean newValue = !individualRoute.isHidden();
setVisibilityInfo(vVisibility, newValue);
individualRoute.setHidden(newValue);
reloadIndividualRoute.run();
});
dialog.findViewById(R.id.item_delete).setOnClickListener(v1 -> SimpleDialog.of(activity).setTitle(R.string.map_clear_individual_route).setMessage(R.string.map_clear_individual_route_confirm).confirm((d, w) -> {
clearIndividualRoute.run();
updateDialogIndividualRoute(dialog, individualRoute, setTarget);
}));
dialog.findViewById(R.id.indivroute_export_route).setOnClickListener(v1 -> new IndividualRouteExport(activity, individualRoute, false));
dialog.findViewById(R.id.indivroute_export_track).setOnClickListener(v1 -> new IndividualRouteExport(activity, individualRoute, true));
final CheckBox vAutoTarget = dialog.findViewById(R.id.auto_target);
vAutoTarget.setChecked(Settings.isAutotargetIndividualRoute());
vAutoTarget.setOnClickListener(v1 -> {
setAutotargetIndividualRoute(activity, individualRoute, !Settings.isAutotargetIndividualRoute());
updateDialogClearTargets(popup, individualRoute, setTarget);
});
} else {
dialog.findViewById(R.id.indivroute).setVisibility(View.GONE);
}
}
private void updateDialogTracks(final View dialog, final Tracks tracks) {
if (dialog == null) {
return;
}
final LinearLayout tracklist = dialog.findViewById(R.id.tracklist);
tracklist.removeAllViews();
dialog.findViewById(R.id.trackroute_load).setOnClickListener(v1 -> fileSelectorTrack.selectMultipleFiles(null, PersistableFolder.GPX.getUri()));
tracks.traverse((key, route) -> {
final View vt = activity.getLayoutInflater().inflate(R.layout.routes_tracks_item, null);
((TextView) vt.findViewById(R.id.item_title)).setText(tracks.getDisplayname(key));
vt.findViewById(R.id.item_center).setOnClickListener(v1 -> {
if (null != route) {
route.setCenter(centerOnPosition);
}
});
final ImageButton vVisibility = vt.findViewById(R.id.item_visibility);
if (route == null) {
vVisibility.setVisibility(View.GONE);
} else {
vVisibility.setVisibility(View.VISIBLE);
setVisibilityInfo(vVisibility, route.isHidden());
vVisibility.setOnClickListener(v -> {
final boolean newValue = !route.isHidden();
setVisibilityInfo(vVisibility, newValue);
route.setHidden(newValue);
updateTrack.updateRoute(key, route);
tracks.hide(key, newValue);
});
}
vt.findViewById(R.id.item_delete).setOnClickListener(v1 -> SimpleDialog.of(activity).setTitle(R.string.map_clear_track).setMessage(TextParam.text(String.format(activity.getString(R.string.map_clear_track_confirm), tracks.getDisplayname(key)))).confirm((d, w) -> {
tracks.remove(key);
updateDialogTracks(dialog, tracks);
updateTrack.updateRoute(key, null);
}));
tracklist.addView(vt);
});
}
private void setVisibilityInfo (final ImageButton v, final boolean isHidden) {
v.setImageResource(isHidden ? R.drawable.visibility_off : R.drawable.visibility);
TooltipCompat.setTooltipText(v, activity.getString(isHidden ? R.string.make_visible : R.string.hide));
};
private void updateDialogClearTargets(final View dialog, final IndividualRoute individualRoute, final Action2<Geopoint, String> setTarget) {
final View vClearTargets = dialog.findViewById(R.id.clear_targets);
vClearTargets.setEnabled(isTargetSet.call() || Settings.isAutotargetIndividualRoute());
vClearTargets.setOnClickListener(v1 -> {
if (setTarget != null) {
setTarget.call(null, null);
}
Settings.setAutotargetIndividualRoute(false);
individualRoute.triggerTargetUpdate(true);
ActivityMixin.showToast(activity, R.string.map_manual_targets_cleared);
updateDialogIndividualRoute(dialog, individualRoute, setTarget);
});
}
private boolean isRouteNonEmpty(final Route route) {
return route != null && route.getNumSegments() > 0;
}
public void reloadTrack(final String key, final Tracks.UpdateTrack updateTrack) {
final Uri uri = Trackfiles.getUriFromKey(key);
GPXTrackOrRouteImporter.doImport(activity, uri, (route) -> {
updateDialogTracks(popup, tracks);
updateTrack.updateRoute(key, route);
});
}
public void showTrackInfo(final Route route) {
if (null != route) {
final int numPoints = route.getNumPoints();
Toast.makeText(activity, activity.getResources().getQuantityString(R.plurals.load_track_success, numPoints, numPoints), Toast.LENGTH_SHORT).show();
}
}
public void onPrepareOptionsMenu(final Menu menu, final View anchor, final IndividualRoute route, final Tracks tracks) {
final AtomicBoolean someTrackAvailable = new AtomicBoolean(isRouteNonEmpty(route));
tracks.traverse((key, r) -> {
if (!someTrackAvailable.get() && isRouteNonEmpty(r)) {
someTrackAvailable.set(true);
}
});
anchor.setVisibility(someTrackAvailable.get() ? View.VISIBLE : View.GONE);
}
public boolean onActivityResult(final int requestCode, final int resultCode, final Intent data) {
if (fileSelectorRoute.onActivityResult(requestCode, resultCode, data)) {
return true;
}
if (requestCode == REQUEST_SORT_INDIVIDUAL_ROUTE) {
reloadIndividualRoute.run();
return true;
}
return (fileSelectorTrack.onActivityResult(requestCode, resultCode, data));
}
public Bundle getState() {
final Bundle bundle = new Bundle();
bundle.putBundle(STATE_CSAH_ROUTE, this.fileSelectorRoute.getState());
bundle.putBundle(STATE_CSAH_TRACK, this.fileSelectorTrack.getState());
return bundle;
}
public static void setAutotargetIndividualRoute(final Activity activity, final IndividualRoute route, final boolean newValue) {
Settings.setAutotargetIndividualRoute(newValue);
route.triggerTargetUpdate(!Settings.isAutotargetIndividualRoute());
ActivityMixin.invalidateOptionsMenu(activity);
}
}
|
package java.awt;
class PolyEdge {
private int x1;
private int y1;
//private int x2;
private int y2;
private float m;
private float c;
private boolean vertical;
PolyEdge(int x1, int y1, int x2, int y2) {
// sort lowest to highest
if (y2 < y1) {
int swap;
swap = x1; x1 = x2; x2 = swap;
swap = y1; y1 = y2; y2 = swap;
}
this.x1 = x1;
this.y1 = y1;
//this.x2 = x2;
this.y2 = y2;
if (x1 == x2) {
vertical = true;
m = 0;
} else {
m = (float)(y2 - y1) / (float)(x2 - x1);
c = (-x1 * m) + y1;
vertical = false;
}
}
public boolean intersects(int y) {
if (y <= y2 && y >= y1 && y1 != y2) {
return true;
}
return false;
}
public int intersectionX(int y) {
if (vertical) {
return x1;
}
return (int)(((y - c) / m) + 0.5f);
}
}
|
package com.microsoft.applicationinsights.library;
import android.content.ContentResolver;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Point;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.Display;
import android.view.WindowManager;
import com.microsoft.applicationinsights.contracts.Application;
import com.microsoft.applicationinsights.contracts.Device;
import com.microsoft.applicationinsights.contracts.Internal;
import com.microsoft.applicationinsights.contracts.Operation;
import com.microsoft.applicationinsights.contracts.Session;
import com.microsoft.applicationinsights.contracts.User;
import com.microsoft.applicationinsights.logging.InternalLogging;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.Map;
import java.util.UUID;
/**
* This class is holding all telemetryContext information.
*/
class TelemetryContext {
protected static final String SHARED_PREFERENCES_KEY = "APP_INSIGHTS_CONTEXT";
protected static final String USER_ID_KEY = "USER_ID";
protected static final String USER_ACQ_KEY = "USER_ACQ";
private static final String TAG = "TelemetryContext";
/**
* The shared preferences INSTANCE for reading persistent context
*/
private SharedPreferences settings;
/**
* Content for tags field of an envelope
*/
private Map<String, String> cachedTags;
/**
* Device telemetryContext.
*/
private String instrumentationKey;
/**
* Device telemetryContext.
*/
private Device device;
/**
* Session telemetryContext.
*/
private Session session;
/**
* User telemetryContext.
*/
private User user;
/**
* Application telemetryContext.
*/
private Application application;
/**
* Internal telemetryContext.
*/
private Internal internal;
/**
* The last session ID
*/
private String lastSessionId;
/**
* The App ID for the envelope (defined as PackageInfo.packageName by CLL team)
*/
private String appIdForEnvelope;
/**
* Operation telemetryContext.
*/
private Operation operation;
/**
* Constructs a new INSTANCE of the Telemetry telemetryContext tag keys
*
* @param appContext the context for this telemetryContext
*/
protected TelemetryContext(Context appContext, String instrumentationKey) {
this.operation = new Operation();
// get an INSTANCE of the shared preferences manager for persistent context fields
this.settings = appContext.getSharedPreferences(SHARED_PREFERENCES_KEY, Context.MODE_PRIVATE);
// initialize static context
this.device = new Device();
this.session = new Session();
this.user = new User();
this.internal = new Internal();
this.application = new Application();
this.lastSessionId = null;
this.instrumentationKey = instrumentationKey;
this.cachedTags = getCachedTags();
configDeviceContext(appContext);
configSessionContext();
configUserContext();
configAppContext(appContext);
configInternalContext(appContext);
}
/**
* Get user the instrumentationKey.
* @return the instrumentation key
*/
protected String getInstrumentationKey() {
return instrumentationKey;
}
/**
* Get user telemetryContext.
* @return the user object
*/
protected User getUser() {
return user;
}
/**
* Get device telemetryContext.
* @return the device object
*/
protected Device getDevice() {
return device;
}
/**
* Operation telemetryContext.
* @return the operation
*/
protected Operation getOperation() {
return operation;
}
/**
* Session telemetryContext.
* @return the session
*/
protected Session getSession() {
return session;
}
/**
* Application telemetryContext.
* @return the application
*/
protected Application getApplication() {
return application;
}
/**
* The package name
*
* @see TelemetryContext#appIdForEnvelope
*/
protected String getPackageName() {
return appIdForEnvelope;
}
/**
* @return a map of the context tags assembled in the required data contract format.
*/
private Map<String, String> getCachedTags() {
if (this.cachedTags == null) {
// create a new hash map and add all context to it
this.cachedTags = new LinkedHashMap<String, String>();
this.application.addToHashMap(cachedTags);
this.internal.addToHashMap(cachedTags);
this.operation.addToHashMap(cachedTags);
}
return this.cachedTags;
}
protected Map<String, String> getContextTags() {
Map<String, String> contextTags = new LinkedHashMap<String, String>();
contextTags.putAll(getCachedTags());
this.device.addToHashMap(contextTags);
this.application.addToHashMap(contextTags);
this.session.addToHashMap(contextTags);
this.user.addToHashMap(contextTags);
this.internal.addToHashMap(contextTags);
return contextTags;
}
// TODO: Synchronize session renewal
/**
* Renews the session context
* <p/>
* The session ID is on demand. Additionally, the isFirst flag is set if no data was
* found in settings and the isNew flag is set each time a new UUID is
* generated.
*/
protected void renewSessionId() {
String newId = UUID.randomUUID().toString();
this.session.setId(newId);
}
/**
* Sets the session context
*/
protected void configSessionContext() {
if (this.lastSessionId == null) {
renewSessionId();
} else {
this.session.setId(this.lastSessionId);
}
}
/**
* Sets the application telemetryContext tags
* @param appContext the android context
*/
protected void configAppContext(Context appContext) {
String version = "unknown";
this.appIdForEnvelope = "";
try {
final PackageManager manager = appContext.getPackageManager();
final PackageInfo info = manager
.getPackageInfo(appContext.getPackageName(), 0);
if (info.packageName != null) {
this.appIdForEnvelope = info.packageName;
}
String appBuild = Integer.toString(info.versionCode);
version = String.format("%s (%S)", this.appIdForEnvelope, appBuild);
} catch (PackageManager.NameNotFoundException e) {
InternalLogging.warn(TAG, "Could not collect application context");
} finally {
this.application.setVer(version);
}
}
/**
* Sets the user context
*/
protected void configUserContext() {
String userId = this.settings.getString(USER_ID_KEY, null);
String userAcq = this.settings.getString(USER_ACQ_KEY, null);
if (userId == null || userAcq == null) {
userId = UUID.randomUUID().toString();
userAcq = Util.dateToISO8601(new Date());
SharedPreferences.Editor editor = this.settings.edit();
editor.putString(USER_ID_KEY, userId);
editor.putString(USER_ACQ_KEY, userAcq);
editor.apply();
}
this.user.setId(userId);
this.user.setAccountAcquisitionDate(userAcq);
}
/**
* Sets the device telemetryContext tags
* @param appContext the android Context
*/
protected void configDeviceContext(Context appContext) {
this.device.setOsVersion(Build.VERSION.RELEASE);
this.device.setOs("Android");
this.device.setModel(Build.MODEL);
this.device.setOemName(Build.MANUFACTURER);
this.device.setLocale(Locale.getDefault().toString());
updateScreenResolution(appContext);
// get device ID
ContentResolver resolver = appContext.getContentResolver();
String deviceIdentifier = Settings.Secure.getString(resolver, Settings.Secure.ANDROID_ID);
if (deviceIdentifier != null) {
this.device.setId(Util.tryHashStringSha256(deviceIdentifier));
}
// check device type
final TelephonyManager telephonyManager = (TelephonyManager)
appContext.getSystemService(Context.TELEPHONY_SERVICE);
if (telephonyManager.getPhoneType() != TelephonyManager.PHONE_TYPE_NONE) {
this.device.setType("Phone");
} else {
this.device.setType("Tablet");
}
// check network type
final ConnectivityManager connectivityManager = (ConnectivityManager)
appContext.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = connectivityManager.getActiveNetworkInfo();
if (activeNetwork != null) {
int networkType = activeNetwork.getType();
String networkString = null;
switch (networkType) {
case ConnectivityManager.TYPE_WIFI:
networkString = "WiFi";
break;
case ConnectivityManager.TYPE_MOBILE:
networkString = "Mobile";
break;
default:
networkString = "Unknown";
InternalLogging.warn(TAG, "Unknown network type:" + networkType);
break;
}
this.device.setNetwork(networkString);
}
// detect emulator
if (Util.isEmulator()) {
this.device.setModel("[Emulator]" + device.getModel());
}
}
// TODO: Synchronize resolution update
protected void updateScreenResolution(Context context) {
String resolutionString = "";
int width = 0;
int height = 0;
WindowManager wm = (WindowManager) context.getSystemService(
Context.WINDOW_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
Point size = new Point();
wm.getDefaultDisplay().getRealSize(size);
width = size.x;
height = size.y;
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
try {
Method mGetRawW = Display.class.getMethod("getRawWidth");
Method mGetRawH = Display.class.getMethod("getRawHeight");
Display display = wm.getDefaultDisplay();
width = (Integer) mGetRawW.invoke(display);
height = (Integer) mGetRawH.invoke(display);
} catch (Exception ex) {
Point size = new Point();
wm.getDefaultDisplay().getSize(size);
width = size.x;
height = size.y;
InternalLogging.error(TAG, ex.toString());
}
} else {
Display d = wm.getDefaultDisplay();
width = d.getWidth();
height = d.getHeight();
}
resolutionString = String.valueOf(height) + "x" + String.valueOf(width);
this.device.setScreenResolution(resolutionString);
}
/**
* Sets the internal package context
*/
protected void configInternalContext(Context appContext) {
String sdkVersionString = "";
String packageName = appContext.getPackageName();
if (appContext != null) {
try {
Bundle bundle = appContext.getPackageManager()
.getApplicationInfo(appContext.getPackageName(), PackageManager.GET_META_DATA)
.metaData;
if (bundle != null) {
sdkVersionString = bundle.getString("com.microsoft.applicationinsights.internal.sdkVersion");
} else {
InternalLogging.warn(TAG, "Could not load sdk version from gradle.properties or manifest");
}
} catch (PackageManager.NameNotFoundException exception) {
InternalLogging.warn(TAG, "Error loading SDK version from manifest");
Log.v(TAG, exception.toString());
}
}
this.internal.setSdkVersion("android:" + sdkVersionString);
}
}
|
package org.csstudio.alarm.treeView.views;
import java.net.URL;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.csstudio.alarm.table.SendAcknowledge;
import org.csstudio.alarm.treeView.AlarmTreePlugin;
import org.csstudio.alarm.treeView.jms.AlarmQueueSubscriber;
import org.csstudio.alarm.treeView.ldap.DirectoryEditException;
import org.csstudio.alarm.treeView.ldap.DirectoryEditor;
import org.csstudio.alarm.treeView.ldap.LdapDirectoryReader;
import org.csstudio.alarm.treeView.ldap.LdapDirectoryStructureReader;
import org.csstudio.alarm.treeView.model.IAlarmTreeNode;
import org.csstudio.alarm.treeView.model.ProcessVariableNode;
import org.csstudio.alarm.treeView.model.Severity;
import org.csstudio.alarm.treeView.model.SubtreeNode;
import org.csstudio.platform.logging.CentralLogger;
import org.csstudio.sds.ui.runmode.RunModeService;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.jobs.IJobChangeEvent;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.core.runtime.jobs.JobChangeAdapter;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.dialogs.IInputValidator;
import org.eclipse.jface.dialogs.InputDialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.ViewerComparator;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.browser.IWebBrowser;
import org.eclipse.ui.part.ViewPart;
import org.eclipse.ui.progress.IWorkbenchSiteProgressService;
import org.eclipse.ui.progress.PendingUpdateAdapter;
/**
* Tree view of process variables and their alarm state. This view uses LDAP
* to get a hierarchy of process variables and displays them in a tree view.
* Process variables which are in an alarm state are visually marked in the
* view.
*/
public class AlarmTreeView extends ViewPart {
/**
* The ID of this view.
*/
private static final String ID = "org.csstudio.alarm.treeView.views.LdapTView";
/**
* The tree viewer that displays the alarm objects.
*/
private TreeViewer _viewer;
/**
* The reload action.
*/
private Action _reloadAction;
/**
* The subscriber to the JMS alarm topic.
*/
private AlarmQueueSubscriber _alarmTopicSubscriber;
/**
* The acknowledge action.
*/
private Action _acknowledgeAction;
/**
* The Run CSS Alarm Display action.
*/
private Action _runCssAlarmDisplayAction;
/**
* The Show Help Page action.
*/
private Action _showHelpPageAction;
/**
* The Show Help Guidance action.
*/
private Action _showHelpGuidanceAction;
/**
* The Create Record action.
*/
private Action _createRecordAction;
/**
* The Create Component action.
*/
private Action _createComponentAction;
/**
* The Delete action.
*/
private Action _deleteNodeAction;
/**
* Returns the id of this view.
* @return the id of this view.
*/
public static String getID(){
return ID;
}
/**
* Creates an LDAP tree viewer.
*/
public AlarmTreeView() {
}
/**
* {@inheritDoc}
*/
public final void createPartControl(final Composite parent) {
_viewer = new TreeViewer(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
_viewer.setContentProvider(new AlarmTreeContentProvider());
_viewer.setLabelProvider(new AlarmTreeLabelProvider());
_viewer.setComparator(new ViewerComparator());
initializeContextMenu();
makeActions();
contributeToActionBars();
getSite().setSelectionProvider(_viewer);
startDirectoryReaderJob();
_viewer.addSelectionChangedListener(new ISelectionChangedListener() {
public void selectionChanged(final SelectionChangedEvent event) {
AlarmTreeView.this.selectionChanged(event);
}
});
}
/**
* Starts a job which reads the contents of the directory in the background.
*/
private void startDirectoryReaderJob() {
final IWorkbenchSiteProgressService progressService =
(IWorkbenchSiteProgressService) getSite().getAdapter(
IWorkbenchSiteProgressService.class);
final SubtreeNode rootNode = new SubtreeNode("ROOT");
Job directoryReader = new LdapDirectoryReader(rootNode);
// Add a listener that sets the viewers input to the root node
// when the reader job is finished.
directoryReader.addJobChangeListener(new JobChangeAdapter() {
@Override
public void done(final IJobChangeEvent event) {
setJmsListenerTree(rootNode);
asyncSetViewerInput(rootNode);
Job directoryUpdater = new LdapDirectoryStructureReader(rootNode);
directoryUpdater.addJobChangeListener(new JobChangeAdapter() {
@Override
public void done(final IJobChangeEvent event) {
getSite().getShell().getDisplay().asyncExec(new Runnable() {
public void run() {
_viewer.refresh();
}
});
}
});
progressService.schedule(directoryUpdater, 0, true);
}
});
// The directory is read in the background. Until then, set the viewer's
// input to a placeholder object.
_viewer.setInput(new Object[] {new PendingUpdateAdapter()});
progressService.schedule(directoryReader, 0, true);
}
/**
* Sets the tree to which the JMS listener will apply updates. If the
* JMS listener is not started yet, this will also initialize and start
* the JMS listener.
* @param tree the tree to which updates should be applied.
*/
private void setJmsListenerTree(final SubtreeNode tree) {
if (_alarmTopicSubscriber == null) {
_alarmTopicSubscriber = new AlarmQueueSubscriber(tree);
_alarmTopicSubscriber.openConnection();
} else {
_alarmTopicSubscriber.setTree(tree);
}
}
/**
* Stops the alarm queue subscriber.
*/
private void disposeJmsListener() {
_alarmTopicSubscriber.closeConnection();
}
/**
* Sets the input for the tree. The actual work will be done asynchronously
* in the UI thread.
* @param inputElement the new input element.
*/
private void asyncSetViewerInput(final SubtreeNode inputElement) {
getSite().getShell().getDisplay().asyncExec(new Runnable() {
public void run() {
_viewer.setInput(inputElement);
}
});
}
/**
* {@inheritDoc}
*/
@Override
public final void dispose() {
disposeJmsListener();
super.dispose();
}
/**
* Called when the selection of the tree changes.
* @param event the selection event.
*/
private void selectionChanged(final SelectionChangedEvent event) {
IStructuredSelection sel = (IStructuredSelection) event.getSelection();
_acknowledgeAction.setEnabled(containsNodeWithUnackAlarm(sel));
_runCssAlarmDisplayAction.setEnabled(hasCssAlarmDisplay(sel.getFirstElement()));
_showHelpGuidanceAction.setEnabled(hasHelpGuidance(sel.getFirstElement()));
_showHelpPageAction.setEnabled(hasHelpPage(sel.getFirstElement()));
}
/**
* Return whether help guidance is available for the given node.
* @param node the node.
* @return <code>true</code> if the node has a help guidance string,
* <code>false</code> otherwise.
*/
private boolean hasHelpGuidance(final Object node) {
if (node instanceof IAlarmTreeNode) {
return ((IAlarmTreeNode) node).getHelpGuidance() != null;
}
return false;
}
/**
* Return whether the given node has an associated help page.
*
* @param node the node.
* @return <code>true</code> if the node has an associated help page,
* <code>false</code> otherwise.
*/
private boolean hasHelpPage(final Object node) {
if (node instanceof IAlarmTreeNode) {
return ((IAlarmTreeNode) node).getHelpPage() != null;
}
return false;
}
/**
* Returns whether the given process variable node in the tree has an
* associated CSS alarm display configured.
*
* @param node the node.
* @return <code>true</code> if a CSS alarm display is configured for the
* node, <code>false</code> otherwise.
*/
private boolean hasCssAlarmDisplay(final Object node) {
if (node instanceof IAlarmTreeNode) {
String display = ((IAlarmTreeNode) node).getCssAlarmDisplay();
return display != null && display.matches(".+\\.css-sds");
}
return false;
}
/**
* Returns whether the given selection contains at least one node with
* an unacknowledged alarm.
*
* @param sel the selection.
* @return <code>true</code> if the selection contains a node with an
* unacknowledged alarm, <code>false</code> otherwise.
*/
private boolean containsNodeWithUnackAlarm(final IStructuredSelection sel) {
Object selectedElement = sel.getFirstElement();
// Note: selectedElement is not instance of IAlarmTreeNode if nothing
// is selected (selectedElement == null), and during initialization,
// when it is an instance of PendingUpdateAdapter.
if (selectedElement instanceof IAlarmTreeNode) {
return ((IAlarmTreeNode) selectedElement)
.getUnacknowledgedAlarmSeverity() != Severity.NO_ALARM;
}
return false;
}
/**
* Adds a context menu to the tree view.
*/
private void initializeContextMenu() {
MenuManager menuMgr = new MenuManager("#PopupMenu");
menuMgr.setRemoveAllWhenShown(true);
// add menu items to the context menu when it is about to show
menuMgr.addMenuListener(new IMenuListener() {
public void menuAboutToShow(final IMenuManager manager) {
AlarmTreeView.this.fillContextMenu(manager);
}
});
// add the context menu to the tree viewer
Menu contextMenu = menuMgr.createContextMenu(_viewer.getTree());
_viewer.getTree().setMenu(contextMenu);
// register the context menu for extension by other plug-ins
getSite().registerContextMenu(menuMgr, _viewer);
}
/**
* Adds tool buttons and menu items to the action bar of this view.
*/
private void contributeToActionBars() {
IActionBars bars = getViewSite().getActionBars();
fillLocalPullDown(bars.getMenuManager());
fillLocalToolBar(bars.getToolBarManager());
}
/**
* Adds the actions for the action bar's pull down menu.
* @param manager the menu manager.
*/
private void fillLocalPullDown(final IMenuManager manager) {
// currently there are no actions in the pulldown menu
}
/**
* Adds the context menu actions.
* @param menu the menu manager.
*/
private void fillContextMenu(final IMenuManager menu) {
IStructuredSelection selection = (IStructuredSelection) _viewer
.getSelection();
if (selection.size() > 0) {
menu.add(_acknowledgeAction);
}
if (selection.size() == 1) {
menu.add(_runCssAlarmDisplayAction);
menu.add(_showHelpGuidanceAction);
menu.add(_showHelpPageAction);
menu.add(new Separator("edit"));
menu.add(_deleteNodeAction);
}
if (selection.size() == 1
&& selection.getFirstElement() instanceof SubtreeNode) {
menu.add(_createRecordAction);
menu.add(_createComponentAction);
}
// adds a separator after which contributed actions from other plug-ins
// will be displayed
menu.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
}
/**
* Adds the tool bar actions.
* @param manager the menu manager.
*/
private void fillLocalToolBar(final IToolBarManager manager) {
manager.add(_reloadAction);
}
/**
* Creates the actions offered by this view.
*/
private void makeActions() {
_reloadAction = new Action() {
public void run() {
startDirectoryReaderJob();
}
};
_reloadAction.setText("Reload");
_reloadAction.setToolTipText("Reload");
_reloadAction.setImageDescriptor(
AlarmTreePlugin.getImageDescriptor("./icons/refresh.gif"));
_acknowledgeAction = new Action() {
@Override
public void run() {
Set<Map<String, String>> messages = new HashSet<Map<String, String>>();
IStructuredSelection selection = (IStructuredSelection) _viewer
.getSelection();
for (Iterator<?> i = selection.iterator(); i
.hasNext();) {
Object o = i.next();
if (o instanceof SubtreeNode) {
SubtreeNode snode = (SubtreeNode) o;
for (ProcessVariableNode pvnode : snode.collectUnacknowledgedAlarms()) {
String name = pvnode.getName();
Severity severity = pvnode.getUnacknowledgedAlarmSeverity();
Map<String, String> properties = new HashMap<String, String>();
properties.put("NAME", name);
properties.put("SEVERITY", severity.toString());
messages.add(properties);
}
} else if (o instanceof ProcessVariableNode) {
ProcessVariableNode pvnode = (ProcessVariableNode) o;
String name = pvnode.getName();
Severity severity = pvnode.getUnacknowledgedAlarmSeverity();
Map<String, String> properties = new HashMap<String, String>();
properties.put("NAME", name);
properties.put("SEVERITY", severity.toString());
messages.add(properties);
}
}
if (!messages.isEmpty()) {
CentralLogger.getInstance().debug(this, "Scheduling send acknowledgement (" + messages.size() + " messages)");
SendAcknowledge ackJob = SendAcknowledge.newFromProperties(messages);
ackJob.schedule();
}
}
};
_acknowledgeAction.setText("Send Acknowledgement");
_acknowledgeAction.setToolTipText("Send alarm acknowledgement");
_acknowledgeAction.setEnabled(false);
_runCssAlarmDisplayAction = new Action() {
@Override
public void run() {
IStructuredSelection selection = (IStructuredSelection) _viewer
.getSelection();
Object selected = selection.getFirstElement();
if (selected instanceof IAlarmTreeNode) {
IAlarmTreeNode node = (IAlarmTreeNode) selected;
IPath path = new Path(node.getCssAlarmDisplay());
Map<String, String> aliases = new HashMap<String, String>();
if (node instanceof ProcessVariableNode) {
aliases.put("channel", node.getName());
}
CentralLogger.getInstance().debug(this, "Opening display: " + path);
RunModeService.getInstance().openDisplayShellInRunMode(path, aliases);
}
}
};
_runCssAlarmDisplayAction.setText("Run Alarm Display");
_runCssAlarmDisplayAction.setToolTipText("Run the alarm display for this PV");
_runCssAlarmDisplayAction.setEnabled(false);
_showHelpGuidanceAction = new Action() {
@Override
public void run() {
IStructuredSelection selection = (IStructuredSelection) _viewer
.getSelection();
Object selected = selection.getFirstElement();
if (selected instanceof IAlarmTreeNode) {
IAlarmTreeNode node = (IAlarmTreeNode) selected;
String helpGuidance = node.getHelpGuidance();
if (helpGuidance != null) {
MessageDialog.openInformation(getSite().getShell(),
node.getName(), helpGuidance);
}
}
}
};
_showHelpGuidanceAction.setText("Show Help Guidance");
_showHelpGuidanceAction.setToolTipText("Show the help guidance for this node");
_showHelpGuidanceAction.setEnabled(false);
_showHelpPageAction = new Action() {
@Override
public void run() {
IStructuredSelection selection = (IStructuredSelection) _viewer
.getSelection();
Object selected = selection.getFirstElement();
if (selected instanceof IAlarmTreeNode) {
IAlarmTreeNode node = (IAlarmTreeNode) selected;
URL helpPage = node.getHelpPage();
if (helpPage != null) {
try {
// Note: we have to pass a browser id here to work
// around a bug in eclipse. The method documentation
// says that createBrowser accepts null but it will
// throw a NullPointerException.
IWebBrowser browser = PlatformUI.getWorkbench()
.getBrowserSupport()
.createBrowser("workaround");
browser.openURL(helpPage);
} catch (PartInitException e) {
CentralLogger.getInstance().error(this,
"Failed to initialize workbench browser.", e);
}
}
}
}
};
_showHelpPageAction.setText("Open Help Page");
_showHelpPageAction.setToolTipText("Open the help page for this node in the web browser");
_showHelpPageAction.setEnabled(false);
_createRecordAction = new Action() {
@Override
public void run() {
IStructuredSelection selection =
(IStructuredSelection) _viewer.getSelection();
Object selected = selection.getFirstElement();
if (selected instanceof SubtreeNode) {
SubtreeNode parent = (SubtreeNode) selected;
String name = promptForRecordName();
if (name != null && !name.equals("")) {
try {
DirectoryEditor.createProcessVariableRecord(parent,
name);
} catch (DirectoryEditException e) {
MessageDialog.openError(getSite().getShell(),
"Create New Record",
"Could not create the new record: " + e.getMessage());
}
_viewer.refresh(parent);
}
}
}
private String promptForRecordName() {
InputDialog dialog = new InputDialog(getSite().getShell(),
"Create New Record", "Record name:", null,
new IInputValidator() {
public String isValid(final String newText) {
if (newText.equals("")) {
return "Please enter a name.";
} else if (newText.indexOf("=") != -1
|| newText.indexOf("/") != -1
|| newText.indexOf(",") != -1) {
return "The following characters are not allowed "
+ "in names: = / ,";
} else {
return null;
}
}
});
if (Window.OK == dialog.open()) {
return dialog.getValue();
}
return null;
}
};
_createRecordAction.setText("Create Record");
_createComponentAction = new Action() {
@Override
public void run() {
IStructuredSelection selection =
(IStructuredSelection) _viewer.getSelection();
Object selected = selection.getFirstElement();
if (selected instanceof SubtreeNode) {
SubtreeNode parent = (SubtreeNode) selected;
String name = promptForRecordName();
if (name != null && !name.equals("")) {
try {
DirectoryEditor.createComponent(parent, name);
} catch (DirectoryEditException e) {
MessageDialog.openError(getSite().getShell(),
"Create New Component",
"Could not create the new component: " + e.getMessage());
}
_viewer.refresh(parent);
}
}
}
private String promptForRecordName() {
InputDialog dialog = new InputDialog(getSite().getShell(),
"Create New Component", "Component name:", null,
new IInputValidator() {
public String isValid(final String newText) {
if (newText.equals("")) {
return "Please enter a name.";
} else if (newText.indexOf("=") != -1
|| newText.indexOf("/") != -1
|| newText.indexOf(",") != -1) {
return "The following characters are not allowed "
+ "in names: = / ,";
} else {
return null;
}
}
});
if (Window.OK == dialog.open()) {
return dialog.getValue();
}
return null;
}
};
_createComponentAction.setText("Create Component");
_deleteNodeAction = new Action() {
@Override
public void run() {
IStructuredSelection selection =
(IStructuredSelection) _viewer.getSelection();
Object selected = selection.getFirstElement();
if (selected instanceof IAlarmTreeNode) {
IAlarmTreeNode nodeToDelete = (IAlarmTreeNode) selected;
SubtreeNode parent = nodeToDelete.getParent();
try {
DirectoryEditor.delete(nodeToDelete);
parent.remove(nodeToDelete);
_viewer.refresh(parent);
} catch (DirectoryEditException e) {
MessageDialog.openError(getSite().getShell(),
"Delete",
"Could not delete this node: " + e.getMessage());
}
}
}
};
_deleteNodeAction.setText("Delete");
}
/**
* Passes the focus request to the viewer's control.
*/
public final void setFocus() {
_viewer.getControl().setFocus();
}
/**
* Refreshes this view.
*/
public final void refresh(){
_viewer.refresh();
}
}
|
package org.ovirt.engine.core.compat.backendcompat;
import java.beans.PropertyDescriptor;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
//This will be a wrapper for import java.beans.PropertyDescriptor;
public class PropertyInfo {
private static final Log log = LogFactory.getLog(PropertyInfo.class);
private PropertyDescriptor pd;
public PropertyInfo(PropertyDescriptor pd) {
this.pd = pd;
}
public String getName() {
return pd.getName();
}
public Object GetValue(Object obj, Object defaultValue) {
Object returnValue = null;
try {
returnValue = pd.getReadMethod().invoke(obj);
} catch (Exception e) {
log.warn("Unable to get value of property: " + pd.getDisplayName() + " for class "
+ obj.getClass().getName());
}
return returnValue == null ? defaultValue : returnValue;
}
public boolean getCanWrite() {
return pd.getWriteMethod() != null;
}
public boolean isPropertyInstanceOf(Class<?> clazz) {
return this.pd.getPropertyType().equals(clazz);
}
}
|
package org.ovirt.engine.core.notifier.filter;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.ovirt.engine.core.notifier.dao.DispatchResult;
import org.ovirt.engine.core.notifier.transport.Observer;
import org.ovirt.engine.core.notifier.transport.Transport;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class FirstMatchSimpleFilterTest {
FirstMatchSimpleFilter filter;
T snmp;
T smtp;
/*
* This replaces the application message representation, the only request we have is to have getName() to return the
* name based on which we filter.
*/
private static class E extends AuditLogEvent {
private String e;
public E(String e) {
this.e = e;
}
@Override
public String getName() {
return e;
}
}
private static class T extends Transport {
private String t;
private List<String> events = new ArrayList<>();
public T(String t) {
this.t = t;
}
@Override
public void dispatchEvent(AuditLogEvent event, String address) {
events.add(event.getName() + "-->" + address);
}
public List<String> getEvents() {
return events;
}
@Override
public String getName() {
return t;
}
@Override
public boolean isActive() {
return true;
}
@Override
public void notifyObservers(DispatchResult data) {
}
@Override
public void registerObserver(Observer observer) {
}
@Override
public void removeObserver(Observer observer) {
}
}
@Before
public void setUp() throws Exception {
filter = new FirstMatchSimpleFilter();
/*
* Here we register two transports into the filter logic.
*
* All we need from a transport is to know its name and able to dispatch messages into it.
*
* transports have nothing to do with application, once initialized.
*/
snmp = new T("snmp");
smtp = new T("smtp");
filter.registerTransport(snmp);
filter.registerTransport(smtp);
}
@After
public void tearDown() throws Exception {
}
@Test
public void testEmptyFilter() throws Exception {
filter.clearFilterEntries();
filter.processEvent(new E("message0"));
filter.processEvent(new E("message1"));
Assert.assertTrue(snmp.getEvents().isEmpty());
}
@Test
public void testConfigurationEntries() throws Exception {
filter.clearFilterEntries();
filter.addFilterEntries(
Collections.singletonList(
new FirstMatchSimpleFilter.FilterEntry("message0", false, "smtp", "[email protected]"))
);
filter.processEvent(new E("message0"));
filter.processEvent(new E("message1"));
Assert.assertTrue(smtp.getEvents().contains("message0-->[email protected]"));
}
@Test
public void testSimpleParse() throws Exception {
filter.clearFilterEntries();
filter.addFilterEntries(
FirstMatchSimpleFilter.parse("include:VDC_STOP(snmp:) " +
"exclude:*")
);
filter.processEvent(new E("VDC_STOP"));
Assert.assertTrue(snmp.getEvents().contains("VDC_STOP
}
@Test
public void testIncludeExcludeOrder() {
String expected = "[email protected]";
filter.clearFilterEntries();
filter.addFilterEntries(
FirstMatchSimpleFilter.parse(
"" +
"include:message1(smtp:" + expected + ") " +
"include:message2(smtp:" + expected + ") " +
"exclude:message3(smtp:" + expected + ") " +
"exclude:message1(smtp:" + expected + ") " +
"include:*"
));
filter.processEvent(new E("message1"));
filter.processEvent(new E("message2"));
filter.processEvent(new E("message3"));
Assert.assertTrue(smtp.getEvents().contains("message1-->" + expected));
Assert.assertTrue(smtp.getEvents().contains("message2-->" + expected));
Assert.assertEquals(2, smtp.getEvents().size());
}
@Test
public void testAll() throws Exception {
filter.clearFilterEntries();
filter.addFilterEntries(Collections.singletonList(
new FirstMatchSimpleFilter.FilterEntry("kuku", false, "snmp", "pupu"))
);
filter.addFilterEntries(Collections.singletonList(
new FirstMatchSimpleFilter.FilterEntry("kuku", false, "smtp", "pupu"))
);
filter.addFilterEntries(
FirstMatchSimpleFilter.parse(
"" +
"include:*"
));
filter.processEvent(new E("message1"));
Assert.assertTrue(snmp.getEvents().contains("message1-->pupu"));
Assert.assertTrue(smtp.getEvents().contains("message1-->pupu"));
}
@Test
public void testFilter() throws Exception {
filter.clearFilterEntries();
/*
* Add configuration filter
*/
filter.addFilterEntries(
FirstMatchSimpleFilter.parse(
"include:message1(smtp:[email protected]) " +
"include:message2(smtp:[email protected]) " +
"exclude:message3(smtp:[email protected]) " +
"exclude:message1(smtp:[email protected]) " +
"include:message2(smtp:[email protected]) " +
"include:message1(smtp:[email protected]) " +
"exclude:message1(snmp:profile1) " +
"exclude:message2(snmp:profile1) " +
"include:*(snmp:profile2) " +
"include:*(snmp:profile1) " +
"exclude:*" +
""
));
filter.processEvent(new E("message0"));
filter.processEvent(new E("message1"));
filter.processEvent(new E("message2"));
Assert.assertTrue(snmp.getEvents().contains("message0-->profile1"));
Assert.assertTrue(snmp.getEvents().contains("message0-->profile2"));
Assert.assertTrue(snmp.getEvents().contains("message1-->profile2"));
Assert.assertTrue(snmp.getEvents().contains("message2-->profile2"));
Assert.assertEquals(4, snmp.getEvents().size());
Assert.assertTrue(smtp.getEvents().contains("message1-->[email protected]"));
Assert.assertTrue(smtp.getEvents().contains("message1-->[email protected]"));
Assert.assertTrue(smtp.getEvents().contains("message2-->[email protected]"));
Assert.assertTrue(smtp.getEvents().contains("message2-->[email protected]"));
Assert.assertEquals(4, smtp.getEvents().size());
}
@Test()
public void testParsePositive() throws Exception {
// Should parse
FirstMatchSimpleFilter.parse("include:message(kuku:pupu) include:message(kuku:pupu)");
}
@Test(expected = IllegalArgumentException.class)
public void testParseNegative1() throws Exception {
// No event
FirstMatchSimpleFilter.parse("include:(kuku:pupu)");
}
@Test(expected = IllegalArgumentException.class)
public void testParseNegative2() throws Exception {
// No Transport
FirstMatchSimpleFilter.parse("include:message(:pupu)");
}
@Test(expected = IllegalArgumentException.class)
public void testParseNegative3() throws Exception {
// Random text
FirstMatchSimpleFilter.parse("lorem ipsum");
}
}
|
package org.intermine.bio.dataconversion;
import java.io.Reader;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.tools.ant.BuildException;
import org.intermine.dataconversion.ItemWriter;
import org.intermine.metadata.Model;
import org.intermine.objectstore.ObjectStoreException;
import org.intermine.util.FormattedTextParser;
import org.intermine.xml.full.Item;
import org.xml.sax.SAXException;
/**
* DataConverter to create items from DRSC RNAi screen date files.
*
* @author Kim Rutherford
* @author Richard Smith
*/
public class FlyRNAiScreenConverter extends BioFileConverter
{
protected Item organism, hfaSource;
private Map<String, Item> genes = new HashMap<String, Item>();
private Map<String, Item> publications = new HashMap<String, Item>();
private Map<String, Item> screenMap = new HashMap<String, Item>();
private static final String TAXON_ID = "7227";
// access to current file for error messages
private String fileName;
private Set<String> hitScreenNames = new HashSet<String>();
private Set<String> detailsScreenNames = new HashSet<String>();
protected IdResolverFactory resolverFactory;
protected static final Logger LOG = Logger.getLogger(FlyRNAiScreenConverter.class);
/**
* Create a new FlyRNAiScreenConverter object.
* @param writer the ItemWriter used to handle the resultant items
* @param model the Model
*/
public FlyRNAiScreenConverter(ItemWriter writer, Model model) {
super(writer, model, "DRSC", "DRSC data set");
// only construct factory here so can be replaced by mock factory in tests
resolverFactory = new FlyBaseIdResolverFactory("gene");
}
private static final Map<String, String> RESULTS_KEY = new HashMap<String, String>();
static {
RESULTS_KEY.put("N", "Not a Hit");
RESULTS_KEY.put("Y", "Hit");
RESULTS_KEY.put("S", "Strong Hit");
RESULTS_KEY.put("M", "Medium Hit");
RESULTS_KEY.put("W", "Weak Hit");
RESULTS_KEY.put("NS", "Not Screened");
}
/**
* {@inheritDoc}
*/
@Override
public void process(Reader reader) throws Exception {
// set up common items
if (organism == null) {
organism = createItem("Organism");
organism.setAttribute("taxonId", TAXON_ID);
store(organism);
}
fileName = getCurrentFile().getName();
if (fileName.startsWith("RNAi_all_hits")) {
processHits(reader);
} else if (fileName.startsWith("RNAi_screen_details")) {
processScreenDetails(reader);
}
}
/**
* Check that we have seen the same screen names in the hits and details files.
* {@inheritDoc}
*/
@Override
public void close() throws Exception {
for (Item screen : screenMap.values()) {
store(screen);
}
Set<String> noDetails = new HashSet<String>();
for (String screenName : hitScreenNames) {
if (!detailsScreenNames.contains(screenName)) {
noDetails.add(screenName);
}
}
Set<String> noHits = new HashSet<String>();
for (String screenName : detailsScreenNames) {
if (!hitScreenNames.contains(screenName)) {
noHits.add(screenName);
}
}
if (!noHits.isEmpty() || !noDetails.isEmpty()) {
String msg = "Screen names from hits file and details file did not match."
+ (noHits.isEmpty()
? ""
: " No hits found for screen detail: '" + noHits + "'")
+ (noDetails.isEmpty()
? ""
: " No details found for screen hit: '" + noDetails + "'");
throw new RuntimeException(msg);
//LOG.error(msg);
}
super.close();
}
private void processHits(Reader reader)
throws ObjectStoreException {
boolean readingData = false;
int headerLength = 0;
Item[] screens = null;
Iterator<?> tsvIter;
try {
tsvIter = FormattedTextParser.parseTabDelimitedReader(reader);
} catch (Exception e) {
throw new BuildException("cannot parse file: " + getCurrentFile(), e);
}
int lineNumber = 0;
while (tsvIter.hasNext()) {
lineNumber++;
String [] line = (String[]) tsvIter.next();
if (!readingData) {
if ("Amplicon".equals(line[0].trim())) {
readingData = true;
headerLength = line.length;
screens = new Item[headerLength - 2];
for (int i = 2; i < line.length; i++) {
// create an array of screen item identifiers (first two slots empty)
String screenName = line[i].trim();
screens[i - 2] = getScreen(screenName);
hitScreenNames.add(screenName);
}
}
} else {
if (line.length != headerLength) {
String msg = "Incorrect number of entries in line number " + lineNumber
+ ": " + line.toString()
+ ". Should be " + headerLength + " but is " + line.length + " instead."
+ " content:" + line[0];
throw new RuntimeException(msg);
}
Set<Item> ampliconGenes = new LinkedHashSet<Item>();
String ampliconIdentifier = line[0].trim();
Item amplicon = createItem("PCRProduct");
amplicon.setAttribute("primaryIdentifier", ampliconIdentifier);
amplicon.setReference("organism", organism);
// the amplicon may target zero or more genes, a gene can be targeted
// by more than one amplicon.
if (StringUtils.isNotEmpty(line[1])) {
String [] geneNames = line[1].split(",");
for (int i = 0; i < geneNames.length; i++) {
String geneSymbol = geneNames[i].trim();
Item gene = newGene(geneSymbol);
if (gene != null) {
ampliconGenes.add(gene);
amplicon.addToCollection("genes", gene);
}
}
}
// loop over screens to create results
for (int j = 0; j < screens.length; j++) {
String resultValue = RESULTS_KEY.get(line[j + 2].trim());
if (resultValue == null) {
throw new RuntimeException("Unrecogised result symbol '" + line[j + 2]
+ "' in line: " + Arrays.asList(line));
}
if (genes.isEmpty()) {
// create a hit that doesn't reference a gene
Item screenHit = createItem("RNAiScreenHit");
String refId = screenHit.getIdentifier();
screenHit.setReference("rnaiScreen", screens[j]);
screenHit.setAttribute("result", resultValue);
screenHit.setReference("pcrProduct", amplicon);
screens[j].addToCollection("rnaiScreenHits", refId);
store(screenHit);
} else {
// create one hit for each gene targeted
for (Item gene : ampliconGenes) {
Item screenHit = createItem("RNAiScreenHit");
String refId = screenHit.getIdentifier();
screenHit.setReference("rnaiScreen", screens[j]);
screenHit.setReference("gene", gene);
screenHit.setAttribute("result", resultValue);
screenHit.setReference("pcrProduct", amplicon);
//screens[j].getCollection("genes").addRefId(gene.getIdentifier());
gene.addToCollection("rnaiResults", screenHit.getIdentifier());
screens[j].addToCollection("rnaiScreenHits", refId);
store(screenHit);
}
}
}
store(amplicon);
}
}
for (Item gene : genes.values()) {
store(gene);
}
}
private void processScreenDetails(Reader reader) throws ObjectStoreException {
Iterator<?> tsvIter;
try {
tsvIter = FormattedTextParser.parseTabDelimitedReader(reader);
} catch (Exception e) {
throw new BuildException("cannot parse file: " + getCurrentFile(), e);
}
while (tsvIter.hasNext()) {
String [] line = (String[]) tsvIter.next();
if (line.length != 5) {
throw new RuntimeException("Did not find five elements in line, found "
+ line.length + ": " + Arrays.asList(line));
}
String pubmedId = line[0].trim();
if ("Pubmed_ID".equals(pubmedId)) {
// skip header
continue;
}
Item publication = getPublication(pubmedId);
String screenName = line[2].trim();
detailsScreenNames.add(screenName);
Item screen = getScreen(screenName);
screen.setAttribute("name", screenName);
screen.setAttribute("cellLine", line[3].trim());
String analysisDescr = line[4].trim();
if (StringUtils.isNotEmpty(analysisDescr)) {
screen.setAttribute("analysisDescription", line[4].trim());
}
screen.setReference("organism", organism);
screen.setReference("publication", publication);
// the hits file may be processed first
screenMap.remove(screenName);
screenMap.put(screenName, screen);
}
}
// Fetch or create a Publication
private Item getPublication(String pubmedId) throws ObjectStoreException {
Item publication = publications.get(pubmedId);
if (publication == null) {
publication = createItem("Publication");
publication.setAttribute("pubMedId", pubmedId);
publications.put(pubmedId, publication);
store(publication);
}
return publication;
}
// Fetch of create an RNAiScreen
private Item getScreen(String screenName) {
Item screen = screenMap.get(screenName);
if (screen == null) {
screen = createItem("RNAiScreen");
screenMap.put(screenName, screen);
}
return screen;
}
/**
* Convenience method to create a new gene Item
* @param geneSymbol the gene symbol
* @return a new gene Item
*/
protected Item newGene(String geneSymbol) {
if (geneSymbol == null) {
throw new RuntimeException("geneSymbol can't be null");
}
IdResolver resolver = resolverFactory.getIdResolver();
int resCount = resolver.countResolutions(TAXON_ID, geneSymbol);
if (resCount != 1) {
LOG.info("RESOLVER: failed to resolve gene to one identifier, ignoring gene: "
+ geneSymbol + " count: " + resCount + " FBgn: "
+ resolver.resolveId(TAXON_ID, geneSymbol));
return null;
}
String primaryIdentifier = resolver.resolveId(TAXON_ID, geneSymbol).iterator().next();
Item item = genes.get(primaryIdentifier);
if (item == null) {
item = createItem("Gene");
item.setAttribute("primaryIdentifier", primaryIdentifier);
item.setReference("organism", organism);
genes.put(primaryIdentifier, item);
}
return item;
}
}
|
package org.bitrepository.protocol.messagebus.logger;
import org.bitrepository.bitrepositorymessages.Message;
import org.bitrepository.bitrepositorymessages.MessageResponse;
import org.bitrepository.protocol.utils.MessageUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Implement the functionality for generic message logging. Open for extension for by custom loggers for specific
* messages.
*/
public class DefaultMessagingLogger implements MessageLogger {
protected final Logger log = LoggerFactory.getLogger(getClass());
@Override
public void logMessageSent(Message message) {
StringBuilder messageSB = new StringBuilder("Sent ");
if (shouldLogFullMessage(message)) {
logFullMessage(appendFullRepresentation(messageSB, message).toString());
} else {
appendMessageIDString(messageSB, message);
if (message.isSetTo()) {
messageSB.append(" to " + message.getTo() + ", ");
}
messageSB.append(" destination " + message.getDestination() + ": ");
appendShortRepresentation(messageSB, message);
logShortMessage(messageSB.toString());
}
}
@Override
public void logMessageReceived(Message message) {
StringBuilder messageSB = new StringBuilder("Received ");
if (shouldLogFullMessage(message)) {
logFullMessage(appendFullRepresentation(messageSB, message).toString());
} else {
appendMessageIDString(messageSB, message);
messageSB.append(" from " + message.getFrom() + ": ");
appendShortRepresentation(messageSB, message);
logShortMessage(messageSB.toString());
}
}
/**
*
Indicated whether the full message should be logged. Can be overridden in custom loggers.
*/
protected boolean shouldLogFullMessage(Message message) {
return log.isTraceEnabled();
}
/**
* Log the full message at trace level. May be overridden to log at a different level for concrete messages.
* @param message The message string to log.
* @return Whether the
*/
protected void logFullMessage(String message) {
log.trace(message);
}
private StringBuilder appendFullRepresentation(StringBuilder messageSB, Message message) {
messageSB.append(message.toString());
return messageSB;
}
/**
* Log the short version of the message at info level.
* May be overridden to log at a different level for concrete messages.
* @param message The message string to log.
*/
protected void logShortMessage(String message) {
log.info(message);
}
private StringBuilder appendShortRepresentation(StringBuilder messageSB, Message message) {
if (message instanceof MessageResponse) {
appendResponseInfo(messageSB, (MessageResponse) message);
}
appendCustomInfo(messageSB, message);
return messageSB;
}
private StringBuilder appendMessageIDString(StringBuilder messageSB, Message message) {
messageSB.append(message.getClass().getSimpleName());
messageSB.append("(" + MessageUtils.getShortConversationID(message.getCorrelationID()) + ")");
return messageSB;
}
private StringBuilder appendResponseInfo(StringBuilder messageSB, MessageResponse response) {
messageSB.append(response.getResponseInfo().getResponseCode() + "(" +
response.getResponseInfo().getResponseText() + ")");
return messageSB;
}
protected StringBuilder appendCustomInfo(StringBuilder messageSB, Message message) {
return messageSB;
}
}
|
package com.zeroq6.blog.operate.web.controller;
import com.zeroq6.blog.common.base.BaseController;
import com.zeroq6.blog.common.base.BaseResponse;
import com.zeroq6.blog.common.domain.CommentDomain;
import com.zeroq6.blog.common.domain.PostDomain;
import com.zeroq6.blog.common.domain.enums.field.EmPostPostType;
import com.zeroq6.blog.operate.service.CommentService;
import com.zeroq6.blog.operate.service.PostService;
import com.zeroq6.common.utils.JsonUtils;
import com.zeroq6.common.utils.MyWebUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
@Controller
@RequestMapping("/comment")
public class CommentController extends BaseController {
private final String postUri = "/post/show/%s";
private final String guestBookUri = "/guestbook";
@Autowired
private PostService postService;
@Autowired
private CommentService commentService;
@RequestMapping(value = "/post")
public String post(CommentDomain commentDomain, HttpServletRequest request, Model view) {
try {
String userAgent = request.getHeader("user-agent");
if (StringUtils.isBlank(userAgent)) {
return redirect(commentDomain);
}
String referer = request.getHeader("referer");
if (StringUtils.isBlank(referer)) {
return redirect(commentDomain);
}
if (!lenLessEqualThan(commentDomain.getUsername(), 32) ||
!lenLessEqualThan(commentDomain.getEmail(), 32) ||
!lenLessEqualThan(commentDomain.getUrl(), 100) ||
!lenLessEqualThan(commentDomain.getContent(), 1000)) {
return redirect(commentDomain);
}
// ip UA
commentDomain.setIp(MyWebUtils.getClientIp(request));
commentDomain.setUserAgent(userAgent);
// trim
commentDomain.setUsername(StringUtils.trim(commentDomain.getUsername()));
commentDomain.setEmail(StringUtils.trim(commentDomain.getEmail()));
commentDomain.setUrl(StringUtils.trim(commentDomain.getUrl()));
commentDomain.setContent(StringUtils.trim(commentDomain.getContent()));
BaseResponse<String> result = commentService.post(commentDomain);
if (result.isSuccess()) {
return redirect(commentDomain) + "#c" + commentDomain.getId();
}
} catch (Exception e) {
logger.error(": " + JsonUtils.toJSONString(commentDomain), e);
}
return redirect(commentDomain);
}
private boolean lenLessEqualThan(String string, int len) {
return StringUtils.isNotBlank(string) && string.length() <= len;
}
private String redirect(CommentDomain commentDomain) {
try {
if (null == commentDomain || null == commentDomain.getPostId()) {
return redirectIndex();
}
PostDomain postDomain = postService.selectOne(new PostDomain().setId(commentDomain.getPostId()), true);
if (null == postDomain) {
return redirectIndex();
}
if (postDomain.getPostType() == EmPostPostType.WENZHANG.value()) {
return "redirect:" + String.format(postUri, postDomain.getId() + "");
} else if (postDomain.getPostType() == EmPostPostType.LIUYAN.value()) {
return "redirect:" + guestBookUri;
} else {
return redirectIndex();
}
} catch (Exception e) {
logger.error("", e);
return redirectIndex();
}
}
}
|
package cmput301f17t26.smores.all_activities;
import android.graphics.drawable.BitmapDrawable;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import java.util.ArrayList;
import cmput301f17t26.smores.R;
import cmput301f17t26.smores.all_exceptions.ImageNotSetException;
import cmput301f17t26.smores.all_exceptions.LocationNotSetException;
import cmput301f17t26.smores.all_models.HabitEvent;
import cmput301f17t26.smores.all_storage_controller.HabitEventController;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
private ArrayList<HabitEvent> userHabitEvents;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
userHabitEvents = HabitEventController.getHabitEventController(this).getFilteredHabitEvents();
for (HabitEvent habitEvent: userHabitEvents) {
try {
//mMap.addMarker(new MarkerOptions().position(habitEvent.getLatLng()).title(habitEvent.getDate().toString()));
mMap.addMarker(new MarkerOptions().position(habitEvent.getLatLng()).title(habitEvent.getDate().toString()).icon(BitmapDescriptorFactory.fromBitmap((habitEvent.getImage()))));
mMap.moveCamera(CameraUpdateFactory.newLatLng(habitEvent.getLatLng()));
} catch (LocationNotSetException e) {
continue;
} catch (ImageNotSetException e) {
continue;
}
}
// Add a marker in Sydney and move the camera
// Added a few more markers to see how this works...
/*LatLng sydney = new LatLng(-34, 151);
//LatLng sydneyTwo = new LatLng(-34, 152);
LatLng sydneyThree = new LatLng(-31, 155);
LatLng sydneyFour = new LatLng(-32, 154);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.addMarker(new MarkerOptions().position(sydneyTwo).title("Marker in Sydney two"));
mMap.addMarker(new MarkerOptions().position(sydneyThree).title("Marker in Sydney three"));
mMap.addMarker(new MarkerOptions().position(sydneyFour).title("Marker in Sydney four"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));*/
}
}
|
package gov.nci.nih.cagrid.tests.core.util;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class IntroduceServiceInfo
{
public static final String INTRODUCE_CREATESERVICE_TASK = "createService";
public static final String INTRODUCE_RESYNCSERVICE_TASK = "resyncService";
public static final String INTRODUCE_SERVICEXML_FILENAME = "introduce.xml";
private String serviceName;
private String namespace;
private String packageName;
private String[] methodNames;
public IntroduceServiceInfo(File serviceXmlDescriptor)
throws ParserConfigurationException, SAXException, IOException
{
super();
SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
ServiceXmlHandler handler = new ServiceXmlHandler();
parser.parse(serviceXmlDescriptor, handler);
this.methodNames = handler.methodNames.toArray(new String[0]);
}
private class ServiceXmlHandler
extends DefaultHandler
{
public ArrayList<String> methodNames = new ArrayList<String>();
public void startElement(
String uri, String lname, String qname, Attributes atts
) {
if (qname.endsWith("Service")) {
serviceName = atts.getValue("name");
namespace = atts.getValue("namespace");
packageName = atts.getValue("packageName");
} else if (qname.endsWith("Method")) {
methodNames.add(atts.getValue("name"));
}
}
}
public String getNamespace()
{
return namespace;
}
public String getPackageName()
{
return packageName;
}
public String getServiceName()
{
return serviceName;
}
public String[] getMethodNames()
{
return methodNames;
}
}
|
package com.akisute.yourwifi.app.model;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.akisute.yourwifi.app.util.GlobalEventBus;
import com.squareup.otto.Subscribe;
import java.util.ArrayList;
import java.util.List;
import butterknife.ButterKnife;
import butterknife.InjectView;
public class NetworkListAdapter extends BaseAdapter {
class ViewHolder {
@InjectView(android.R.id.text1)
TextView textView;
ViewHolder(View view) {
ButterKnife.inject(this, view);
}
}
private final LayoutInflater mLayoutInflater;
private final NetworkCache mNetworkCache = new NetworkCache();
private List<Network> mCurrentList = new ArrayList<Network>();
public NetworkListAdapter(Context context) {
mLayoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public void registerToEventBus() {
GlobalEventBus.getInstance().register(this);
}
public void unregisterFromEventBus() {
GlobalEventBus.getInstance().unregister(this);
}
public void update(List<Network> networkList) {
for (Network network : networkList) {
mNetworkCache.put(network);
}
mCurrentList = mNetworkCache.getAllNetworkList();
notifyDataSetChanged();
}
@Override
public int getCount() {
return mCurrentList.size();
}
@Override
public Network getItem(int position) {
return mCurrentList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if (convertView == null) {
convertView = mLayoutInflater.inflate(android.R.layout.simple_list_item_1, null, false);
viewHolder = new ViewHolder(convertView);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
Network network = getItem(position);
viewHolder.textView.setText(network.getDescription());
return convertView;
}
@Subscribe
public void onNewScanResultsEvent(NetworkScanManager.OnNewScanResultsEvent event) {
update(event.getNetworkList());
}
}
|
package com.example.android.sunshine.app;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.format.Time;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ForecastFragment extends Fragment {
private ArrayAdapter<String> forecastAdapter;
public ForecastFragment() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Create some dummy data for the ListView. Here's a sample weekly forecast
String[] data = {
"Mon 6/23 - Sunny - 31/17",
"Tue 6/24 - Foggy - 21/8",
"Wed 6/25 - Cloudy - 22/17",
"Thurs 6/26 - Rainy - 18/11",
"Fri 6/27 - Foggy - 21/10",
"Sat 6/28 - TRAPPED IN WEATHERSTATION - 23/18",
"Sun 6/29 - Sunny - 20/7"
};
List<String> weekForecast = new ArrayList<>(Arrays.asList(data));
forecastAdapter = new ArrayAdapter<>(getActivity(), R.layout.list_item_forecast, R.id.list_item_forecast_textview, weekForecast);
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
ListView listView = (ListView) rootView.findViewById(R.id.listview_forecast);
listView.setAdapter(forecastAdapter);
return rootView;
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.forecast_fragment, menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_refresh) {
new FetchWeatherTask().execute("94043");
return true;
}
return super.onOptionsItemSelected(item);
}
public class FetchWeatherTask extends AsyncTask<String, Void, String[]> {
private final String LOG_TAG = FetchWeatherTask.class.getSimpleName();
@Override
protected String[] doInBackground(String... params) {
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
String forecastJsonStr = null;
int numDays = 7;
try {
String baseUrl = "http://api.openweathermap.org/data/2.5/forecast/daily?";
Uri builtUri = Uri.parse(baseUrl).buildUpon()
.appendQueryParameter("q", params[0])
.appendQueryParameter("mode", "json")
.appendQueryParameter("units", "metric")
.appendQueryParameter("cnt", Integer.toString(numDays))
.appendQueryParameter("APPID", BuildConfig.OPEN_WEATHER_MAP_API_KEY).build();
URL url = new URL(builtUri.toString());
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line).append("\n");
}
if (buffer.length() == 0) {
return null;
}
forecastJsonStr = buffer.toString();
Log.v(LOG_TAG, "JSON Str: " + forecastJsonStr);
} catch (IOException e) {
Log.e(LOG_TAG, "Error ", e);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e(LOG_TAG, "Error closing stream", e);
}
}
}
try {
return getWeatherDataFromJson(forecastJsonStr, numDays);
} catch (JSONException e) {
Log.e(LOG_TAG, "JSON Error ", e);
}
return null;
}
/* The date/time conversion code is going to be moved outside the asynctask later,
* so for convenience we're breaking it out into its own method now.
*/
private String getReadableDateString(long time) {
// Because the API returns a unix timestamp (measured in seconds),
// it must be converted to milliseconds in order to be converted to valid date.
SimpleDateFormat shortenedDateFormat = new SimpleDateFormat("EEE MMM dd");
return shortenedDateFormat.format(time);
}
/**
* Prepare the weather high/lows for presentation.
*/
private String formatHighLows(double high, double low) {
// For presentation, assume the user doesn't care about tenths of a degree.
long roundedHigh = Math.round(high);
long roundedLow = Math.round(low);
String highLowStr = roundedHigh + "/" + roundedLow;
return highLowStr;
}
/**
* Take the String representing the complete forecast in JSON Format and
* pull out the data we need to construct the Strings needed for the wireframes.
* <p>
* Fortunately parsing is easy: constructor takes the JSON string and converts it
* into an Object hierarchy for us.
*/
private String[] getWeatherDataFromJson(String forecastJsonStr, int numDays)
throws JSONException {
// These are the names of the JSON objects that need to be extracted.
final String OWM_LIST = "list";
final String OWM_WEATHER = "weather";
final String OWM_TEMPERATURE = "temp";
final String OWM_MAX = "max";
final String OWM_MIN = "min";
final String OWM_DESCRIPTION = "main";
JSONObject forecastJson = new JSONObject(forecastJsonStr);
JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST);
// OWM returns daily forecasts based upon the local time of the city that is being
// asked for, which means that we need to know the GMT offset to translate this data
// properly.
// Since this data is also sent in-order and the first day is always the
// current day, we're going to take advantage of that to get a nice
// normalized UTC date for all of our weather.
Time dayTime = new Time();
dayTime.setToNow();
// we start at the day returned by local time. Otherwise this is a mess.
int julianStartDay = Time.getJulianDay(System.currentTimeMillis(), dayTime.gmtoff);
// now we work exclusively in UTC
dayTime = new Time();
String[] resultStrs = new String[numDays];
for (int i = 0; i < weatherArray.length(); i++) {
// For now, using the format "Day, description, hi/low"
String day;
String description;
String highAndLow;
// Get the JSON object representing the day
JSONObject dayForecast = weatherArray.getJSONObject(i);
// The date/time is returned as a long. We need to convert that
// into something human-readable, since most people won't read "1400356800" as
// "this saturday".
long dateTime;
// Cheating to convert this to UTC time, which is what we want anyhow
dateTime = dayTime.setJulianDay(julianStartDay + i);
day = getReadableDateString(dateTime);
// description is in a child array called "weather", which is 1 element long.
JSONObject weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0);
description = weatherObject.getString(OWM_DESCRIPTION);
// Temperatures are in a child object called "temp". Try not to name variables
// "temp" when working with temperature. It confuses everybody.
JSONObject temperatureObject = dayForecast.getJSONObject(OWM_TEMPERATURE);
double high = temperatureObject.getDouble(OWM_MAX);
double low = temperatureObject.getDouble(OWM_MIN);
highAndLow = formatHighLows(high, low);
resultStrs[i] = day + " - " + description + " - " + highAndLow;
}
for (String s : resultStrs) {
Log.v(LOG_TAG, "Forecast entry: " + s);
}
return resultStrs;
}
@Override
protected void onPostExecute(String[] result) {
if (result != null) {
forecastAdapter.clear();
forecastAdapter.addAll(result);
}
}
}
}
|
package com.powsybl.cgmes.conversion.elements;
import java.util.Comparator;
import com.powsybl.cgmes.model.CgmesModelException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.powsybl.cgmes.conversion.Context;
import com.powsybl.cgmes.model.CgmesNames;
import com.powsybl.iidm.network.RatioTapChangerAdder;
import com.powsybl.iidm.network.ThreeWindingsTransformer;
import com.powsybl.iidm.network.TwoWindingsTransformer;
import com.powsybl.triplestore.api.PropertyBag;
import com.powsybl.triplestore.api.PropertyBags;
public class RatioTapChangerConversion extends AbstractIdentifiedObjectConversion {
public RatioTapChangerConversion(PropertyBag rtc, Context context) {
super("RatioTapChanger", rtc, context);
tx2 = context.tapChangerTransformers().transformer2(id);
tx3 = context.tapChangerTransformers().transformer3(id);
lowStep = rtc.asInt("lowStep");
highStep = rtc.asInt("highStep");
neutralStep = rtc.asInt("neutralStep");
position = getTapPosition(rtc.asInt("normalStep", neutralStep));
ltcFlag = rtc.asBoolean("ltcFlag", false);
}
@Override
public boolean valid() {
if (tx2 == null && tx3 == null) {
invalid("Missing transformer");
return false;
}
if (tx3 != null) {
int side = context.tapChangerTransformers().whichSide(id);
if (side == 1) {
String reason0 = String.format(
"Not supported at end 1 of 3wtx. txId 'name' 'substation': %s '%s' '%s'",
tx3.getId(),
tx3.getName(),
tx3.getSubstation().getName());
// Check if the step is at neutral and regulating control is disabled
boolean regulating = p.asBoolean("regulatingControlEnabled", false);
if (position == neutralStep && !regulating) {
ignored(reason0 + ", but is at neutralStep and regulating control disabled");
} else {
String reason = String.format(
"%s, tap step: %d, regulating control enabled: %b",
reason0,
position,
regulating);
invalid(reason);
}
return false;
}
}
return inRange("defaultStep", neutralStep, lowStep, highStep) &&
inRange("position", position, lowStep, highStep);
}
@Override
public void convert() {
RatioTapChangerAdder rtca = adder();
if (rtca == null) {
invalid("Could not create ratio tap changer adder");
return;
}
rtca.setLowTapPosition(lowStep).setTapPosition(position);
if (tabular()) {
addStepsFromTable(rtca);
} else {
addStepsFromStepVoltageIncrement(rtca);
}
rtca.setLoadTapChangingCapabilities(ltcFlag);
rtca.add();
}
private RatioTapChangerAdder adder() {
if (tx2 != null) {
return tx2.newRatioTapChanger();
} else if (tx3 != null) {
int side = context.tapChangerTransformers().whichSide(id);
if (side == 1) {
// No supported in IIDM model
return null;
} else if (side == 2) {
return tx3.getLeg2().newRatioTapChanger();
} else if (side == 3) {
return tx3.getLeg3().newRatioTapChanger();
}
}
return null;
}
private void addStepsFromTable(RatioTapChangerAdder rtca) {
String tableId = p.getId(CgmesNames.RATIO_TAP_CHANGER_TABLE);
if (tableId == null) {
missing(CgmesNames.RATIO_TAP_CHANGER_TABLE);
return;
}
LOG.debug("RatioTapChanger {} table {}", id, tableId);
PropertyBags table = context.ratioTapChangerTable(tableId);
if (table.isEmpty()) {
missing("points for RatioTapChangerTable " + tableId);
return;
}
Comparator<PropertyBag> byStep = Comparator.comparingInt((PropertyBag p) -> p.asInt("step"));
table.sort(byStep);
boolean rtcAtSide1 = rtcAtSide1();
for (PropertyBag point : table) {
// CGMES uses ratio to define the relationship between voltage ends while IIDM uses rho
// ratio and rho as complex numbers are reciprocals. Given V1 and V2 the complex voltages at end 1 and end 2 of a branch we have:
// V2 = V1 * rho and V2 = V1 / ratio
// This is why we have: rho=1/ratio
double rho = 1 / point.asDouble("ratio", 1.0);
// When given in RatioTapChangerTablePoint
// r, x, g, b of the step are already percentage deviations of nominal values
int step = point.asInt("step");
double r = fixing(point, "r", 0, tableId, step);
double x = fixing(point, "x", 0, tableId, step);
double g = fixing(point, "g", 0, tableId, step);
double b = fixing(point, "b", 0, tableId, step);
// Impedance/admittance deviation is required when tap changer is defined at
// side 2
// (In IIDM model the ideal ratio is always at side 1, left of impedance)
double dz = 0;
double dy = 0;
if (!rtcAtSide1) {
double rho2 = rho * rho;
dz = (1 / rho2 - 1) * 100;
dy = (rho2 - 1) * 100;
}
if (LOG.isDebugEnabled()) {
LOG.debug(" {} {} {} {} {} {} {} {}", step, rho, r, x, g, b, dz, dy);
}
// We have to merge previous explicit corrections defined for the tap
// with dz, dy that appear when moving ideal ratio to side 1
// R' = R * (1 + r/100) * (1 + dz/100) ==> r' = r + dz + r * dz / 100
rtca.beginStep()
.setRho(rtcAtSide1 ? rho : 1 / rho)
.setR(r + dz + r * dz / 100)
.setX(x + dz + r * dz / 100)
.setG(g + dy + g * dy / 100)
.setB(b + dy + b * dy / 100)
.endStep();
}
}
private double fixing(PropertyBag point, String attr, double defaultValue, String tableId, int step) {
double value = point.asDouble(attr, defaultValue);
if (Double.isNaN(value)) {
fixed(
"RatioTapChangerTablePoint " + attr + " for step " + step + " in table " + tableId,
"invalid value " + point.get(attr));
return defaultValue;
}
return value;
}
private void addStepsFromStepVoltageIncrement(RatioTapChangerAdder rtca) {
boolean rtcAtSide1 = rtcAtSide1();
if (LOG.isDebugEnabled() && rtcAtSide1 && tx2 != null) {
LOG.debug(
"Transformer {} ratio tap changer moved from side 2 to side 1, impedance/admittance corrections",
tx2.getId());
}
double stepVoltageIncrement = p.asDouble("stepVoltageIncrement");
double du = stepVoltageIncrement / 100;
for (int step = lowStep; step <= highStep; step++) {
int n = step - neutralStep;
double rho = rtcAtSide1 ? 1 / (1 + n * du) : (1 + n * du);
// Impedance/admittance deviation is required when ratio tap changer
// is defined at side 2
// (In IIDM model the ideal ratio is always at side 1)
double dz = 0;
double dy = 0;
if (!rtcAtSide1) {
double rho2 = rho * rho;
dz = (rho2 - 1) * 100; // Use the initial ratio before moving it
dy = (1 / rho2 - 1) * 100; // Use the initial ratio before moving it
if (LOG.isDebugEnabled()) {
LOG.debug(String.format("RTC2to1 corrections %4d %12.8f %12.8f %12.8f",
step, n * du, dz, dy));
}
}
rtca.beginStep()
.setRho(rho)
.setR(dz)
.setX(dz)
.setG(dy)
.setB(dy)
.endStep();
}
}
private boolean rtcAtSide1() {
// From CIM1 converter:
// For 2 winding transformers, rho is 1/(1 + n*du) if rtc is at side 1
// For 3 winding transformers rho is always considered at side 1 (network side)
if (tx2 != null) {
return context.tapChangerTransformers().whichSide(id) == 1;
} else if (tx3 != null) {
return true;
}
return false;
}
private boolean tabular() {
return p.containsKey(CgmesNames.RATIO_TAP_CHANGER_TABLE);
}
private int getTapPosition(int defaultStep) {
switch (context.config().getProfileUsedForInitialStateValues()) {
case SSH:
return fromContinuous(p.asDouble("step", p.asDouble("SVtapStep", defaultStep)));
case SV:
return fromContinuous(p.asDouble("SVtapStep", p.asDouble("step", defaultStep)));
default:
throw new CgmesModelException("Unexpected profile used for initial flows values: " + context.config().getProfileUsedForInitialStateValues());
}
}
private final TwoWindingsTransformer tx2;
private final ThreeWindingsTransformer tx3;
private final int lowStep;
private final int highStep;
private final int neutralStep;
private final int position;
private final boolean ltcFlag;
private static final Logger LOG = LoggerFactory.getLogger(RatioTapChangerConversion.class);
}
|
package com.example.android.sunshine.app;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.format.Time;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ForecastFragment extends android.support.v4.app.Fragment {
public ForecastFragment() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
// String array with fake data to populate the ListView
String[] forecastArray = {
"Today - Sunny - 88 / 63",
"Tomorrow - Sunny - 68 / 54"
};
// Initialize a List of fake data from the string array
List<String> weekForecast = new ArrayList<String>(
Arrays.asList(forecastArray));
// Add an ArrayAdapter used to populate the ListView
mForecastAdapter = new ArrayAdapter<String>(
this.getActivity(), R.layout.list_item_forecast, R.id.list_item_forecast_textview,
weekForecast
);
// Retrieve ListView and set adapter
ListView listView_forecast = (ListView) rootView.findViewById(
R.id.listView_forecast);
listView_forecast.setAdapter(mForecastAdapter);
// These two need to be declared outside the try/catch
// so that they can be closed in the finally block.
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
// Will contain the raw JSON response as a string.
String forecastJsonStr = null;
return rootView;
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// Inflate the menu; this adds items to the action bar if it is present.
inflater.inflate(R.menu.forecastfragment, menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_refresh) {
FetchWeatherTask fetchWeatherTask = new FetchWeatherTask();
fetchWeatherTask.execute("11230");
return true;
}
return super.onOptionsItemSelected(item);
}
public class FetchWeatherTask extends AsyncTask<String, Void, String[]> {
// Get the name of the class for the Log messages
private final String LOG_TAG = FetchWeatherTask.class.getSimpleName();
// Makes an Http "GET" request to the OWM API
// and retrieves a JSON string of weather data.
// Then calls a method to parse the data and
// returns an array of forecast strings to
// onPostExecute()
@Override
protected String[] doInBackground(String... params) {
// If no zip code, return null
if(params.length == 0)
return null;
// These two need to be declared outside the try/catch
// so that they can be closed in the finally block.
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
// Will contain the raw JSON response as a string.
String forecastJsonStr = null;
// Array to hold the parsed JSON weather data
String[] weatherForecastArray = null;
// Values for query param keys
String zipCode = params[0]; // Postal code can be retrieved from params[0]
String format = "json";
String units = "metric";
int numDays = 7;
// Query parameter keys needed to construct uri
final String BASE_URL = "http://api.openweathermap.org/data/2.5/forecast/daily?";
final String ZIP_PARAM = "zip";
final String FORMAT_PARAM = "mode";
final String UNITS_PARAM = "units";
final String DAYS_PARAM = "cnt";
final String API_KEY_PARAM = "appid";
try {
// Construct the URL for the OpenWeatherMap query
// Possible parameters are avaiable at OWM's forecast API page, at
// http://openweathermap.org/API#forecast
// Build uri by appending params using URI.Builder
Uri uri = Uri.parse(BASE_URL).buildUpon().
appendQueryParameter(ZIP_PARAM, zipCode).
appendQueryParameter(FORMAT_PARAM, format).
appendQueryParameter(UNITS_PARAM, units).
appendQueryParameter(DAYS_PARAM, Integer.toString(numDays)).
appendQueryParameter(API_KEY_PARAM, OPEN_WEATHER_API_KEY).
build();
// Assign uri to url to be used to open a connection
URL url = new URL(uri.toString());
// Create the request to OpenWeatherMap, and open the connection
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// Read the input stream into a String
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
// Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
// But it does make debugging a *lot* easier if you print out the completed
// buffer for debugging.
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
return null;
}
forecastJsonStr = buffer.toString();
} catch (IOException e) {
Log.e("LOG_TAG", "Error ", e);
// If the code didn't successfully get the weather data, there's no point in attemping
// to parse it.
return null;
} finally{
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e("LOG_TAG", "Error closing stream", e);
}
}
}
// Parse JSON data and store in an array
try {
weatherForecastArray = getWeatherDataFromJson(forecastJsonStr, numDays);
} catch (JSONException e) {
e.printStackTrace();
}
// Return a string array of weather forecast data
return weatherForecastArray;
}
// Checks if returned array holds data.
// If it does, then it clears the ArrayAdapter
// and adds each string from the array one by one
// into the ArrayAdapter
@Override
protected void onPostExecute(String[] weatherForecastArray) {
if(weatherForecastArray != null) {
mForecastAdapter.clear();
for(String forecastPerDay : weatherForecastArray)
mForecastAdapter.add(forecastPerDay);
}
}
/**
* Take the String representing the complete forecast in JSON Format and
* pull out the data we need to construct the Strings needed for the wireframes.
*
* Fortunately parsing is easy: constructor takes the JSON string and converts it
* into an Object hierarchy for us.
*/
private String[] getWeatherDataFromJson(String forecastJsonStr, int numDays)
throws JSONException {
// These are the names of the JSON objects that need to be extracted.
final String OWM_LIST = "list";
final String OWM_WEATHER = "weather";
final String OWM_TEMPERATURE = "temp";
final String OWM_MAX = "max";
final String OWM_MIN = "min";
final String OWM_DESCRIPTION = "main";
JSONObject forecastJson = new JSONObject(forecastJsonStr);
JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST);
// OWM returns daily forecasts based upon the local time of the city that is being
// asked for, which means that we need to know the GMT offset to translate this data
// properly.
// Since this data is also sent in-order and the first day is always the
// current day, we're going to take advantage of that to get a nice
// normalized UTC date for all of our weather.
Time dayTime = new Time();
dayTime.setToNow();
// we start at the day returned by local time. Otherwise this is a mess.
int julianStartDay = Time.getJulianDay(System.currentTimeMillis(), dayTime.gmtoff);
// now we work exclusively in UTC
dayTime = new Time();
String[] resultStrs = new String[numDays];
for(int i = 0; i < weatherArray.length(); i++) {
// For now, using the format "Day, description, hi/low"
String day;
String description;
String highAndLow;
// Get the JSON object representing the day
JSONObject dayForecast = weatherArray.getJSONObject(i);
// The date/time is returned as a long. We need to convert that
// into something human-readable, since most people won't read "1400356800" as
// "this saturday".
long dateTime;
// Cheating to convert this to UTC time, which is what we want anyhow
dateTime = dayTime.setJulianDay(julianStartDay+i);
day = getReadableDateString(dateTime);
// description is in a child array called "weather", which is 1 element long.
JSONObject weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0);
description = weatherObject.getString(OWM_DESCRIPTION);
// Temperatures are in a child object called "temp". Try not to name variables
// "temp" when working with temperature. It confuses everybody.
JSONObject temperatureObject = dayForecast.getJSONObject(OWM_TEMPERATURE);
double high = temperatureObject.getDouble(OWM_MAX);
double low = temperatureObject.getDouble(OWM_MIN);
highAndLow = formatHighLows(high, low);
resultStrs[i] = day + " - " + description + " - " + highAndLow;
}
return resultStrs;
}
/* The date/time conversion code is going to be moved outside the asynctask later,
* so for convenience we're breaking it out into its own method now.
*/
private String getReadableDateString(long time){
// Because the API returns a unix timestamp (measured in seconds),
// it must be converted to milliseconds in order to be converted to valid date.
SimpleDateFormat shortenedDateFormat = new SimpleDateFormat("EEE MMM dd");
return shortenedDateFormat.format(time);
}
/**
* Prepare the weather high/lows for presentation.
*/
private String formatHighLows(double high, double low) {
// For presentation, assume the user doesn't care about tenths of a degree.
long roundedHigh = Math.round(high);
long roundedLow = Math.round(low);
String highLowStr = roundedHigh + "/" + roundedLow;
return highLowStr;
}
}
// Open Weather API Key to be used in the uri
protected static final String OPEN_WEATHER_API_KEY = "7f1777cc20ba2ac8b65cfafd8145b58c";
// ArrayAdapter used to populate the ListView
ArrayAdapter<String> mForecastAdapter;
}
|
package com.sequenceiq.cloudbreak.cloud.template.compute;
import static com.sequenceiq.cloudbreak.cloud.scheduler.PollGroup.CANCELLED;
import static com.sequenceiq.cloudbreak.cloud.template.compute.CloudFailureHandler.ScaleContext;
import static java.lang.String.format;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import javax.inject.Inject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;
import com.google.common.collect.Ordering;
import com.google.common.primitives.Ints;
import com.sequenceiq.cloudbreak.api.model.AdjustmentType;
import com.sequenceiq.cloudbreak.cloud.context.AuthenticatedContext;
import com.sequenceiq.cloudbreak.cloud.exception.CloudConnectorException;
import com.sequenceiq.cloudbreak.cloud.model.CloudInstance;
import com.sequenceiq.cloudbreak.cloud.model.CloudResource;
import com.sequenceiq.cloudbreak.cloud.model.CloudResourceStatus;
import com.sequenceiq.cloudbreak.cloud.model.CloudStack;
import com.sequenceiq.cloudbreak.cloud.model.CloudVmInstanceStatus;
import com.sequenceiq.cloudbreak.cloud.model.Group;
import com.sequenceiq.cloudbreak.cloud.model.InstanceStatus;
import com.sequenceiq.cloudbreak.cloud.model.Platform;
import com.sequenceiq.cloudbreak.cloud.model.ResourceStatus;
import com.sequenceiq.cloudbreak.cloud.scheduler.CancellationException;
import com.sequenceiq.cloudbreak.cloud.scheduler.PollGroup;
import com.sequenceiq.cloudbreak.cloud.scheduler.SyncPollingScheduler;
import com.sequenceiq.cloudbreak.cloud.store.InMemoryStateStore;
import com.sequenceiq.cloudbreak.cloud.task.PollTask;
import com.sequenceiq.cloudbreak.cloud.template.ComputeResourceBuilder;
import com.sequenceiq.cloudbreak.cloud.template.context.ResourceBuilderContext;
import com.sequenceiq.cloudbreak.cloud.template.init.ResourceBuilders;
import com.sequenceiq.cloudbreak.cloud.template.task.ResourcePollTaskFactory;
import com.sequenceiq.cloudbreak.common.type.ResourceType;
@Service
public class ComputeResourceService {
private static final Logger LOGGER = LoggerFactory.getLogger(ComputeResourceService.class);
@Value("${cb.gcp.stopStart.batch.size}")
private Integer stopStartBatchSize;
@Value("${cb.gcp.create.batch.size}")
private Integer createBatchSize;
@Inject
private AsyncTaskExecutor resourceBuilderExecutor;
@Inject
private ApplicationContext applicationContext;
@Inject
private ResourceBuilders resourceBuilders;
@Inject
private CloudFailureHandler cloudFailureHandler;
@Inject
private SyncPollingScheduler<List<CloudVmInstanceStatus>> syncVMPollingScheduler;
@Inject
private SyncPollingScheduler<List<CloudResourceStatus>> syncPollingScheduler;
@Inject
private ResourcePollTaskFactory resourcePollTaskFactory;
public List<CloudResourceStatus> buildResourcesForLaunch(ResourceBuilderContext ctx, AuthenticatedContext auth, CloudStack cloudStack,
AdjustmentType adjustmentType, Long threshold) {
return new ResourceBuilder(ctx, auth).buildResources(cloudStack, cloudStack.getGroups(), false, adjustmentType, threshold);
}
public List<CloudResourceStatus> buildResourcesForUpscale(ResourceBuilderContext ctx, AuthenticatedContext auth, CloudStack cloudStack,
Iterable<Group> groups) {
return new ResourceBuilder(ctx, auth).buildResources(cloudStack, groups, true, AdjustmentType.BEST_EFFORT, null);
}
public List<CloudResourceStatus> deleteResources(ResourceBuilderContext context, AuthenticatedContext auth,
Iterable<CloudResource> resources, boolean cancellable) {
List<CloudResourceStatus> results = new ArrayList<>();
Collection<Future<ResourceRequestResult<List<CloudResourceStatus>>>> futures = new ArrayList<>();
Platform platform = auth.getCloudContext().getPlatform();
List<ComputeResourceBuilder<ResourceBuilderContext>> builders = resourceBuilders.compute(platform);
int numberOfBuilders = builders.size();
for (int i = numberOfBuilders - 1; i >= 0; i
ComputeResourceBuilder<?> builder = builders.get(i);
List<CloudResource> resourceList = getResources(builder.resourceType(), resources);
for (CloudResource cloudResource : resourceList) {
ResourceDeleteThread thread = createThread(ResourceDeleteThread.NAME, context, auth, cloudResource, builder, cancellable);
Future<ResourceRequestResult<List<CloudResourceStatus>>> future = resourceBuilderExecutor.submit(thread);
futures.add(future);
if (isRequestFull(futures.size(), context)) {
results.addAll(flatList(waitForRequests(futures).get(FutureResult.SUCCESS)));
}
}
// wait for builder type to finish before starting the next one
results.addAll(flatList(waitForRequests(futures).get(FutureResult.SUCCESS)));
}
return results;
}
public List<CloudVmInstanceStatus> stopInstances(ResourceBuilderContext context, AuthenticatedContext auth,
List<CloudResource> resources, List<CloudInstance> cloudInstances) {
return stopStart(context, auth, resources, cloudInstances);
}
public List<CloudVmInstanceStatus> startInstances(ResourceBuilderContext context, AuthenticatedContext auth,
List<CloudResource> resources, List<CloudInstance> cloudInstances) {
return stopStart(context, auth, resources, cloudInstances);
}
private List<CloudVmInstanceStatus> stopStart(ResourceBuilderContext context,
AuthenticatedContext auth, List<CloudResource> resources, List<CloudInstance> instances) {
List<CloudVmInstanceStatus> results = new ArrayList<>();
Platform platform = auth.getCloudContext().getPlatform();
List<ComputeResourceBuilder<ResourceBuilderContext>> builders = resourceBuilders.compute(platform);
if (!context.isBuild()) {
Collections.reverse(builders);
}
for (ComputeResourceBuilder<?> builder : builders) {
List<CloudResource> resourceList = getResources(builder.resourceType(), resources);
List<CloudInstance> allInstances = getCloudInstances(resourceList, instances);
if (!allInstances.isEmpty()) {
LOGGER.debug("Split {} instances to {} chunks to execute the stop/start operation parallel", allInstances.size(), stopStartBatchSize);
AtomicInteger counter = new AtomicInteger();
Collection<List<CloudInstance>> instancesChunks = allInstances.stream()
.collect(Collectors.groupingBy(it -> counter.getAndIncrement() / stopStartBatchSize)).values();
Collection<Future<ResourceRequestResult<List<CloudVmInstanceStatus>>>> futures = new ArrayList<>();
for (List<CloudInstance> instancesChunk : instancesChunks) {
LOGGER.debug("Submit stop/start operation thread with {} instances", instancesChunk.size());
ResourceStopStartThread thread = createThread(ResourceStopStartThread.NAME, context, auth, instancesChunk, builder);
Future<ResourceRequestResult<List<CloudVmInstanceStatus>>> future = resourceBuilderExecutor.submit(thread);
futures.add(future);
}
if (!futures.isEmpty()) {
LOGGER.debug("Wait for all {} stop/start threads to finish", futures.size());
List<List<CloudVmInstanceStatus>> instancesStatuses = waitForRequests(futures).get(FutureResult.SUCCESS);
for (List<CloudVmInstanceStatus> vmStatuses : instancesStatuses) {
LOGGER.debug("Poll {} instance's state whether they have reached the stopped/started state", vmStatuses.size());
List<CloudInstance> checkInstances = vmStatuses.stream().map(CloudVmInstanceStatus::getCloudInstance).collect(Collectors.toList());
PollTask<List<CloudVmInstanceStatus>> pollTask = resourcePollTaskFactory
.newPollComputeStatusTask(builder, auth, context, checkInstances);
try {
List<CloudVmInstanceStatus> statuses = pollInstancesRetriable(pollTask);
results.addAll(statuses);
} catch (Exception e) {
LOGGER.debug("Failed to poll the instances status of {}, set the status to failed", checkInstances, e);
results.addAll(vmStatuses.stream()
.map(vs -> new CloudVmInstanceStatus(vs.getCloudInstance(), InstanceStatus.FAILED, e.getMessage()))
.collect(Collectors.toList()));
}
}
}
} else {
LOGGER.debug("Cloud resources are not instances so they cannot be stopped or started, skipping builder type {}", builder.resourceType());
}
}
return results;
}
private <T> Map<FutureResult, List<T>> waitForRequests(Collection<Future<ResourceRequestResult<T>>> futures) {
Map<FutureResult, List<T>> result = new EnumMap<>(FutureResult.class);
result.put(FutureResult.FAILED, new ArrayList<>());
result.put(FutureResult.SUCCESS, new ArrayList<>());
int requests = futures.size();
LOGGER.info("Waiting for {} requests to finish", requests);
try {
for (Future<ResourceRequestResult<T>> future : futures) {
ResourceRequestResult<T> resourceRequestResult = future.get();
if (FutureResult.FAILED == resourceRequestResult.getStatus()) {
result.get(FutureResult.FAILED).add(resourceRequestResult.getResult());
} else {
result.get(FutureResult.SUCCESS).add(resourceRequestResult.getResult());
}
}
} catch (InterruptedException | ExecutionException e) {
LOGGER.error("Failed to execute the request", e);
}
LOGGER.info("{} requests have finished, continue with next group", requests);
futures.clear();
return result;
}
private boolean isRequestFull(int runningRequests, ResourceBuilderContext context) {
return isRequestFullWithCloudPlatform(1, runningRequests, context);
}
private boolean isRequestFullWithCloudPlatform(int numberOfBuilders, int runningRequests, ResourceBuilderContext context) {
return (runningRequests * numberOfBuilders) % context.getParallelResourceRequest() == 0;
}
private List<CloudResource> getResources(ResourceType resourceType, Iterable<CloudResource> resources) {
List<CloudResource> selected = new ArrayList<>();
for (CloudResource resource : resources) {
if (resourceType == resource.getType()) {
selected.add(resource);
}
}
return selected;
}
private <T> T createThread(String name, Object... args) {
return (T) applicationContext.getBean(name, args);
}
private List<CloudInstance> getCloudInstances(List<CloudResource> cloudResource, List<CloudInstance> instances) {
List<CloudInstance> result = new ArrayList<>();
for (CloudResource resource : cloudResource) {
for (CloudInstance instance : instances) {
if (instance.getInstanceId().equalsIgnoreCase(resource.getName()) || instance.getInstanceId().equalsIgnoreCase(resource.getReference())) {
result.add(instance);
}
}
}
return result;
}
private List<CloudResourceStatus> flatList(Iterable<List<CloudResourceStatus>> lists) {
List<CloudResourceStatus> result = new ArrayList<>();
for (List<CloudResourceStatus> list : lists) {
result.addAll(list);
}
return result;
}
@Retryable(value = Exception.class, maxAttempts = 3, backoff = @Backoff(delay = 1000, multiplier = 2, maxDelay = 10000))
public List<CloudResourceStatus> pollSingleResourceRetriable(PollTask<List<CloudResourceStatus>> pollTask, CloudResourceStatus status)
throws ExecutionException, InterruptedException, java.util.concurrent.TimeoutException {
try {
return syncPollingScheduler.schedule(pollTask);
} catch (CloudConnectorException exception) {
if (exception.getMessage().contains("QUOTA_EXCEEDED")) {
return List.of(new CloudResourceStatus(status.getCloudResource(), ResourceStatus.FAILED, exception.getMessage(), status.getPrivateId()));
} else {
throw exception;
}
}
}
@Retryable(value = Exception.class, maxAttempts = 3, backoff = @Backoff(delay = 1000, multiplier = 2, maxDelay = 10000))
public List<CloudVmInstanceStatus> pollInstancesRetriable(PollTask<List<CloudVmInstanceStatus>> pollTask)
throws ExecutionException, InterruptedException, java.util.concurrent.TimeoutException {
return syncVMPollingScheduler.schedule(pollTask);
}
private class ResourceBuilder {
private final ResourceBuilderContext ctx;
private final AuthenticatedContext auth;
ResourceBuilder(ResourceBuilderContext ctx, AuthenticatedContext auth) {
this.ctx = ctx;
this.auth = auth;
}
public List<CloudResourceStatus> buildResources(CloudStack cloudStack, Iterable<Group> groups,
Boolean upscale, AdjustmentType adjustmentType, Long threshold) {
List<CloudResourceStatus> results = new ArrayList<>();
Collection<Future<ResourceRequestResult<List<CloudResourceStatus>>>> futures = new ArrayList<>();
for (Group group : getOrderedCopy(groups)) {
List<CloudInstance> instances = group.getInstances();
LOGGER.debug("Split the instances to {} chunks to execute the operation in parallel", createBatchSize);
AtomicInteger counter = new AtomicInteger();
Collection<List<CloudInstance>> instancesChunks = instances.stream()
.collect(Collectors.groupingBy(it -> counter.getAndIncrement() / createBatchSize)).values();
for (List<CloudInstance> instancesChunk : instancesChunks) {
LOGGER.debug("Submit the create operation thread with {} instances", instancesChunk.size());
ResourceCreateThread thread = createThread(ResourceCreateThread.NAME, instancesChunk, group, ctx, auth, cloudStack);
Future<ResourceRequestResult<List<CloudResourceStatus>>> future = resourceBuilderExecutor.submit(thread);
futures.add(future);
}
if (!futures.isEmpty()) {
LOGGER.debug("Wait for all {} creation threads to finish", futures.size());
List<List<CloudResourceStatus>> cloudResourceStatusChunks = waitForRequests(futures).get(FutureResult.SUCCESS);
List<CloudResourceStatus> resourceStatuses = waitForResourceCreations(cloudResourceStatusChunks);
List<CloudResourceStatus> failedResources = filterResourceStatuses(resourceStatuses, ResourceStatus.FAILED);
cloudFailureHandler.rollback(auth, failedResources, group, getFullNodeCount(groups), ctx,
resourceBuilders, new ScaleContext(upscale, adjustmentType, threshold));
results.addAll(filterResourceStatuses(resourceStatuses, ResourceStatus.CREATED));
}
}
return results;
}
private List<CloudResourceStatus> waitForResourceCreations(List<List<CloudResourceStatus>> cloudResourceStatusChunks) {
List<CloudResourceStatus> result = new ArrayList<>();
for (List<CloudResourceStatus> cloudResourceStatuses : cloudResourceStatusChunks) {
List<CloudResourceStatus> instanceResourceStatuses = cloudResourceStatuses.stream()
.filter(crs -> ResourceType.isInstanceResource(crs.getCloudResource().getType()))
.filter(crs -> ResourceStatus.IN_PROGRESS.equals(crs.getStatus())).collect(Collectors.toList());
if (!instanceResourceStatuses.isEmpty()) {
LOGGER.debug("Poll {} instance's state whether they have reached the created state", instanceResourceStatuses.size());
CloudResource resourceProbe = instanceResourceStatuses.get(0).getCloudResource();
Optional<ComputeResourceBuilder<ResourceBuilderContext>> builderOpt = determineComputeResourceBuilder(resourceProbe);
if (builderOpt.isEmpty()) {
LOGGER.debug("No resource builder found for type {}", resourceProbe.getType());
continue;
}
ComputeResourceBuilder<ResourceBuilderContext> builder = builderOpt.get();
LOGGER.debug("Determined resource builder for instances: {}", builder.resourceType());
for (CloudResourceStatus instanceResourceStatus : instanceResourceStatuses) {
PollGroup pollGroup = InMemoryStateStore.getStack(auth.getCloudContext().getId());
if (CANCELLED.equals(pollGroup)) {
throw new CancellationException(format("Building of %s has been cancelled", instanceResourceStatus));
}
CloudResource instance = instanceResourceStatus.getCloudResource();
PollTask<List<CloudResourceStatus>> pollTask = resourcePollTaskFactory
.newPollResourceTask(builder, auth, List.of(instance), ctx, true);
try {
List<CloudResourceStatus> statuses = pollSingleResourceRetriable(pollTask, instanceResourceStatus);
instanceResourceStatus.setStatus(statuses.get(0).getStatus());
} catch (Exception e) {
LOGGER.debug("Failure during polling the instance status of {}", instanceResourceStatus, e);
cloudResourceStatuses.stream().filter(crs -> crs.getPrivateId().equals(instanceResourceStatus.getPrivateId())).forEach(crs -> {
crs.setStatus(ResourceStatus.FAILED);
crs.setStatusReason(e.getMessage());
});
}
}
result.addAll(cloudResourceStatuses);
} else {
result.addAll(cloudResourceStatuses);
LOGGER.debug("No instances to poll");
}
}
return result;
}
private List<CloudResourceStatus> filterResourceStatuses(List<CloudResourceStatus> cloudResourceStatuses, ResourceStatus resourceStatus) {
return cloudResourceStatuses.stream().filter(rs -> resourceStatus.equals(rs.getStatus())).collect(Collectors.toList());
}
private Optional<ComputeResourceBuilder<ResourceBuilderContext>> determineComputeResourceBuilder(CloudResource resource) {
return resourceBuilders.compute(auth.getCloudContext().getPlatform())
.stream().filter(rb -> rb.resourceType().equals(resource.getType())).findFirst();
}
private int getFullNodeCount(Iterable<Group> groups) {
int fullNodeCount = 0;
for (Group group : groups) {
fullNodeCount += group.getInstancesSize();
}
return fullNodeCount;
}
private Iterable<Group> getOrderedCopy(Iterable<Group> groups) {
Ordering<Group> byLengthOrdering = new Ordering<>() {
@Override
public int compare(Group left, Group right) {
return Ints.compare(left.getInstances().size(), right.getInstances().size());
}
};
return byLengthOrdering.sortedCopy(groups);
}
}
}
|
package com.example.tylerpelaez.didit;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import java.util.ArrayList;
import static android.app.Activity.RESULT_OK;
public class CreateHabitFragment extends Fragment {
public CreateHabitFragment() {
}
public CreateHabitListAdapter mCreateHabitListAdapter;
private ArrayList<Integer> mSelectedItems;
private boolean everyOther;
private int num_skip;
private int cur_num_descriptors = 0;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
this.getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
// Inflate the menu; this adds items to the action bar if it is present.
inflater.inflate(R.menu.menu_create_habit, menu);
return;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.create_habit_fragment, container, false);
Spinner spinner = (Spinner) rootView.findViewById(R.id.number_spinner);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getContext(),
R.array.number_array, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinner.setAdapter(adapter);
//int iCurrentSelection = spinner.getSelectedItemPosition();
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
private boolean initializedView = false;
@Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
if (!initializedView) {
initializedView = true;
} else {
switch (parent.getId()) {
case R.id.list_item_spinner: {
break;
}
case R.id.number_spinner: {
cur_num_descriptors = pos;
//Log.d("hi", Integer.toString(mCreateHabitListAdapter.labels.size()));
//Log.d("HI", Integer.toString(pos));
//Log.d("HI", (String) parent.getSelectedItem());
for (int i = 15; i > pos - 1; i
if (mCreateHabitListAdapter.getItem(i) != null) {
mCreateHabitListAdapter.remove(Integer.toString(i));
}
}
for (int i = mCreateHabitListAdapter.labels.size(); i < pos; i++) {
mCreateHabitListAdapter.add(Integer.toString(i));
}
//Log.d("HERE", "yo");
break;
}
}
}
// An item was selected. You can retrieve the selected item using
// parent.getItemAtPosition(pos)
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
// Another interface callback
}
});
NDSpinner day_spinner = (NDSpinner) rootView.findViewById(R.id.day_select_spinner);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter2 = ArrayAdapter.createFromResource(getContext(),
R.array.day_spinner_array, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
day_spinner.setAdapter(adapter2);
final TextView textView = (TextView) rootView.findViewById(R.id.text_view_days_selected);
//int iCurrentSelection = spinner.getSelectedItemPosition();
mSelectedItems = new ArrayList();
num_skip = 0;
everyOther = false;
day_spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
private boolean initializedView = false;
@Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
if (!initializedView) {
initializedView = true;
} else {
switch (parent.getId()) {
case R.id.day_select_spinner: {
if(pos == 0) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.every_x_days_title)
.setSingleChoiceItems(R.array.every_x_days_array, 0,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
num_skip = which;
}
})
// Set the action buttons
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
everyOther = true;
// User clicked OK, so save the mSelectedItems results somewhere
// or return them to the component that opened the dialog
textView.setText(Integer.toString(num_skip + 1));
dialog.dismiss();
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
AlertDialog dialog = builder.create();
dialog.show();
} else if (pos == 1) {
boolean[] itemsChecked = {false, false, false, false, false, false, false};
for(int i=0;i<itemsChecked.length;i++){
if(mSelectedItems.contains(i))
itemsChecked[i]=true;
}
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.pick_day_title)
.setMultiChoiceItems(R.array.weekdays_array, itemsChecked,
new DialogInterface.OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface dialog, int which,
boolean isChecked) {
if (isChecked) {
// If the user checked the item, add it to the selected items
mSelectedItems.add(which);
} else if (mSelectedItems.contains(which)) {
// Else, if the item is already in the array, remove it
mSelectedItems.remove(Integer.valueOf(which));
}
}
})
// Set the action buttons
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
everyOther = false;
// User clicked OK, so save the mSelectedItems results somewhere
// or return them to the component that opened the dialog
String[] letters = getResources().getStringArray(R.array.weekdays_abbr_array);
String newString = "";
for (int i = 0; i < mSelectedItems.size(); ++i) {
newString += letters[mSelectedItems.get(i)];
}
textView.setText(newString);
dialog.dismiss();
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
mSelectedItems.clear();
dialog.dismiss();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
break;
}
}
}
// An item was selected. You can retrieve the selected item using
// parent.getItemAtPosition(pos)
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
// Another interface callback
}
});
ListView listView = (ListView) rootView.findViewById(R.id.create_listView);
mCreateHabitListAdapter = new CreateHabitListAdapter(getContext(), new ArrayList<String>());
listView.setAdapter(mCreateHabitListAdapter);
return rootView;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_submit_habit:
EditText editText = (EditText) getActivity().findViewById(R.id.enter_name_field);
String text = editText.getText().toString();
if (text.equals("")) {
return true;
}
if (!everyOther && mSelectedItems.size() ==0) {
return true;
}
//if (everyOther && num_skip == -1) {
// return true;
Habit habit = new Habit(text);
if (everyOther) {
habit.setEveryOther(true, num_skip);
} else {
habit.setEveryOther(false, 0);
String[] weekdays = getResources().getStringArray(R.array.weekdays_array);
for (int i = 0; i < mSelectedItems.size(); ++i) {
habit.addWeekday(weekdays[i]);
}
}
for(int i = 0; i < mCreateHabitListAdapter.labels.size(); i++ ) {
Log.d("yes", mCreateHabitListAdapter.labels.get(i));
if (mCreateHabitListAdapter.labels.get(i).equals("")) {
Log.d("here", Integer.toString(i));
Log.d("here", Integer.toString(mCreateHabitListAdapter.labels.size()));
Log.d("here", mCreateHabitListAdapter.labels.get(i));
return true;
} else {
//Log.d("HERE:", mCreateHabitListAdapter.labels.get(i) + "," + mCreateHabitListAdapter.types.get(i));
habit.addDescriptor(mCreateHabitListAdapter.labels.get(i), mCreateHabitListAdapter.types.get(i));
}
}
Intent returnIntent = new Intent();
returnIntent.putExtra("returnHabit", habit);
getActivity().setResult(RESULT_OK, returnIntent);
getActivity().finish();
return true;
default:
// If we got here, the user's action was not recognized.
// Invoke the superclass to handle it.
return super.onOptionsItemSelected(item);
}
}
}
|
package io.cloudslang.maven.compiler;
import io.cloudslang.lang.compiler.SlangCompiler;
import io.cloudslang.lang.compiler.SlangSource;
import io.cloudslang.lang.compiler.configuration.SlangCompilerSpringConfig;
import io.cloudslang.lang.compiler.modeller.model.Executable;
import io.cloudslang.lang.compiler.modeller.result.ExecutableModellingResult;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.io.IOUtils;
import org.codehaus.plexus.compiler.AbstractCompiler;
import org.codehaus.plexus.compiler.CompilerConfiguration;
import org.codehaus.plexus.compiler.CompilerException;
import org.codehaus.plexus.compiler.CompilerMessage;
import org.codehaus.plexus.compiler.CompilerOutputStyle;
import org.codehaus.plexus.compiler.CompilerResult;
import org.codehaus.plexus.component.annotations.Component;
import org.codehaus.plexus.util.DirectoryScanner;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import static java.util.Collections.emptySet;
@Component(role = org.codehaus.plexus.compiler.Compiler.class, hint = "cloudslang")
public class CloudSlangMavenCompiler extends AbstractCompiler {
private static String IGNORE_DEPENDENCIES = "ignore-dependencies";
private static String IGNORE_ERRORS = "ignore-errors";
private SlangCompiler slangCompiler;
private boolean compileWithDependencies;
private CompilerMessage.Kind errorLevel;
public CloudSlangMavenCompiler() {
super(CompilerOutputStyle.ONE_OUTPUT_FILE_FOR_ALL_INPUT_FILES, null, null, null);
ApplicationContext ctx = new AnnotationConfigApplicationContext(SlangCompilerSpringConfig.class);
slangCompiler = ctx.getBean(SlangCompiler.class);
}
@Override
public boolean canUpdateTarget(CompilerConfiguration configuration) throws CompilerException {
return false;
}
@Override
public CompilerResult performCompile(CompilerConfiguration config) throws CompilerException {
init(config);
CompilerResult compilerResult = new CompilerResult();
List<CompilerMessage> compilerMessage = new ArrayList<>();
//we do not want the source files that were calculated because we have multiple suffix
//and the framework support only one via the inputFileEnding
config.setSourceFiles(null);
String[] sourceFiles = getSourceFiles(config);
Map<String, byte[]> dependenciesSourceFiles = getDependenciesSourceFiles(config);
if (sourceFiles.length > 0) {
System.out.println("Compiling " + sourceFiles.length + " " + "source file" + (sourceFiles.length == 1 ? "" : "s"));
for (String sourceFile : sourceFiles) {
compilerMessage.addAll(compileFile(sourceFile, sourceFiles, dependenciesSourceFiles));
}
if (compilerMessage.size() > 0) {
compilerResult.setCompilerMessages(compilerMessage);
//we want to set it to false only in case we want to fail the build
if (errorLevel.equals(CompilerMessage.Kind.ERROR)) {
compilerResult.setSuccess(false);
}
}
}
return compilerResult;
}
private void init(CompilerConfiguration config) {
//This parameter is passed in the compiler plugin whether to compile the flow with its dependencies
compileWithDependencies = !config.getCustomCompilerArgumentsAsMap().containsKey(IGNORE_DEPENDENCIES);
//This parameter is used to control the error level. if not set only warnings will be shown
errorLevel = config.getCustomCompilerArgumentsAsMap().containsKey(IGNORE_ERRORS) ? CompilerMessage.Kind.WARNING : CompilerMessage.Kind.ERROR;
}
private List<CompilerMessage> compileFile(String sourceFile, String[] sourceFiles, Map<String, byte[]> dependenciesSourceFiles) {
ExecutableModellingResult executableModellingResult;
List<CompilerMessage> compilerMessages = new ArrayList<>();
try {
SlangSource slangSource = SlangSource.fromFile(new File(sourceFile));
executableModellingResult = slangCompiler.preCompileSource(slangSource);
if (!CollectionUtils.isEmpty(executableModellingResult.getErrors())) {
for (RuntimeException runtimeException : executableModellingResult.getErrors()) {
compilerMessages.add(new CompilerMessage(sourceFile + ": " + runtimeException.getMessage(), errorLevel));
}
} else {
if (compileWithDependencies) {
compilerMessages.addAll(validateSlangModelWithDependencies(executableModellingResult, sourceFiles, dependenciesSourceFiles, sourceFile));
}
}
} catch (Exception e) {
compilerMessages.add(new CompilerMessage(sourceFile + ": " + e.getMessage(), errorLevel));
}
return compilerMessages;
}
private List<CompilerMessage> validateSlangModelWithDependencies(ExecutableModellingResult executableModellingResult, String[] dependencies, Map<String, byte[]> dependenciesSourceFiles, String sourceFile) {
List<CompilerMessage> compilerMessages = new ArrayList<>();
Set<Executable> dependenciesExecutables = new HashSet<>();
Executable executable = executableModellingResult.getExecutable();
//we need to verify only flows
if (!executable.getType().equals("flow")) {
return compilerMessages;
}
for (String dependency : dependencies) {
try {
SlangSource slangSource = SlangSource.fromFile(new File(dependency));
executableModellingResult = slangCompiler.preCompileSource(slangSource);
dependenciesExecutables.add(executableModellingResult.getExecutable());
} catch (Exception e) {
this.getLogger().warn("Could not compile source: " + dependency);
}
}
for (Map.Entry<String, byte[]> dependencyEntry : dependenciesSourceFiles.entrySet()) {
try {
SlangSource slangSource = SlangSource.fromBytes(dependencyEntry.getValue(), dependencyEntry.getKey());
executableModellingResult = slangCompiler.preCompileSource(slangSource);
dependenciesExecutables.add(executableModellingResult.getExecutable());
} catch (Exception e) {
this.getLogger().warn("Could not compile source: " + dependencyEntry.getKey());
}
}
List<RuntimeException> exceptions = slangCompiler.validateSlangModelWithDirectDependencies(executable, dependenciesExecutables);
for (RuntimeException runtimeException : exceptions) {
compilerMessages.add(new CompilerMessage(sourceFile + ": " + runtimeException.getMessage(), errorLevel));
}
return compilerMessages;
}
public String[] createCommandLine(CompilerConfiguration config) throws CompilerException {
return null;
}
protected static String[] getSourceFiles(CompilerConfiguration config) {
Set<String> sources = new HashSet<>();
for (String sourceLocation : config.getSourceLocations()) {
sources.addAll(getSourceFilesForSourceRoot(config, sourceLocation));
}
return sources.toArray(new String[sources.size()]);
}
private static Map<String, byte[]> getDependenciesSourceFiles(CompilerConfiguration config) throws CompilerException {
if (config.getClasspathEntries().isEmpty()) {
return Collections.emptyMap();
}
Map<String, byte[]> sources = new HashMap<>();
for (String dependency : config.getClasspathEntries()) {
try {
sources.putAll(getSourceFilesForDependencies(dependency));
} catch (IOException e) {
throw new CompilerException("Cannot load sources from: " + dependency + ". " + e.getMessage());
}
}
return sources;
}
private static Map<String, byte[]> getSourceFilesForDependencies(String dependency) throws IOException {
Path path = Paths.get(dependency);
if (!Files.exists(path) || !path.toString().toLowerCase().endsWith(".jar")) {
return Collections.emptyMap();
}
Map<String, byte[]> sources = new HashMap<>();
try (JarFile jar = new JarFile(dependency)) {
Enumeration enumEntries = jar.entries();
while (enumEntries.hasMoreElements()) {
JarEntry file = (JarEntry) enumEntries.nextElement();
if ((file == null) || (file.isDirectory()) || (!file.getName().endsWith(".sl.yaml") && !file.getName().endsWith(".sl") && !file.getName().endsWith(".sl.yml"))) {
continue;
}
byte[] bytes;
try (InputStream is = jar.getInputStream(file)) {
bytes = IOUtils.toByteArray(is);
sources.put(file.getName(), bytes);
}
}
}
return sources;
}
// we need to override this as it is hard coded java file extensions
protected static Set<String> getSourceFilesForSourceRoot(CompilerConfiguration config, String sourceLocation) {
Path path = Paths.get(sourceLocation);
if (!Files.exists(path)) {
return emptySet();
}
DirectoryScanner scanner = new DirectoryScanner();
scanner.setBasedir(sourceLocation);
Set<String> includes = config.getIncludes();
if (includes != null && !includes.isEmpty()) {
String[] inclStrs = includes.toArray(new String[includes.size()]);
scanner.setIncludes(inclStrs);
} else {
scanner.setIncludes(new String[]{"**/*.sl.yaml", "**/*.sl", "**/*.sl.yml"});
}
Set<String> configExcludes = config.getExcludes();
if (configExcludes != null && !configExcludes.isEmpty()) {
String[] exclStrs = configExcludes.toArray(new String[configExcludes.size()]);
scanner.setExcludes(exclStrs);
} else {
scanner.setExcludes(new String[]{"**/*prop.sl"});
}
scanner.scan();
String[] sourceDirectorySources = scanner.getIncludedFiles();
Set<String> sources = new HashSet<>();
for (String sourceDirectorySource : sourceDirectorySources) {
sources.add(new File(sourceLocation, sourceDirectorySource).getPath());
}
return sources;
}
}
|
package com.fcdream.dress.kenny.activity;
import android.app.Activity;
import android.graphics.drawable.AnimationDrawable;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import com.fcdream.dress.kenny.App;
import com.fcdream.dress.kenny.R;
import com.fcdream.dress.kenny.adapter.DressItemAdapter;
import com.fcdream.dress.kenny.adapter.OnItemClickListener;
import com.fcdream.dress.kenny.bo.DressItem;
import com.fcdream.dress.kenny.bus.MyCallback;
import com.fcdream.dress.kenny.bus.TestBus;
import com.fcdream.dress.kenny.ioc.BindLayout;
import com.fcdream.dress.kenny.ioc.BindView;
import com.fcdream.dress.kenny.log.MyLog;
import com.fcdream.dress.kenny.speech.BaseSpeechSynthesizer;
import com.fcdream.dress.kenny.speech.SpeechFactory;
import com.fcdream.dress.kenny.speech.SpeechSynthesizerError;
import com.fcdream.dress.kenny.utils.SpaceItemDecoration;
import android.support.v7.widget.RecyclerView;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;
@BindLayout(layout = R.layout.fragment_main_page_list)
public class MainListFragment extends BaseMainPageFragment implements BaseSpeechSynthesizer.SpeechSynthesizerListener
, OnItemClickListener {
private String currentSearchKey;
@BindView(id = R.id.dress_content_list_view)
private RecyclerView dressRecyclerView;
private DressItemAdapter dressItemAdapter;
@BindView(id = R.id.shop_content_list_view)
private RecyclerView shopRecyclerView;
@BindView(id = R.id.back, clickEvent = "dealHandleBack", click = true)
private ImageView backImage;
private ImageView robotImage;
@BindView(id = R.id.speech_mic, clickEvent = "dealMicImageClick", click = true)
private ImageView micImage;
@BindView(id = R.id.speech_speak, clickEvent = "dealSpeakImageClick", click = true)
private ImageView speakImage;
@BindView(id = R.id.search_edit_text)
private EditText searchEditText;
private boolean canSpeak = true;
LinearLayoutManager dressLayoutManager;
BaseSpeechSynthesizer speechSynthesizer;
AnimationDrawable speakAnimation;
@Override
protected void initView(Activity activity, View sourceView) {
speakAnimation = (AnimationDrawable) getActivity().getResources().getDrawable(R.drawable.anim_speak);
dealChangeSpeakStatus(STATE_SPEAK_NORMAL);
searchEditText.setOnEditorActionListener((v, actionId, event) -> {
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
dealSearch(searchEditText.getText().toString());
}
return false;
});
dressLayoutManager = new LinearLayoutManager(activity);
dressLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
dressRecyclerView.setLayoutManager(dressLayoutManager);
dressRecyclerView.setHasFixedSize(true);
// dressRecyclerView.addItemDecoration(new SpaceItemDecoration((int) getResources().getDimension(R.dimen.list_page_content_dress_content_item_margin)));
dressItemAdapter = new DressItemAdapter(getActivity(), this);
dressRecyclerView.setAdapter(dressItemAdapter);
speechSynthesizer = SpeechFactory.createSpeechSynthesizer(SpeechFactory.TYPE_BAIDU);
speechSynthesizer.setSpeechSynthesizerListener(this);
}
@Override
protected void initData(Activity activity) {
}
public void dealSearch(String currentSearchKey) {
if (TextUtils.isEmpty(currentSearchKey)) {
return;
}
searchEditText.setText(currentSearchKey);
if (TextUtils.equals(currentSearchKey, this.currentSearchKey)) {
} else {
this.currentSearchKey = currentSearchKey;
}
TestBus.testSearchDress(new MyCallback<List<DressItem>>() {
@Override
public void callback(boolean success, List<DressItem> list) {
if (list == null || list.size() == 0) {
return;
}
dressItemAdapter.getDataList().clear();
dressItemAdapter.getDataList().addAll(list);
dressItemAdapter.notifyDataSetChanged();
}
}, "q", currentSearchKey);
}
public void dealHandleBack(View view) {
if (isFragmentIfaceValid()) {
ifaceReference.get().dealFragmentBack(this);
}
}
@Override
public String getFragmentType() {
return BaseMainFragmentIface.TYPE_MAIN_LIST;
}
public void autoScroll() {
int firstCompletelyVisibleItemPosition = dressLayoutManager.findFirstCompletelyVisibleItemPosition();
MyLog.i("dsminfo", firstCompletelyVisibleItemPosition + "-" + dressRecyclerView.getChildCount());
int scrollToPosition = firstCompletelyVisibleItemPosition;
if (firstCompletelyVisibleItemPosition != 0) {
scrollToPosition = firstCompletelyVisibleItemPosition + 1;
}
if (scrollToPosition >= dressRecyclerView.getChildCount()) {
return;
}
dressRecyclerView.smoothScrollToPosition(scrollToPosition);
DressItemAdapter.ViewHolder childViewHolder = (DressItemAdapter.ViewHolder) dressRecyclerView.getChildViewHolder(dressRecyclerView.getChildAt(2));
childViewHolder.bgImage.setVisibility(View.VISIBLE);
if (scrollToPosition - 1 >= 0) {
childViewHolder = (DressItemAdapter.ViewHolder) dressRecyclerView.getChildViewHolder(dressRecyclerView.getChildAt(scrollToPosition - 1));
childViewHolder.bgImage.setVisibility(View.GONE);
}
App.postDelayToMainLooper(new Runnable() {
@Override
public void run() {
autoScroll();
}
}, 5000);
}
@Override
public void onSynthesizeStart(String s) {
}
@Override
public void onSynthesizeDataArrived(String s, byte[] bytes, int i) {
}
@Override
public void onSynthesizeFinish(String s) {
}
@Override
public void onSpeechStart(String s) {
dealChangeSpeakStatus(STATE_SPEAKING);
}
@Override
public void onSpeechProgressChanged(String s, int i) {
}
@Override
public void onSpeechFinish(String s) {
dealChangeSpeakStatus(STATE_SPEAK_NORMAL);
}
@Override
public void onError(String s, SpeechSynthesizerError speechError) {
}
@Override
public void onItemClick(View view, int position, Object object) {
if (canSpeak && object != null && object instanceof DressItem) {
dealStartSpeak(((DressItem) object).title);
}
}
public void dealSpeakImageClick(View view) {
canSpeak = !canSpeak;
if (!canSpeak && isFragmentIfaceValid()) {
speechSynthesizer.stop();
}
dealChangeSpeakStatus(canSpeak ? STATE_SPEAK_NORMAL : STATE_SPEAK_DISABLE);
}
public void dealMicImageClick(View view) {
if (isFragmentIfaceValid()) {
dealStopSpeak();
ifaceReference.get().getSpeech().start();
}
}
private static String STATE_SPEAKING = "state_speaking";
private static String STATE_SPEAK_NORMAL = "state_speak_normal";
private static String STATE_SPEAK_DISABLE = "state_speak_disable";
private void dealChangeSpeakStatus(String state) {
if (TextUtils.equals(state, STATE_SPEAKING)) {
speakImage.setImageDrawable(speakAnimation);
speakAnimation.start();
} else if (TextUtils.equals(state, STATE_SPEAK_NORMAL)) {
speakAnimation.stop();
speakImage.setImageResource(R.drawable.speak4);
} else if (TextUtils.equals(state, STATE_SPEAK_DISABLE)) {
speakAnimation.stop();
speakImage.setImageResource(R.drawable.icon_not_speak);
}
}
@Override
public void onListenEnd(String info) {
dealSearch(info);
}
private void dealStopSpeak() {
speechSynthesizer.destroy();
dealChangeSpeakStatus(canSpeak ? STATE_SPEAK_NORMAL : STATE_SPEAK_DISABLE);
}
private void dealStartSpeak(String info) {
speechSynthesizer.init(getActivity());
speechSynthesizer.speak(info);
}
}
|
package com.frodo.github.business.explore;
import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.ViewGroup;
import com.frodo.app.android.ui.FragmentScheduler;
import com.frodo.app.android.ui.fragment.StatedFragment;
import com.frodo.github.R;
import com.frodo.github.bean.ShowCase;
import com.frodo.github.bean.dto.response.Repo;
import com.frodo.github.view.CircleProgressDialog;
import com.frodo.github.view.ViewProvider;
import com.mikepenz.octicons_typeface_library.Octicons;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.BiFunction;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ExploreFragment extends StatedFragment<ExploreView, ExploreModel>
{
private static final String STATE_SHOWCASE = "state_showcase";
private static final String STATE_REPOSITORIES = "state_repositories";
private ArrayList<ShowCase> showCases;
private ArrayList<Repo> repositories;
@Override public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Override public ExploreView createUIView(Context context, LayoutInflater inflater, ViewGroup container)
{
return new ExploreView(this, inflater, container);
}
@Override public void onFirstTimeLaunched()
{
loadDataWithReactor();
}
@Override public void onSaveState(Bundle outState)
{
if (this.showCases != null)
{
outState.putParcelableArrayList(STATE_SHOWCASE, this.showCases);
}
if (this.repositories != null)
{
outState.putParcelableArrayList(STATE_REPOSITORIES, this.repositories);
}
}
@Override public void onRestoreState(Bundle savedInstanceState)
{
if (savedInstanceState.containsKey(STATE_SHOWCASE) && savedInstanceState.containsKey(STATE_REPOSITORIES))
{
this.showCases = savedInstanceState.getParcelableArrayList(STATE_SHOWCASE);
this.repositories = savedInstanceState.getParcelableArrayList(STATE_REPOSITORIES);
getUIView().showShowCaseList(showCases);
getUIView().showTrendingRepositoryList(repositories);
}
else
{
loadDataWithReactor();
}
}
@Override public void onResume()
{
super.onResume();
((AppCompatActivity) getActivity()).getSupportActionBar().setTitle(tag());
}
@Override public String tag()
{
return "Explore";
}
@Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater)
{
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.menu_explore, menu);
updateMenu(menu);
}
private void updateMenu(Menu menu)
{
ViewProvider.updateMenuItem(getAndroidContext(), menu, R.id.action_trending, Octicons.Icon.oct_pulse);
}
@Override public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.action_trending:
FragmentScheduler.nextFragment(getAndroidContext(), TrendingFragment.class);
break;
}
return super.onOptionsItemSelected(item);
}
@SuppressLint ("CheckResult") private void loadDataWithReactor()
{
final Observable<List<ShowCase>> showCaseObservable = getModel().loadShowCasesWithReactor();
final Observable<List<Repo>> repositoryObservable = getModel().loadTrendingRepositoriesInWeeklyWithReactor();
Observable.combineLatest(showCaseObservable, repositoryObservable,
new BiFunction<List<ShowCase>, List<Repo>, Map<String, Object>>()
{
@Override public Map<String, Object> apply(List<ShowCase> showCases, List<Repo> repos)
{
Map<String, Object> map = new HashMap<>(2);
map.put(STATE_SHOWCASE, showCases);
map.put(STATE_REPOSITORIES, repos);
return map;
}
}).doOnSubscribe(new Consumer<Disposable>()
{
@Override public void accept(Disposable disposable)
{
getUIView().showEmptyView();
CircleProgressDialog.showLoadingDialog(getAndroidContext());
}
}).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<Map<String, Object>>()
{
@Override public void accept(Map<String, Object> result)
{
CircleProgressDialog.hideLoadingDialog();
ArrayList<ShowCase> showCases = (ArrayList<ShowCase>) result.get(STATE_SHOWCASE);
ArrayList<Repo> repositories = (ArrayList<Repo>) result.get(STATE_REPOSITORIES);
ExploreFragment.this.showCases = showCases;
ExploreFragment.this.repositories = repositories;
getUIView().hideEmptyView();
getUIView().showShowCaseList(showCases);
getUIView().showTrendingRepositoryList(repositories);
}
}, new Consumer<Throwable>()
{
@Override public void accept(Throwable throwable)
{
CircleProgressDialog.hideLoadingDialog();
if (getModel().isEnableCached())
{
List<ShowCase> showCases = getModel().getShowCasesFromCache();
if (showCases != null)
{
getUIView().showShowCaseList(showCases);
}
}
getUIView().showErrorView(
ViewProvider.handleError(getMainController().getConfig().isDebug(), throwable));
}
});
}
}
|
package com.googlecode.jslint4java.eclipse.builder;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectDescription;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IWorkbenchPart;
import com.googlecode.jslint4java.eclipse.JSLintLog;
public class ToggleNatureAction implements IObjectActionDelegate {
private ISelection selection;
/*
* (non-Javadoc)
*
* @see org.eclipse.ui.IActionDelegate#run(org.eclipse.jface.action.IAction)
*/
public void run(IAction action) {
if (selection instanceof IStructuredSelection) {
for (Iterator<?> it = ((IStructuredSelection) selection).iterator(); it
.hasNext();) {
Object element = it.next();
IProject project = null;
if (element instanceof IProject) {
project = (IProject) element;
} else if (element instanceof IAdaptable) {
project = (IProject) ((IAdaptable) element)
.getAdapter(IProject.class);
}
if (project != null) {
toggleNature(project);
}
}
}
}
/*
* (non-Javadoc)
*
* @see org.eclipse.ui.IActionDelegate#selectionChanged(org.eclipse.jface.action.IAction,
* org.eclipse.jface.viewers.ISelection)
*/
public void selectionChanged(IAction action, ISelection selection) {
this.selection = selection;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.ui.IObjectActionDelegate#setActivePart(org.eclipse.jface.action.IAction,
* org.eclipse.ui.IWorkbenchPart)
*/
public void setActivePart(IAction action, IWorkbenchPart targetPart) {
}
/**
* Toggles sample nature on a project
*
* @param project
* to have sample nature added or removed
*/
private void toggleNature(IProject project) {
try {
IProjectDescription description = project.getDescription();
List<String> natures = new ArrayList<String>(Arrays.asList(description.getNatureIds()));
if (natures.contains(JSLintNature.NATURE_ID)) {
// Remove the nature.
natures.remove(JSLintNature.NATURE_ID);
} else {
// Add the nature.
natures.add(JSLintNature.NATURE_ID);
}
description.setNatureIds(natures.toArray(new String[natures.size()]));
project.setDescription(description, null);
} catch (CoreException e) {
JSLintLog.logError(e);
}
}
}
|
package com.kickstarter.ui.activities;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.MotionEvent;
import android.view.SurfaceView;
import android.view.View;
import android.widget.MediaController;
import android.widget.ProgressBar;
import com.google.android.exoplayer.AspectRatioFrameLayout;
import com.google.android.exoplayer.ExoPlayer;
import com.kickstarter.R;
import com.kickstarter.libs.BaseActivity;
import com.kickstarter.libs.KSRendererBuilder;
import com.kickstarter.libs.KSVideoPlayer;
import com.kickstarter.models.Project;
import com.kickstarter.models.Video;
import com.kickstarter.ui.IntentKey;
import butterknife.Bind;
import butterknife.ButterKnife;
public final class VideoPlayerActivity extends BaseActivity implements KSVideoPlayer.Listener {
private MediaController mediaController;
private KSVideoPlayer player;
private long playerPosition;
private Video video;
public @Bind(R.id.video_player_layout) View rootView;
public @Bind(R.id.surface_view) SurfaceView surfaceView;
public @Bind(R.id.loading_indicator) ProgressBar loadingIndicatorProgressBar;
public @Bind(R.id.video_frame) AspectRatioFrameLayout videoFrame;
@Override
public void onCreate(@Nullable final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.video_player_layout);
ButterKnife.bind(this);
final Intent intent = getIntent();
final Project project = intent.getParcelableExtra(IntentKey.PROJECT);
video = project.video();
mediaController = new MediaController(this);
mediaController.setAnchorView(rootView);
rootView.setOnTouchListener(((view, motionEvent) -> {
if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
toggleControlsVisibility();
}
return true;
}));
}
@Override
public void onDestroy() {
super.onDestroy();
releasePlayer();
}
@Override
public void onResume() {
super.onResume();
preparePlayer();
}
@Override
public void onPause() {
super.onPause();
releasePlayer();
}
@Override
public void onStateChanged(final boolean playWhenReady, final int playbackState) {
if (playbackState == ExoPlayer.STATE_ENDED) {
finish();
}
if (playbackState == ExoPlayer.STATE_BUFFERING) {
loadingIndicatorProgressBar.setVisibility(View.VISIBLE);
} else {
loadingIndicatorProgressBar.setVisibility(View.GONE);
}
}
@Override
public void onWindowFocusChanged(final boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (hasFocus) {
rootView.setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_IMMERSIVE
);
}
}
private void releasePlayer() {
if (player != null) {
playerPosition = player.getCurrentPosition();
player.release();
player = null;
}
}
public void preparePlayer() {
// Create player
player = new KSVideoPlayer(new KSRendererBuilder(this, video.high()));
player.setListener(this);
player.seekTo(playerPosition); // todo: will be used for inline video playing
// Set media controller
mediaController.setMediaPlayer(player.getPlayerControl());
mediaController.setEnabled(true);
player.prepare();
player.setSurface(surfaceView.getHolder().getSurface());
player.setPlayWhenReady(true);
}
public void toggleControlsVisibility() {
if (mediaController.isShowing()) {
mediaController.hide();
} else {
mediaController.show();
}
}
}
|
package de.christinecoenen.code.zapp.utils;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.pm.ShortcutInfo;
import android.content.pm.ShortcutManager;
import android.graphics.drawable.Icon;
import android.os.Build;
import java.util.Collections;
import de.christinecoenen.code.zapp.ChannelDetailActivity;
import de.christinecoenen.code.zapp.model.ChannelModel;
/**
* Collection of helper functions to access the ShortcutManager API
* in a safe way.
*/
public class ShortcutHelper {
/**
* Adds the given channel as shortcut to the launcher icon.
* Only call on api level >= 25.
* @param context to access system services
* @param channel channel to create a shortcut for
* @return true if the channel could be added
*/
@TargetApi(25)
public static boolean addShortcutForChannel(Context context, ChannelModel channel) {
ShortcutManager shortcutManager = context.getSystemService(ShortcutManager.class);
ShortcutInfo shortcut = new ShortcutInfo.Builder(context, channel.getId())
.setShortLabel(channel.getName())
.setLongLabel(channel.getName())
.setIcon(Icon.createWithResource(context, channel.getDrawableId()))
.setIntent(ChannelDetailActivity.getStartIntent(context, channel.getId()))
.build();
return shortcutManager.addDynamicShortcuts(Collections.singletonList(shortcut));
}
/**
* Removes the given channel as shortcut from the launcher icon.
* Only call on api level >= 25.
* @param context to access system services
* @param channelId id of the channel you want to remove from shorcut menu
*/
@TargetApi(25)
public static void removeShortcutForChannel(Context context, String channelId) {
ShortcutManager shortcutManager = context.getSystemService(ShortcutManager.class);
shortcutManager.removeDynamicShortcuts(Collections.singletonList(channelId));
}
/**
* Call to report a shortcut used.
* You may call this using any api level.
* @param context to access system services
* @param channelId id of the channel that has been selected
*/
public static void reportShortcutUsageGuarded(Context context, String channelId) {
if (areShortcutsSupported()) {
ShortcutManager shortcutManager = context.getSystemService(ShortcutManager.class);
shortcutManager.reportShortcutUsed(channelId);
}
}
/**
* @return true if the current api level supports shortcuts
*/
public static boolean areShortcutsSupported() {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1;
}
}
|
package jp.blanktar.ruumusic.client.main;
import java.util.List;
import java.util.Stack;
import android.support.annotation.IntRange;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.UiThread;
import android.app.Activity;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v7.widget.SearchView;
import android.text.TextUtils;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import jp.blanktar.ruumusic.R;
import jp.blanktar.ruumusic.util.Preference;
import jp.blanktar.ruumusic.util.RuuClient;
import jp.blanktar.ruumusic.util.RuuDirectory;
import jp.blanktar.ruumusic.util.RuuFile;
import jp.blanktar.ruumusic.util.RuuFileBase;
@UiThread
public class PlaylistFragment extends Fragment implements SearchView.OnQueryTextListener, SearchView.OnCloseListener{
private Preference preference;
private RuuClient client;
private RuuAdapter adapter;
private final Stack<DirectoryInfo> directoryCache = new Stack<>();
@NonNull private ListStatus status = ListStatus.LOADING;
@Nullable DirectoryInfo current;
@Nullable public String searchQuery = null;
@Override
@NonNull
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState){
View view = inflater.inflate(R.layout.fragment_playlist, container, false);
preference = new Preference(view.getContext());
client = new RuuClient(getContext());
adapter = new RuuAdapter(view.getContext());
final ListView lv = (ListView)view.findViewById(R.id.playlist);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener(){
@Override
public void onItemClick(@NonNull AdapterView<?> parent, @Nullable View view, int position, long id){
RuuFileBase selected = (RuuFileBase)lv.getItemAtPosition(position);
if(selected.isDirectory()){
changeDir((RuuDirectory)selected);
}else{
changeMusic((RuuFile)selected);
}
}
});
registerForContextMenu(lv);
String currentPath = preference.CurrentViewPath.get();
try{
if(currentPath != null){
changeDir(RuuDirectory.getInstance(getContext(), currentPath));
searchQuery = preference.LastSearchQuery.get();
if(searchQuery != null){
onQueryTextSubmit(searchQuery);
}
}else{
RuuDirectory dir = RuuDirectory.rootCandidate(getContext());
RuuDirectory root = RuuDirectory.rootDirectory(getContext());
if(!root.contains(dir)){
changeDir(root);
}else{
changeDir(dir);
}
}
}catch(RuuFileBase.NotFound err){
try{
changeDir(RuuDirectory.rootDirectory(getContext()));
}catch(RuuFileBase.NotFound e){
Toast.makeText(getActivity(), getString(R.string.cant_open_dir, e.path), Toast.LENGTH_LONG).show();
preference.RootDirectory.remove();
}
}
return view;
}
@Override
public void onDestroy(){
client.release();
super.onDestroy();
}
@Override
public void onCreateContextMenu(@NonNull ContextMenu menu, @NonNull View view, @NonNull ContextMenu.ContextMenuInfo info){
super.onCreateContextMenu(menu, view, info);
RuuFileBase file = adapter.getItem(((AdapterView.AdapterContextMenuInfo)info).position);
boolean openable = getActivity().getPackageManager().queryIntentActivities(file.toIntent(), 0).size() > 0;
if(file.isDirectory()){
menu.setHeaderTitle(file.getName() + "/");
getActivity().getMenuInflater().inflate(R.menu.directory_context_menu, menu);
menu.findItem(R.id.action_open_dir_with_other_app).setVisible(openable);
}else{
menu.setHeaderTitle(file.getName());
getActivity().getMenuInflater().inflate(R.menu.music_context_menu, menu);
menu.findItem(R.id.action_open_music_with_other_app).setVisible(openable);
}
}
@Override
public boolean onContextItemSelected(@NonNull MenuItem item){
RuuFileBase file = adapter.getItem(((AdapterView.AdapterContextMenuInfo)item.getMenuInfo()).position);
switch(item.getItemId()){
case R.id.action_open_directory:
changeDir((RuuDirectory)file);
return true;
case R.id.action_open_music:
changeMusic((RuuFile)file);
return true;
case R.id.action_open_dir_with_other_app:
case R.id.action_open_music_with_other_app:
startActivity(file.toIntent());
return true;
case R.id.action_web_search_dir:
case R.id.action_web_search_music:
startActivity((new Intent(Intent.ACTION_WEB_SEARCH)).putExtra(SearchManager.QUERY, file.getName()));
return true;
default:
return super.onContextItemSelected(item);
}
}
public void updateTitle(@NonNull Activity activity){
if(current == null){
activity.setTitle("");
}else{
try{
activity.setTitle(current.path.getRuuPath());
}catch(RuuFileBase.OutOfRootDirectory e){
activity.setTitle("");
Toast.makeText(getActivity(), getString(R.string.out_of_root, current.path.getFullPath()), Toast.LENGTH_LONG).show();
}
}
}
private void updateTitle(){
updateTitle(getActivity());
}
public void updateRoot(){
updateTitle();
updateMenu();
if(current != null){
changeDir(current.path);
}
}
private void updateStatus(@NonNull ListStatus status){
this.status = status;
try{
switch(status){
case LOADING:
((TextView)getActivity().findViewById(R.id.playlist_message)).setText(R.string.loading_list);
break;
case EMPTY:
((TextView)getActivity().findViewById(R.id.playlist_message)).setText(R.string.empty_list);
break;
case SHOWN:
getActivity().findViewById(R.id.playlist).setVisibility(View.VISIBLE);
getActivity().findViewById(R.id.playlist_message).setVisibility(View.GONE);
break;
}
}catch(NullPointerException e){
return;
}
if(status != ListStatus.SHOWN){
final Handler handler = new Handler();
(new Handler()).postDelayed(new Runnable(){
@Override
public void run(){
if(PlaylistFragment.this.status != ListStatus.SHOWN){
handler.post(new Runnable(){
@Override
public void run(){
getActivity().findViewById(R.id.playlist_message).setVisibility(View.VISIBLE);
getActivity().findViewById(R.id.playlist).setVisibility(View.GONE);
}
});
}
}
}, 100);
}
}
public void updateStatus(){
updateStatus(status);
}
void changeDir(@NonNull RuuDirectory dir){
try{
dir.getRuuPath();
}catch(RuuFileBase.OutOfRootDirectory e){
Toast.makeText(getActivity(), getString(R.string.out_of_root, dir.getFullPath()), Toast.LENGTH_LONG).show();
return;
}
MainActivity main = (MainActivity)getActivity();
if(main.searchView != null && !main.searchView.isIconified()){
main.searchView.setQuery("", false);
main.searchView.setIconified(true);
}
while(!directoryCache.empty() && !directoryCache.peek().path.contains(dir)){
directoryCache.pop();
}
if(!directoryCache.empty() && directoryCache.peek().path.equals(dir)){
current = directoryCache.pop();
}else{
if(current != null){
current.selection = ((ListView)getActivity().findViewById(R.id.playlist)).getFirstVisiblePosition();
directoryCache.push(current);
}
current = new DirectoryInfo(dir);
}
preference.CurrentViewPath.set(current.path.getFullPath());
if(((MainActivity)getActivity()).getCurrentPage() == MainActivity.Page.PLAYLIST){
updateTitle();
}
adapter.setRuuFiles(current);
}
public void updateMenu(@NonNull MainActivity activity){
if(activity.getCurrentPage() != MainActivity.Page.PLAYLIST){
return;
}
Menu menu = activity.menu;
if(menu != null){
RuuDirectory rootDirectory;
try{
rootDirectory = RuuDirectory.rootDirectory(getContext());
}catch(RuuFileBase.NotFound e){
Toast.makeText(getActivity(), getString(R.string.cant_open_dir, "root directory"), Toast.LENGTH_LONG).show();
return;
}
menu.findItem(R.id.action_set_root).setVisible(current != null && !rootDirectory.equals(current.path) && searchQuery == null);
menu.findItem(R.id.action_unset_root).setVisible(!rootDirectory.getFullPath().equals("/") && searchQuery == null);
menu.findItem(R.id.action_search_play).setVisible(searchQuery != null);
menu.findItem(R.id.action_search_play).setEnabled(adapter.getCount() > 0);
menu.findItem(R.id.action_recursive_play).setVisible(searchQuery == null && adapter.getCount() > 0);
menu.findItem(R.id.menu_search).setVisible(true);
}
}
private void updateMenu(){
updateMenu((MainActivity)getActivity());
}
private void changeMusic(@NonNull RuuFile file){
client.play(file);
((MainActivity)getActivity()).moveToPlayer();
}
public boolean onBackKey(){
SearchView search = ((MainActivity)getActivity()).searchView;
if(search != null && !search.isIconified()){
search.setQuery("", false);
search.setIconified(true);
onClose();
return true;
}
RuuDirectory root;
try{
root = RuuDirectory.rootDirectory(getContext());
}catch(RuuFileBase.NotFound e){
return false;
}
if(current == null){
return false;
}else if(current.path.equals(root)){
return false;
}else{
try{
changeDir(current.path.getParent());
}catch(RuuFileBase.OutOfRootDirectory e){
return false;
}
return true;
}
}
public void setSearchQuery(@NonNull RuuDirectory path, @NonNull String query){
changeDir(path);
((MainActivity)getActivity()).searchView.setIconified(false);
((MainActivity)getActivity()).searchView.setQuery(query, true);
}
@Override
public boolean onQueryTextChange(@NonNull String text){
return false;
}
@Override
public boolean onQueryTextSubmit(@NonNull final String text){
if(current == null){
return false;
}
if(TextUtils.isEmpty(text)){
onClose();
return false;
}
SearchView sv = ((MainActivity)getActivity()).searchView;
if(sv != null){
sv.clearFocus();
}
updateStatus(ListStatus.LOADING);
final Handler handler = new Handler();
(new Thread(new Runnable(){
@Override
public void run(){
final List<RuuFileBase> filtered = current.path.search(text);
handler.post(new Runnable(){
@Override
public void run(){
searchQuery = text;
adapter.setSearchResults(filtered);
preference.LastSearchQuery.set(text);
}
});
}
})).start();
return false;
}
@Override
public boolean onClose(){
adapter.resumeFromSearch();
searchQuery = null;
preference.LastSearchQuery.remove();
updateMenu();
return false;
}
enum ListStatus{
LOADING,
EMPTY,
SHOWN
}
class DirectoryInfo{
public final RuuDirectory path;
public int selection = 0;
public DirectoryInfo(@NonNull RuuDirectory path){
this.path = path;
}
}
@UiThread
private class RuuAdapter extends ArrayAdapter<RuuFileBase>{
@Nullable private DirectoryInfo dirInfo;
RuuAdapter(@NonNull Context context){
super(context, R.layout.list_item);
}
void setRuuFiles(@NonNull final DirectoryInfo dirInfo){
searchQuery = null;
this.dirInfo = dirInfo;
updateStatus(ListStatus.LOADING);
final Handler handler = new Handler();
(new Thread(new Runnable(){
@Override
public void run(){
handler.post(new Runnable(){
@Override
public void run(){
clear();
try{
RuuDirectory rootDirectory = RuuDirectory.rootDirectory(getContext());
if(!rootDirectory.equals(dirInfo.path) && rootDirectory.contains(dirInfo.path)){
add(dirInfo.path.getParent());
}
}catch(RuuFileBase.NotFound | RuuFileBase.OutOfRootDirectory e){
}
for(RuuDirectory dir: dirInfo.path.getDirectories()){
add(dir);
}
for(RuuFile music: dirInfo.path.getMusics()){
add(music);
}
ListView listView = (ListView)getActivity().findViewById(R.id.playlist);
if(listView != null){
listView.setSelection(dirInfo.selection);
}
updateStatus(ListStatus.SHOWN);
updateMenu();
}
});
}
})).start();
}
void setSearchResults(@NonNull final List<RuuFileBase> results){
updateStatus(ListStatus.LOADING);
if(dirInfo != null && getActivity() != null && getActivity().findViewById(R.id.playlist) != null){
dirInfo.selection = ((ListView)getActivity().findViewById(R.id.playlist)).getFirstVisiblePosition();
}
clear();
if(results.size() == 0){
updateStatus(ListStatus.EMPTY);
return;
}
for(RuuFileBase result: results){
add(result);
}
ListView listView = (ListView)getActivity().findViewById(R.id.playlist);
if(listView != null){
listView.setSelection(0);
}
updateStatus(ListStatus.SHOWN);
updateMenu();
}
void resumeFromSearch(){
if(dirInfo != null){
clear();
setRuuFiles(dirInfo);
}
}
@Override
public int getViewTypeCount(){
return 3;
}
@Override
@IntRange(from=0, to=2)
public int getItemViewType(int position){
if(searchQuery != null){
return 2;
}
if(getItem(position).isDirectory() && dirInfo != null && ((RuuDirectory)getItem(position)).contains(dirInfo.path)){
return 1;
}else{
return 0;
}
}
@Override
@NonNull
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent){
RuuFileBase item = getItem(position);
if(searchQuery != null){
if(convertView == null){
convertView = ((LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.list_item_search, null);
}
((TextView)convertView.findViewById(R.id.search_name)).setText(item.getName() + (item.isDirectory() ? "/" : ""));
try{
((TextView)convertView.findViewById(R.id.search_path)).setText(item.getParent().getRuuPath());
}catch(RuuFileBase.OutOfRootDirectory e){
((TextView)convertView.findViewById(R.id.search_path)).setText("");
}
}else{
assert dirInfo != null;
if(item.isDirectory() && ((RuuDirectory)item).contains(dirInfo.path)){
if(convertView == null){
convertView = ((LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.list_item_upper, null);
}
}else{
if(convertView == null){
convertView = ((LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.list_item, null);
}
((TextView)convertView).setText(item.getName() + (item.isDirectory() ? "/" : ""));
}
}
return convertView;
}
}
}
|
package org.mazhuang.guanggoo.topiclist;
import android.content.Context;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import org.mazhuang.guanggoo.router.FragmentFactory;
import org.mazhuang.guanggoo.R;
import org.mazhuang.guanggoo.base.BaseFragment;
import org.mazhuang.guanggoo.data.entity.TopicList;
import org.mazhuang.guanggoo.util.ConstantUtil;
import org.mazhuang.guanggoo.util.DimensUtil;
import org.mazhuang.guanggoo.util.UrlUtil;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;
/**
* @author mazhuang
*/
public class TopicListFragment extends BaseFragment<TopicListContract.Presenter> implements TopicListContract.View,
SwipeRefreshLayout.OnRefreshListener {
private TopicListAdapter mAdapter;
private boolean mLoadable = false;
int pastVisibleItems, visibleItemCount, totalItemCount;
@BindView(R.id.list) RecyclerView mRecyclerView;
@BindView(R.id.refresh_layout) SwipeRefreshLayout mRefreshLayout;
@BindView(R.id.empty) SwipeRefreshLayout mEmptyLayout;
@BindView(R.id.fab) CircleImageView mFabButton;
@BindView(R.id.no_content) TextView mNoContentTextView;
private boolean mFirstFetchFinished = false;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_topic_list, container, false);
ButterKnife.bind(this, root);
initViews();
if (!mAdapter.isFilled()) {
mPresenter.getTopicList();
}
return root;
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initParams();
}
@Override
public void onResume() {
super.onResume();
if (!mFirstFetchFinished && mListener != null) {
mRefreshLayout.setRefreshing(true);
mEmptyLayout.setRefreshing(true);
}
}
private void initViews() {
Context context = getContext();
final LinearLayoutManager layoutManager = new LinearLayoutManager(context);
mRecyclerView.setLayoutManager(layoutManager);
if (mAdapter == null) {
mAdapter = new TopicListAdapter(mListener);
}
mRecyclerView.setAdapter(mAdapter);
mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
//check for scroll down
if (dy > 0) {
visibleItemCount = layoutManager.getChildCount();
totalItemCount = layoutManager.getItemCount();
pastVisibleItems = layoutManager.findFirstVisibleItemPosition();
if (mLoadable) {
if ((visibleItemCount + pastVisibleItems) >= totalItemCount) {
mLoadable = false;
if (totalItemCount >= ConstantUtil.TOPICS_PER_PAGE && totalItemCount <= ConstantUtil.MAX_TOPICS) {
mPresenter.getMoreTopic(totalItemCount / ConstantUtil.TOPICS_PER_PAGE + 1);
} else {
Toast.makeText(getActivity(), "1024", Toast.LENGTH_SHORT).show();
}
}
}
}
}
});
initSwipeLayout(mRefreshLayout);
initSwipeLayout(mEmptyLayout);
handleEmptyList();
handleFabButton();
}
private void handleFabButton() {
if (getPageType() == FragmentFactory.PageType.HOME_TOPIC_LIST ||
getPageType() == FragmentFactory.PageType.NODE_TOPIC_LIST) {
mFabButton.setVisibility(View.VISIBLE);
}
}
private void initSwipeLayout(SwipeRefreshLayout swipeRefreshLayout) {
swipeRefreshLayout.setOnRefreshListener(this);
swipeRefreshLayout.setColorSchemeResources(R.color.main);
}
@OnClick({R.id.fab})
public void onClick(View v) {
switch (v.getId()) {
case R.id.fab:
onNewTopic();
break;
default:
break;
}
}
private void onNewTopic() {
if (mPageType == FragmentFactory.PageType.HOME_TOPIC_LIST) {
if (mListener != null) {
mListener.openPage(ConstantUtil.SELECT_NODE_URL, getString(R.string.select_node_to_new_topic));
}
} else if (mPageType == FragmentFactory.PageType.NODE_TOPIC_LIST) {
String nodeCode = UrlUtil.getNodeCode(mUrl);
if (mListener != null && !TextUtils.isEmpty(nodeCode)) {
mListener.openPage(String.format(ConstantUtil.NEW_TOPIC_BASE_URL, nodeCode), getString(R.string.new_topic));
}
}
}
@Override
public void onGetTopicListSucceed(TopicList topicList) {
finishRefresh();
if (getContext() == null) {
return;
}
if (topicList.getTopics().isEmpty()) {
mNoContentTextView.setText(R.string.no_content);
}
mLoadable = topicList.isHasMore();
mAdapter.setData(topicList.getTopics());
handleEmptyList();
}
@Override
public void onGetTopicListFailed(String msg) {
finishRefresh();
if (getContext() == null) {
return;
}
mNoContentTextView.setText(R.string.no_content);
Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
handleEmptyList();
}
private void handleEmptyList() {
if (mAdapter.getItemCount() == 0) {
mEmptyLayout.setVisibility(View.VISIBLE);
mRefreshLayout.setVisibility(View.GONE);
} else {
mEmptyLayout.setVisibility(View.GONE);
mRefreshLayout.setVisibility(View.VISIBLE);
}
}
@Override
public String getTitle() {
if (TextUtils.isEmpty(mTitle)) {
return getString(R.string.topic_list);
} else {
return mTitle;
}
}
@Override
public void onGetMoreTopicSucceed(TopicList topicList) {
if (getContext() == null) {
return;
}
mLoadable = topicList.isHasMore();
mAdapter.addData(topicList.getTopics());
}
@Override
public void onGetMoreTopicFailed(String msg) {
if (getContext() == null) {
return;
}
Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
}
@Override
public void onRefresh() {
if (!mFirstFetchFinished) {
return;
}
mNoContentTextView.setText("");
mPresenter.getTopicList();
}
private void finishRefresh() {
mRefreshLayout.setRefreshing(false);
mEmptyLayout.setRefreshing(false);
if (!mFirstFetchFinished) {
mFirstFetchFinished = true;
}
}
}
|
package org.openlmis.core.view.holder;
import android.text.InputFilter;
import android.view.View;
import org.apache.commons.lang.StringUtils;
import org.openlmis.core.R;
import org.openlmis.core.view.viewmodel.InventoryViewModel;
import org.openlmis.core.view.widget.InputFilterMinMax;
public class UnpackKitViewHolder extends PhysicalInventoryViewHolder {
public UnpackKitViewHolder(View itemView) {
super(itemView);
etQuantity.setHint(R.string.hint_quantity_in_unpack_kit);
}
public void populate(InventoryViewModel inventoryViewModel) {
etQuantity.setFilters(new InputFilter[]{new InputFilterMinMax(0, 2 * (int)inventoryViewModel.getKitExpectQuantity() - 1)});
populate(inventoryViewModel, StringUtils.EMPTY);
tvStockOnHandInInventory.setText(context.getString(R.string.label_unpack_kit_quantity_expected,
Long.toString(inventoryViewModel.getKitExpectQuantity())));
}
}
|
package org.worshipsongs.activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.OpenableColumns;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.worshipsongs.CommonConstants;
import org.worshipsongs.WorshipSongApplication;
import org.worshipsongs.dao.SongDao;
import org.worshipsongs.dialog.CustomDialogBuilder;
import org.worshipsongs.domain.DialogConfiguration;
import org.worshipsongs.locator.IImportDatabaseLocator;
import org.worshipsongs.locator.ImportDatabaseLocator;
import org.worshipsongs.service.PresentationScreenService;
import org.worshipsongs.utils.PropertyUtils;
import org.worshipsongs.worship.R;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
/**
* Author : Madasamy
* Version : 3.x
*/
public class DatabaseSettingActivity extends AppCompatActivity
{
private IImportDatabaseLocator importDatabaseLocator = new ImportDatabaseLocator();
private SongDao songDao = new SongDao(WorshipSongApplication.getContext());
private SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(WorshipSongApplication.getContext());
private PresentationScreenService presentationScreenService;
private ProgressBar progressBar;
private Button defaultDatabaseButton;
private TextView resultTextView;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.database_layout);
setActionBar();
setImportDatabaseButton();
setProgressBar();
setDefaultDatabaseButton();
setResultTextView();
presentationScreenService = new PresentationScreenService(this);
}
private void setActionBar()
{
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowTitleEnabled(true);
getSupportActionBar().setTitle(R.string.database);
}
private void setImportDatabaseButton()
{
Button importDatabaseButton = (Button) findViewById(R.id.upload_database_button);
importDatabaseButton.setOnClickListener(new ImportDatabaseOnClickListener());
}
private class ImportDatabaseOnClickListener implements View.OnClickListener
{
@Override
public void onClick(View view)
{
showDatabaseTypeDialog();
}
}
private void showDatabaseTypeDialog()
{
AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(DatabaseSettingActivity.this, R.style.MyDialogTheme));
builder.setTitle(getString(R.string.type));
builder.setItems(R.array.dataBaseTypes, new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
importDatabaseLocator.load(DatabaseSettingActivity.this, getStringObjectMap(which));
dialog.cancel();
}
});
AlertDialog dialog = builder.create();
dialog.getListView().setSelector(android.R.color.darker_gray);
dialog.show();
}
@NonNull
private Map<String, Object> getStringObjectMap(int which)
{
Map<String, Object> objectMap = new HashMap<String, Object>();
objectMap.put(CommonConstants.INDEX_KEY, which);
objectMap.put(CommonConstants.PROGRESS_BAR_KEY, progressBar);
//objectMap.put(CommonConstants.FRAGMENT_KEY, DatabaseSettingActivity.this);
objectMap.put(CommonConstants.TEXTVIEW_KEY, resultTextView);
objectMap.put(CommonConstants.REVERT_DATABASE_BUTTON_KEY, defaultDatabaseButton);
return objectMap;
}
private void setDefaultDatabaseButton()
{
defaultDatabaseButton = (Button) findViewById(R.id.default_database_button);
defaultDatabaseButton.setVisibility(sharedPreferences.getBoolean(CommonConstants.SHOW_REVERT_DATABASE_BUTTON_KEY, false) ? View.VISIBLE : View.GONE);
defaultDatabaseButton.setOnClickListener(new DefaultDbOnClickListener());
}
private class DefaultDbOnClickListener implements View.OnClickListener
{
@Override
public void onClick(View v)
{
DialogConfiguration dialogConfiguration = new DialogConfiguration("",
getString(R.string.message_database_confirmation));
CustomDialogBuilder customDialogBuilder = new CustomDialogBuilder(DatabaseSettingActivity.this, dialogConfiguration);
customDialogBuilder.getBuilder().setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
try {
songDao.close();
songDao.copyDatabase("", true);
songDao.open();
sharedPreferences.edit().putBoolean(CommonConstants.SHOW_REVERT_DATABASE_BUTTON_KEY, false).apply();
defaultDatabaseButton.setVisibility(View.GONE);
updateResultTextview();
dialog.cancel();
} catch (IOException ex) {
Log.e(DatabaseSettingActivity.this.getClass().getSimpleName(), "Error occurred while coping database " + ex);
}
}
});
customDialogBuilder.getBuilder().setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
dialog.cancel();
}
});
customDialogBuilder.getBuilder().show();
}
}
private void setResultTextView()
{
resultTextView = (TextView) findViewById(R.id.result_textview);
resultTextView.setText(getCountQueryResult());
}
private void setProgressBar()
{
progressBar = (ProgressBar) findViewById(R.id.progress_bar);
progressBar.setVisibility(View.GONE);
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId()) {
case android.R.id.home:
finish();
break;
}
return true;
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent intent)
{
progressBar.setVisibility(View.VISIBLE);
switch (requestCode) {
case 1:
if (resultCode == RESULT_OK) {
Uri uri = intent.getData();
doCopyFile(uri, getFileName(uri));
}
break;
}
progressBar.setVisibility(View.GONE);
super.onActivityResult(requestCode, resultCode, intent);
}
private void doCopyFile(Uri uri, String fileName)
{
try {
String fileExtension = FilenameUtils.getExtension(fileName);
if ("sqlite".equalsIgnoreCase(fileExtension)) {
showConfirmationDialog(uri, fileName);
} else {
copyFile(uri);
}
} finally {
getDestinationFile().deleteOnExit();
}
}
private void showConfirmationDialog(final Uri uri, String fileName)
{
String formattedMessage = String.format(getResources().getString(R.string.message_chooseDatabase_confirmation), fileName);
DialogConfiguration dialogConfiguration = new DialogConfiguration(getString(R.string.confirmation),
formattedMessage);
CustomDialogBuilder customDialogBuilder = new CustomDialogBuilder(DatabaseSettingActivity.this, dialogConfiguration);
customDialogBuilder.getBuilder().setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
copyFile(uri);
dialog.cancel();
}
});
customDialogBuilder.getBuilder().setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
dialog.cancel();
}
});
customDialogBuilder.getBuilder().show();
}
private void copyFile(Uri uri)
{
try {
File destinationFile = getDestinationFile();
InputStream inputStream = getContentResolver().openInputStream(uri);
OutputStream outputstream = new FileOutputStream(destinationFile);
byte[] data = new byte[inputStream.available()];
inputStream.read(data);
outputstream.write(data);
inputStream.close();
outputstream.close();
Log.i(DatabaseSettingActivity.this.getClass().getSimpleName(), "Size of file " + FileUtils.sizeOf(destinationFile));
validateDatabase(getDestinationFile().getAbsolutePath());
} catch (IOException ex) {
Log.i(DatabaseSettingActivity.class.getSimpleName(), "Error occurred while coping file" + ex);
}
}
File getDestinationFile()
{
return new File(getCacheDir().getAbsolutePath(), CommonConstants.DATABASE_NAME);
}
private String getFileName(Uri uri)
{
File selectedFile = new File(uri.toString());
String fileName = "";
if (uri.toString().startsWith("content:
Cursor cursor = null;
try {
cursor = getContentResolver().query(uri, null, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
fileName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
}
} finally {
cursor.close();
}
} else {
fileName = selectedFile.getName();
}
return fileName;
}
private void validateDatabase(String absolutePath)
{
try {
resultTextView.setText("");
songDao.close();
songDao.copyDatabase(absolutePath, true);
songDao.open();
if (songDao.isValidDataBase()) {
updateResultTextview();
sharedPreferences.edit().putBoolean(CommonConstants.SHOW_REVERT_DATABASE_BUTTON_KEY, true).apply();
defaultDatabaseButton.setVisibility(sharedPreferences.getBoolean(CommonConstants.SHOW_REVERT_DATABASE_BUTTON_KEY,
false) ? View.VISIBLE : View.GONE);
FileUtils.deleteQuietly(PropertyUtils.getPropertyFile(DatabaseSettingActivity.this, CommonConstants.SERVICE_PROPERTY_TEMP_FILENAME));
Toast.makeText(this, R.string.import_database_successfull, Toast.LENGTH_SHORT).show();
} else {
showWarningDialog();
}
} catch (IOException e) {
e.printStackTrace();
Log.i(DatabaseSettingActivity.this.getClass().getSimpleName(), "Error occurred while coping external db" + e);
}
}
private void updateResultTextview()
{
resultTextView.setText("");
resultTextView.setText(getCountQueryResult());
}
private void showWarningDialog()
{
DialogConfiguration dialogConfiguration = new DialogConfiguration(getString(R.string.warning),
getString(R.string.message_database_invalid));
CustomDialogBuilder customDialogBuilder = new CustomDialogBuilder(DatabaseSettingActivity.this, dialogConfiguration);
customDialogBuilder.getBuilder().setCancelable(false);
customDialogBuilder.getBuilder().setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
try {
songDao.close();
songDao.copyDatabase("", true);
songDao.open();
dialog.cancel();
} catch (IOException e) {
e.printStackTrace();
}
}
});
customDialogBuilder.getBuilder().show();
}
public String getCountQueryResult()
{
String count = null;
try {
count = String.valueOf(songDao.count());
} catch (Exception e) {
count = "";
}
return String.format(getString(R.string.songs_count), count);
}
@Override
protected void onResume()
{
super.onResume();
presentationScreenService.onResume();
}
@Override
protected void onPause()
{
super.onPause();
presentationScreenService.onPause();
}
@Override
protected void onStop()
{
super.onStop();
presentationScreenService.onStop();
}
}
|
package sample.regexp;
import org.openjdk.jmh.runner.RunnerException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) throws RunnerException {
Pattern pattern = Pattern.compile("([a-z]+)([0-9]+)");
Matcher matcher = pattern.matcher("abc123de45fg");
int groupCount = matcher.groupCount();
System.out.println("groupCount=" + groupCount);
while (matcher.find()) {
System.out.println("==========");
String group = matcher.group();
System.out.println("group=" + group);
for (int i=0; i<=groupCount; i++) {
String g = matcher.group(i);
System.out.println("group(" + i + ")=" + g);
}
}
}
}
|
package org.ccnx.ccn.protocol;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import org.ccnx.ccn.config.SystemConfiguration;
import org.ccnx.ccn.impl.encoding.CCNProtocolDTags;
import org.ccnx.ccn.impl.encoding.GenericXMLEncodable;
import org.ccnx.ccn.impl.encoding.XMLDecoder;
import org.ccnx.ccn.impl.encoding.XMLEncodable;
import org.ccnx.ccn.impl.encoding.XMLEncoder;
import org.ccnx.ccn.impl.support.Log;
import org.ccnx.ccn.io.content.ContentDecodingException;
import org.ccnx.ccn.io.content.ContentEncodingException;
public class WirePacket extends GenericXMLEncodable implements XMLEncodable {
protected GenericXMLEncodable _content = null;
public WirePacket() {
}; // for use by decoders
public WirePacket(GenericXMLEncodable content) {
_content = content;
}
public void decode(XMLDecoder decoder) throws ContentDecodingException {
if (decoder.peekStartElement(CCNProtocolDTags.Interest)) {
_content = new Interest();
_content.decode(decoder);
} else if (decoder.peekStartElement(CCNProtocolDTags.ContentObject)) {
_content = new ContentObject();
_content.decode(decoder);
if( Log.isLoggable(Level.FINEST) )
SystemConfiguration.logObject(Level.FINEST, "packetDecode", (ContentObject)_content);
}
Log.finest("Finished decoding wire packet.");
}
@Override
public void encode(XMLEncoder encoder) throws ContentEncodingException {
if (!validate()) {
throw new ContentEncodingException("Cannot encode " + this.getClass().getName() + ": bad or missing values.");
}
_content.encode(encoder);
}
@Override
public boolean validate() {
if (null == _content) {
return false;
}
if ( ! (_content instanceof Interest || _content instanceof ContentObject) ) {
return false;
}
return true;
}
@Override
public long getElementLabel() { // unused, we add nothing to encoding
return -1;
}
public XMLEncodable getPacket() {
return _content;
}
public List<Interest> interests() {
ArrayList<Interest> list = new ArrayList<Interest>();
if (_content instanceof Interest)
list.add((Interest)_content);
return list;
}
public List<ContentObject> data() {
ArrayList<ContentObject> list = new ArrayList<ContentObject>();
if (_content instanceof ContentObject)
list.add((ContentObject)_content);
return list;
}
}
|
package org.jpos.iso;
/**
* Implements EBCDIC Interpreter. Strings are converted to and from EBCDIC
* bytes.
*
* @author joconnor
* @version $Revision$ $Date$
*/
public class EbcdicInterpreter implements Interpreter
{
/** An instance of this Interpreter. Only one needed for the whole system */
public static final EbcdicInterpreter INSTANCE = new EbcdicInterpreter();
/**
* (non-Javadoc)
*
* @see org.jpos.iso.Interpreter#interpret(java.lang.String)
*/
public void interpret(String data, byte[] b, int offset)
{
ISOUtil.asciiToEbcdic(data, b, offset);
}
/**
* (non-Javadoc)
*
* @see org.jpos.iso.Interpreter#uninterpret(byte[])
*/
public String uninterpret(byte[] rawData, int offset, int length)
{
return ISOUtil.ebcdicToAscii(rawData, offset, length);
}
/**
* (non-Javadoc)
*
* @see org.jpos.iso.Interpreter#getPackedLength(int)
*/
public int getPackedLength(int nDataUnits)
{
return nDataUnits;
}
}
|
package us.myles.ViaVersion.protocols.protocolsnapshotto1_12_2;
import us.myles.ViaVersion.api.PacketWrapper;
import us.myles.ViaVersion.api.data.UserConnection;
import us.myles.ViaVersion.api.platform.providers.ViaProviders;
import us.myles.ViaVersion.api.protocol.Protocol;
import us.myles.ViaVersion.api.remapper.PacketHandler;
import us.myles.ViaVersion.api.remapper.PacketRemapper;
import us.myles.ViaVersion.api.remapper.ValueCreator;
import us.myles.ViaVersion.api.remapper.ValueTransformer;
import us.myles.ViaVersion.api.type.Type;
import us.myles.ViaVersion.packets.State;
import us.myles.ViaVersion.protocols.protocol1_9_3to1_9_1_2.storage.ClientWorld;
import us.myles.ViaVersion.protocols.protocolsnapshotto1_12_2.data.MappingData;
import us.myles.ViaVersion.protocols.protocolsnapshotto1_12_2.packets.EntityPackets;
import us.myles.ViaVersion.protocols.protocolsnapshotto1_12_2.packets.InventoryPackets;
import us.myles.ViaVersion.protocols.protocolsnapshotto1_12_2.packets.WorldPackets;
import us.myles.ViaVersion.protocols.protocolsnapshotto1_12_2.providers.BlockEntityProvider;
import us.myles.ViaVersion.protocols.protocolsnapshotto1_12_2.providers.PaintingProvider;
import us.myles.ViaVersion.protocols.protocolsnapshotto1_12_2.storage.BlockStorage;
import us.myles.ViaVersion.protocols.protocolsnapshotto1_12_2.storage.EntityTracker;
import us.myles.ViaVersion.protocols.protocolsnapshotto1_12_2.storage.TabCompleteTracker;
// Development of 1.13 support!
public class ProtocolSnapshotTo1_12_2 extends Protocol {
static {
MappingData.init();
}
@Override
protected void registerPackets() {
// Register grouped packet changes
EntityPackets.register(this);
WorldPackets.register(this);
InventoryPackets.register(this);
// Outgoing packets
// Statistics
registerOutgoing(State.PLAY, 0x07, 0x07, new PacketRemapper() {
@Override
public void registerMap() {
// TODO: This packet has changed
handler(new PacketHandler() {
@Override
public void handle(PacketWrapper wrapper) throws Exception {
wrapper.cancel();
}
});
}
});
registerOutgoing(State.PLAY, 0xF, 0xE);
// Tab-Complete
registerOutgoing(State.PLAY, 0xE, 0x10, new PacketRemapper() {
@Override
public void registerMap() {
create(new ValueCreator() {
@Override
public void write(PacketWrapper wrapper) throws Exception {
wrapper.write(Type.VAR_INT, wrapper.user().get(TabCompleteTracker.class).getTransactionId());
String input = wrapper.user().get(TabCompleteTracker.class).getInput();
// Start & End
int index;
int length;
// If no input or new word (then it's the start)
if (input.endsWith(" ") || input.length() == 0) {
index = input.length();
length = 0;
} else {
// Otherwise find the last space (+1 as we include it)
int lastSpace = input.lastIndexOf(" ") + 1;
index = lastSpace;
length = input.length() - lastSpace;
}
// Write index + length
wrapper.write(Type.VAR_INT, index);
wrapper.write(Type.VAR_INT, length);
int count = wrapper.passthrough(Type.VAR_INT);
for (int i = 0; i < count; i++) {
String suggestion = wrapper.read(Type.STRING);
// If we're at the start then handle removing slash
if (suggestion.startsWith("/") && index == 0) {
suggestion = suggestion.substring(1);
}
wrapper.write(Type.STRING, suggestion);
wrapper.write(Type.BOOLEAN, false);
}
}
});
}
});
// New packet 0x11, declare commands
registerOutgoing(State.PLAY, 0x11, 0x12);
registerOutgoing(State.PLAY, 0x12, 0x13);
registerOutgoing(State.PLAY, 0x13, 0x14);
registerOutgoing(State.PLAY, 0x15, 0x16);
registerOutgoing(State.PLAY, 0x17, 0x18);
registerOutgoing(State.PLAY, 0x1A, 0x1B);
registerOutgoing(State.PLAY, 0x1B, 0x1C);
registerOutgoing(State.PLAY, 0x1C, 0x1D);
registerOutgoing(State.PLAY, 0x1D, 0x1E);
registerOutgoing(State.PLAY, 0x1E, 0x1F);
registerOutgoing(State.PLAY, 0x1F, 0x20);
registerOutgoing(State.PLAY, 0x21, 0x22);
// Join (save dimension id)
registerOutgoing(State.PLAY, 0x23, 0x24, new PacketRemapper() {
@Override
public void registerMap() {
map(Type.INT); // 0 - Entity ID
map(Type.UNSIGNED_BYTE); // 1 - Gamemode
map(Type.INT); // 2 - Dimension
handler(new PacketHandler() {
@Override
public void handle(PacketWrapper wrapper) throws Exception {
ClientWorld clientChunks = wrapper.user().get(ClientWorld.class);
int dimensionId = wrapper.get(Type.INT, 1);
clientChunks.setEnvironment(dimensionId);
// Send fake declare commands
wrapper.create(0x11, new ValueCreator() {
@Override
public void write(PacketWrapper wrapper) {
wrapper.write(Type.VAR_INT, 2); // Size
// Write root node
wrapper.write(Type.VAR_INT, 0); // Mark as command
wrapper.write(Type.VAR_INT, 1); // 1 child
wrapper.write(Type.VAR_INT, 1); // Child is at 1
// Write arg node
wrapper.write(Type.VAR_INT, 0x02 | 0x04 | 0x10); // Mark as command
wrapper.write(Type.VAR_INT, 0); // No children
// Extra data
wrapper.write(Type.STRING, "args"); // Arg name
wrapper.write(Type.STRING, "brigadier:string");
wrapper.write(Type.VAR_INT, 2); // Greedy
wrapper.write(Type.STRING, "minecraft:ask_server"); // Ask server
wrapper.write(Type.VAR_INT, 0); // Root node index
}
}).send(ProtocolSnapshotTo1_12_2.class);
PacketWrapper tagsPacket = wrapper.create(0x54, new ValueCreator() {
@Override
public void write(PacketWrapper wrapper) throws Exception {
wrapper.write(Type.VAR_INT, 0);
wrapper.write(Type.VAR_INT, 0);
}
});
tagsPacket.send(ProtocolSnapshotTo1_12_2.class);
tagsPacket.send(ProtocolSnapshotTo1_12_2.class);
}
});
}
});
registerOutgoing(State.PLAY, 0x24, 0x25);
registerOutgoing(State.PLAY, 0x25, 0x26);
registerOutgoing(State.PLAY, 0x26, 0x27);
registerOutgoing(State.PLAY, 0x27, 0x28);
registerOutgoing(State.PLAY, 0x28, 0x29);
registerOutgoing(State.PLAY, 0x29, 0x2A);
registerOutgoing(State.PLAY, 0x2A, 0x2B);
// Craft recipe response
registerOutgoing(State.PLAY, 0x2B, 0x2C, new PacketRemapper() {
@Override
public void registerMap() {
handler(new PacketHandler() {
@Override
public void handle(PacketWrapper wrapper) throws Exception {
// TODO This packet changed
wrapper.cancel();
}
});
}
});
registerOutgoing(State.PLAY, 0x2C, 0x2D);
registerOutgoing(State.PLAY, 0x2D, 0x2E);
registerOutgoing(State.PLAY, 0x2E, 0x2F);
registerOutgoing(State.PLAY, 0x2F, 0x31);
registerOutgoing(State.PLAY, 0x30, 0x32);
// Recipe
registerOutgoing(State.PLAY, 0x31, 0x33, new PacketRemapper() {
@Override
public void registerMap() {
handler(new PacketHandler() {
@Override
public void handle(PacketWrapper wrapper) throws Exception {
// TODO: This has changed >.>
wrapper.cancel();
}
});
}
});
registerOutgoing(State.PLAY, 0x33, 0x35);
registerOutgoing(State.PLAY, 0x34, 0x36);
// Respawn (save dimension id)
registerOutgoing(State.PLAY, 0x35, 0x37, new PacketRemapper() {
@Override
public void registerMap() {
map(Type.INT); // 0 - Dimension ID
handler(new PacketHandler() {
@Override
public void handle(PacketWrapper wrapper) throws Exception {
ClientWorld clientWorld = wrapper.user().get(ClientWorld.class);
int dimensionId = wrapper.get(Type.INT, 0);
clientWorld.setEnvironment(dimensionId);
}
});
}
});
registerOutgoing(State.PLAY, 0x36, 0x38);
registerOutgoing(State.PLAY, 0x37, 0x39);
registerOutgoing(State.PLAY, 0x38, 0x3A);
registerOutgoing(State.PLAY, 0x39, 0x3B);
registerOutgoing(State.PLAY, 0x3A, 0x3C);
registerOutgoing(State.PLAY, 0x3B, 0x3D);
registerOutgoing(State.PLAY, 0x3D, 0x3F);
registerOutgoing(State.PLAY, 0x3E, 0x40);
registerOutgoing(State.PLAY, 0x40, 0x42);
registerOutgoing(State.PLAY, 0x41, 0x43);
// Scoreboard Objective
registerOutgoing(State.PLAY, 0x42, 0x44, new PacketRemapper() {
@Override
public void registerMap() {
map(Type.STRING);
map(Type.BYTE);
handler(new PacketHandler() {
@Override
public void handle(PacketWrapper wrapper) throws Exception {
if (wrapper.get(Type.BYTE, 0) == 0 || wrapper.get(Type.BYTE, 0) == 1) {
wrapper.passthrough(Type.STRING);
String type = wrapper.read(Type.STRING);
// integer or hearts
wrapper.write(Type.VAR_INT, type.equals("integer") ? 0 : 1);
}
}
});
}
});
registerOutgoing(State.PLAY, 0x43, 0x45);
// Team packet
registerOutgoing(State.PLAY, 0x44, 0x46, new PacketRemapper() {
@Override
public void registerMap() {
map(Type.STRING); // 0 - Team Name
map(Type.BYTE); // 1 - Mode
handler(new PacketHandler() {
@Override
public void handle(PacketWrapper wrapper) throws Exception {
byte action = wrapper.get(Type.BYTE, 0);
if (action == 0 || action == 2) {
wrapper.passthrough(Type.STRING); // Display Name
wrapper.read(Type.STRING); // Prefix !REMOVED! TODO alternative or drop?
wrapper.read(Type.STRING); // Suffix !REMOVED!
wrapper.passthrough(Type.BYTE); // Flags
wrapper.passthrough(Type.STRING); // Name Tag Visibility
wrapper.passthrough(Type.STRING); // Collision rule
// Handle new colors
byte color = wrapper.read(Type.BYTE);
if (color == -1) // -1 is no longer active, use white instead
wrapper.write(Type.VAR_INT, 15);
else
wrapper.write(Type.VAR_INT, (int) color);
}
}
});
}
});
registerOutgoing(State.PLAY, 0x45, 0x47);
registerOutgoing(State.PLAY, 0x46, 0x48);
registerOutgoing(State.PLAY, 0x47, 0x49);
registerOutgoing(State.PLAY, 0x48, 0x4A);
// Sound Effect packet
registerOutgoing(State.PLAY, 0x49, 0x4C, new PacketRemapper() {
@Override
public void registerMap() {
map(Type.VAR_INT); // 0 - Sound ID
handler(new PacketHandler() {
@Override
public void handle(PacketWrapper wrapper) throws Exception {
int soundId = wrapper.get(Type.VAR_INT, 0);
wrapper.set(Type.VAR_INT, 0, getNewSoundID(soundId));
}
});
}
});
registerOutgoing(State.PLAY, 0x4A, 0x4D);
registerOutgoing(State.PLAY, 0x4B, 0x4E);
registerOutgoing(State.PLAY, 0x4C, 0x4F);
// Advancements
registerOutgoing(State.PLAY, 0x4D, 0x50, new PacketRemapper() {
@Override
public void registerMap() {
handler(new PacketHandler() {
@Override
public void handle(PacketWrapper wrapper) throws Exception {
wrapper.cancel();
}
});
}
});
registerOutgoing(State.PLAY, 0x4E, 0x51);
registerOutgoing(State.PLAY, 0x4F, 0x52);
// New packet 0x52 - Declare Recipes
// New packet 0x53 - Tags
// Incoming packets
registerIncoming(State.PLAY, 0x2, 0x1);
registerIncoming(State.PLAY, 0x3, 0x2);
registerIncoming(State.PLAY, 0x4, 0x3);
// Tab-Complete
registerIncoming(State.PLAY, 0x1, 0x4, new PacketRemapper() {
@Override
public void registerMap() {
handler(new PacketHandler() {
@Override
public void handle(PacketWrapper wrapper) throws Exception {
int tid = wrapper.read(Type.VAR_INT);
// Save transaction id
wrapper.user().get(TabCompleteTracker.class).setTransactionId(tid);
}
});
// Prepend /
map(Type.STRING, new ValueTransformer<String, String>(Type.STRING) {
@Override
public String transform(PacketWrapper wrapper, String inputValue) {
wrapper.user().get(TabCompleteTracker.class).setInput(inputValue);
return "/" + inputValue;
}
});
// Fake the end of the packet
create(new ValueCreator() {
@Override
public void write(PacketWrapper wrapper) {
wrapper.write(Type.BOOLEAN, false);
wrapper.write(Type.OPTIONAL_POSITION, null);
}
});
}
});
// Craft recipe request
registerIncoming(State.PLAY, 0x12, 0x12, new PacketRemapper() {
@Override
public void registerMap() {
handler(new PacketHandler() {
@Override
public void handle(PacketWrapper wrapper) throws Exception {
// TODO: This has changed >.>
wrapper.cancel();
}
});
}
});
}
@Override
public void init(UserConnection userConnection) {
userConnection.put(new EntityTracker(userConnection));
userConnection.put(new TabCompleteTracker(userConnection));
if (!userConnection.has(ClientWorld.class))
userConnection.put(new ClientWorld(userConnection));
userConnection.put(new BlockStorage(userConnection));
}
@Override
protected void register(ViaProviders providers) {
providers.register(BlockEntityProvider.class, new BlockEntityProvider());
providers.register(PaintingProvider.class, new PaintingProvider());
}
private int getNewSoundID(final int oldID){
int newID = oldID;
if (oldID >= 10)
newID += 5;
if (oldID >= 86)
newID++;
if (oldID >= 166)
newID += 4;
if (oldID >= 226)
newID++;
if (oldID >= 380)
newID += 7;
if (oldID >= 385)
newID += 4;
if (oldID >= 352)
newID += 5;
if (oldID >= 438)
newID++;
if (oldID >= 443)
newID += 12;
if (oldID >= 485)
newID++;
if (oldID >= 508)
newID += 2;
if (oldID >= 512)
newID++;
if (oldID >= 514)
newID++;
if (oldID >= 524)
newID += 8;
return newID;
// TODO 18w08b
}
}
|
package biomodel.gui.textualeditor;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import main.Gui;
import main.util.Utility;
import org.sbml.libsbml.*;
import biomodel.annotation.AnnotationUtility;
import biomodel.gui.ModelEditor;
import biomodel.parser.BioModel;
import biomodel.util.GlobalConstants;
/**
* This is a class for creating SBML events.
*
* @author Chris Myers
*
*/
public class Events extends JPanel implements ActionListener, MouseListener {
/* TODO: YOU NEED MOST OF THE ITEMS BELOW */
private static final long serialVersionUID = 1L;
private JButton addEvent, addTrans, removeEvent, editEvent;
private JList events; // JList of events
private JList eventAssign; // JList of event assignments
private BioModel bioModel;
private ModelEditor modelEditor;
private Gui biosim;
private boolean isTextual;
/* Create event panel */
/* TODO: ONLY NEED TO MAKE A COPY OF bioModel */
public Events(Gui biosim, BioModel bioModel, ModelEditor modelEditor, boolean isTextual) {
super(new BorderLayout());
this.bioModel = bioModel;
this.biosim = biosim;
this.isTextual = isTextual;
this.modelEditor = modelEditor;
Model model = bioModel.getSBMLDocument().getModel();
addEvent = new JButton("Add Event");
addTrans = new JButton("Add Transition");
if (biosim.lema) {
removeEvent = new JButton("Remove Transition");
editEvent = new JButton("Edit Transition");
} else {
removeEvent = new JButton("Remove Event");
editEvent = new JButton("Edit Event");
}
events = new JList();
eventAssign = new JList();
ListOf listOfEvents = model.getListOfEvents();
String[] ev = new String[(int) model.getNumEvents()];
for (int i = 0; i < model.getNumEvents(); i++) {
org.sbml.libsbml.Event event = (org.sbml.libsbml.Event) listOfEvents.get(i);
if (!event.isSetId()) {
String eventId = "event0";
int en = 0;
while (bioModel.isSIdInUse(eventId)) {
en++;
eventId = "event" + en;
}
event.setId(eventId);
}
ev[i] = event.getId();
}
JPanel addRem = new JPanel();
if (!biosim.lema) {
addRem.add(addEvent);
}
if (isTextual) {
addRem.add(addTrans);
addTrans.addActionListener(this);
}
addRem.add(removeEvent);
addRem.add(editEvent);
addEvent.addActionListener(this);
removeEvent.addActionListener(this);
editEvent.addActionListener(this);
JLabel panelLabel;
if (biosim.lema) {
panelLabel = new JLabel("List of Transitions:");
} else {
panelLabel = new JLabel("List of Events:");
}
JScrollPane scroll = new JScrollPane();
scroll.setMinimumSize(new Dimension(260, 220));
scroll.setPreferredSize(new Dimension(276, 152));
scroll.setViewportView(events);
Utility.sort(ev);
events.setListData(ev);
events.setSelectedIndex(0);
events.addMouseListener(this);
this.add(panelLabel, "North");
this.add(scroll, "Center");
this.add(addRem, "South");
};
/**
* Creates a frame used to edit events or create new ones.
*/
public String eventEditor(String option,String selected,boolean isTransition) {
String[] origAssign = null;
String[] assign = new String[0];
String[] placeAssign = new String[0];
ArrayList<String> presetPlaces = new ArrayList<String>();
/* TODO: YOU NEED TO CREATE THE PANEL */
JPanel eventPanel = new JPanel(new BorderLayout());
/* TODO: TO HERE */
// JPanel evPanel = new JPanel(new GridLayout(2, 2));
JPanel evPanel = new JPanel(new GridLayout(10, 2));
if (isTransition) {
evPanel.setLayout(new GridLayout(8, 2));
}
JLabel IDLabel = new JLabel("ID:");
JLabel NameLabel = new JLabel("Name:");
JLabel triggerLabel;
if (isTransition) {
triggerLabel = new JLabel("Enabling condition:");
} else {
triggerLabel = new JLabel("Trigger:");
}
JLabel delayLabel = new JLabel("Delay:");
JLabel priorityLabel = new JLabel("Priority:");
JLabel assignTimeLabel = new JLabel("Use values at trigger time:");
JLabel persistentTriggerLabel;
if (isTransition) {
persistentTriggerLabel = new JLabel("Enabling is persistent:");
} else {
persistentTriggerLabel = new JLabel("Trigger is persistent:");
}
JLabel initialTriggerLabel = new JLabel("Trigger initially true:");
JLabel dynamicProcessLabel = new JLabel("Dynamic Process:");
JLabel onPortLabel = new JLabel("Is Mapped to a Port:");
JLabel failTransitionLabel = new JLabel("Fail transition:");
JTextField eventID = new JTextField(12);
JTextField eventName = new JTextField(12);
JTextField eventTrigger = new JTextField(12);
JTextField eventDelay = new JTextField(12);
JTextField eventPriority = new JTextField(12);
JCheckBox assignTime = new JCheckBox("");
JCheckBox persistentTrigger = new JCheckBox("");
JCheckBox initialTrigger = new JCheckBox("");
JCheckBox failTransition = new JCheckBox("");
JComboBox dynamicProcess = new JComboBox(new String[] {"none",
"Symmetric Division","Asymmetric Division","Death", "Move Random", "Move Left", "Move Right", "Move Above", "Move Below"});
JCheckBox onPort = new JCheckBox();
if (bioModel != null && bioModel.IsWithinCompartment() == false) {
dynamicProcess.setEnabled(false);
dynamicProcess.setSelectedItem("none");
}
/* TODO: NEED TO ADD OBJECTIVES LIST AND BUTTONS */
JPanel eventAssignPanel = new JPanel(new BorderLayout());
JPanel addEventAssign = new JPanel();
JButton addAssignment = new JButton("Add Assignment");
JButton removeAssignment = new JButton("Remove Assignment");
JButton editAssignment = new JButton("Edit Assignment");
addEventAssign.add(addAssignment);
addEventAssign.add(removeAssignment);
addEventAssign.add(editAssignment);
addAssignment.addActionListener(this);
removeAssignment.addActionListener(this);
editAssignment.addActionListener(this);
JLabel eventAssignLabel = new JLabel("List of Assignments:");
eventAssign.removeAll();
eventAssign.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
JScrollPane scroll = new JScrollPane();
scroll.setMinimumSize(new Dimension(260, 220));
scroll.setPreferredSize(new Dimension(276, 152));
scroll.setViewportView(eventAssign);
/* TODO: TO HERE */
int Eindex = -1;
String selectedID = "";
if (option.equals("OK")) {
ListOf e = bioModel.getSBMLDocument().getModel().getListOfEvents();
for (int i = 0; i < bioModel.getSBMLDocument().getModel().getNumEvents(); i++) {
org.sbml.libsbml.Event event = (org.sbml.libsbml.Event) e.get(i);
if (event.getId().equals(selected)) {
isTransition = SBMLutilities.isTransition(event);
if (isTransition) {
evPanel.setLayout(new GridLayout(8, 2));
}
Eindex = i;
eventID.setText(event.getId());
selectedID = event.getId();
eventName.setText(event.getName());
String trigger = SBMLutilities.myFormulaToString(event.getTrigger().getMath());
ASTNode triggerMath = event.getTrigger().getMath();
for (int j = 0; j < bioModel.getSBMLDocument().getModel().getNumParameters(); j++) {
Parameter parameter = bioModel.getSBMLDocument().getModel().getParameter(j);
if (parameter!=null && SBMLutilities.isPlace(parameter)) {
if (!isTextual && (trigger.contains("eq("+parameter.getId()+", 1)")||
trigger.contains("("+parameter.getId()+" == 1)"))) {
triggerMath = SBMLutilities.removePreset(triggerMath, parameter.getId());
presetPlaces.add(parameter.getId());
}
}
}
eventTrigger.setText(bioModel.removeBooleans(triggerMath));
String dynamic = AnnotationUtility.parseDynamicAnnotation(event);
if (dynamic!=null) {
dynamicProcess.setSelectedItem(dynamic);
}
if (event.isSetDelay() && event.getDelay().isSetMath()) {
ASTNode delay = event.getDelay().getMath();
if ((delay.getType() == libsbml.AST_FUNCTION) && (delay.getName().equals("priority"))) {
eventDelay.setText(SBMLutilities.myFormulaToString(delay.getLeftChild()));
eventPriority.setText(SBMLutilities.myFormulaToString(delay.getRightChild()));
}
else {
eventDelay.setText(bioModel.removeBooleans(delay));
}
}
if (event.getUseValuesFromTriggerTime()) {
assignTime.setSelected(true);
}
if (AnnotationUtility.checkObsoleteAnnotation(event.getTrigger(),"<TriggerCanBeDisabled/>")) {
persistentTrigger.setSelected(false);
}
else {
persistentTrigger.setSelected(true);
}
if (AnnotationUtility.checkObsoleteAnnotation(event.getTrigger(),"<TriggerInitiallyFalse/>")) {
initialTrigger.setSelected(false);
}
else {
initialTrigger.setSelected(true);
}
if (event.isSetPriority()) {
eventPriority.setText(bioModel.removeBooleans(event.getPriority().getMath()));
}
if (event.getTrigger().isSetPersistent()) {
persistentTrigger.setSelected(event.getTrigger().getPersistent());
if (isTransition) {
Rule r = bioModel.getSBMLDocument().getModel().getRule(GlobalConstants.TRIGGER + "_" + event.getId());
if (r != null) {
persistentTrigger.setSelected(true);
triggerMath = r.getMath();
if (triggerMath.getType()==libsbml.AST_FUNCTION_PIECEWISE && triggerMath.getNumChildren() > 2) {
triggerMath = triggerMath.getChild(1);
if (triggerMath.getType()==libsbml.AST_LOGICAL_OR) {
triggerMath = triggerMath.getLeftChild();
trigger = SBMLutilities.myFormulaToString(triggerMath);
for (int j = 0; j < bioModel.getSBMLDocument().getModel().getNumParameters(); j++) {
Parameter parameter = bioModel.getSBMLDocument().getModel().getParameter(j);
if (parameter!=null && SBMLutilities.isPlace(parameter)) {
if (!isTextual && (trigger.contains("eq("+parameter.getId()+", 1)")||
trigger.contains("("+parameter.getId()+" == 1)"))) {
triggerMath = SBMLutilities.removePreset(triggerMath, parameter.getId());
//presetPlaces.add(parameter.getId());
}
}
}
eventTrigger.setText(bioModel.removeBooleans(triggerMath));
}
}
}
} else {
persistentTrigger.setSelected(false);
}
}
if (event.getTrigger().isSetInitialValue()) {
initialTrigger.setSelected(event.getTrigger().getInitialValue());
}
if (bioModel.getPortByIdRef(event.getId())!=null) {
onPort.setSelected(true);
} else {
onPort.setSelected(false);
}
int numPlaces=0;
int numFail=0;
for (int j = 0; j < event.getNumEventAssignments(); j++) {
EventAssignment ea = event.getEventAssignment(j);
Parameter parameter = bioModel.getSBMLDocument().getModel().getParameter(ea.getVariable());
if (parameter!=null && SBMLutilities.isPlace(parameter)) {
numPlaces++;
} else if (ea.getVariable().equals(GlobalConstants.FAIL)) {
numFail++;
}
}
if (isTextual) {
assign = new String[(int) event.getNumEventAssignments()-(numFail)];
} else {
assign = new String[(int) event.getNumEventAssignments()-(numPlaces+numFail)];
}
if (isTextual) {
placeAssign = new String[0];
} else {
placeAssign = new String[numPlaces];
}
origAssign = new String[(int) event.getNumEventAssignments()];
int k=0;
int l=0;
for (int j = 0; j < event.getNumEventAssignments(); j++) {
Parameter parameter =
bioModel.getSBMLDocument().getModel().getParameter(event.getEventAssignment(j).getVariable());
EventAssignment ea = event.getEventAssignment(j);
if (parameter!=null && SBMLutilities.isPlace(parameter)) {
if (isTextual) {
assign[l] = ea.getVariable() + " := " + SBMLutilities.myFormulaToString(ea.getMath());
l++;
} else {
placeAssign[k] = ea.getVariable() + " := " + SBMLutilities.myFormulaToString(ea.getMath());
k++;
}
} else if (ea.getVariable().equals(GlobalConstants.FAIL)){
failTransition.setSelected(true);
} else {
String assignMath = SBMLutilities.myFormulaToString(ea.getMath());
if (parameter!=null && SBMLutilities.isBoolean(parameter)) {
assignMath = bioModel.removeBooleanAssign(event.getEventAssignment(j).getMath());
}
assign[l] = ea.getVariable() + " := " + assignMath;
l++;
}
origAssign[j] = ea.getVariable() + " := " + SBMLutilities.myFormulaToString(ea.getMath());
}
}
}
}
else {
String eventId = "event0";
if (isTransition) eventId = "t0";
int en = 0;
while (bioModel.isSIdInUse(eventId)) {
en++;
if (isTransition) eventId = "t" + en;
else eventId = "event" + en;
}
eventID.setText(eventId);
}
/* TODO: NEED THIS STUFF */
Utility.sort(assign);
eventAssign.setListData(assign);
eventAssign.setSelectedIndex(0);
eventAssign.addMouseListener(this);
eventAssignPanel.add(eventAssignLabel, "North");
eventAssignPanel.add(scroll, "Center");
eventAssignPanel.add(addEventAssign, "South");
/* TODO: TO HERE */
evPanel.add(IDLabel);
evPanel.add(eventID);
evPanel.add(NameLabel);
evPanel.add(eventName);
evPanel.add(triggerLabel);
evPanel.add(eventTrigger);
evPanel.add(delayLabel);
evPanel.add(eventDelay);
evPanel.add(priorityLabel);
evPanel.add(eventPriority);
if (!isTransition) {
evPanel.add(assignTimeLabel);
evPanel.add(assignTime);
}
evPanel.add(persistentTriggerLabel);
evPanel.add(persistentTrigger);
if (!isTransition) {
evPanel.add(initialTriggerLabel);
evPanel.add(initialTrigger);
evPanel.add(dynamicProcessLabel);
evPanel.add(dynamicProcess);
} else {
evPanel.add(failTransitionLabel);
evPanel.add(failTransition);
}
evPanel.add(onPortLabel);
evPanel.add(onPort);
eventPanel.add(evPanel, "North");
/* TODO: NEED TO ADD OBJECTIVES TO PANEL */
eventPanel.add(eventAssignPanel, "South");
Object[] options = { option, "Cancel" };
String title = "Event Editor";
if (isTransition) {
title = "Transition Editor";
}
int value = JOptionPane.showOptionDialog(Gui.frame, eventPanel, title, JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null,
options, options[0]);
boolean error = true;
while (error && value == JOptionPane.YES_OPTION) {
/* TODO: TO HERE */
assign = new String[eventAssign.getModel().getSize()];
for (int i = 0; i < eventAssign.getModel().getSize(); i++) {
assign[i] = eventAssign.getModel().getElementAt(i).toString();
}
error = SBMLutilities.checkID(bioModel.getSBMLDocument(), eventID.getText().trim(), selectedID, false, false);
if (eventTrigger.getText().trim().equals("")) {
JOptionPane.showMessageDialog(Gui.frame, "Event must have a trigger formula.", "Enter Trigger Formula", JOptionPane.ERROR_MESSAGE);
error = true;
}
else if (SBMLutilities.myParseFormula(eventTrigger.getText().trim()) == null) {
JOptionPane.showMessageDialog(Gui.frame, "Trigger formula is not valid.", "Enter Valid Formula", JOptionPane.ERROR_MESSAGE);
error = true;
}
else if (!bioModel.addBooleans(eventTrigger.getText().trim()).returnsBoolean(bioModel.getSBMLDocument().getModel())) {
JOptionPane.showMessageDialog(Gui.frame, "Trigger formula must be of type Boolean.",
"Enter Valid Formula", JOptionPane.ERROR_MESSAGE);
error = true;
}
else if (!eventDelay.getText().trim().equals("") && SBMLutilities.myParseFormula(eventDelay.getText().trim()) == null) {
JOptionPane.showMessageDialog(Gui.frame, "Delay formula is not valid.", "Enter Valid Formula", JOptionPane.ERROR_MESSAGE);
error = true;
}
else if (!eventPriority.getText().trim().equals("") && SBMLutilities.myParseFormula(eventPriority.getText().trim()) == null) {
JOptionPane.showMessageDialog(Gui.frame, "Priority formula is not valid.", "Enter Valid Formula", JOptionPane.ERROR_MESSAGE);
error = true;
}
else if (bioModel.getSBMLDocument().getLevel() < 3 && assign.length == 0) {
JOptionPane.showMessageDialog(Gui.frame, "Event must have at least one event assignment.", "Event Assignment Needed",
JOptionPane.ERROR_MESSAGE);
error = true;
}
else {
ArrayList<String> invalidVars = SBMLutilities.getInvalidVariables(bioModel.getSBMLDocument(), eventTrigger.getText().trim(), "", false);
if (invalidVars.size() > 0) {
String invalid = "";
for (int i = 0; i < invalidVars.size(); i++) {
if (i == invalidVars.size() - 1) {
invalid += invalidVars.get(i);
}
else {
invalid += invalidVars.get(i) + "\n";
}
}
String message;
message = "Event trigger contains unknown variables.\n\n" + "Unknown variables:\n" + invalid;
JTextArea messageArea = new JTextArea(message);
messageArea.setLineWrap(true);
messageArea.setWrapStyleWord(true);
messageArea.setEditable(false);
JScrollPane scrolls = new JScrollPane();
scrolls.setMinimumSize(new Dimension(300, 300));
scrolls.setPreferredSize(new Dimension(300, 300));
scrolls.setViewportView(messageArea);
JOptionPane.showMessageDialog(Gui.frame, scrolls, "Unknown Variables", JOptionPane.ERROR_MESSAGE);
error = true;
}
if (!error) {
invalidVars = SBMLutilities.getInvalidVariables(bioModel.getSBMLDocument(), eventDelay.getText().trim(), "", false);
if (invalidVars.size() > 0) {
String invalid = "";
for (int i = 0; i < invalidVars.size(); i++) {
if (i == invalidVars.size() - 1) {
invalid += invalidVars.get(i);
}
else {
invalid += invalidVars.get(i) + "\n";
}
}
String message;
message = "Event delay contains unknown variables.\n\n" + "Unknown variables:\n" + invalid;
JTextArea messageArea = new JTextArea(message);
messageArea.setLineWrap(true);
messageArea.setWrapStyleWord(true);
messageArea.setEditable(false);
JScrollPane scrolls = new JScrollPane();
scrolls.setMinimumSize(new Dimension(300, 300));
scrolls.setPreferredSize(new Dimension(300, 300));
scrolls.setViewportView(messageArea);
JOptionPane.showMessageDialog(Gui.frame, scrolls, "Unknown Variables", JOptionPane.ERROR_MESSAGE);
error = true;
}
}
if (!error) {
invalidVars = SBMLutilities.getInvalidVariables(bioModel.getSBMLDocument(), eventPriority.getText().trim(), "", false);
if (invalidVars.size() > 0) {
String invalid = "";
for (int i = 0; i < invalidVars.size(); i++) {
if (i == invalidVars.size() - 1) {
invalid += invalidVars.get(i);
}
else {
invalid += invalidVars.get(i) + "\n";
}
}
String message;
message = "Event priority contains unknown variables.\n\n" + "Unknown variables:\n" + invalid;
JTextArea messageArea = new JTextArea(message);
messageArea.setLineWrap(true);
messageArea.setWrapStyleWord(true);
messageArea.setEditable(false);
JScrollPane scrolls = new JScrollPane();
scrolls.setMinimumSize(new Dimension(300, 300));
scrolls.setPreferredSize(new Dimension(300, 300));
scrolls.setViewportView(messageArea);
JOptionPane.showMessageDialog(Gui.frame, scrolls, "Unknown Variables", JOptionPane.ERROR_MESSAGE);
error = true;
}
}
if (!error) {
error = SBMLutilities.checkNumFunctionArguments(bioModel.getSBMLDocument(),
bioModel.addBooleans(eventTrigger.getText().trim()));
}
if ((!error) && (!eventDelay.getText().trim().equals(""))) {
error = SBMLutilities.checkNumFunctionArguments(bioModel.getSBMLDocument(),
bioModel.addBooleans(eventDelay.getText().trim()));
if (!error) {
if (bioModel.addBooleans(eventDelay.getText().trim()).returnsBoolean(bioModel.getSBMLDocument().getModel())) {
JOptionPane.showMessageDialog(Gui.frame, "Event delay must evaluate to a number.", "Number Expected",
JOptionPane.ERROR_MESSAGE);
error = true;
}
}
}
if ((!error) && (!eventPriority.getText().trim().equals(""))) {
error = SBMLutilities.checkNumFunctionArguments(bioModel.getSBMLDocument(),
bioModel.addBooleans(eventPriority.getText().trim()));
if (!error) {
if (bioModel.addBooleans(eventPriority.getText().trim()).returnsBoolean(bioModel.getSBMLDocument().getModel())) {
JOptionPane.showMessageDialog(Gui.frame, "Event priority must evaluate to a number.", "Number Expected",
JOptionPane.ERROR_MESSAGE);
error = true;
}
}
}
}
if (!error) {
//edit event
if (option.equals("OK")) {
events.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
String[] ev = new String[events.getModel().getSize()];
for (int i = 0; i < events.getModel().getSize(); i++) {
ev[i] = events.getModel().getElementAt(i).toString();
}
events.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
org.sbml.libsbml.Event e = (org.sbml.libsbml.Event) (bioModel.getSBMLDocument().getModel().getListOfEvents()).get(Eindex);
e.setUseValuesFromTriggerTime(assignTime.isSelected());
while (e.getNumEventAssignments() > 0) {
e.getListOfEventAssignments().remove(0);
}
for (int i = 0; i < assign.length; i++) {
EventAssignment ea = e.createEventAssignment();
String var = assign[i].split(" ")[0];
ea.setVariable(var);
Parameter p = bioModel.getSBMLDocument().getModel().getParameter(var);
if (p != null && SBMLutilities.isBoolean(p)) {
ea.setMath(bioModel.addBooleanAssign(assign[i].split(":=")[1].trim()));
} else {
ea.setMath(SBMLutilities.myParseFormula(assign[i].split(":=")[1].trim()));
}
if (p == null && var.endsWith("_"+GlobalConstants.RATE)) {
p = bioModel.getSBMLDocument().getModel().createParameter();
p.setId(var);
p.setConstant(false);
p.setValue(0);
RateRule r = bioModel.getSBMLDocument().getModel().createRateRule();
r.setMetaId(GlobalConstants.RULE+"_" + var);
r.setVariable(var.replace("_" + GlobalConstants.RATE,""));
r.setMath(SBMLutilities.myParseFormula(var));
}
error = checkEventAssignmentUnits(ea);
if (error) break;
}
for (int i = 0; i < placeAssign.length; i++) {
EventAssignment ea = e.createEventAssignment();
ea.setVariable(placeAssign[i].split(" ")[0]);
ea.setMath(SBMLutilities.myParseFormula(placeAssign[i].split(":=")[1].trim()));
error = checkEventAssignmentUnits(ea);
if (error) break;
}
if (!error) {
if (eventDelay.getText().trim().equals("")) {
e.unsetDelay();
}
else {
String oldDelayStr = "";
if (e.isSetDelay()) {
oldDelayStr = SBMLutilities.myFormulaToString(e.getDelay().getMath());
}
e.createDelay();
e.getDelay().setMath(bioModel.addBooleans(eventDelay.getText().trim()));
error = checkEventDelayUnits(e.getDelay());
if (error) {
if (oldDelayStr.equals("")) {
e.unsetDelay();
}
else {
e.createDelay();
e.getDelay().setMath(SBMLutilities.myParseFormula(oldDelayStr));
}
}
}
}
if (!error) {
if (eventPriority.getText().trim().equals("")) {
e.unsetPriority();
}
else {
e.createPriority();
e.getPriority().setMath(bioModel.addBooleans(eventPriority.getText().trim()));
}
}
if (!error) {
e.createTrigger();
if (!persistentTrigger.isSelected()) {
e.getTrigger().setPersistent(false);
ASTNode triggerMath = bioModel.addBooleans(eventTrigger.getText().trim());
if (!isTextual) {
for (int j = 0; j < presetPlaces.size(); j++) {
triggerMath = SBMLutilities.addPreset(triggerMath, presetPlaces.get(j));
}
}
e.getTrigger().setMath(triggerMath);
if (isTransition) {
Rule r = bioModel.getSBMLDocument().getModel().getRule(GlobalConstants.TRIGGER + "_" + e.getId());
if (r != null) {
r.removeFromParentAndDelete();
}
Parameter p = bioModel.getSBMLDocument().getModel().getParameter(GlobalConstants.TRIGGER + "_" + e.getId());
if (p != null) {
p.removeFromParentAndDelete();
}
}
}
else {
if (isTransition) {
e.getTrigger().setPersistent(false);
ASTNode leftChild = bioModel.addBooleans(eventTrigger.getText().trim());
if (!isTextual) {
for (int j = 0; j < presetPlaces.size(); j++) {
leftChild = SBMLutilities.addPreset(leftChild, presetPlaces.get(j));
}
}
ASTNode rightChild = SBMLutilities.myParseFormula("eq(" + GlobalConstants.TRIGGER + "_" + e.getId() + ",1)");
if (!isTextual) {
for (int j = 0; j < presetPlaces.size(); j++) {
rightChild = SBMLutilities.addPreset(rightChild, presetPlaces.get(j));
}
}
ASTNode ruleMath = SBMLutilities.myParseFormula("piecewise(1,or(" + SBMLutilities.myFormulaToString(leftChild) + "," +
SBMLutilities.myFormulaToString(rightChild) + "),0)");
Parameter p = bioModel.getSBMLDocument().getModel().getParameter(GlobalConstants.TRIGGER + "_" + e.getId());
if (p == null) {
p = bioModel.getSBMLDocument().getModel().createParameter();
p.setId(GlobalConstants.TRIGGER + "_" + e.getId());
p.setConstant(false);
p.setValue(0);
}
Rule r = bioModel.getSBMLDocument().getModel().getRule(GlobalConstants.TRIGGER + "_" + e.getId());
if (r == null) {
r = bioModel.getSBMLDocument().getModel().createAssignmentRule();
r.setVariable(GlobalConstants.TRIGGER + "_" + e.getId());
}
r.setMetaId(GlobalConstants.TRIGGER + "_" + GlobalConstants.RULE+"_"+e.getId());
r.setMath(ruleMath);
ASTNode triggerMath = SBMLutilities.myParseFormula(GlobalConstants.TRIGGER + "_" + e.getId());
if (!isTextual) {
for (int j = 0; j < presetPlaces.size(); j++) {
triggerMath = SBMLutilities.addPreset(triggerMath, presetPlaces.get(j));
}
}
e.getTrigger().setMath(triggerMath);
} else {
e.getTrigger().setPersistent(true);
ASTNode triggerMath = bioModel.addBooleans(eventTrigger.getText().trim());
if (!isTextual) {
for (int j = 0; j < presetPlaces.size(); j++) {
triggerMath = SBMLutilities.addPreset(triggerMath, presetPlaces.get(j));
}
}
e.getTrigger().setMath(triggerMath);
}
}
if (!initialTrigger.isSelected()) {
e.getTrigger().setInitialValue(false);
}
else {
e.getTrigger().setInitialValue(true);
}
if (eventID.getText().trim().equals("")) {
e.unsetId();
}
else {
e.setId(eventID.getText().trim());
}
if (eventName.getText().trim().equals("")) {
e.unsetName();
}
else {
e.setName(eventName.getText().trim());
}
if (failTransition.isSelected()) {
Parameter p = bioModel.getSBMLDocument().getModel().getParameter(GlobalConstants.FAIL);
if (p==null) {
p = bioModel.getSBMLDocument().getModel().createParameter();
p.setId(GlobalConstants.FAIL);
p.setSBOTerm(GlobalConstants.SBO_BOOLEAN);
p.setConstant(false);
p.setValue(0);
Constraint c = bioModel.getSBMLDocument().getModel().createConstraint();
c.setMetaId(GlobalConstants.FAIL_TRANSITION);
SBMLutilities.createFunction(bioModel.getSBMLDocument().getModel(), "G", "Globally Property",
"lambda(t,x,or(not(t),x))");
c.setMath(SBMLutilities.myParseFormula("G(true,!(eq(fail,1)))"));
}
EventAssignment ea = e.getEventAssignment(GlobalConstants.FAIL);
if (ea==null) {
ea = e.createEventAssignment();
ea.setVariable(GlobalConstants.FAIL);
ea.setMath(SBMLutilities.myParseFormula("piecewise(1,true,0)"));
}
} else {
EventAssignment ea = e.getEventAssignment(GlobalConstants.FAIL);
if (ea != null) {
ea.removeFromParentAndDelete();
}
}
Port port = bioModel.getPortByIdRef(selectedID);
if (port!=null) {
if (onPort.isSelected()) {
port.setId(GlobalConstants.EVENT+"__"+e.getId());
port.setIdRef(e.getId());
} else {
port.removeFromParentAndDelete();
}
} else {
if (onPort.isSelected()) {
port = bioModel.getSBMLCompModel().createPort();
port.setId(GlobalConstants.EVENT+"__"+e.getId());
port.setIdRef(e.getId());
}
}
int index = events.getSelectedIndex();
ev[index] = e.getId();
Utility.sort(ev);
events.setListData(ev);
events.setSelectedIndex(index);
}
//edit dynamic process
if (!error) {
if (!((String)dynamicProcess.getSelectedItem()).equals("none")) {
AnnotationUtility.setDynamicAnnotation(e, (String)dynamicProcess.getSelectedItem());
}
else {
AnnotationUtility.removeDynamicAnnotation(e);
}
}
else {
while (e.getNumEventAssignments() > 0) {
e.getListOfEventAssignments().remove(0);
}
for (int i = 0; i < origAssign.length; i++) {
EventAssignment ea = e.createEventAssignment();
ea.setVariable(origAssign[i].split(" ")[0]);
ea.setMath(SBMLutilities.myParseFormula(origAssign[i].split(":=")[1].trim()));
}
}
} //end if option is "ok"
//add event
else {
JList add = new JList();
org.sbml.libsbml.Event e = bioModel.getSBMLDocument().getModel().createEvent();
if (isTransition) {
e.setSBOTerm(GlobalConstants.SBO_PETRI_NET_TRANSITION);
}
e.setUseValuesFromTriggerTime(assignTime.isSelected());
e.createTrigger();
if (!eventID.getText().trim().equals("")) {
e.setId(eventID.getText().trim());
}
if (!eventName.getText().trim().equals("")) {
e.setName(eventName.getText().trim());
}
if (!persistentTrigger.isSelected()) {
e.getTrigger().setPersistent(false);
e.getTrigger().setMath(bioModel.addBooleans(eventTrigger.getText().trim()));
}
else {
if (isTransition) {
e.getTrigger().setPersistent(false);
ASTNode leftChild = bioModel.addBooleans(eventTrigger.getText().trim());
if (!isTextual) {
for (int j = 0; j < presetPlaces.size(); j++) {
leftChild = SBMLutilities.addPreset(leftChild, presetPlaces.get(j));
}
}
ASTNode rightChild = SBMLutilities.myParseFormula("eq(" + GlobalConstants.TRIGGER + "_" + e.getId() + ",1)");
if (!isTextual) {
for (int j = 0; j < presetPlaces.size(); j++) {
rightChild = SBMLutilities.addPreset(rightChild, presetPlaces.get(j));
}
}
ASTNode ruleMath = SBMLutilities.myParseFormula("piecewise(1,or(" + SBMLutilities.myFormulaToString(leftChild) + "," +
SBMLutilities.myFormulaToString(rightChild) + "),0)");
Parameter p = bioModel.getSBMLDocument().getModel().getParameter(GlobalConstants.TRIGGER + "_" + e.getId());
if (p == null) {
p = bioModel.getSBMLDocument().getModel().createParameter();
p.setId(GlobalConstants.TRIGGER + "_" + e.getId());
p.setConstant(false);
p.setValue(0);
}
Rule r = bioModel.getSBMLDocument().getModel().getRule(GlobalConstants.TRIGGER + "_" + e.getId());
if (r == null) {
r = bioModel.getSBMLDocument().getModel().createAssignmentRule();
r.setVariable(GlobalConstants.TRIGGER + "_" + e.getId());
}
r.setMetaId(GlobalConstants.TRIGGER + "_" + GlobalConstants.RULE+"_"+e.getId());
r.setMath(ruleMath);
ASTNode triggerMath = SBMLutilities.myParseFormula(GlobalConstants.TRIGGER + "_" + e.getId());
if (!isTextual) {
for (int j = 0; j < presetPlaces.size(); j++) {
triggerMath = SBMLutilities.addPreset(triggerMath, presetPlaces.get(j));
}
}
e.getTrigger().setMath(triggerMath);
} else {
e.getTrigger().setPersistent(true);
e.getTrigger().setMath(bioModel.addBooleans(eventTrigger.getText().trim()));
}
}
if (!initialTrigger.isSelected()) {
e.getTrigger().setInitialValue(false);
}
else {
e.getTrigger().setInitialValue(true);
}
if (!eventPriority.getText().trim().equals("")) {
e.createPriority();
e.getPriority().setMath(bioModel.addBooleans(eventPriority.getText().trim()));
}
if (!eventDelay.getText().trim().equals("")) {
e.createDelay();
e.getDelay().setMath(bioModel.addBooleans(eventDelay.getText().trim()));
error = checkEventDelayUnits(e.getDelay());
}
if (!error) {
for (int i = 0; i < assign.length; i++) {
EventAssignment ea = e.createEventAssignment();
String var = assign[i].split(" ")[0];
if (var.endsWith("\'")) {
var = "rate_" + var.replace("\'","");
}
ea.setVariable(var);
Parameter p = bioModel.getSBMLDocument().getModel().getParameter(var);
if (p != null && SBMLutilities.isBoolean(p)) {
ea.setMath(bioModel.addBooleanAssign(assign[i].split(":=")[1].trim()));
} else {
ea.setMath(SBMLutilities.myParseFormula(assign[i].split(":=")[1].trim()));
}
if (p == null && var.endsWith("_" + GlobalConstants.RATE)) {
p = bioModel.getSBMLDocument().getModel().createParameter();
p.setId(var);
p.setConstant(false);
p.setValue(0);
RateRule r = bioModel.getSBMLDocument().getModel().createRateRule();
r.setMetaId(GlobalConstants.RULE+"_" + var);
r.setVariable(var.replace("_"+GlobalConstants.RATE,""));
r.setMath(SBMLutilities.myParseFormula(var));
}
error = checkEventAssignmentUnits(ea);
if (error)
break;
}
}
//add dynamic process
if (!error) {
if (!((String)dynamicProcess.getSelectedItem()).equals("none")) {
AnnotationUtility.setDynamicAnnotation(e, (String)dynamicProcess.getSelectedItem());
}
if (failTransition.isSelected()) {
Parameter p = bioModel.getSBMLDocument().getModel().getParameter(GlobalConstants.FAIL);
if (p==null) {
p = bioModel.getSBMLDocument().getModel().createParameter();
p.setId(GlobalConstants.FAIL);
p.setSBOTerm(GlobalConstants.SBO_BOOLEAN);
p.setConstant(false);
p.setValue(0);
Constraint c = bioModel.getSBMLDocument().getModel().createConstraint();
c.setMetaId(GlobalConstants.FAIL_TRANSITION);
SBMLutilities.createFunction(bioModel.getSBMLDocument().getModel(), "G", "Globally Property",
"lambda(t,x,or(not(t),x))");
c.setMath(SBMLutilities.myParseFormula("G(true,!(eq(fail,1)))"));
}
EventAssignment ea = e.getEventAssignment(GlobalConstants.FAIL);
if (ea==null) {
ea = e.createEventAssignment();
ea.setVariable(GlobalConstants.FAIL);
ea.setMath(SBMLutilities.myParseFormula("piecewise(1,true,0)"));
}
} else {
EventAssignment ea = e.getEventAssignment(GlobalConstants.FAIL);
if (ea != null) {
ea.removeFromParentAndDelete();
}
}
if (onPort.isSelected()) {
Port port = bioModel.getSBMLCompModel().createPort();
port.setId(GlobalConstants.EVENT+"__"+e.getId());
port.setIdRef(e.getId());
}
}
Object[] adding = { e.getId() };
// Object[] adding = {
// myFormulaToString(e.getTrigger().getMath()) };
add.setListData(adding);
add.setSelectedIndex(0);
events.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
String[] ev = new String[events.getModel().getSize()];
for (int i = 0; i < events.getModel().getSize(); i++) {
ev[i] = events.getModel().getElementAt(i).toString();
}
adding = Utility.add(ev, events, add, null, null, null, null, null, Gui.frame);
ev = new String[adding.length];
for (int i = 0; i < adding.length; i++) {
ev[i] = (String) adding[i];
}
Utility.sort(ev);
int index = events.getSelectedIndex();
events.setListData(ev);
events.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
if (bioModel.getSBMLDocument().getModel().getNumEvents() == 1) {
events.setSelectedIndex(0);
}
else {
events.setSelectedIndex(index);
}
if (error) {
removeTheEvent(bioModel, SBMLutilities.myFormulaToString(e.getTrigger().getMath()));
}
}
}
/* TODO: NEED THIS STUFF */
if (error) {
value = JOptionPane.showOptionDialog(Gui.frame, eventPanel, title, JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE,
null, options, options[0]);
}
}
if (value == JOptionPane.NO_OPTION) {
return selected;
}
modelEditor.setDirty(true);
bioModel.makeUndoPoint();
return eventID.getText().trim();
/* TODO: TO HERE */
}
/**
* Check the units of an event delay
*/
private boolean checkEventDelayUnits(Delay delay) {
bioModel.getSBMLDocument().getModel().populateListFormulaUnitsData();
if (delay.containsUndeclaredUnits()) {
if (biosim.getCheckUndeclared()) {
JOptionPane.showMessageDialog(Gui.frame, "Event assignment delay contains literals numbers or parameters with undeclared units.\n"
+ "Therefore, it is not possible to completely verify the consistency of the units.", "Contains Undeclared Units",
JOptionPane.WARNING_MESSAGE);
}
return false;
}
else if (biosim.getCheckUnits()) {
if (SBMLutilities.checkUnitsInEventDelay(bioModel.getSBMLDocument(), delay)) {
JOptionPane.showMessageDialog(Gui.frame, "Event delay should be units of time.", "Event Delay Not Time Units",
JOptionPane.ERROR_MESSAGE);
return true;
}
}
return false;
}
/**
* Check the units of an event assignment
*/
private boolean checkEventAssignmentUnits(EventAssignment assign) {
bioModel.getSBMLDocument().getModel().populateListFormulaUnitsData();
if (assign.containsUndeclaredUnits()) {
if (biosim.getCheckUndeclared()) {
JOptionPane.showMessageDialog(Gui.frame, "Event assignment to " + assign.getVariable()
+ " contains literals numbers or parameters with undeclared units.\n"
+ "Therefore, it is not possible to completely verify the consistency of the units.", "Contains Undeclared Units",
JOptionPane.WARNING_MESSAGE);
}
return false;
}
else if (biosim.getCheckUnits()) {
if (SBMLutilities.checkUnitsInEventAssignment(bioModel.getSBMLDocument(), assign)) {
JOptionPane.showMessageDialog(Gui.frame, "Units on the left and right-hand side for the event assignment " + assign.getVariable()
+ " do not agree.", "Units Do Not Match", JOptionPane.ERROR_MESSAGE);
return true;
}
}
return false;
}
/**
* Refresh events panel
*/
public void refreshEventsPanel() {
Model model = bioModel.getSBMLDocument().getModel();
ListOf listOfEvents = model.getListOfEvents();
String[] ev = new String[(int) model.getNumEvents()];
for (int i = 0; i < model.getNumEvents(); i++) {
org.sbml.libsbml.Event event = (org.sbml.libsbml.Event) listOfEvents.get(i);
if (!event.isSetId()) {
String eventId = "event0";
int en = 0;
while (bioModel.isSIdInUse(eventId)) {
en++;
eventId = "event" + en;
}
event.setId(eventId);
}
ev[i] = event.getId();
}
Utility.sort(ev);
events.setListData(ev);
events.setSelectedIndex(0);
}
/**
* Remove an event from a list and SBML gcm.getSBMLDocument()
*
* @param events
* a list of events
* @param gcm.getSBMLDocument()
* an SBML gcm.getSBMLDocument() from which to remove the event
* @param usedIDs
* a list of all IDs current in use
* @param ev
* an array of all events
*/
private void removeEvent(JList events, BioModel gcm) {
int index = events.getSelectedIndex();
if (index != -1) {
String selected = ((String) events.getSelectedValue());
removeTheEvent(gcm, selected);
events.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
Utility.remove(events);
events.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
if (index < events.getModel().getSize()) {
events.setSelectedIndex(index);
}
else {
events.setSelectedIndex(index - 1);
}
modelEditor.setDirty(true);
gcm.makeUndoPoint();
}
}
/**
* Remove an event from an SBML gcm.getSBMLDocument()
*
* @param gcm.getSBMLDocument()
* the SBML gcm.getSBMLDocument() from which to remove the event
* @param selected
* the event Id to remove
*/
public void removeTheEvent(BioModel gcm, String selected) {
ListOf EL = gcm.getSBMLDocument().getModel().getListOfEvents();
for (int i = 0; i < gcm.getSBMLDocument().getModel().getNumEvents(); i++) {
org.sbml.libsbml.Event E = (org.sbml.libsbml.Event) EL.get(i);
if (E.getId().equals(selected)) {
EL.remove(i);
}
}
for (long i = 0; i < gcm.getSBMLCompModel().getNumPorts(); i++) {
Port port = gcm.getSBMLCompModel().getPort(i);
if (port.isSetIdRef() && port.getIdRef().equals(selected)) {
gcm.getSBMLCompModel().removePort(i);
break;
}
}
if (gcm.getSBMLLayout().getLayout("iBioSim") != null) {
Layout layout = gcm.getSBMLLayout().getLayout("iBioSim");
if (layout.getAdditionalGraphicalObject(GlobalConstants.GLYPH+"__"+selected)!=null) {
layout.removeAdditionalGraphicalObject(GlobalConstants.GLYPH+"__"+selected);
}
if (layout.getTextGlyph(GlobalConstants.TEXT_GLYPH+"__"+selected) != null) {
layout.removeTextGlyph(GlobalConstants.TEXT_GLYPH+"__"+selected);
}
}
}
/**
* Creates a frame used to edit event assignments or create new ones.
*
*/
/* TODO: EVENT ASSIGNMENT EDITOR */
private void eventAssignEditor(BioModel gcm, JList eventAssign, String option) {
if (option.equals("OK") && eventAssign.getSelectedIndex() == -1) {
JOptionPane.showMessageDialog(Gui.frame, "No event assignment selected.", "Must Select an Event Assignment", JOptionPane.ERROR_MESSAGE);
return;
}
/* TODO: BUILD YOUR OBJECTIVE PANEL HERE */
JPanel eventAssignPanel = new JPanel();
JPanel EAPanel = new JPanel();
JLabel idLabel = new JLabel("Variable:");
JLabel eqnLabel = new JLabel("Assignment:");
JComboBox eaID = new JComboBox();
String selected;
/* TODO: TO HERE */
String[] assign = new String[eventAssign.getModel().getSize()];
for (int i = 0; i < eventAssign.getModel().getSize(); i++) {
assign[i] = eventAssign.getModel().getElementAt(i).toString();
}
if (option.equals("OK")) {
selected = ((String) eventAssign.getSelectedValue()).split(" ")[0];
}
else {
selected = "";
}
Model model = gcm.getSBMLDocument().getModel();
ListOf ids = model.getListOfCompartments();
for (int i = 0; i < model.getNumCompartments(); i++) {
String id = ((Compartment) ids.get(i)).getId();
if (!((Compartment) ids.get(i)).getConstant()) {
if (keepVarEvent(gcm, assign, selected, id)) {
eaID.addItem(id);
}
}
}
for (int i = 0; i < model.getNumParameters(); i++) {
Parameter p = model.getParameter(i);
if ((!isTextual && SBMLutilities.isPlace(p))||p.getId().endsWith("_"+GlobalConstants.RATE)) continue;
String id = p.getId();
if (!p.getConstant()) {
if (keepVarEvent(gcm, assign, selected, id)) {
eaID.addItem(id);
}
if (!SBMLutilities.isBoolean(p) && !SBMLutilities.isPlace(p)) {
if (keepVarEvent(gcm, assign, selected, id+"_"+GlobalConstants.RATE)) {
eaID.addItem(id+"_"+GlobalConstants.RATE);
}
}
}
}
ids = model.getListOfSpecies();
for (int i = 0; i < model.getNumSpecies(); i++) {
String id = ((Species) ids.get(i)).getId();
if (!((Species) ids.get(i)).getConstant()) {
if (keepVarEvent(gcm, assign, selected, id)) {
eaID.addItem(id);
}
}
}
ids = model.getListOfReactions();
for (int i = 0; i < model.getNumReactions(); i++) {
Reaction reaction = (Reaction) ids.get(i);
ListOf ids2 = reaction.getListOfReactants();
for (int j = 0; j < reaction.getNumReactants(); j++) {
SpeciesReference reactant = (SpeciesReference) ids2.get(j);
if ((reactant.isSetId()) && (!reactant.getId().equals("")) && !(reactant.getConstant())) {
String id = reactant.getId();
if (keepVarEvent(gcm, assign, selected, id)) {
eaID.addItem(id);
}
}
}
ids2 = reaction.getListOfProducts();
for (int j = 0; j < reaction.getNumProducts(); j++) {
SpeciesReference product = (SpeciesReference) ids2.get(j);
if ((product.isSetId()) && (!product.getId().equals("")) && !(product.getConstant())) {
String id = product.getId();
if (keepVarEvent(gcm, assign, selected, id)) {
eaID.addItem(id);
}
}
}
}
JTextField eqn = new JTextField(30);
if (option.equals("OK")) {
String selectAssign = ((String) eventAssign.getSelectedValue());
eaID.setSelectedItem(selectAssign.split(" ")[0]);
eqn.setText(selectAssign.split(":=")[1].trim());
}
/* TODO: BUILD PANEL */
EAPanel.add(idLabel);
EAPanel.add(eaID);
EAPanel.add(eqnLabel);
EAPanel.add(eqn);
eventAssignPanel.add(EAPanel);
Object[] options = { option, "Cancel" };
int value = JOptionPane.showOptionDialog(Gui.frame, eventAssignPanel, "Event Asssignment Editor", JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
boolean error = true;
while (error && value == JOptionPane.YES_OPTION) {
error = false;
/* TODO: TO HERE */
if (eqn.getText().trim().equals("")) {
JOptionPane.showMessageDialog(Gui.frame, "Event assignment is missing.", "Enter Assignment", JOptionPane.ERROR_MESSAGE);
error = true;
}
else if (SBMLutilities.myParseFormula(eqn.getText().trim()) == null) {
JOptionPane.showMessageDialog(Gui.frame, "Event assignment is not valid.", "Enter Valid Assignment", JOptionPane.ERROR_MESSAGE);
error = true;
}
else {
ArrayList<String> invalidVars = SBMLutilities.getInvalidVariables(gcm.getSBMLDocument(), eqn.getText().trim(), "", false);
if (invalidVars.size() > 0) {
String invalid = "";
for (int i = 0; i < invalidVars.size(); i++) {
if (i == invalidVars.size() - 1) {
invalid += invalidVars.get(i);
}
else {
invalid += invalidVars.get(i) + "\n";
}
}
String message;
message = "Event assignment contains unknown variables.\n\n" + "Unknown variables:\n" + invalid;
JTextArea messageArea = new JTextArea(message);
messageArea.setLineWrap(true);
messageArea.setWrapStyleWord(true);
messageArea.setEditable(false);
JScrollPane scrolls = new JScrollPane();
scrolls.setMinimumSize(new Dimension(300, 300));
scrolls.setPreferredSize(new Dimension(300, 300));
scrolls.setViewportView(messageArea);
JOptionPane.showMessageDialog(Gui.frame, scrolls, "Unknown Variables", JOptionPane.ERROR_MESSAGE);
error = true;
}
if (!error) {
Parameter p = bioModel.getSBMLDocument().getModel().getParameter((String)eaID.getSelectedItem());
ASTNode assignMath = SBMLutilities.myParseFormula(eqn.getText().trim());
if (p != null && SBMLutilities.isBoolean(p)) {
assignMath = bioModel.addBooleanAssign(eqn.getText().trim());
}
error = SBMLutilities.checkNumFunctionArguments(gcm.getSBMLDocument(), assignMath);
if (!error) {
if (p != null && SBMLutilities.isBoolean(p)) {
if (!SBMLutilities.myParseFormula(eqn.getText().trim()).returnsBoolean(bioModel.getSBMLDocument().getModel())) {
JOptionPane.showMessageDialog(Gui.frame, "Event assignment must evaluate to a Boolean.", "Boolean Expected",
JOptionPane.ERROR_MESSAGE);
error = true;
}
} else {
if (SBMLutilities.myParseFormula(eqn.getText().trim()).returnsBoolean(bioModel.getSBMLDocument().getModel())) {
JOptionPane.showMessageDialog(Gui.frame, "Event assignment must evaluate to a number.", "Number Expected",
JOptionPane.ERROR_MESSAGE);
error = true;
}
}
}
}
}
/* TODO: THIS PART TO ACTUALLY PUT THE STUFF BACK ON THE FIRST PANEL */
if (!error) {
if (option.equals("OK")) {
int index = eventAssign.getSelectedIndex();
eventAssign.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
assign = Utility.getList(assign, eventAssign);
eventAssign.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
assign[index] = eaID.getSelectedItem() + " := " + eqn.getText().trim();
Utility.sort(assign);
eventAssign.setListData(assign);
eventAssign.setSelectedIndex(index);
}
else {
JList add = new JList();
int index = eventAssign.getSelectedIndex();
Object[] adding = { eaID.getSelectedItem() + " := " + eqn.getText().trim() };
add.setListData(adding);
add.setSelectedIndex(0);
eventAssign.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
adding = Utility.add(assign, eventAssign, add, null, null, null, null, null, Gui.frame);
assign = new String[adding.length];
for (int i = 0; i < adding.length; i++) {
assign[i] = (String) adding[i];
}
Utility.sort(assign);
eventAssign.setListData(assign);
eventAssign.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
if (adding.length == 1) {
eventAssign.setSelectedIndex(0);
}
else {
eventAssign.setSelectedIndex(index);
}
}
}
if (error) {
value = JOptionPane.showOptionDialog(Gui.frame, eventAssignPanel, "Event Assignment Editor", JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
}
}
if (value == JOptionPane.NO_OPTION) {
return;
}
}
/* TODO: TO HERE */
/**
* Determines if a variable is already used in assignment rule or another
* event assignment
*/
private boolean keepVarEvent(BioModel gcm, String[] assign, String selected, String id) {
if (!selected.equals(id)) {
for (int j = 0; j < assign.length; j++) {
if (id.equals(assign[j].split(" ")[0])) {
return false;
}
}
ListOf r = gcm.getSBMLDocument().getModel().getListOfRules();
for (int i = 0; i < gcm.getSBMLDocument().getModel().getNumRules(); i++) {
Rule rule = (Rule) r.get(i);
if (rule.isAssignment() && rule.getVariable().equals(id))
return false;
}
}
return true;
}
/**
* Remove an event assignment
*
* @param eventAssign
* Jlist of event assignments for selected event
* @param assign
* String array of event assignments for selected event
*/
/* TODO: remove objective */
private void removeAssignment(JList eventAssign) {
int index = eventAssign.getSelectedIndex();
if (index != -1) {
eventAssign.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
Utility.remove(eventAssign);
eventAssign.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
if (index < eventAssign.getModel().getSize()) {
eventAssign.setSelectedIndex(index);
}
else {
eventAssign.setSelectedIndex(index - 1);
}
}
}
/* TODO: NEED ALL THE FUNCTIONS BELOW */
public void actionPerformed(ActionEvent e) {
// if the add event button is clicked
if (e.getSource() == addEvent) {
eventEditor("Add","",false);
}else if (e.getSource() == addTrans) {
eventEditor("Add","",true);
}
// if the edit event button is clicked
else if (e.getSource() == editEvent) {
if (events.getSelectedIndex() == -1) {
JOptionPane.showMessageDialog(Gui.frame, "No event selected.", "Must Select an Event", JOptionPane.ERROR_MESSAGE);
return;
}
String selected = ((String) events.getSelectedValue());
eventEditor("OK",selected,false);
}
// if the remove event button is clicked
else if (e.getSource() == removeEvent) {
removeEvent(events, bioModel);
}
/* TODO: ONLY NEED THE PART BELOW HERE */
// if the add event assignment button is clicked
else if (((JButton) e.getSource()).getText().equals("Add Assignment")) {
eventAssignEditor(bioModel, eventAssign, "Add");
}
// if the edit event assignment button is clicked
else if (((JButton) e.getSource()).getText().equals("Edit Assignment")) {
eventAssignEditor(bioModel, eventAssign, "OK");
}
// if the remove event assignment button is clicked
else if (((JButton) e.getSource()).getText().equals("Remove Assignment")) {
removeAssignment(eventAssign);
}
}
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
if (e.getSource() == events) {
if (events.getSelectedIndex() == -1) {
JOptionPane.showMessageDialog(Gui.frame, "No event selected.", "Must Select an Event", JOptionPane.ERROR_MESSAGE);
return;
}
String selected = ((String) events.getSelectedValue());
eventEditor("OK",selected,false);
}
else if (e.getSource() == eventAssign) {
eventAssignEditor(bioModel, eventAssign, "OK");
}
}
}
/**
* This method currently does nothing.
*/
public void mouseEntered(MouseEvent e) {
}
/**
* This method currently does nothing.
*/
public void mouseExited(MouseEvent e) {
}
/**
* This method currently does nothing.
*/
public void mousePressed(MouseEvent e) {
}
/**
* This method currently does nothing.
*/
public void mouseReleased(MouseEvent e) {
}
}
|
package br.com.dbsoft.util;
import java.sql.Connection;
import java.sql.Date;
import java.sql.Time;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.DateFormatSymbols;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.concurrent.TimeUnit;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
import org.apache.log4j.Logger;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.Days;
import org.joda.time.LocalDate;
import org.joda.time.LocalDateTime;
import org.joda.time.Seconds;
import br.com.dbsoft.core.DBSSDK;
import br.com.dbsoft.error.DBSIOException;
import br.com.dbsoft.io.DBSDAO;
public class DBSDate{
public enum PERIODICIDADE{
DIARIA ("Dia(s)","Diária", 1),
MENSAL ("Mês(es)", "Mensal", 2),
ANUAL ("Ano(s)", "Anual", 3),
IRREGULAR ("Irregular", "Irregular", 4),
EMISSAO ("Emissão", "Emissão", 5),
VENCIMENTO ("Vencimento", "Vencimento", 6);
public static PERIODICIDADE get(Object pCode) {
Integer xI = DBSNumber.toInteger(pCode, null);
return get(xI);
}
public static PERIODICIDADE get(Integer pCode) {
if (pCode == null){
return null;
}
switch (pCode) {
case 1:
return PERIODICIDADE.DIARIA;
case 2:
return PERIODICIDADE.MENSAL;
case 3:
return PERIODICIDADE.ANUAL;
case 4:
return PERIODICIDADE.IRREGULAR;
case 5:
return PERIODICIDADE.EMISSAO;
case 6:
return PERIODICIDADE.VENCIMENTO;
}
return null;
}
private String wName;
private String wName2;
private int wCode;
private PERIODICIDADE(String pName, String pName2, int pCode) {
this.wName = pName;
this.wName2 = pName2;
this.wCode = pCode;
}
public String getName() {
return wName;
}
public String getName2() {
return wName2;
}
public int getCode() {
return wCode;
}
}
public enum BASE{
PADRAO,
D_MENOS_UM,
PRIMEIRO_DIA_DO_MES,
PRIMEIRO_DIA_DO_ANO,
PRIMEIRO_DIA_UTIL_DO_MES,
PRIMEIRO_DIA_UTIL_DO_ANO,
DIA_UTIL,
PRIMEIRO_DIA_DO_MES_ANTERIOR;
}
protected static Logger wLogger = Logger.getLogger(DBSDate.class);
//
//## Public Methods #
//
/**
* Retorna a data e hora de hoje.
* @return Hora de Hoje
*/
public static DateTime getNowDateTime() {
// return new org.joda.time.DateTime();
return org.joda.time.LocalDateTime.now().toDateTime();
}
public static Date getNowDate() {
return getNowDate(false);
}
public static Date getNowDate(boolean pIncludeTime) {
if (pIncludeTime){
try{
Calendar xCurrentTime = Calendar.getInstance();
return new Date((xCurrentTime.getTime()).getTime());
}catch(Exception e){
return null;
}
}else{
return toDate(org.joda.time.LocalDate.now().toDate());
}
}
/**
* Retorna a hora de hoje.
* @return Hora de Hoje
*/
public static Time getNowTime() {
Calendar xCurrentTime = Calendar.getInstance();
return new Time(xCurrentTime.getTimeInMillis());
}
/**
* Retorna a data e hora atual.
* @return Data e hora atual
*/
public static Timestamp getNowTimestamp() {
Calendar xCurrentTime = Calendar.getInstance();
return new Timestamp(xCurrentTime.getTimeInMillis());
}
/**
* Calcula a quantidade de segundos entre duas datas
* @param pTimeInicio Hora Inicio
* @param pTimeFim Hora Fim
* @return Quantidade de segundos
*/
public static int getTimeDif(DateTime pTimeInicio, DateTime pTimeFim){
if (pTimeInicio.equals(pTimeFim)){
return 0;
}
int xSeconds = Seconds.secondsBetween(pTimeInicio.toLocalDateTime(), pTimeFim.toLocalDateTime()).getSeconds();
return xSeconds;
}
public static boolean isDate(String pData) {
if (toDate(pData) != null){
return true;
}
return false;
}
public static boolean isTime(String pHora) {
DateFormat xFormat = new SimpleDateFormat("HH:mm:ss");
xFormat.setLenient(false);
try {
xFormat.parse(pHora);
return true;
} catch (ParseException e) {
//DBSError.showException(e);
return false;
}
}
public static Date toDate(String pDia, String pMes, String pAno) {
return toDate(pDia + "/" + pMes + "/"+ pAno);
}
public static Date toDate(int pDia, int pMes, int pAno) {
return toDate(pDia + "/" + pMes + "/"+ pAno);
}
public static Date toDate(String pData) {
if (pData == null){
return null;
}
DateFormat xFormat;
// Testa se existe '-' na data passada
if (pData.contains("-")){
// Data no formato ISO
xFormat = new SimpleDateFormat("yy-MM-dd");
}else{
// Data no formato ABNT
xFormat = new SimpleDateFormat("dd/MM/yy");
}
Date xDate = Date.valueOf("0001-01-01");
Long xDateTime = 0L;
xFormat.setLenient(false);
try {
xDateTime = xFormat.parse(pData).getTime();
xDate.setTime(xDateTime);
} catch (ParseException e) {
//DBSError.showException(e);
return null;
}
return xDate;
}
public static Date toDate(Long pMilliSeconds) {
if (DBSObject.isNull(pMilliSeconds)) {
return null;
}
Date xData = new Date(pMilliSeconds);
return xData;
}
/**
* Retorna uma Data do tipo Date, a partir de uma data do tipo Calendar.
* @param pData
* @return Data no tipo Date
*/
public static Date toDate(Calendar pData) {
if (DBSObject.isNull(pData)) {
return null;
}
return toDate(pData.getTimeInMillis());
}
/**
* Retorna uma Data do tipo Date, a partir de uma data do tipo Timestamp.
* @param pData
* @return Data no tipo Date
*/
public static Date toDate(Timestamp pData) {
if (DBSObject.isNull(pData)) {
return null;
}
return toDate(pData.getTime());
}
/**
* Retorna uma Data do tipo Date, a partir de uma data do tipo java.util.Date.
* @param pData
* @return Data no tipo Date
*/
public static Date toDate(java.util.Date pData) {
if (DBSObject.isNull(pData)) {
return null;
}
return toDate(pData.getTime());
}
/**
* Retorna uma Data do tipo Date, a partir de uma data do tipo Timestamp.
* @param pData
* @return Data no tipo Date
*/
public static Date toDate(Object pData) {
if (DBSObject.isEmpty(pData)) {
return null;
}
if (pData instanceof Timestamp) {
return toDate((Timestamp) pData);
} else if (pData instanceof String) {
return toDate((String) pData);
} else if (pData instanceof Time) {
return new Date(((Time) pData).getTime());
} else {
return (Date) pData;
}
}
/**
* Retorna uma Data do tipo Date, a partir de uma data do tipo LocalDate.
* @param pData
* @return Data no tipo Date
*/
public static Date toDate(LocalDate pData) {
java.util.Date xData0 = pData.toDate();
java.sql.Date xData = new java.sql.Date(xData0.getTime());
return xData;
}
/**
* Retorna uma Data do tipo Date, a partir de uma data do tipo DateTime
* @param pData
* @return Data no tipo Date
*/
public static Date toDate(DateTime pData) {
java.util.Date xData0 = pData.toDate();
java.sql.Date xData = new java.sql.Date(xData0.getTime());
return xData;
}
public static Date toDate(XMLGregorianCalendar pData) {
if (DBSObject.isEmpty(pData)) {
return null;
}
DateTime xDataTime = new DateTime(pData.getYear(), pData.getMonth(), pData.getDay(), pData.getHour(), pData.getMinute());
return DBSDate.toDate(xDataTime);
}
public static XMLGregorianCalendar toXMLGregorianCalendar(Object pDate){
return toXMLGregorianCalendar(toDate(pDate));
}
public static XMLGregorianCalendar toXMLGregorianCalendar(Date pDate){
GregorianCalendar gCalendar = new GregorianCalendar();
gCalendar.setTime(pDate);
XMLGregorianCalendar xmlCalendar = null;
try {
xmlCalendar = DatatypeFactory.newInstance().newXMLGregorianCalendar(gCalendar);
} catch (DatatypeConfigurationException ex) {
wLogger.error(ex);
}
return xmlCalendar;
}
/**
* Retorna a data e hora no tipo Date, a partir de uma string com data e hora.
* @param pData no formado dd/mm/aaaa hh:mm:ss
* @return Retorna a data formatada
*/
public static Date toDateDMYHMS(String pData) {
if (pData.contains("-")) {
// Data no formato ISO
return pvToDateLong(pData, "dd-MM-yyyy HH:mm:ss");
}else{
// Data no formato ABNT
return pvToDateLong(pData, "dd/MM/yyyy HH:mm:ss");
}
}
public static Date toDateYMDHMS(String pData) {
if (pData.contains("-")) {
// Data no formato ISO
return pvToDateLong(pData, "yyyy-MM-dd HH:mm:ss");
}else if(pData.contains("/")){
// Data no formato ABNT
return pvToDateLong(pData, "yyyy/MM/dd HH:mm:ss");
}else {
// Data no formato ABNT
return pvToDateLong(pData, "yyyyMMddHHmmss");
}
}
/**
* Parse de string para data.
* @param pValue String no formato YYYYMMDD.
* @return Date
*/
public static Date toDateYYYY_MM_DD(String pValue) {
Date xData = null;
String xAno = DBSString.getSubString(pValue, 1, 4);
String xMes = DBSString.getSubString(pValue, 6, 2);
String xDia = DBSString.getSubString(pValue, 9, 2);
xData = toDate(xDia, xMes, xAno);
return xData;
}
/**
* Parse de string para data.
* @param pValue String no formato YYYYMMDD.
* @return Date
*/
public static Date toDateYYYYMMDD(String pValue) {
Date xData = null;
String xAno = DBSString.getSubString(pValue, 1, 4);
String xMes = DBSString.getSubString(pValue, 5, 2);
String xDia = DBSString.getSubString(pValue, 7, 2);
xData = toDate(xDia, xMes, xAno);
return xData;
}
/**
* Parse de string para data.
* @param pValue String no formato YYMMDD.
* @return Date
*/
public static Date toDateYYMMDD(String pValue) {
Date xData = null;
String xAno = DBSString.getSubString(pValue, 1, 2);
String xMes = DBSString.getSubString(pValue, 3, 2);
String xDia = DBSString.getSubString(pValue, 5, 2);
xData = toDate(xDia, xMes, xAno);
return xData;
}
/**
* Retorna o Date no dia primeiro da Data no formato mes/ano (Ex.: mar/15, fev/15)
* @param pDate Data no formato mes/ano (Ex.: mar/15, fev/15)
* @return
*/
public static Date toDateMYY(String pDate) {
int xMes = getMonthNumberFromShortMonthName(DBSString.getSubString(pDate, 1, 3));
int xAno = DBSNumber.toInteger(DBSString.getSubString(pDate, 5, 2));
return toDate(01, xMes, xAno);
}
/**
* Retorna uma Data do tipo Timestamp, a partir de uma data do tipo Date.
* @param pData
* @return
*/
public static Timestamp toTimestamp(Date pData){
if (DBSObject.isEmpty(pData)) {
return null;
}
Timestamp xT = new Timestamp(pData.getTime());
return xT;
}
/**
* Retorna uma Data do tipo <b>Timestamp</b> a partir da quantidade de milisegundos.
* @param pMilliSeconds
* @return
*/
public static Timestamp toTimestamp(Long pMilliSeconds){
Timestamp xT = new Timestamp(toDateTime(pMilliSeconds).getMillis());
return xT;
}
/**
* Retorna uma Data do tipo <b>Timestamp</b> a partir da quantidade de milisegundos.
* @param pData
* @return
*/
public static Timestamp toTimestamp(Integer pMilliSeconds){
Timestamp xT = new Timestamp(toDateTime(pMilliSeconds.longValue()).getMillis());
return xT;
}
/**
* Retorna uma Data do tipo <b>Timestamp</b> a partir da hora.
* @param pData
* @return
*/
public static Timestamp toTimestamp(Time pTime){
Timestamp xT = new Timestamp(pTime.getTime());
return xT;
}
/**
* Retorna uma Data do tipo Timestamp, a partir de uma data do tipo Object.
* Se object for ""(vazio), retorna nulo.
* @param pData
* @return
*/
public static Timestamp toTimestamp(Object pData){
if (DBSObject.isEmpty(pData)) {
return null;
}
if (pData.equals("")){
return null;
}else if (pData instanceof Date){
return new Timestamp(((Date) pData).getTime());
} else if (pData instanceof Time) {
return new Timestamp(((Time) pData).getTime());
} else if (pData instanceof Timestamp) {
return (Timestamp) pData;
} else if (pData instanceof Integer) {
return new Timestamp((Integer) pData);
} else {
return (Timestamp) pData;
}
}
/**
* Retorna uma Data do tipo Timestamp, a partir de uma data do tipo String
* com o formato Ano(4)/Mes/Dia Hora:Minuto:Segundo
* @param pData
* @return
*/
public static Timestamp toTimestampYMDHMS(String pData){
Date xData = DBSDate.toDateYMDHMS(pData);
return DBSDate.toTimestamp(xData);
}
/**
* Retorna uma Data do tipo Timestamp, a partir de uma data do tipo String
* com o formato Dia/Mes/Ano(4) Hora:Minuto:Segundo
* @param pData
* @return
*/
public static Timestamp toTimestampDMYHMS(String pData){
Date xData = DBSDate.toDateDMYHMS(pData);
return DBSDate.toTimestamp(xData);
}
/**
* Retorna a hora a partir da string no formato HH:MM:SS
* @param pHora no formato HH:MM:SS (24hrs)
* @return hora
*/
public static Time toTime(String pHora){
DateFormat xFormat = new SimpleDateFormat("HH:mm:ss");
xFormat.setLenient(true);
Time xTime = Time.valueOf("0:0:0");
try {
xTime.setTime(xFormat.parse(pHora).getTime());
} catch (ParseException e) {
// throw e;
//DBSError.showException(e);
return null;
}
return xTime;
}
/**
* Retorna a hora a partir das strings de hora, minuto e segundo.
* @param pHora
* @param pMinuto
* @param pSegundo
* @return Hora
* @throws ParseException
*/
public static Time toTime(String pHora, String pMinuto, String pSegundo) {
DateFormat xFormat = new SimpleDateFormat("HH:mm:ss");
xFormat.setLenient(true);
Time xTime = Time.valueOf("0:0:0");
try {
xTime.setTime(xFormat.parse(pHora + ":" + pMinuto + ":" + pSegundo).getTime());
} catch (ParseException e) {
return null;
}
return xTime;
}
/**
* Retorna a hora a partir das strings de hora, minuto e segundo
* @param pHora
* @param pMinuto
* @param pSegundo
* @return Hora
* @throws ParseException
*/
public static Time toTime(Long pHora, Long pMinuto, Long pSegundo) {
return toTime(pHora.toString(),pMinuto.toString(), pSegundo.toString());
}
/**
* Retorna a hora a partir das strings de hora, minuto e segundo
* @param pHora
* @param pMinuto
* @param pSegundo
* @return Hora
* @throws ParseException
*/
public static Time toTime(Integer pHora, Integer pMinuto, Integer pSegundo) {
return toTime(pHora.toString(),pMinuto.toString(), pSegundo.toString());
}
/**
* Retorna a hora a partir da quantidade de milisegundos.
* @param pMilliseconds
* @return hora
*/
public static Time toTime(Long pMilliseconds){
return toTime(TimeUnit.MILLISECONDS.toHours(pMilliseconds),
TimeUnit.MILLISECONDS.toMinutes(pMilliseconds),
TimeUnit.MILLISECONDS.toSeconds(pMilliseconds));
}
/**
* Retorna a hora a partir do object.
* @param pMilliseconds
* @return hora
*/
public static Time toTime(Object pObject){
if (DBSObject.isEmpty(pObject)) {
return null;
}
if (pObject instanceof Time){
return (Time) pObject;
}else if (pObject instanceof Date){
return toTime((Date) pObject);
} else if (pObject instanceof Timestamp) {
return toTime((Timestamp) pObject);
} else if (pObject instanceof Number){
return toTime((Long) pObject);
} else {
return (Time) pObject;
}
}
/**
* Retorna a hora a partir da quantidade de timestamp.
* @param pMilliseconds
* @return hora
*/
public static Time toTime(Timestamp pTimestamp){
Calendar xC = toCalendar(pTimestamp);
return toTime(xC.get(Calendar.HOUR_OF_DAY), xC.get(Calendar.MINUTE), xC.get(Calendar.SECOND));
}
/**
* Retorna a hora a partir da data.
* @param pMilliseconds
* @return hora
*/
public static Time toTime(Date pDate){
Calendar xC = toCalendar(pDate);
return toTime(xC.get(Calendar.HOUR_OF_DAY), xC.get(Calendar.MINUTE), xC.get(Calendar.SECOND));
}
/**
* Retornar data no tipo Calender a partir de data no tipo Date
* @param pData do tipo Date que se seja converte
* @return Data convertida para o tipo Calendar
*/
public static Calendar toCalendar(Date pData){
if (pData == null){
return null;
}
Calendar xData = Calendar.getInstance();
xData.setTime(pData);
return xData;
}
/**
* Retornar data no tipo Calender a partir de data no tipo Timestamp
* @param pTime do tipo Date que se seja converte
* @return Data convertida para o tipo Calendar
*/
public static Calendar toCalendar(Timestamp pTime){
if (pTime == null){
return null;
}
Calendar xData = Calendar.getInstance();
xData.setTime(pTime);
return xData;
}
/**
* Retornar data no tipo Calendar, a partir do dia, mes e ano informado
* @param pDia
* @param pMes
* @param pAno
* @return Data no formato Calendar
*/
public static Calendar toCalendar(int pDia, int pMes, int pAno) {
Calendar xC = Calendar.getInstance();
xC.set(pAno, pMes, pDia);
return xC;
}
/**
* Retornar data no tipo Calendar, a partir da quantidade de milisegundos.
* @param pDia
* @param pMes
* @param pAno
* @return Data no formato Calendar
*/
public static Calendar toCalendar(Long pMilliseconds) {
Calendar xC = Calendar.getInstance();
xC.setTimeInMillis(pMilliseconds);
return xC;
}
public static DateTime toDateTime(Long pMilliSeconds) {
return new DateTime(pMilliSeconds, DateTimeZone.UTC);
}
/**
* Retorna o dia a partir de uma data.
* @param pData
* @return dia
*/
public static Integer getDay(Date pData){
Calendar xData = toCalendar(pData);
return xData.get(Calendar.DAY_OF_MONTH);
}
/**
* Retorna o mes a partir de uma date(date)
* @param pData
* @return mes
*/
public static Integer getMonth(Date pData){
Calendar xData = toCalendar(pData);
return xData.get(Calendar.MONTH) + 1;
}
/**
* Retorna o ano a partir de uma date(date)
* @param pData
* @return Ano
*/
public static Integer getYear(Date pData){
Calendar xData = toCalendar(pData);
return xData.get(Calendar.YEAR);
}
/**
* Retorna a hora(sem minutos ou segundos) a partir de um timestamp
* @param pData
* @return Ano
*/
public static Integer getHour(Timestamp pTime){
Calendar xData = toCalendar(pTime);
return xData.get(Calendar.HOUR_OF_DAY);
}
/**
* Retorna o minuto a partir de um timestamp
* @param pData
* @return Ano
*/
public static Integer getMinute(Timestamp pTime){
Calendar xData = toCalendar(pTime);
return xData.get(Calendar.MINUTE);
}
/**
* Retorna o segundo a partir de um timestamp
* @param pData
* @return Ano
*/
public static Integer getSecond(Timestamp pTime){
Calendar xData = toCalendar(pTime);
return xData.get(Calendar.SECOND);
}
public static int getDays(Connection pConexao, Date pDataInicio, Date pDataFim, boolean pUtil) {
return getDays(pConexao, pDataInicio, pDataFim, pUtil, -1, null);
}
public static int getDays(Connection pConexao, Date pDataInicio, Date pDataFim, boolean pUtil, String pApplicationColumnName) {
return getDays(pConexao, pDataInicio, pDataFim, pUtil, -1, pApplicationColumnName);
}
public static int getDays(Connection pConexao, Date pDataInicio, Date pDataFim, boolean pUtil, int pCidade) {
return getDays(pConexao, pDataInicio, pDataFim, pUtil, pCidade, null);
}
public static int getDays(Connection pConexao, Date pDataInicio, Date pDataFim, boolean pUtil, int pCidade, String pApplicationColumnName) {
int xDias;
int xSinal=1;
if (DBSObject.isEmpty(pDataInicio)
|| DBSObject.isEmpty(pDataFim)
|| pDataInicio.equals(pDataFim)) {
return 0;
} else {
if (pUtil){
xDias = getDateDif(pDataInicio, pDataFim);
if (xDias < 0){
xSinal = -1;
}
return xSinal * (Math.abs(xDias) - getWeekends(pDataInicio, pDataFim) - getHolidays(pConexao, pDataInicio, pDataFim, pCidade, pApplicationColumnName));
} else {
return getDateDif(pDataInicio, pDataFim);
}
}
}
/**
* Calcula a quantidade de meses entre duas datas
* @param pDataInicio Data inicio
* @param pDataFim Data fim
* @return Quantidade de meses
*/
public static int getMonths(Date pDataInicio, Date pDataFim){
Calendar xDataInicio = toCalendar(pDataInicio);
Calendar xDataFim = toCalendar(pDataFim);
return getMonths(xDataInicio, xDataFim);
}
/**
* Calcula a quantidade de meses entre duas datas
* @param pDataInicio Data inicio
* @param pDataFim Data fim
* @return Quantidade de meses
*/
public static int getMonths(Calendar pDataInicio, Calendar pDataFim){
int xAnos = pDataFim.get(Calendar.YEAR) - pDataInicio.get(Calendar.YEAR); //Anos entre duas Data;
int xMeses = pDataFim.get(Calendar.MONTH) - pDataInicio.get(Calendar.MONTH); //Anos entre duas Data;
return (xAnos * 12) + xMeses;
}
/**
* Calcula a quantidade de anos entre duas datas
* @param pDataInicio Data inicio
* @param pDataFim Data fim
* @return Quantidade de anos
*/
public static int getYears(Date pDataInicio, Date pDataFim){
Calendar xDataInicio = toCalendar(pDataInicio);
Calendar xDataFim = toCalendar(pDataFim);
return getYears(xDataInicio, xDataFim);
}
/**
* Calcula a quantidade de anos entre duas data
* @param pDataInicio Data inicio
* @param pDataFim Data fim
* @return Quantidade de anos
*/
public static int getYears(Calendar pDataInicio, Calendar pDataFim){
//Anos entre duas datas
return pDataFim.get(Calendar.YEAR) - pDataInicio.get(Calendar.YEAR);
}
public static Date addDays(Date pDataBase, int pPrazo){
if (pDataBase!=null){
if (pPrazo==0){
return pDataBase;
}else{
LocalDate xDT = new DateTime(pDataBase).toLocalDate();
xDT = xDT.plusDays(pPrazo);
return DBSDate.toDate(xDT);
//int xDias = Days.daysBetween(new DateTime(pDataBase).toLocalDate(), new DateTime(pDataFim).toLocalDate()).getDays();
}
}else{
return null;
}
}
/**
* Calcula a data a partir da database adicionada de dias.<br/>
* @param pDataBase
* @param pPrazo
* @param pIncludeTime Se considera a hora
* @return Data
* @return
*/
public static Date addDays(Date pDataBase, int pPrazo, Boolean pIncludeTime){
if (pDataBase!=null){
if (pPrazo==0){
return pDataBase;
}else{
if (pIncludeTime){
LocalDateTime xDT = new DateTime(pDataBase).toLocalDateTime();
xDT = xDT.plusDays(pPrazo);
return DBSDate.toDate(xDT.toDateTime());
}else{
LocalDate xDT = new DateTime(pDataBase).toLocalDate();
xDT = xDT.plusDays(pPrazo);
return DBSDate.toDate(xDT);
}
//int xDias = Days.daysBetween(new DateTime(pDataBase).toLocalDate(), new DateTime(pDataFim).toLocalDate()).getDays();
}
}else{
return null;
}
}
/**
* Calcula a data a partir da database adicionada de meses
* @param pDataBase Data base
* @param pPrazo em dias
* @return Data
*/
public static Date addMonths(Date pDataBase, int pPrazo){
if (pDataBase!=null){
if (pPrazo==0){
return pDataBase;
}else{
LocalDate xDT = new DateTime(pDataBase).toLocalDate();
xDT = xDT.plusMonths(pPrazo);
return DBSDate.toDate(xDT);
//int xDias = Days.daysBetween(new DateTime(pDataBase).toLocalDate(), new DateTime(pDataFim).toLocalDate()).getDays();
}
}else{
return null;
}
}
/**
* Calcula a data a partir da database adicionada de anos
* @param pDataBase Data base
* @param pPrazo em dias
* @return Data
*/
public static Date addYears(Date pDataBase, int pPrazo){
if (pDataBase!=null){
if (pPrazo==0){
return pDataBase;
}else{
LocalDate xDT = new DateTime(pDataBase).toLocalDate();
xDT = xDT.plusYears(pPrazo);
return DBSDate.toDate(xDT);
//int xDias = Days.daysBetween(new DateTime(pDataBase).toLocalDate(), new DateTime(pDataFim).toLocalDate()).getDays();
}
}else{
return null;
}
}
/**
* Adiciona horas a uma data informada.
* @param Data e Hora
* @param pMinutes
* @return
*/
public static Date addHour(Date pDate, int pHour){
LocalDateTime xDT = new LocalDateTime(pDate);
xDT = xDT.plusHours(pHour);
return DBSDate.toDate(xDT.toDateTime());
}
/**
* Adiciona minutos a uma data informada.
* @param Data e Hora
* @param pMinutes
* @return
*/
public static Date addMinutes(Date pDate, int pMinutes){
LocalDateTime xDT = new LocalDateTime(pDate);
xDT = xDT.plusMinutes(pMinutes);
return DBSDate.toDate(xDT.toDateTime());
}
/**
* Adiciona minutos a uma data informada.
* @param Data e Hora
* @param pMinutes
* @return
*/
public static Date addMinutes(Timestamp pDate, int pMinutes){
Date xDate = DBSDate.toDate(pDate);
return addMinutes(xDate, pMinutes);
}
/**
* Adiciona minutos a uma data informada.
* @param pDate Data e Hora
* @param pSeconds
* @return
*/
public static Date addSeconds(Date pDate, int pSeconds){
LocalDateTime xDT = new LocalDateTime(pDate);
xDT = xDT.plusSeconds(pSeconds);
return DBSDate.toDate(xDT.toDateTime());
}
/**
* Calcula a quantidade de dias entre duas datas
* @param pDataInicio Data Inicio
* @param pDataFim Data Fim
* @return Quantidade de dias
*/
public static int getDateDif(Date pDataInicio, Date pDataFim){
if (pDataInicio.equals(pDataFim)){
return 0;
}
return Days.daysBetween(new DateTime(pDataInicio).toLocalDate(), new DateTime(pDataFim).toLocalDate()).getDays();
}
public static boolean isBusinessDay(Connection pConexao, Date pData, int pCidade, String pApplicationColumnName){
Calendar xData = Calendar.getInstance();
xData.setTime(pData);
//Dia anterior
xData.add(Calendar.DAY_OF_MONTH, -1);
if (getHolidays(pConexao, toDate(xData), pData, pCidade, pApplicationColumnName) > 0 ||
toCalendar(pData).get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY ||
toCalendar(pData).get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY){
return false;
}
return true;
}
public static boolean isBusinessDay(Connection pConexao, Date pData, int pCidade){
return isBusinessDay(pConexao, pData, pCidade, null);
}
public static boolean isBusinessDay(Connection pConexao, Date pData){
return isBusinessDay(pConexao, pData, -1);
}
public static int getHolidays(Connection pConexao, Date pDataInicio, Date pDataFim) {
return getHolidays(pConexao, pDataInicio, pDataFim, -1);
}
public static int getHolidays(Connection pConexao, Date pDataInicio, Date pDataFim, int pCidade) {
return getHolidays(pConexao, pDataInicio, pDataFim, pCidade, null);
}
public static int getHolidays(Connection pConexao, Date pDataInicio, Date pDataFim, int pCidade, String pApplicationColumnName) {
if (pConexao == null
|| pDataInicio == null
|| pDataFim == null){
wLogger.error("getFeriados: Valores nulos");
return 0;
}
Integer xDias = 0;
Date xDataInicio;
Date xDataFim;
xDataInicio = toDate(getDay(pDataInicio), getMonth(pDataInicio), 1000);
xDataFim = toDate(getDay(pDataFim), getMonth(pDataFim), 1000);
//Recupera feriados nacionais
xDias = pvGetHolidays(pConexao, xDataInicio, xDataFim, pCidade, pApplicationColumnName);
xDias += pvGetHolidays(pConexao, pDataInicio, pDataFim, pCidade, pApplicationColumnName);
return xDias;
}
public static int getWeekends(Date pDataInicio, Date pDataFim){
Double xDiasI;
Double xDiasF;
int xDias;
Date xDataBase;
xDataBase = DBSDate.toDate(01,01,1900);
xDiasI = (((DBSDate.getDateDif(xDataBase,pDataInicio)+1)/7)-0.001); //Quantidade de semanas existentes na data inicio
xDiasF = (((DBSDate.getDateDif(xDataBase,pDataFim)+1)/7)-0.001); //Quantidade de semanas existenstes na data fim
xDias = (xDiasF.intValue() - xDiasI.intValue()) * 2;
xDias = Math.abs(xDias);
// Ajusta os dias caso as data seja um final de semana
if (pDataFim.compareTo(pDataInicio) > 0) {
if (DBSDate.toCalendar(pDataInicio).get(Calendar.DAY_OF_WEEK) == 7){
xDias
}
if (DBSDate.toCalendar(pDataFim).get(Calendar.DAY_OF_WEEK) == 7){
xDias++;
}
} else {
// Ajusta os dias se as datas forem iguais a domingo
if (DBSDate.toCalendar(pDataInicio).get(Calendar.DAY_OF_WEEK) == 1){
xDias
}
if (DBSDate.toCalendar(pDataFim).get(Calendar.DAY_OF_WEEK) == 1){
xDias++;
}
}
return xDias;
}
public static Date getNextDate(Connection pConexao, Date pDataBase, int pPrazo, boolean pUtil){
return getNextDate(pConexao, pDataBase, pPrazo, pUtil, -1, null);
}
public static Date getNextDate(Connection pConexao, Date pDataBase, int pPrazo, boolean pUtil, int pCidade){
return getNextDate(pConexao, pDataBase, pPrazo, pUtil, pCidade, null);
}
public static Date getNextDate(Connection pConexao, Date pDataBase, int pPrazo, boolean pUtil, int pCidade, String pApplicationColumnName){
Date xDataFim = pDataBase;
if (pDataBase == null){
return null;
}
if (pPrazo == 0){
if (pUtil){
while (!isBusinessDay(pConexao, xDataFim, pCidade, pApplicationColumnName)) {
xDataFim = DBSDate.addDays(xDataFim, 1);
}
}
return xDataFim;
}
if (pUtil){
xDataFim = pvGetProximaDataUtil(pConexao,pDataBase,pPrazo,pCidade, pApplicationColumnName);
return xDataFim;
}else{
xDataFim = DBSDate.addDays(xDataFim, pPrazo);
return xDataFim;
}
}
public static String getMonthNameShort(Date pData){
String xRetorno = "";
if (pData == null) {
return xRetorno;
}
DateFormatSymbols xDF= new DateFormatSymbols(new Locale("pt", "BR"));
xRetorno = xDF.getShortMonths()[DBSDate.getMonth(pData)];
return xRetorno;
}
public static String getMonthName(Date pData){
String xRetorno = "";
if (pData == null) {
return xRetorno;
}
return getMonthsNames()[DBSDate.getMonth(pData)-1];// xRetorno;
}
/**
* Retorna array com os nomes de todos os meses
* @return
*/
public static String[] getMonthsNames(){
DateFormatSymbols xDF= new DateFormatSymbols(new Locale("pt", "BR"));
// DateFormatSymbols xDF = new DateFormatSymbols();
return xDF.getMonths();
}
/**
* Objetivo: Retorna nome da Semana a partir de uma data
* @param pData
* @return Nome da semana a partir de uma data.
*/
public static String getWeekdayName(Date pData){
int xDiaSemana = getWeekdayNumber(pData);
String xRetorno = "";
if (xDiaSemana==-1) {
return xRetorno;
}
DateFormatSymbols xDF= new DateFormatSymbols(new Locale("pt", "BR"));
xRetorno = xDF.getWeekdays()[xDiaSemana];
return xRetorno;
}
/**
* Objetivo: Retorna nome da Semana abreviado a partir de uma data
* @param pData
* @return Nome da semana a partir de uma data.
*/
public static String getWeekdayNameShort(Date pData){
int xDiaSemana = getWeekdayNumber(pData);
String xRetorno = "";
if (xDiaSemana==-1) {
return xRetorno;
}
DateFormatSymbols xDF= new DateFormatSymbols(new Locale("pt", "BR"));
xRetorno = xDF.getShortWeekdays()[xDiaSemana];
return xRetorno;
}
public static Date getFirstDayOfTheMonth(Connection pConexao, Date pData, boolean pUtil){
if (pData == null){
return null;
}
Calendar xData = toCalendar(pData);
pData = toDate(01,xData.get(Calendar.MONTH)+1,xData.get(Calendar.YEAR));
return getNextDate(pConexao, pData, 0, pUtil);
}
public static Date getLastDayOfTheMonth(Connection pConexao, Date pData, boolean pUtil){
if (pData == null){
return null;
}
Calendar xData = toCalendar(pData);
xData.add(Calendar.MONTH, 1);
pData = getFirstDayOfTheMonth(pConexao, toDate(xData), false);
//Encontra o dia anterior
return getNextDate(pConexao, pData, -1, pUtil);
}
public static Date getFirstDayOfTheYear(Connection pConexao, Date pData, boolean pUtil) {
if (pData == null){
return null;
}
Calendar xData = toCalendar(pData);
//Primeiro dia do ano
pData = toDate(1,1,xData.get(Calendar.YEAR));
if (pUtil){
return getNextDate(pConexao, pData, 0, pUtil);
}
return pData;
}
public static Date getLastDayOfTheYear(Connection pConexao, Date pData, boolean pUtil){
if (pData == null){
return null;
}
Calendar xData = toCalendar(pData);
//Primeiro Dia do ano Seguinte
pData = toDate(1,1,xData.get(Calendar.YEAR)+1);
//Menos um dia
return getNextDate(pConexao, pData,-1,pUtil);
}
public static int getDaysOfTheYear(Connection pConexao, int pAno, boolean pUtil, int pCidade, String pApplicationColumnName){
Date xInicio = DBSDate.toDate("31","12", String.valueOf(pAno - 1));
Date xFim = DBSDate.toDate("31","12", String.valueOf(pAno));
return DBSDate.getDays(pConexao, xInicio, xFim, pUtil, pCidade, pApplicationColumnName);
}
public static int getDaysOfTheYear(Connection pConexao, int pAno, boolean pUtil, int pCidade){
return getDaysOfTheYear(pConexao, pAno, pUtil, pCidade, null);
}
public static int getDaysOfTheYear(Connection pConexao, int pAno, boolean pUtil){
return getDaysOfTheYear(pConexao, pAno, pUtil, -1);
}
public static int getDaysOfTheMonth(Connection pConexao, Date pData, boolean pUtil, int pCidade, String pApplicationColumnName) {
if (pData == null){
return 0;
}
Date xInicio = getFirstDayOfTheMonth(pConexao, pData, false);
Date xFim = getLastDayOfTheMonth(pConexao, pData, false);
xInicio = getNextDate(pConexao, xInicio,-1,false, pCidade);
return getDays(pConexao, xInicio, xFim, pUtil, pCidade, pApplicationColumnName);
}
public static int getDaysOfTheMonth(Connection pConexao, Date pData, boolean pUtil, int pCidade) {
return getDaysOfTheMonth(pConexao, pData, pUtil, pCidade, null);
}
public static int getDaysOfTheMonth(Connection pConexao, Date pData, boolean pUtil) {
return getDaysOfTheMonth(pConexao, pData, pUtil, -1);
}
public static int getWeekdayNumber(Date pData){
Calendar xCalendar = Calendar.getInstance();
if (pData == null) {
return -1;
}
xCalendar.setTime(pData);
return xCalendar.get(Calendar.DAY_OF_WEEK);
}
public static int getWeekdayNumber(String pMes){
String[] xMeses = DBSDate.getMonthsNames();
int xI = 0;
//Uniformiza texto
pMes = pMes.trim().toUpperCase();
for (String xMes : xMeses){
//Uniformiza texto
xMes = xMes.trim().toUpperCase();
xI++;
if (!xMes.equals("")
&& xMes.equals(pMes)){
return xI;
}
}
return 0;
// if (pMes.toUpperCase().equals("JANEIRO")) {
// xRetorno = 1;
// if (pMes.toUpperCase().equals("FEVEREIRO")) {
// xRetorno = 2;
// xRetorno = 3;
// if (pMes.toUpperCase().equals("ABRIL")) {
// xRetorno = 4;
// if (pMes.toUpperCase().equals("MAIO")) {
// xRetorno = 5;
// if (pMes.toUpperCase().equals("JUNHO")) {
// xRetorno = 6;
// if (pMes.toUpperCase().equals("JULHO")) {
// xRetorno = 7;
// if (pMes.toUpperCase().equals("AGOSTO")) {
// xRetorno = 8;
// if (pMes.toUpperCase().equals("SETEMBRO")) {
// xRetorno = 9;
// if (pMes.toUpperCase().equals("OUTUBRO")) {
// xRetorno = 10;
// if (pMes.toUpperCase().equals("NOVEMBRO")) {
// xRetorno = 11;
// if (pMes.toUpperCase().equals("DEZEMBRO")) {
// xRetorno = 12;
// return xRetorno;
}
public static int getMonthNumberFromShortMonthName(String pMes){
String[] xMeses = DBSDate.getMonthsNames();
int xI = 0;
//Uniformiza texto
pMes = pMes.trim().toUpperCase();
for (String xMes : xMeses){
//Uniformiza texto
xMes = xMes.trim().toUpperCase();
xI++;
if (!xMes.equals("")
&& pMes.equals(DBSString.getSubString(xMes, 1, 3))){
return xI;
}
}
return 0;
}
public static Date getNextWeek(Connection pConexao, Date pDataAtual, int pPrazo, int pDiaDaSemana, boolean pUtil, int pCidade, String pApplicationColumnName){
if (pDataAtual == null){
return null;
}
if (pDiaDaSemana <= 0 || pDiaDaSemana > 7){
return null;
}
//Calcula um data aproximada a data desejada
pDataAtual = getNextDate(pConexao, pDataAtual, pPrazo, false, pCidade);
Calendar xData = toCalendar(pDataAtual);
while (xData.get(Calendar.DAY_OF_WEEK) != pDiaDaSemana) {
pDataAtual = getNextDate(pConexao, toDate(xData), 1, false, pCidade);
xData.setTime(pDataAtual);
}
if (pUtil && !isBusinessDay(pConexao, pDataAtual, pCidade, pApplicationColumnName)){
int xSinal=1;
if (pPrazo<0){
xSinal=-1;
}
pDataAtual = getNextDate(pConexao, pDataAtual, xSinal, true, pCidade);
}
return pDataAtual;
}
public static Date getNextWeek(Connection pConexao, Date pDataAtual, int pPrazo, int pDiaDaSemana, boolean pUtil, int pCidade){
return getNextWeek(pConexao, pDataAtual, pPrazo, pDiaDaSemana, pUtil, pCidade, null);
}
public static Date getNextWeek(Connection pConexao, Date pDataAtual, int pPrazo, int pDiaDaSemana, boolean pUtil){
return getNextWeek(pConexao, pDataAtual, pPrazo, pDiaDaSemana, pUtil, -1);
}
public static Date getNextAnniversary(Connection pConexao, Date pData, int pPrazo, PERIODICIDADE pPeriodicidade, boolean pUtil, int pCidade, String pApplicationColumnName){
if (pData == null
|| pPeriodicidade == null){
return null;
}
Calendar xData = toCalendar(pData);
if (pPeriodicidade == PERIODICIDADE.DIARIA){
xData.add(Calendar.DAY_OF_MONTH, pPrazo);
} else if (pPeriodicidade == PERIODICIDADE.MENSAL){
xData.add(Calendar.MONTH, pPrazo);
} else if (pPeriodicidade == PERIODICIDADE.ANUAL) {
xData.add(Calendar.YEAR, pPrazo);
}
return getNextDate(pConexao, toDate(xData), 0, pUtil, pCidade, pApplicationColumnName);
}
public static Date getNextAnniversary(Connection pConexao, Date pData, int pPrazo, PERIODICIDADE pPeriodicidade, boolean pUtil, int pCidade){
return getNextAnniversary(pConexao, pData, pPrazo, pPeriodicidade, pUtil, pCidade, null);
}
public static Date getNextAnniversary(Connection pConexao, Date pData, int pPrazo, PERIODICIDADE pPeriodicidade, boolean pUtil){
return getNextAnniversary(pConexao, pData, pPrazo, pPeriodicidade, pUtil, -1);
}
// public static Date getVencimento(Connection pConexao, int pParcela, Date pPrimeiraParcela, PERIODICIDADE pPeriodicidade, int pPrazo, boolean pUtil, String pApplicationColumnName){
// if (pPrimeiraParcela == null || pPeriodicidade == null){
// return null;
// return getProximoAniversario(pConexao, pPrimeiraParcela, pPrazo * DBSNumber.toInteger(pParcela-1), pPeriodicidade, pUtil, -1, pApplicationColumnName);
// //MOVIDO DE DBSFND - era usado em CALCULAPUBEAN
public static Date getDueDate(Connection pConnection, Integer pParcelas, Date pPrimeiraParcela, PERIODICIDADE pPeriodicidade, Integer pPrazo, boolean pUtil, String pApplicationColumnName) {
Date xVencimento = pPrimeiraParcela;
if (DBSObject.isEmpty(xVencimento)) return xVencimento;
if (PERIODICIDADE.DIARIA.equals(pPeriodicidade)) {
xVencimento = DBSDate.getNextDate(pConnection, xVencimento, pPrazo * (pParcelas - 1), false, -1, pApplicationColumnName);
if (pUtil) {
if (!DBSDate.isBusinessDay(pConnection, xVencimento, -1)) {
xVencimento = DBSDate.getNextDate(pConnection, xVencimento, 1, true, -1, pApplicationColumnName);
}
}
} else {
xVencimento = DBSDate.getNextAnniversary(pConnection, xVencimento, pPrazo * DBSNumber.toInteger(pParcelas - 1), pPeriodicidade, pUtil, -1, pApplicationColumnName);
}
return xVencimento;
}
private static int pvGetHolidays(Connection pConexao, Date pDataInicio, Date pDataFim, int pCidade, String pApplicationColumnName) {
if (DBSSDK.TABLE.FERIADO.equals("")){
wLogger.error("DBSSDK.TABLE.FERIADO em branco, Favor informar o tarefa que contém o cadastro de feriados.");
return 0;
}
String xSql;
String xFiltroCidade= "";
Integer xDias = 0;
DBSDAO<Object> xDao = new DBSDAO<Object>(pConexao);
xSql = "SELECT * FROM " + DBSSDK.TABLE.FERIADO + " ";
if (pDataInicio.after(pDataFim)) {
xSql += "WHERE DATA >=" + DBSIO.toSQLDate(pConexao, pDataFim) +
" AND DATA <" + DBSIO.toSQLDate(pConexao, pDataInicio) ;
} else {
xSql += "WHERE DATA >" + DBSIO.toSQLDate(pConexao, pDataInicio) +
" AND DATA <=" + DBSIO.toSQLDate(pConexao, pDataFim) ;
}
if (DBSObject.isIdValid(pCidade)) {
xFiltroCidade = " OR CIDADE_ID = " + pCidade;
}
xSql += " AND (" + DBSIO.toSQLNull(pConexao, "CIDADE_ID") + " OR CIDADE_ID = -1 " + xFiltroCidade + ")";// Objetivo: Retorna quantidade de feriados em dias
//ALBERTO
if (!DBSObject.isEmpty(pApplicationColumnName)) {
xSql += " AND "+ pApplicationColumnName + " = -1";
}
try {
if (xDao.open(xSql)) {
xDao.moveBeforeFirstRow();
while (xDao.moveNextRow()) {
//Se feriado for final de semana, ignora
if (DBSDate.getWeekdayNumber(DBSDate.toDate(xDao.getValue("DATA"))) != Calendar.SATURDAY
&& DBSDate.getWeekdayNumber(DBSDate.toDate(xDao.getValue("DATA"))) != Calendar.SUNDAY) {
xDias += 1;
}
}
xDao.close();
}
} catch (DBSIOException e) {
wLogger.error(e);
}
return xDias;
}
// privates
private static Date pvGetProximaDataUtil(Connection pConexao, Date pDataBase, int pPrazo, int pCidade, String pApplicationColumnName){
Date xDataFim = DBSDate.addDays(pDataBase, pPrazo);
int xDiasNaoUteis = getWeekends(pDataBase, xDataFim) +
getHolidays(pConexao, pDataBase, xDataFim, pCidade, pApplicationColumnName);
if (pPrazo < 0){
xDiasNaoUteis = -xDiasNaoUteis;
}
if (xDiasNaoUteis!=0){
xDataFim = pvGetProximaDataUtil(pConexao,xDataFim,xDiasNaoUteis,pCidade, pApplicationColumnName);
}
return xDataFim;
}
private static Date pvToDateLong(String pData, String pDateFormat) {
if (pData == null){
return null;
}
DateFormat xFormat = DateFormat.getDateInstance(DateFormat.LONG, new Locale("pt", "BR"));
xFormat = new SimpleDateFormat(pDateFormat);
Date xDate = new Date(0);
xFormat.setLenient(false);
try {
xDate.setTime(xFormat.parse(pData).getTime());
} catch (ParseException e) {
wLogger.error(e);
return null;
}
return xDate;
}
}
|
package br.com.fixturefactory;
import static br.com.fixturefactory.function.DateTimeFunction.DateType.AFTER;
import static br.com.fixturefactory.function.DateTimeFunction.DateType.BEFORE;
import static br.com.fixturefactory.function.NameFunction.NameType.FIRST;
import static br.com.fixturefactory.function.NameFunction.NameType.LAST;
import static br.com.fixturefactory.util.DateTimeUtil.toCalendar;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.LinkedHashSet;
import java.util.Set;
import com.mdimension.jchronic.Options;
import br.com.bfgex.Gender;
import br.com.fixturefactory.base.CalendarInterval;
import br.com.fixturefactory.base.CalendarSequence;
import br.com.fixturefactory.base.Interval;
import br.com.fixturefactory.base.Range;
import br.com.fixturefactory.base.Sequence;
import br.com.fixturefactory.function.AssociationFunction;
import br.com.fixturefactory.function.ChronicFunction;
import br.com.fixturefactory.function.DateTimeFunction;
import br.com.fixturefactory.function.FixtureFunction;
import br.com.fixturefactory.function.Function;
import br.com.fixturefactory.function.NameFunction;
import br.com.fixturefactory.function.NumberSequence;
import br.com.fixturefactory.function.RandomFunction;
import br.com.fixturefactory.function.RegexFunction;
import br.com.fixturefactory.function.SequenceFunction;
import br.com.fixturefactory.util.Chainable;
public class Rule {
private Set<Property> properties = new LinkedHashSet<Property>();
public void add(String property, Object value) {
this.properties.add(new Property(property, value));
}
public void add(String property, Function function) {
this.properties.add(new Property(property, function));
}
/**
* @deprecated use {@link one(clazz, label)} instead.
*/
@Deprecated
public Function fixture(Class<?> clazz, String label) {
return new FixtureFunction(clazz, label);
}
/**
* @deprecated use {@link has(quantity).of(clazz, label)} instead.
*/
@Deprecated
public Function fixture(Class<?> clazz, Integer quantity, String label) {
return new FixtureFunction(clazz, label, quantity);
}
public Chainable has(int quantity) {
return new AssociationFunction(new FixtureFunction(null, null, quantity));
}
public AssociationFunction one(Class<?> clazz, String label) {
return new AssociationFunction(new FixtureFunction(clazz, label));
}
public Function one(Class<?> clazz, String label, String targetAttribute) {
return new AssociationFunction(new FixtureFunction(clazz, label), targetAttribute);
}
public Function random(Class<?> clazz, Object... dataset) {
return new RandomFunction(clazz, dataset);
}
public Function random(Object... dataset) {
return new RandomFunction(dataset);
}
public Function random(Class<?> clazz, Range range) {
return new RandomFunction(clazz, range);
}
public Function name() {
return new NameFunction();
}
public Function name(Gender gender) {
return new NameFunction(gender);
}
public Function firstName() {
return new NameFunction(FIRST);
}
public Function firstName(Gender gender) {
return new NameFunction(FIRST, gender);
}
public Function lastName() {
return new NameFunction(LAST);
}
public Function beforeDate(String source, SimpleDateFormat format) {
return new DateTimeFunction(toCalendar(source, format), BEFORE);
}
public Function afterDate(String source, SimpleDateFormat format) {
return new DateTimeFunction(toCalendar(source, format), AFTER);
}
public Function randomDate(String startDate, String endDate, DateFormat format) {
return new DateTimeFunction(toCalendar(startDate, format), toCalendar(endDate, format));
}
public Function regex(String regex) {
return new RegexFunction(regex);
}
public Range range(Number start, Number end) {
return new Range(start, end);
}
public Function sequence(Sequence<?> sequence) {
return new SequenceFunction(sequence);
}
public Function sequence(Number startWith, int incrementBy) {
return new SequenceFunction(new NumberSequence(startWith, incrementBy));
}
public Function sequenceDate(String base, CalendarInterval interval) {
return this.sequenceDate(base, new SimpleDateFormat("yyyy-MM-dd"), interval);
}
public Function sequenceDate(String base, DateFormat simpleDateFormat, CalendarInterval interval) {
return new SequenceFunction(new CalendarSequence(toCalendar(base, simpleDateFormat), interval));
}
public Function instant(String dateText) {
return new ChronicFunction(dateText);
}
public Function instant(String dateText, Options options) {
return new ChronicFunction(dateText, options);
}
public Interval increment(int interval) {
return new Interval(interval);
}
public Interval decrement(int interval) {
return new Interval(interval*(-1));
}
public Set<Property> getProperties() {
return properties;
}
}
|
package com.blamejared.mcbot;
import com.blamejared.mcbot.commands.api.CommandRegistrar;
import com.blamejared.mcbot.listeners.ChannelListener;
import com.blamejared.mcbot.mcp.DataDownloader;
import sx.blah.discord.api.ClientBuilder;
import sx.blah.discord.api.IDiscordClient;
import sx.blah.discord.api.events.EventSubscriber;
import sx.blah.discord.handle.impl.events.guild.channel.message.MessageDeleteEvent;
import sx.blah.discord.handle.impl.events.guild.channel.message.MessageReceivedEvent;
import sx.blah.discord.handle.impl.events.guild.channel.message.MessageUpdateEvent;
import sx.blah.discord.handle.obj.IChannel;
public class MCBot {
public static IDiscordClient instance;
public static void main(String[] args) {
instance = new ClientBuilder().withToken(args[0]).login();
CommandRegistrar.INSTANCE.slurpCommands();
DataDownloader.INSTANCE.start();
instance.getDispatcher().registerListener(new MCBot());
instance.getDispatcher().registerListener(new ChannelListener());
}
public static IChannel getChannel(String name) {
final IChannel[] channel = new IChannel[1];
instance.getGuilds().forEach(guild -> guild.getChannels().forEach(chan -> {
if(chan.getName().equalsIgnoreCase(name)) {
channel[0] = chan;
}
}));
return channel[0];
}
@EventSubscriber
public void onMessageDeleted(MessageDeleteEvent event) {
if(event.getChannel().getName().equalsIgnoreCase("bot-log")) {
return;
}
getChannel("bot-log").sendMessage(event.getAuthor().getName() + " Deleted message : ```" + event.getMessage().getContent().replaceAll("```", "") + "``` from channel: " + event.getChannel().getName());
}
@EventSubscriber
public void onMessageEdited(MessageUpdateEvent event) {
if(event.getChannel().getName().equalsIgnoreCase("bot-log")) {
return;
}
if(event.getAuthor().isBot()) {
return;
}
getChannel("bot-log").sendMessage(event.getAuthor().getName() + " Edited message: ```" + event.getOldMessage().getContent().replaceAll("```", "") + "``` -> ```" + event.getNewMessage().getContent().replaceAll("```", "") + "``` from channel: " + event.getChannel().getName());
}
@EventSubscriber
public void onMessageRecieved(MessageReceivedEvent event) {
if(event.getMessage().getChannel().getName().equals("general-discussion")) {
boolean isGif = false;
if(event.getMessage().getContent().contains(".gif")) {
isGif = true;
}
if(event.getMessage().getContent().contains("https://giphy.com")) {
isGif = true;
}
if(event.getMessage().getContent().contains("https://tenor.co")) {
isGif = true;
}
if(isGif) {
event.getMessage().delete();
event.getChannel().sendMessage("Sorry! GIFs are not allowed in this chat! Head to <#235949539138338816>");
}
}
}
}
|
package com.box.sdk;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.GZIPInputStream;
/**
* Used to read HTTP responses from the Box API.
*
* <p>All responses from the REST API are read using this class or one of its subclasses. This class wraps {@link
* HttpURLConnection} in order to provide a simpler interface that can automatically handle various conditions specific
* to Box's API. When a response is contructed, it will throw a {@link BoxAPIException} if the response from the API
* was an error. Therefore every BoxAPIResponse instance is guaranteed to represent a successful response.</p>
*
* <p>This class usually isn't instantiated directly, but is instead returned after calling {@link BoxAPIRequest#send}.
* </p>
*/
public class BoxAPIResponse {
private static final Logger LOGGER = Logger.getLogger(BoxAPIResponse.class.getName());
private static final int BUFFER_SIZE = 8192;
private final HttpURLConnection connection;
private int responseCode;
private String bodyString;
/**
* The raw InputStream is the stream returned directly from HttpURLConnection.getInputStream(). We need to keep
* track of this stream in case we need to access it after wrapping it inside another stream.
*/
private InputStream rawInputStream;
/**
* The regular InputStream is the stream that will be returned by getBody(). This stream might be a GZIPInputStream
* or a ProgressInputStream (or both) that wrap the raw InputStream.
*/
private InputStream inputStream;
/**
* Constructs an empty BoxAPIResponse without an associated HttpURLConnection.
*/
public BoxAPIResponse() {
this.connection = null;
}
/**
* Constructs a BoxAPIResponse using an HttpURLConnection.
* @param connection a connection that has already sent a request to the API.
*/
public BoxAPIResponse(HttpURLConnection connection) {
this.connection = connection;
this.inputStream = null;
try {
this.responseCode = this.connection.getResponseCode();
} catch (IOException e) {
throw new BoxAPIException("Couldn't connect to the Box API due to a network error.", e);
}
if (!isSuccess(this.responseCode)) {
this.logResponse();
throw new BoxAPIException("The API returned an error code: " + this.responseCode, this.responseCode,
this.bodyToString());
}
this.logResponse();
}
/**
* Gets the response code returned by the API.
* @return the response code returned by the API.
*/
public int getResponseCode() {
return this.responseCode;
}
/**
* Gets the length of this response's body as indicated by the "Content-Length" header.
* @return the length of the response's body.
*/
public long getContentLength() {
return this.connection.getContentLength();
}
/**
* Gets an InputStream for reading this response's body.
* @return an InputStream for reading the response's body.
*/
public InputStream getBody() {
return this.getBody(null);
}
/**
* Gets an InputStream for reading this response's body which will report its read progress to a ProgressListener.
* @param listener a listener for monitoring the read progress of the body.
* @return an InputStream for reading the response's body.
*/
public InputStream getBody(ProgressListener listener) {
if (this.inputStream == null) {
String contentEncoding = this.connection.getContentEncoding();
try {
if (this.rawInputStream == null) {
this.rawInputStream = this.connection.getInputStream();
}
if (listener == null) {
this.inputStream = this.rawInputStream;
} else {
this.inputStream = new ProgressInputStream(this.rawInputStream, listener,
this.getContentLength());
}
if (contentEncoding != null && contentEncoding.equalsIgnoreCase("gzip")) {
this.inputStream = new GZIPInputStream(this.inputStream);
}
} catch (IOException e) {
throw new BoxAPIException("Couldn't connect to the Box API due to a network error.", e);
}
}
return this.inputStream;
}
/**
* Disconnects this response from the server and frees up any network resources. The body of this response can no
* longer be read after it has been disconnected.
*/
public void disconnect() {
if (this.connection == null) {
return;
}
try {
if (this.rawInputStream == null) {
this.rawInputStream = this.connection.getInputStream();
}
// We need to manually read from the raw input stream in case there are any remaining bytes. There's a bug
// where a wrapping GZIPInputStream may not read to the end of a chunked response, causing Java to not
// return the connection to the connection pool.
byte[] buffer = new byte[BUFFER_SIZE];
int n = this.rawInputStream.read(buffer);
while (n != -1) {
n = this.rawInputStream.read(buffer);
}
this.rawInputStream.close();
if (this.inputStream != null) {
this.inputStream.close();
}
} catch (IOException e) {
throw new BoxAPIException("Couldn't finish closing the connection to the Box API due to a network error or "
+ "because the stream was already closed.", e);
}
}
@Override
public String toString() {
String lineSeparator = System.getProperty("line.separator");
Map<String, List<String>> headers = this.connection.getHeaderFields();
StringBuilder builder = new StringBuilder();
builder.append("Response");
builder.append(lineSeparator);
builder.append(this.connection.getRequestMethod());
builder.append(' ');
builder.append(this.connection.getURL().toString());
builder.append(lineSeparator);
builder.append(headers.get(null).get(0));
builder.append(lineSeparator);
for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
String key = entry.getKey();
if (key == null) {
continue;
}
List<String> nonEmptyValues = new ArrayList<String>();
for (String value : entry.getValue()) {
if (value != null && value.trim().length() != 0) {
nonEmptyValues.add(value);
}
}
if (nonEmptyValues.size() == 0) {
continue;
}
builder.append(key);
builder.append(": ");
for (String value : nonEmptyValues) {
builder.append(value);
builder.append(", ");
}
builder.delete(builder.length() - 2, builder.length());
builder.append(lineSeparator);
}
String bodyString = this.bodyToString();
if (bodyString != null && bodyString != "") {
builder.append(lineSeparator);
builder.append(bodyString);
}
return builder.toString().trim();
}
/**
* Returns a string representation of this response's body. This method is used when logging this response's body.
* By default, it returns an empty string (to avoid accidentally logging binary data) unless the response contained
* an error message.
* @return a string representation of this response's body.
*/
protected String bodyToString() {
if (this.bodyString == null && !isSuccess(this.responseCode)) {
this.bodyString = readErrorStream(this.getErrorStream());
}
return this.bodyString;
}
/**
* Returns the response error stream, handling the case when it contains gzipped data.
* @return gzip decoded (if needed) error stream or null
*/
private InputStream getErrorStream() {
InputStream errorStream = this.connection.getErrorStream();
if (errorStream != null) {
final String contentEncoding = this.connection.getContentEncoding();
if (contentEncoding != null && contentEncoding.equalsIgnoreCase("gzip")) {
try {
errorStream = new GZIPInputStream(errorStream);
} catch (IOException e) {
// just return the error stream as is
}
}
}
return errorStream;
}
private void logResponse() {
if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.log(Level.FINE, this.toString());
}
}
private static boolean isSuccess(int responseCode) {
return responseCode >= 200 && responseCode < 300;
}
private static String readErrorStream(InputStream stream) {
if (stream == null) {
return null;
}
InputStreamReader reader = new InputStreamReader(stream, StandardCharsets.UTF_8);
StringBuilder builder = new StringBuilder();
char[] buffer = new char[BUFFER_SIZE];
try {
int read = reader.read(buffer, 0, BUFFER_SIZE);
while (read != -1) {
builder.append(buffer, 0, read);
read = reader.read(buffer, 0, BUFFER_SIZE);
}
reader.close();
} catch (IOException e) {
return null;
}
return builder.toString();
}
}
|
package com.brettonw.bag;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
/**
* A collection of text-based values store in key/value pairs (maintained in a sorted array).
*/
public class BagObject {
private static final Logger log = LogManager.getLogger (BagObject.class);
private static final int START_SIZE = 1;
private static final int DOUBLING_CAP = 16;
private Pair[] container;
private int count;
/**
* Create a new BagObject with a default underlying storage size.
*/
public BagObject () {
count = 0;
container = new Pair[START_SIZE];
}
/**
* Create a new BagObject with hint for the underlying storage size.
*
* @param size The expected number of elements in the BagObject, treated as a hint to optimize
* memory allocation. If additional elements are stored, the BagObject will revert
* to normal allocation behavior.
*/
public BagObject (int size) {
count = 0;
container = new Pair[size];
}
/**
* Return the number of elements stored in the BagObject.
*
* @return the count of elements in the underlying store. This is distinct from the capacity of
* the underlying store.
*/
public int getCount () {
return count;
}
private void grow (int gapIndex) {
Pair src[] = container;
if (count == container.length) {
// if the array is smaller than the cap then double its size, otherwise just add the block
int newSize = (count > DOUBLING_CAP) ? (count + DOUBLING_CAP) : (count * 2);
container = new Pair[newSize];
System.arraycopy (src, 0, container, 0, gapIndex);
}
System.arraycopy (src, gapIndex, container, gapIndex + 1, count - gapIndex);
++count;
}
private int binarySearch (String key) {
Pair term = new Pair (key);
return Arrays.binarySearch (container, 0, count, term);
}
/**
* Using a binary search of the underlying store, finds where the element mapped to the key
* would be, and returns it.
*
* @param key A string value used to index the element.
* @return The indexed element (if found), or null
*/
public Object getObject (String key) {
int index = binarySearch (key);
if (index >= 0) {
Pair pair = container[index];
return pair.getValue ();
}
return null;
}
/**
* Using a binary search of the underlying store, finds where the element mapped to the key
* should be, and stores it. If the element already exists, it is replaced with the new one. If
* the element does not already exist, the underlying store is shifted to make a space for it.
* The shift might cause the underlying store to be resized if there is insufficient room.
* <p>
* Note that null values for the element are NOT stored, as returning null from getObject would
* be indistinguishable from a call to getObject with an unknown key.
*
* @param key A string value used to index the element.
* @param object The element to store.
* @return The BagObject, so that operations can be chained together.
*/
public BagObject put (String key, Object object) {
// convert the incoming object to the internal store format, we don't store null values, as
// that is indistinguishable on the get from fetching a non-existent key
object = BagHelper.objectify (object);
if (object != null) {
int index = binarySearch (key);
if (index >= 0) {
container[index].setValue (object);
} else {
// the binary search returns a funky encoding of the index where the new value
// should go when it's not there, so we have to decode that number (-index - 1)
index = -(index + 1);
grow (index);
container[index] = new Pair (key, object);
}
}
return this;
}
/**
* Using a binary search of the underlying store, finds where the element mapped to the key
* should be, and removes it. If the element doesn't exist, nothing happens. If
* the element is removed, the underlying store is shifted to close the space where it was.
* removing elements will never cause the underlying store to shrink.
*
* @param key A string value used to index the element.
* @return The BagObject, so that operations can be chained together.
*/
public BagObject remove (String key) {
int index = binarySearch (key);
if (index >= 0) {
int gapIndex = index + 1;
System.arraycopy (container, gapIndex, container, index, count - gapIndex);
--count;
}
return this;
}
/**
* Retrieve a mapped element and return it as a String.
*
* @param key A string value used to index the element.
* @return The element as a string, or null if the element is not found (or not a String).
*/
public String getString (String key) {
Object object = getObject (key);
try {
return (String) object;
} catch (ClassCastException exception) {
log.warn ("Cannot cast value type (" + object.getClass ().getName () + ") to String for key (" + key + ")");
}
return null;
}
/**
* Retrieve a mapped element and return it as a Boolean.
*
* @param key A string value used to index the element.
* @return The element as a Boolean, or null if the element is not found.
*/
public Boolean getBoolean (String key) {
String string = getString (key);
return (string != null) ? Boolean.parseBoolean (string) : null;
}
/**
* Retrieve a mapped element and return it as a Long.
*
* @param key A string value used to index the element.
* @return The element as a Long, or null if the element is not found.
*/
@SuppressWarnings ("WeakerAccess")
public Long getLong (String key) {
String string = getString (key);
return (string != null) ? Long.parseLong (string) : null;
}
/**
* Retrieve a mapped element and return it as an Integer.
*
* @param key A string value used to index the element.
* @return The element as an Integer, or null if the element is not found.
*/
public Integer getInteger (String key) {
Long value = getLong (key);
return (value != null) ? value.intValue () : null;
}
/**
* Retrieve a mapped element and return it as a Double.
*
* @param key A string value used to index the element.
* @return The element as a Double, or null if the element is not found.
*/
public Double getDouble (String key) {
String string = getString (key);
return (string != null) ? Double.parseDouble (string) : null;
}
/**
* Retrieve a mapped element and return it as a Float.
*
* @param key A string value used to index the element.
* @return The element as a Float, or null if the element is not found.
*/
public Float getFloat (String key) {
Double value = getDouble (key);
return (value != null) ? value.floatValue () : null;
}
/**
* Retrieve a mapped element and return it as a BagObject.
*
* @param key A string value used to index the element.
* @return The element as a BagObject, or null if the element is not found.
*/
public BagObject getBagObject (String key) {
Object object = getObject (key);
try {
return (BagObject) object;
} catch (ClassCastException exception) {
log.warn ("Cannot cast value type (" + object.getClass ().getName () + ") to BagObject for key (" + key + ")");
}
return null;
}
/**
* Retrieve a mapped element and return it as a BagArray.
*
* @param key A string value used to index the element.
* @return The element as a BagArray, or null if the element is not found.
*/
public BagArray getBagArray (String key) {
Object object = getObject (key);
try {
return (BagArray) object;
} catch (ClassCastException exception) {
log.warn ("Cannot cast value type (" + object.getClass ().getName () + ") to BagArray for key (" + key + ")");
}
return null;
}
/**
* Return whether or not the requested key is present in the BagObject.
*
* @param key A string value used to index an element.
* @return A boolean value, true if the key is present in the underlying store. Note that null
* values are not stored (design decision), so this equivalent to checking for null.
*/
public boolean has (String key) {
return (binarySearch (key) >= 0);
}
/**
* Returns an array of the keys contained in the underlying map.
*
* @return The keys in the underlying map as an array of Strings.
*/
public String[] keys () {
String keys[] = new String[count];
for (int i = 0; i < count; ++i) {
keys[i] = container[i].getKey ();
}
return keys;
}
/**
* Returns the BagObject represented as JSON.
*
* @return A String containing the JSON representation of the underlying store.
*/
@Override
public String toString () {
StringBuilder result = new StringBuilder ();
boolean isFirst = true;
for (int i = 0; i < count; ++i) {
result.append (isFirst ? "" : ",");
isFirst = false;
Pair pair = container[i];
result
.append (BagHelper.quote (pair.getKey ()))
.append (":")
.append (BagHelper.stringify (pair.getValue ()));
}
return BagHelper.enclose (result.toString (), "{}");
}
/**
* Returns a BagObject extracted from a JSON representation.
*
* @param input A String containing a JSON encoding of a BagObject.
* @return A new BagObject containing the elements encoded in the input.
*/
public static BagObject fromString (String input) {
// parse the string out... it is assumed to be a well formed BagObject serialization
BagParser parser = new BagParser (input);
return parser.ReadBagObject ();
}
/**
* Returns a BagObject extracted from a JSON representation.
*
* @param inputStream An InputStream containing a JSON encoding of a BagObject.
* @return A new BagObject containing the elements encoded in the input.
*/
public static BagObject fromStream (InputStream inputStream) throws IOException {
BagParser parser = new BagParser (inputStream);
return parser.ReadBagObject ();
}
/**
* Returns a BagObject extracted from a JSON representation.
*
* @param file A File containing a JSON encoding of a BagObject.
* @return A new BagObject containing the elements encoded in the input.
*/
public static BagObject fromFile (File file) throws IOException {
BagParser parser = new BagParser (file);
return parser.ReadBagObject ();
}
}
|
package com.bugsnag.android;
import java.io.File;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.UUID;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageInfo;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.provider.Settings.Secure;
import com.bugsnag.Error;
import com.bugsnag.MetaData;
import com.bugsnag.Metrics;
import com.bugsnag.Notification;
import com.bugsnag.http.HttpClient;
import com.bugsnag.http.NetworkException;
import com.bugsnag.http.BadResponseException;
import com.bugsnag.utils.JSONUtils;
public class Client extends com.bugsnag.Client {
private static final String PREFS_NAME = "Bugsnag";
private static final String UNSENT_ERROR_PATH = "/bugsnag-errors/";
private static final String NOTIFIER_NAME = "Android Bugsnag Notifier";
private static final String NOTIFIER_VERSION = "2.0.6";
private Logger logger;
private Context applicationContext;
private String cachePath;
public Client(Context androidContext, String apiKey, boolean enableMetrics) {
super(apiKey);
// Start the session timer
Diagnostics.startSessionTimer();
// Create a logger
logger = new Logger();
setLogger(logger);
// Get the application context, many things need this
applicationContext = androidContext.getApplicationContext();
cachePath = prepareCachePath();
// Get the uuid for metrics and userId
String uuid = getUUID();
// Get package information
String packageName = getPackageName();
String packageVersion = getPackageVersion(packageName);
// Set notifier info
setNotifierName(NOTIFIER_NAME);
setNotifierVersion(NOTIFIER_VERSION);
// Set common meta-data
setUserId(uuid);
setOsVersion(android.os.Build.VERSION.RELEASE);
setAppVersion(packageVersion);
setProjectPackages(packageName);
setReleaseStage(guessReleaseStage(packageName));
setNotifyReleaseStages("production", "development");
addToTab("Device", "Android Version", android.os.Build.VERSION.RELEASE);
addToTab("Device", "Device Type", android.os.Build.MODEL);
addToTab("Application", "Package Name", packageName);
addToTab("Application", "Package Version", packageVersion);
// Send metrics data (DAU/MAU etc) if enabled
if(enableMetrics) {
makeMetricsRequest(uuid);
}
// Flush any queued exceptions
flushErrors();
logger.info("Bugsnag is loaded and ready to handle exceptions");
}
public void notify(Throwable e) {
notify(e, null);
}
public void notify(Throwable e, MetaData overrides) {
try {
// Generate diagnostic data
MetaData diagnostics = new Diagnostics(applicationContext);
// Merge local metaData into diagnostics
MetaData metaData = diagnostics.merge(overrides);
// Create the error object to send
final Error error = createError(e, metaData);
// Set the error's context
String topActivityName = ActivityStack.getTopActivityName();
if(topActivityName != null) {
error.setContext(topActivityName);
}
// Send the error
safeAsync(new Runnable() {
@Override
public void run() {
try {
Notification notif = createNotification(error);
notif.deliver();
} catch (NetworkException ex) {
// Write error to disk for later sending
logger.info("Could not send error(s) to Bugsnag, saving to disk to send later");
writeErrorToDisk(error);
}
}
});
} catch(Exception ex) {
logger.warn("Error notifying Bugsnag", ex);
}
}
private void flushErrors() {
if(cachePath == null) return;
safeAsync(new Runnable() {
@Override
public void run() {
// Create a notification
Notification notif = createNotification();
List<File> sentFiles = new LinkedList<File>();
// Look up all saved error files
File exceptionDir = new File(cachePath);
if(exceptionDir.exists() && exceptionDir.isDirectory()) {
for(File errorFile : exceptionDir.listFiles()) {
if(errorFile.exists() && errorFile.isFile()) {
// Save filename in a "to delete" array
sentFiles.add(errorFile);
try {
// Read error from disk and add to notification
String errorString = Utils.readFileAsString(errorFile);
notif.addError(errorString);
logger.debug(String.format("Added unsent error (%s) to notification", errorFile.getName()));
} catch (IOException e) {
logger.warn("Problem reading unsent error from disk", e);
}
}
}
}
try {
// Send the notification
notif.deliver();
// Delete the files if notification worked
for(File file : sentFiles) {
logger.debug("Deleting unsent error file " + file.getName());
file.delete();
}
} catch (IOException e) {
logger.info("Could not flush error(s) to Bugsnag, will try again later");
}
}
});
}
public void setContext(Activity context) {
String contextString = ActivityStack.getContextName(context);
setContext(contextString);
}
private void makeMetricsRequest(final String userId) {
safeAsync(new Runnable() {
@Override
public void run() {
try {
Metrics metrics = createMetrics(userId);
metrics.deliver();
} catch (NetworkException ex) {
// Write error to disk for later sending
logger.info("Could not send metrics to Bugsnag");
} catch (BadResponseException ex) {
// The notification was delivered, but Bugsnag sent a non-200 response
logger.warn(ex.getMessage());
}
}
});
}
private String guessReleaseStage(String packageName) {
String releaseStage = "production";
try {
ApplicationInfo ai = applicationContext.getPackageManager().getApplicationInfo(packageName, 0);
boolean debuggable = (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
if(debuggable) {
releaseStage = "development";
}
} catch(Exception e) {
logger.warn("Could not guess release stage", e);
}
return releaseStage;
}
private String prepareCachePath() {
String path = null;
try {
path = applicationContext.getCacheDir().getAbsolutePath() + UNSENT_ERROR_PATH;
File outFile = new File(path);
outFile.mkdirs();
if(!outFile.exists()) {
logger.warn("Could not prepare cache directory");
path = null;
}
} catch(Exception e) {
logger.warn("Could not prepare cache directory", e);
path = null;
}
return path;
}
private void writeErrorToDisk(Error error) {
if(cachePath == null) return;
String errorString = error.toString();
if(errorString.length() > 0) {
// Write the error to disk
String filename = String.format("%s%d.json", cachePath, System.currentTimeMillis());
try {
Utils.writeStringToFile(errorString, filename);
logger.debug(String.format("Saved unsent error to disk (%s) ", filename));
} catch (IOException e) {
logger.warn("Could not save error to disk", e);
}
}
}
private String getUUID() {
String uuid = Secure.getString(applicationContext.getContentResolver(), Secure.ANDROID_ID);;
if(uuid == null) {
final SharedPreferences settings = applicationContext.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
uuid = settings.getString("userId", null);
if(uuid == null) {
uuid = UUID.randomUUID().toString();
// Save if for future
final String finalUuid = uuid;
safeAsync(new Runnable() {
@Override
public void run() {
SharedPreferences.Editor editor = settings.edit();
editor.putString("userId", finalUuid);
editor.commit();
}
});
}
}
return uuid;
}
private String getPackageName() {
return applicationContext.getPackageName();
}
private String getPackageVersion(String packageName) {
String packageVersion = null;
try {
PackageInfo pi = applicationContext.getPackageManager().getPackageInfo(packageName, 0);
packageVersion = pi.versionName;
} catch(Exception e) {
logger.warn("Could not get package version", e);
}
return packageVersion;
}
private void safeAsync(final Runnable delegate) {
new AsyncTask <Void, Void, Void>() {
protected Void doInBackground(Void... voi) {
try {
delegate.run();
} catch (Exception e) {
logger.warn("Error in bugsnag", e);
}
return null;
}
}.execute();
}
}
|
package com.github.jsonj;
import static com.github.jsonj.tools.JsonBuilder.fromObject;
import static com.github.jsonj.tools.JsonBuilder.primitive;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Stream;
import org.apache.commons.lang.StringUtils;
import com.github.jsonj.exceptions.JsonTypeMismatchException;
import com.github.jsonj.tools.JsonBuilder;
import com.github.jsonj.tools.JsonSerializer;
/**
* Representation of json arrays.
*/
public class JsonArray extends ArrayList<JsonElement> implements JsonElement {
private static final long serialVersionUID = -1269731858619421388L;
public JsonArray() {
super();
}
public JsonArray(Collection<?> existing) {
super();
for(Object o: existing) {
add(fromObject(o));
}
}
public JsonArray(Stream<Object> s) {
super();
s.forEach(o -> this.addObject(o));
}
/**
* Allows you to add any kind of object.
* @param o the value; will be passed through fromObject()
* @return true if object was added
*/
public boolean addObject(Object o) {
return this.add(fromObject(o));
}
/**
* Variant of add that takes a string instead of a JsonElement. The inherited add only supports JsonElement.
* @param s string
* @return true if element was added successfully
*/
public boolean add(final String s) {
return add(primitive(s));
}
/**
* Variant of add that adds one or more strings.
* @param strings values
*/
public void add(final String...strings) {
for (String s : strings) {
add(primitive(s));
}
}
/**
* Variant of add that adds one or more numbers (float/int).
* @param numbers values
*/
public void add(final Number...numbers) {
for (Number n : numbers) {
add(primitive(n));
}
}
/**
* Variant of add that adds one or more booleans.
* @param booleans values
*/
public void add(final Boolean...booleans) {
for (Boolean b : booleans) {
add(primitive(b));
}
}
/**
* Variant of add that adds one or more JsonElements.
* @param elements elements
*/
public void add(final JsonElement...elements) {
for (JsonElement element : elements) {
add(element);
}
}
/**
* Variant of add that adds one or more JsonBuilders. This means you don't have to call get() on the builder when adding object builders.
* @param elements builders
*/
public void add(JsonBuilder...elements) {
for (JsonBuilder element : elements) {
add(element.get());
}
}
@Override
public boolean addAll(@SuppressWarnings("rawtypes") Collection c) {
for (Object element : c) {
if(element instanceof JsonElement) {
add((JsonElement)element);
} else {
add(primitive(element));
}
}
return c.size() != 0;
}
/**
* Convenient method providing a few alternate ways of extracting elements
* from a JsonArray.
*
* @param label label
* @return the first element in the array matching the label or the n-th
* element if the label is an integer and the element an object or
* an array.
*/
public JsonElement get(final String label) {
int i = 0;
try{
for (JsonElement e : this) {
if(e.isPrimitive() && e.asPrimitive().asString().equals(label)) {
return e;
} else if((e.isObject() || e.isArray()) && Integer.valueOf(label).equals(i)) {
return e;
}
i++;
}
} catch(NumberFormatException e) {
// fail gracefully
return null;
}
// the element was not found
return null;
}
public JsonElement first() {
return get(0);
}
public JsonElement last() {
return get(size()-1);
}
/**
* Variant of contains that checks if the array contains something that can be extracted with JsonElement get(final String label).
* @param label label
* @return true if the array contains the element
*/
public boolean contains(final String label) {
return get(label) != null;
}
@Override
public JsonType type() {
return JsonType.array;
}
@Override
public JsonObject asObject() {
throw new JsonTypeMismatchException("not an object");
}
@Override
public JsonArray asArray() {
return this;
}
@Override
public JsonSet asSet() {
JsonSet set = JsonBuilder.set();
set.addAll(this);
return set;
}
public double[] asDoubleArray() {
double[] result = new double[size()];
int i=0;
for(JsonElement e: this) {
result[i++] = e.asPrimitive().asDouble();
}
return result;
}
public int[] asIntArray() {
int[] result = new int[size()];
int i=0;
for(JsonElement e: this) {
result[i++] = e.asPrimitive().asInt();
}
return result;
}
public String[] asStringArray() {
String[] result = new String[size()];
int i=0;
for(JsonElement e: this) {
result[i++] = e.asPrimitive().asString();
}
return result;
}
@Override
public JsonPrimitive asPrimitive() {
throw new JsonTypeMismatchException("not a primitive");
}
@Override
public float asFloat() {
throw new JsonTypeMismatchException("not a primitive");
}
@Override
public double asDouble() {
throw new JsonTypeMismatchException("not a primitive");
}
@Override
public int asInt() {
throw new JsonTypeMismatchException("not a primitive");
}
@Override
public long asLong() {
throw new JsonTypeMismatchException("not a primitive");
}
@Override
public boolean asBoolean() {
throw new JsonTypeMismatchException("not a primitive");
}
@Override
public String asString() {
throw new JsonTypeMismatchException("not a primitive");
}
@Override
public boolean isObject() {
return false;
}
@Override
public boolean isArray() {
return true;
}
@Override
public boolean isPrimitive() {
return false;
}
@Override
public boolean equals(final Object o) {
if (o == null) {
return false;
}
if (!(o instanceof JsonArray)) {
return false;
}
JsonArray array = (JsonArray) o;
if (size() != array.size()) {
return false;
}
for(int i=0; i<size();i++) {
JsonElement e1 = get(i);
JsonElement e2 = array.get(i);
if(!e1.equals(e2)) {
return false;
}
}
return true;
}
@Override
public int hashCode() {
int code = 7;
for (JsonElement e : this) {
code += e.hashCode();
}
return code;
}
@Override
public Object clone() {
return deepClone();
}
@SuppressWarnings("unchecked")
@Override
public JsonArray deepClone() {
JsonArray array = new JsonArray();
for (JsonElement jsonElement : this) {
JsonElement e = jsonElement.deepClone();
array.add(e);
}
return array;
}
public boolean isNotEmpty() {
return !isEmpty();
}
@Override
public boolean isEmpty() {
boolean empty = true;
if(size() > 0) {
for (JsonElement element : this) {
empty = empty && element.isEmpty();
if(!empty) {
return false;
}
}
}
return empty;
}
@Override
public boolean remove(Object o) {
if(o instanceof JsonElement) {
return super.remove(o);
} else {
// try remove it as a primitive.
return super.remove(primitive(o));
}
}
@Override
public void removeEmpty() {
Iterator<JsonElement> iterator = iterator();
while (iterator.hasNext()) {
JsonElement jsonElement = iterator.next();
if(jsonElement.isEmpty()) {
iterator.remove();
} else {
jsonElement.removeEmpty();
}
}
}
@Override
public String toString() {
return JsonSerializer.serialize(this,false);
}
@Override
public void serialize(Writer w) throws IOException {
w.append(JsonSerializer.OPEN_BRACKET);
Iterator<JsonElement> it = iterator();
while (it.hasNext()) {
JsonElement jsonElement = it.next();
jsonElement.serialize(w);
if(it.hasNext()) {
w.append(JsonSerializer.COMMA);
}
}
w.append(JsonSerializer.CLOSE_BRACKET);
}
@Override
public String prettyPrint() {
return JsonSerializer.serialize(this, true);
}
@Override
public boolean isNumber() {
return false;
}
@Override
public boolean isBoolean() {
return false;
}
@Override
public boolean isNull() {
return false;
}
@Override
public boolean isString() {
return false;
}
/**
* Replaces the first matching element.
* @param e1 original
* @param e2 replacement
* @return true if the element was replaced.
*/
public boolean replace(JsonElement e1, JsonElement e2) {
int index = indexOf(e1);
if(index>=0) {
set(index, e2);
return true;
} else {
return false;
}
}
/**
* Replaces the element.
* @param e1 original
* @param e2 replacement
* @return true if element was replaced
*/
public boolean replace(Object e1, Object e2) {
return replace(fromObject(e1),fromObject(e2));
}
/**
* Convenient replace method that allows you to replace an object based on field equality for a specified field.
* Useful if you have an id field in your objects. Note, the array may contain non objects as well or objects
* without the specified field. Those elements won't be replaced of course.
*
* @param e1 object you want replaced; must have a value at the specified path
* @param e2 replacement
* @param path path
* @return true if something was replaced.
*/
public boolean replaceObject(JsonObject e1, JsonObject e2, String...path) {
JsonElement compareElement = e1.get(path);
if(compareElement == null) {
throw new IllegalArgumentException("specified path may not be null in object " + StringUtils.join(path));
}
int i=0;
for(JsonElement e: this) {
if(e.isObject()) {
JsonElement fieldValue = e.asObject().get(path);
if(compareElement.equals(fieldValue)) {
set(i,e2);
return true;
}
}
i++;
}
return false;
}
/**
* Convenience method to prevent casting JsonElement to JsonObject when iterating in the common case that you have
* an array of JsonObjects.
*
* @return iterable that iterates over JsonObjects instead of JsonElements.
*/
public Iterable<JsonObject> objects() {
final JsonArray parent=this;
return new Iterable<JsonObject>() {
@Override
public Iterator<JsonObject> iterator() {
final Iterator<JsonElement> iterator = parent.iterator();
return new Iterator<JsonObject>() {
@Override
public boolean hasNext() {
return iterator.hasNext();
}
@Override
public JsonObject next() {
return iterator.next().asObject();
}
@Override
public void remove() {
iterator.remove();
}
};
}
};
}
public Stream<JsonObject> streamObjects() {
return stream().map(e -> e.asObject());
}
public Stream<JsonArray> streamArrays() {
return stream().map(e -> e.asArray());
}
public Stream<String> streamStrings() {
return stream().map(e -> e.asString());
}
public Stream<JsonElement> map(Function<JsonElement,JsonElement> f) {
return stream().map(f);
}
public Stream<JsonObject> mapObjects(Function<JsonObject, JsonObject> f) {
return streamObjects().map(f);
}
public void forEachObject(Consumer<? super JsonObject> action) {
for (JsonElement e : this) {
action.accept(e.asObject());
}
}
/**
* Convenience method to prevent casting JsonElement to JsonArray when iterating in the common case that you have
* an array of JsonArrays.
*
* @return iterable that iterates over JsonArrays instead of JsonElements.
*/
public Iterable<JsonArray> arrays() {
final JsonArray parent=this;
return new Iterable<JsonArray>() {
@Override
public Iterator<JsonArray> iterator() {
final Iterator<JsonElement> iterator = parent.iterator();
return new Iterator<JsonArray>() {
@Override
public boolean hasNext() {
return iterator.hasNext();
}
@Override
public JsonArray next() {
return iterator.next().asArray();
}
@Override
public void remove() {
iterator.remove();
}
};
}
};
}
/**
* Convenience method to prevent casting JsonElement to String when iterating in the common case that you have
* an array of strings.
*
* @return iterable that iterates over Strings instead of JsonElements.
*/
public Iterable<String> strings() {
final JsonArray parent=this;
return new Iterable<String>() {
@Override
public Iterator<String> iterator() {
final Iterator<JsonElement> iterator = parent.iterator();
return new Iterator<String>() {
@Override
public boolean hasNext() {
return iterator.hasNext();
}
@Override
public String next() {
return iterator.next().asString();
}
@Override
public void remove() {
iterator.remove();
}
};
}
};
}
/**
* Convenience method to prevent casting JsonElement to Double when iterating in the common case that you have
* an array of doubles.
*
* @return iterable that iterates over Doubles instead of JsonElements.
*/
public Iterable<Double> doubles() {
final JsonArray parent=this;
return new Iterable<Double>() {
@Override
public Iterator<Double> iterator() {
final Iterator<JsonElement> iterator = parent.iterator();
return new Iterator<Double>() {
@Override
public boolean hasNext() {
return iterator.hasNext();
}
@Override
public Double next() {
return iterator.next().asDouble();
}
@Override
public void remove() {
iterator.remove();
}
};
}
};
}
/**
* Convenience method to prevent casting JsonElement to Long when iterating in the common case that you have
* an array of longs.
*
* @return iterable that iterates over Longs instead of JsonElements.
*/
public Iterable<Long> longs() {
final JsonArray parent=this;
return new Iterable<Long>() {
@Override
public Iterator<Long> iterator() {
final Iterator<JsonElement> iterator = parent.iterator();
return new Iterator<Long>() {
@Override
public boolean hasNext() {
return iterator.hasNext();
}
@Override
public Long next() {
return iterator.next().asLong();
}
@Override
public void remove() {
iterator.remove();
}
};
}
};
}
/**
* Convenience method to prevent casting JsonElement to Long when iterating in the common case that you have
* an array of longs.
*
* @return iterable that iterates over Longs instead of JsonElements.
*/
public Iterable<Integer> ints() {
final JsonArray parent=this;
return new Iterable<Integer>() {
@Override
public Iterator<Integer> iterator() {
final Iterator<JsonElement> iterator = parent.iterator();
return new Iterator<Integer>() {
@Override
public boolean hasNext() {
return iterator.hasNext();
}
@Override
public Integer next() {
return iterator.next().asInt();
}
@Override
public void remove() {
iterator.remove();
}
};
}
};
}
}
|
package it.unibz.inf.ontop.iq.optimizer.impl;
import com.google.common.collect.*;
import it.unibz.inf.ontop.injection.CoreSingletons;
import it.unibz.inf.ontop.injection.IntermediateQueryFactory;
import it.unibz.inf.ontop.injection.OptimizationSingletons;
import it.unibz.inf.ontop.iq.IQ;
import it.unibz.inf.ontop.iq.IQTree;
import it.unibz.inf.ontop.iq.node.ExtensionalDataNode;
import it.unibz.inf.ontop.iq.node.TrueNode;
import it.unibz.inf.ontop.iq.optimizer.SelfJoinSameTermIQOptimizer;
import it.unibz.inf.ontop.iq.transform.IQTreeTransformer;
import it.unibz.inf.ontop.iq.visitor.RequiredExtensionalDataNodeExtractor;
import it.unibz.inf.ontop.model.term.ImmutableExpression;
import it.unibz.inf.ontop.model.term.TermFactory;
import it.unibz.inf.ontop.model.term.Variable;
import it.unibz.inf.ontop.model.term.VariableOrGroundTerm;
import it.unibz.inf.ontop.utils.ImmutableCollectors;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.stream.IntStream;
import java.util.stream.Stream;
@Singleton
public class SelfJoinSameTermIQOptimizerImpl implements SelfJoinSameTermIQOptimizer {
private final IQTreeTransformer lookForDistinctTransformer;
private final IntermediateQueryFactory iqFactory;
@Inject
protected SelfJoinSameTermIQOptimizerImpl(OptimizationSingletons optimizationSingletons, IntermediateQueryFactory iqFactory) {
this.iqFactory = iqFactory;
this.lookForDistinctTransformer = new LookForDistinctTransformerImpl(
SameTermSelfJoinTransformer::new,
optimizationSingletons);
}
@Override
public IQ optimize(IQ query) {
IQTree initialTree = query.getTree();
IQTree newTree = lookForDistinctTransformer.transform(initialTree);
return (newTree.equals(initialTree))
? query
: iqFactory.createIQ(query.getProjectionAtom(), newTree)
.normalizeForOptimization();
}
/**
* TODO: explain
*/
protected static class SameTermSelfJoinTransformer extends AbstractDiscardedVariablesTransformer {
private final IQTreeTransformer lookForDistinctTransformer;
private final OptimizationSingletons optimizationSingletons;
private final IntermediateQueryFactory iqFactory;
private final TermFactory termFactory;
private final RequiredExtensionalDataNodeExtractor requiredExtensionalDataNodeExtractor;
protected SameTermSelfJoinTransformer(ImmutableSet<Variable> discardedVariables,
IQTreeTransformer lookForDistinctTransformer,
OptimizationSingletons optimizationSingletons) {
super(discardedVariables, lookForDistinctTransformer, optimizationSingletons.getCoreSingletons());
this.lookForDistinctTransformer = lookForDistinctTransformer;
this.optimizationSingletons = optimizationSingletons;
CoreSingletons coreSingletons = optimizationSingletons.getCoreSingletons();
iqFactory = coreSingletons.getIQFactory();
termFactory = coreSingletons.getTermFactory();
requiredExtensionalDataNodeExtractor = optimizationSingletons.getRequiredExtensionalDataNodeExtractor();
}
@Override
protected AbstractDiscardedVariablesTransformer update(ImmutableSet<Variable> newDiscardedVariables) {
return new SameTermSelfJoinTransformer(newDiscardedVariables, lookForDistinctTransformer, optimizationSingletons);
}
/**
* TODO: explain
*
* Only removes some children that are extensional data nodes
*/
@Override
protected Optional<IQTree> furtherSimplifyInnerJoinChildren(ImmutableList<ImmutableSet<Variable>> discardedVariablesPerChild,
Optional<ImmutableExpression> optionalFilterCondition,
ImmutableList<IQTree> partiallySimplifiedChildren) {
//Mutable
final List<IQTree> currentChildren = Lists.newArrayList(partiallySimplifiedChildren);
IntStream.range(0, partiallySimplifiedChildren.size())
.boxed()
.filter(i -> isDetectedAsRedundant(
currentChildren.get(i),
discardedVariablesPerChild.get(i),
IntStream.range(0, partiallySimplifiedChildren.size())
.filter(j -> j!= i)
.boxed()
.map(currentChildren::get)))
// SIDE-EFFECT
.forEach(i -> currentChildren.set(i, iqFactory.createTrueNode()));
ImmutableSet<Variable> variablesToFilterNulls = IntStream.range(0, partiallySimplifiedChildren.size())
.filter(i -> currentChildren.get(i).getRootNode() instanceof TrueNode)
.boxed()
.map(i -> Sets.difference(partiallySimplifiedChildren.get(i).getVariables(),
discardedVariablesPerChild.get(i)))
.flatMap(Collection::stream)
.collect(ImmutableCollectors.toSet());
return Optional.of(variablesToFilterNulls)
// If no variable to filter, no change, returns empty
.filter(vs -> !vs.isEmpty())
.map(vs -> vs.stream()
.map(termFactory::getDBIsNotNull))
.map(s -> optionalFilterCondition
.map(f -> Stream.concat(Stream.of(f), s))
.orElse(s))
.flatMap(termFactory::getConjunction)
.map(iqFactory::createInnerJoinNode)
// NB: will be normalized later on
.map(n -> iqFactory.createNaryIQTree(n, ImmutableList.copyOf(currentChildren)));
}
/**
* Should not return any false positive
*/
boolean isDetectedAsRedundant(IQTree child, ImmutableSet<Variable> discardedVariables, Stream<IQTree> otherChildren) {
return Optional.of(child)
.filter(c -> c instanceof ExtensionalDataNode)
.map(c -> (ExtensionalDataNode) c)
.filter(d1 -> otherChildren
.flatMap(t -> t.acceptVisitor(requiredExtensionalDataNodeExtractor))
.anyMatch(d2 -> isDetectedAsRedundant(d1, d2, discardedVariables)))
.isPresent();
}
private boolean isDetectedAsRedundant(ExtensionalDataNode dataNode, ExtensionalDataNode otherDataNode,
ImmutableSet<Variable> discardedVariables) {
if (!dataNode.getRelationDefinition().equals(otherDataNode.getRelationDefinition()))
return false;
ImmutableMap<Integer, ? extends VariableOrGroundTerm> argumentMap = dataNode.getArgumentMap();
ImmutableMap<Integer, ? extends VariableOrGroundTerm> otherArgumentMap = otherDataNode.getArgumentMap();
ImmutableSet<Integer> firstIndexes = argumentMap.keySet();
ImmutableSet<Integer> otherIndexes = otherArgumentMap.keySet();
Sets.SetView<Integer> allIndexes = Sets.union(firstIndexes, otherIndexes);
Sets.SetView<Integer> commonIndexes = Sets.intersection(firstIndexes, otherIndexes);
ImmutableList<? extends VariableOrGroundTerm> differentArguments = allIndexes.stream()
.filter(i -> !(commonIndexes.contains(i) && argumentMap.get(i).equals(otherArgumentMap.get(i))))
.flatMap(i -> Optional.ofNullable(argumentMap.get(i))
.map(Stream::of)
.orElseGet(Stream::empty))
.collect(ImmutableCollectors.toList());
// There must be at least one match
if (differentArguments.size() == allIndexes.size())
return false;
/*
* All the non-matching arguments of the atom must be discarded variables
*/
return discardedVariables.containsAll(differentArguments);
}
}
}
|
package com.bustiblelemons.cthulhator.character.history.logic;
import android.content.Context;
import com.bustiblelemons.async.AbsSimpleAsync;
import com.bustiblelemons.cthulhator.character.characterslist.model.SavedCharacter;
import com.bustiblelemons.cthulhator.character.history.model.HistoryEvent;
import com.bustiblelemons.cthulhator.character.history.model.TimeSpan;
import java.util.Collection;
import java.util.Set;
import java.util.TreeSet;
public class LoadHistoryEventsAsyn
extends AbsSimpleAsync<TimeSpan, Set<HistoryEvent>> {
private final SavedCharacter mSavedCharacter;
private OnHistoryEventsLoaded onHistoryEventsLoaded;
private TimeSpan mTimespan;
public LoadHistoryEventsAsyn(Context context, SavedCharacter savedCharacter) {
super(context);
mSavedCharacter = savedCharacter;
}
public void setOnHistoryEventsLoaded(OnHistoryEventsLoaded onHistoryEventsLoaded) {
this.onHistoryEventsLoaded = onHistoryEventsLoaded;
}
@Override
protected Set<HistoryEvent> call(TimeSpan... params) throws Exception {
Set<HistoryEvent> result = new TreeSet<HistoryEvent>(HistoryComparators.DATE_DES);
Collection<HistoryEvent> fullHistory = mSavedCharacter.getFullHistory();
HistoryEvent birthEvent = HistoryEventFactory.from(getContext())
.withCharacter(mSavedCharacter)
.buildBirthEvent();
fullHistory.add(birthEvent);
result.addAll(fullHistory);
publishProgress(mTimespan, result);
return null;
}
@Override
protected boolean onException(Exception e) {
return false;
}
@Override
public void onProgressUpdate(TimeSpan param, Set<HistoryEvent> result) {
if (onHistoryEventsLoaded != null) {
onHistoryEventsLoaded.onHistoryEventsLoaded(param, result);
}
}
public interface OnHistoryEventsLoaded {
/**
* @param events set of sorted events by date;
*/
void onHistoryEventsLoaded(TimeSpan span, Set<HistoryEvent> events);
}
}
|
package com.ninty.cmd;
import com.ninty.cmd.base.ICmdBase;
import com.ninty.cmd.base.NoOperandCmd;
import com.ninty.runtime.NiFrame;
import java.nio.ByteBuffer;
public class CmdConstants {
static class NOP extends NoOperandCmd{
}
static class ACONST_NULL extends NoOperandCmd{
@Override
public void exec(NiFrame frame) {
frame.getOperandStack().pushRef(null);
}
}
static class DCONST_0 extends NoOperandCmd{
@Override
public void exec(NiFrame frame) {
frame.getOperandStack().pushDouble(0.0);
}
}
static class DCONST_1 extends NoOperandCmd{
@Override
public void exec(NiFrame frame) {
frame.getOperandStack().pushDouble(1.0);
}
}
static class FCONST_0 extends NoOperandCmd{
@Override
public void exec(NiFrame frame) {
frame.getOperandStack().pushFloat(0.0f);
}
}
static class FCONST_1 extends NoOperandCmd{
@Override
public void exec(NiFrame frame) {
frame.getOperandStack().pushFloat(1.0f);
}
}
static class FCONST_2 extends NoOperandCmd{
@Override
public void exec(NiFrame frame) {
frame.getOperandStack().pushFloat(2.0f);
}
}
static class ICONST_M1 extends NoOperandCmd{
@Override
public void exec(NiFrame frame) {
frame.getOperandStack().pushInt(-1);
}
}
static class ICONST_0 extends NoOperandCmd{
@Override
public void exec(NiFrame frame) {
frame.getOperandStack().pushInt(0);
}
}
static class ICONST_1 extends NoOperandCmd{
@Override
public void exec(NiFrame frame) {
frame.getOperandStack().pushInt(1);
}
}
static class ICONST_2 extends NoOperandCmd{
@Override
public void exec(NiFrame frame) {
frame.getOperandStack().pushInt(2);
}
}
static class ICONST_3 extends NoOperandCmd{
@Override
public void exec(NiFrame frame) {
frame.getOperandStack().pushInt(3);
}
}
static class ICONST_4 extends NoOperandCmd{
@Override
public void exec(NiFrame frame) {
frame.getOperandStack().pushInt(4);
}
}
static class ICONST_5 extends NoOperandCmd{
@Override
public void exec(NiFrame frame) {
frame.getOperandStack().pushInt(5);
}
}
static class LCONST_0 extends NoOperandCmd{
@Override
public void exec(NiFrame frame) {
frame.getOperandStack().pushInt(0);
}
}
static class LCONST_1 extends NoOperandCmd{
@Override
public void exec(NiFrame frame) {
frame.getOperandStack().pushInt(1);
}
}
static class BIPUSH implements ICmdBase{
int val;
@Override
public void init(ByteBuffer bb) {
val = bb.get();
}
@Override
public void exec(NiFrame frame) {
frame.getOperandStack().pushInt(val);
}
}
static class SIPUSH implements ICmdBase{
int val;
@Override
public void init(ByteBuffer bb) {
val = bb.getShort();
}
@Override
public void exec(NiFrame frame) {
frame.getOperandStack().pushInt(val);
}
}
}
|
package ucar.unidata.geoloc.projection;
import com.google.common.math.DoubleMath;
import ucar.nc2.constants.CDM;
import ucar.nc2.constants.CF;
import ucar.unidata.geoloc.*;
import ucar.unidata.util.SpecialMathFunction;
/**
* Transverse Mercator projection, spherical earth.
* Projection plane is a cylinder tangent to the earth at tangentLon.
* See John Snyder, Map Projections used by the USGS, Bulletin 1532, 2nd edition (1983), p 53
*
* @author John Caron
*/
public class TransverseMercator extends ProjectionImpl {
private double lat0, lon0, scale, earthRadius;
private double falseEasting, falseNorthing;
@Override
public ProjectionImpl constructCopy() {
ProjectionImpl result = new TransverseMercator(getOriginLat(), getTangentLon(),
getScale(), getFalseEasting(), getFalseNorthing(), getEarthRadius());
result.setDefaultMapArea(defaultMapArea);
result.setName(name);
return result;
}
/**
* Constructor with default parameteres
*/
public TransverseMercator() {
this(40.0, -105.0, .9996);
}
/**
* Construct a TransverseMercator Projection.
*
* @param lat0 origin of projection coord system is at (lat0, tangentLon)
* @param tangentLon longitude that the cylinder is tangent at ("central meridian")
* @param scale scale factor along the central meridian
*/
public TransverseMercator(double lat0, double tangentLon, double scale) {
this(lat0, tangentLon, scale, 0.0, 0.0, EARTH_RADIUS);
}
/**
* Construct a TransverseMercator Projection.
*
* @param lat0 origin of projection coord system is at (lat0, tangentLon)
* @param tangentLon longitude that the cylinder is tangent at ("central meridian")
* @param scale scale factor along the central meridian
* @param east false easting in km
* @param north false northing in km
*/
public TransverseMercator(double lat0, double tangentLon, double scale, double east, double north) {
this(lat0, tangentLon, scale, east, north, EARTH_RADIUS);
}
/**
* Construct a TransverseMercator Projection.
*
* @param lat0 origin of projection coord system is at (lat0, tangentLon)
* @param tangentLon longitude that the cylinder is tangent at ("central meridian")
* @param scale scale factor along the central meridian
* @param east false easting in units of km
* @param north false northing in units of km
* @param radius earth radius in km
*/
public TransverseMercator(double lat0, double tangentLon, double scale, double east, double north, double radius) {
super("TransverseMercator", false);
this.lat0 = Math.toRadians(lat0);
this.lon0 = Math.toRadians(tangentLon);
this.earthRadius = radius;
this.scale = scale * earthRadius;
this.falseEasting = (!Double.isNaN(east)) ? east : 0.0;
this.falseNorthing = (!Double.isNaN(north)) ? north : 0.0;
addParameter(CF.GRID_MAPPING_NAME, CF.TRANSVERSE_MERCATOR);
addParameter(CF.LONGITUDE_OF_CENTRAL_MERIDIAN, tangentLon);
addParameter(CF.LATITUDE_OF_PROJECTION_ORIGIN, lat0);
addParameter(CF.SCALE_FACTOR_AT_CENTRAL_MERIDIAN, scale);
addParameter(CF.EARTH_RADIUS, earthRadius * 1000);
if ((falseEasting != 0.0) || (falseNorthing != 0.0)) {
addParameter(CF.FALSE_EASTING, falseEasting);
addParameter(CF.FALSE_NORTHING, falseNorthing);
addParameter(CDM.UNITS, "km");
}
}
// bean properties
/**
* Get the scale
*
* @return the scale
*/
public double getScale() {
return scale / earthRadius;
}
/**
* Get the tangent longitude in degrees
*
* @return the origin longitude.
*/
public double getTangentLon() {
return Math.toDegrees(lon0);
}
/**
* Get the origin latitude in degrees
*
* @return the origin latitude.
*/
public double getOriginLat() {
return Math.toDegrees(lat0);
}
/**
* Get the false easting, in units of km.
*
* @return the false easting.
*/
public double getFalseEasting() {
return falseEasting;
}
/**
* Get the false northing, in units of km
*
* @return the false northing.
*/
public double getFalseNorthing() {
return falseNorthing;
}
public double getEarthRadius() {
return earthRadius;
}
// setters for IDV serialization - do not use except for object creating
/**
* Set the scale
*
* @param scale the scale
*/
public void setScale(double scale) {
this.scale = earthRadius * scale;
}
/**
* Set the origin latitude
*
* @param lat the origin latitude
*/
public void setOriginLat(double lat) {
lat0 = Math.toRadians(lat);
}
/**
* Set the tangent longitude
*
* @param lon the tangent longitude
*/
public void setTangentLon(double lon) {
lon0 = Math.toRadians(lon);
}
/**
* Set the false_easting, in km.
* natural_x_coordinate + false_easting = x coordinate
* @param falseEasting x offset
*/
public void setFalseEasting(double falseEasting) {
this.falseEasting = falseEasting;
}
/**
* Set the false northing, in km.
* natural_y_coordinate + false_northing = y coordinate
* @param falseNorthing y offset
*/
public void setFalseNorthing(double falseNorthing) {
this.falseNorthing = falseNorthing;
}
/**
* Get the label to be used in the gui for this type of projection
*
* @return Type label
*/
public String getProjectionTypeLabel() {
return "Transverse mercator";
}
/**
* Get the parameters as a String
*
* @return the parameters as a String
*/
public String paramsToString() {
return toString();
}
@Override
public String toString() {
return "TransverseMercator{" +
"lat0=" + lat0 +
", lon0=" + lon0 +
", scale=" + scale +
", earthRadius=" + earthRadius +
", falseEasting=" + falseEasting +
", falseNorthing=" + falseNorthing +
'}';
}
/**
* Does the line between these two points cross the projection "seam".
*
* @param pt1 the line goes between these two points
* @param pt2 the line goes between these two points
* @return false if there is no seam
*/
public boolean crossSeam(ProjectionPoint pt1, ProjectionPoint pt2) {
// either point is infinite
if (ProjectionPointImpl.isInfinite(pt1)
|| ProjectionPointImpl.isInfinite(pt2)) {
return true;
}
double y1 = pt1.getY() - falseNorthing;
double y2 = pt2.getY() - falseNorthing;
// opposite signed long lines
return (y1 * y2 < 0) && (Math.abs(y1 - y2) > 2 * earthRadius);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
TransverseMercator that = (TransverseMercator) o;
double tolerance = 1e-6;
if (DoubleMath.fuzzyCompare(that.earthRadius, earthRadius, tolerance) != 0) return false;
if (DoubleMath.fuzzyCompare(that.falseEasting, falseEasting, tolerance) != 0) return false;
if (DoubleMath.fuzzyCompare(that.falseNorthing, falseNorthing, tolerance) != 0) return false;
if (DoubleMath.fuzzyCompare(that.lat0, lat0, tolerance) != 0) return false;
if (DoubleMath.fuzzyCompare(that.lon0, lon0, tolerance) != 0) return false;
if (DoubleMath.fuzzyCompare(that.scale, scale, tolerance) != 0) return false;
if ((defaultMapArea == null) != (that.defaultMapArea == null)) return false; // common case is that these are null
if (defaultMapArea != null && !that.defaultMapArea.equals(defaultMapArea)) return false;
return true;
}
@Override
public int hashCode() {
int result;
long temp;
temp = lat0 != +0.0d ? Double.doubleToLongBits(lat0) : 0L;
result = (int) (temp ^ (temp >>> 32));
temp = lon0 != +0.0d ? Double.doubleToLongBits(lon0) : 0L;
result = 31 * result + (int) (temp ^ (temp >>> 32));
temp = scale != +0.0d ? Double.doubleToLongBits(scale) : 0L;
result = 31 * result + (int) (temp ^ (temp >>> 32));
temp = earthRadius != +0.0d ? Double.doubleToLongBits(earthRadius) : 0L;
result = 31 * result + (int) (temp ^ (temp >>> 32));
temp = falseEasting != +0.0d ? Double.doubleToLongBits(falseEasting) : 0L;
result = 31 * result + (int) (temp ^ (temp >>> 32));
temp = falseNorthing != +0.0d ? Double.doubleToLongBits(falseNorthing) : 0L;
result = 31 * result + (int) (temp ^ (temp >>> 32));
return result;
}
/*MACROBODY
projToLatLon {} {
double x = (fromX-falseEasting)/scale;
double d = (fromY-falseNorthing)/scale + lat0;
toLon = Math.toDegrees(lon0 + Math.atan2(SpecialMathFunction.sinh(x), Math.cos(d)));
toLat = Math.toDegrees(Math.asin( Math.sin(d)/ SpecialMathFunction.cosh(x)));
}
latLonToProj {} {
double lon = Math.toRadians(fromLon);
double lat = Math.toRadians(fromLat);
double dlon = lon-lon0;
double b = Math.cos( lat) * Math.sin(dlon);
// infinite projection
if ((Math.abs(Math.abs(b) - 1.0)) < TOLERANCE) {
toX = 0.0; toY = 0.0;
} else {
toX = scale * SpecialMathFunction.atanh(b) + falseEasting;
toY = scale * (Math.atan2(Math.tan(lat),Math.cos(dlon)) - lat0) + falseNorthing;
}
}
MACROBODY*/
/*BEGINGENERATED*/
/*
Note this section has been generated using the convert.tcl script.
This script, run as:
tcl convert.tcl TransverseMercator.java
takes the actual projection conversion code defined in the MACROBODY
section above and generates the following 6 methods
*/
/**
* Convert a LatLonPoint to projection coordinates
*
* @param latLon convert from these lat, lon coordinates
* @param result the object to write to
* @return the given result
*/
public ProjectionPoint latLonToProj(LatLonPoint latLon,
ProjectionPointImpl result) {
double toX, toY;
double fromLat = latLon.getLatitude();
double fromLon = latLon.getLongitude();
double lon = Math.toRadians(fromLon);
double lat = Math.toRadians(fromLat);
double dlon = lon - lon0;
double b = Math.cos(lat) * Math.sin(dlon);
// infinite projection
if ((Math.abs(Math.abs(b) - 1.0)) < TOLERANCE) {
toX = 0.0;
toY = 0.0;
} else {
toX = scale * SpecialMathFunction.atanh(b);
toY = scale * (Math.atan2(Math.tan(lat), Math.cos(dlon)) - lat0);
}
result.setLocation(toX + falseEasting, toY + falseNorthing);
return result;
}
public LatLonPoint projToLatLon(ProjectionPoint world,
LatLonPointImpl result) {
double toLat, toLon;
double fromX = world.getX();
double fromY = world.getY();
double x = (fromX - falseEasting) / scale;
double d = (fromY - falseNorthing) / scale + lat0;
toLon = Math.toDegrees(lon0 + Math.atan2(Math.sinh(x), Math.cos(d)));
toLat = Math.toDegrees(Math.asin(Math.sin(d) / Math.cosh(x)));
result.setLatitude(toLat);
result.setLongitude(toLon);
return result;
}
/**
* Convert lat/lon coordinates to projection coordinates.
*
* @param from array of lat/lon coordinates: from[2][n],
* where from[0][i], from[1][i] is the (lat,lon)
* coordinate of the ith point
* @param to resulting array of projection coordinates,
* where to[0][i], to[1][i] is the (x,y) coordinate
* of the ith point
* @param latIndex index of latitude in "from"
* @param lonIndex index of longitude in "from"
* @return the "to" array.
*/
public float[][] latLonToProj(float[][] from, float[][] to, int latIndex,
int lonIndex) {
int cnt = from[0].length;
float[] fromLatA = from[latIndex];
float[] fromLonA = from[lonIndex];
float[] resultXA = to[INDEX_X];
float[] resultYA = to[INDEX_Y];
double toX, toY;
for (int i = 0; i < cnt; i++) {
double fromLat = fromLatA[i];
double fromLon = fromLonA[i];
double lon = Math.toRadians(fromLon);
double lat = Math.toRadians(fromLat);
double dlon = lon - lon0;
double b = Math.cos(lat) * Math.sin(dlon);
// infinite projection
if ((Math.abs(Math.abs(b) - 1.0)) < TOLERANCE) {
toX = 0.0;
toY = 0.0;
} else {
toX = scale * SpecialMathFunction.atanh(b) + falseEasting;
toY = scale * (Math.atan2(Math.tan(lat), Math.cos(dlon)) - lat0) + falseNorthing;
}
resultXA[i] = (float) toX;
resultYA[i] = (float) toY;
}
return to;
}
/**
* Convert lat/lon coordinates to projection coordinates.
*
* @param from array of lat/lon coordinates: from[2][n], where
* (from[0][i], from[1][i]) is the (lat,lon) coordinate
* of the ith point
* @param to resulting array of projection coordinates: to[2][n]
* where (to[0][i], to[1][i]) is the (x,y) coordinate
* of the ith point
* @return the "to" array
*/
public float[][] projToLatLon(float[][] from, float[][] to) {
int cnt = from[0].length;
float[] fromXA = from[INDEX_X];
float[] fromYA = from[INDEX_Y];
float[] toLatA = to[INDEX_LAT];
float[] toLonA = to[INDEX_LON];
double toLat, toLon;
for (int i = 0; i < cnt; i++) {
double fromX = fromXA[i];
double fromY = fromYA[i];
double x = (fromX - falseEasting) / scale;
double d = (fromY - falseNorthing) / scale + lat0;
toLon = Math.toDegrees(lon0 + Math.atan2(Math.sinh(x), Math.cos(d)));
toLat = Math.toDegrees(Math.asin(Math.sin(d) / Math.cosh(x)));
toLatA[i] = (float) toLat;
toLonA[i] = (float) toLon;
}
return to;
}
/**
* Convert lat/lon coordinates to projection coordinates.
*
* @param from array of lat/lon coordinates: from[2][n],
* where from[0][i], from[1][i] is the (lat,lon)
* coordinate of the ith point
* @param to resulting array of projection coordinates,
* where to[0][i], to[1][i] is the (x,y) coordinate
* of the ith point
* @param latIndex index of latitude in "from"
* @param lonIndex index of longitude in "from"
* @return the "to" array.
*/
public double[][] latLonToProj(double[][] from, double[][] to,
int latIndex, int lonIndex) {
int cnt = from[0].length;
double[] fromLatA = from[latIndex];
double[] fromLonA = from[lonIndex];
double[] resultXA = to[INDEX_X];
double[] resultYA = to[INDEX_Y];
double toX, toY;
for (int i = 0; i < cnt; i++) {
double fromLat = fromLatA[i];
double fromLon = fromLonA[i];
double lon = Math.toRadians(fromLon);
double lat = Math.toRadians(fromLat);
double dlon = lon - lon0;
double b = Math.cos(lat) * Math.sin(dlon);
// infinite projection
if ((Math.abs(Math.abs(b) - 1.0)) < TOLERANCE) {
toX = 0.0;
toY = 0.0;
} else {
toX = scale * SpecialMathFunction.atanh(b) + falseEasting;
toY = scale * (Math.atan2(Math.tan(lat), Math.cos(dlon)) - lat0) + falseNorthing;
}
resultXA[i] = (double) toX;
resultYA[i] = (double) toY;
}
return to;
}
/**
* Convert lat/lon coordinates to projection coordinates.
*
* @param from array of lat/lon coordinates: from[2][n], where
* (from[0][i], from[1][i]) is the (lat,lon) coordinate
* of the ith point
* @param to resulting array of projection coordinates: to[2][n]
* where (to[0][i], to[1][i]) is the (x,y) coordinate
* of the ith point
* @return the "to" array
*/
public double[][] projToLatLon(double[][] from, double[][] to) {
int cnt = from[0].length;
double[] fromXA = from[INDEX_X];
double[] fromYA = from[INDEX_Y];
double[] toLatA = to[INDEX_LAT];
double[] toLonA = to[INDEX_LON];
double toLat, toLon;
for (int i = 0; i < cnt; i++) {
double fromX = fromXA[i];
double fromY = fromYA[i];
double x = (fromX - falseEasting) / scale;
double d = (fromY - falseNorthing) / scale + lat0;
toLon = Math.toDegrees(lon0 + Math.atan2(Math.sinh(x), Math.cos(d)));
toLat = Math.toDegrees(Math.asin(Math.sin(d) / Math.cosh(x)));
toLatA[i] = (double) toLat;
toLonA[i] = (double) toLon;
}
return to;
}
/*ENDGENERATED*/
}
|
package com.nottesla.roosight;
import org.opencv.core.Core;
import org.opencv.core.Mat;
import java.awt.*;
import java.io.File;
public class Test {
public static void main(String[] args) throws InterruptedException {
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
Mat mat = new Mat((long) 18364734);
// Mat mat1 = new Mat();
// process(new File("/tmp/images/0.jpg"));
File files[] = new File("/tmp/images").listFiles();
for (int i = 0; i < files.length; ++i) {
// process(files[i]);
}
}
public static void process(File file) {
if (!file.getName().endsWith(".jpg") || file.getName().endsWith(".jpg.jpg")) {
return;
}
System.out.println(file.getName());
System.out.printf("Usage: %d/%d (%d%%)", Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(), Runtime.getRuntime().totalMemory(), (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) * 100 / Runtime.getRuntime().totalMemory());
RooColorImage colorImage = new RooColorImage(file.getAbsolutePath());
RooConfig config = new RooConfig();
config.setMinArea(400);
config.setMinPerimeter(300);
config.setRGB(0, 220, 55, 255, 25, 240);
config.setHSL(37, 100, 30, 255, 150, 255);
config.setHSV(37, 100, 30, 255, 50, 255);
RooProcessor rooProcessor = new RooProcessor(config);
RooBinaryImage thresh = rooProcessor.processImage(colorImage);
thresh.blur(1);
RooContour[] contours = rooProcessor.findContours(thresh);
colorImage.drawContours(contours, new RooColor(Color.RED), 2);
colorImage.markContours(contours, new RooColor(Color.RED), 1);
colorImage.writeToFile(file.getAbsolutePath() + ".jpg");
}
}
|
package io.debezium.connector.postgresql.connection;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.OffsetDateTime;
import java.time.OffsetTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.format.DateTimeParseException;
import java.time.format.SignStyle;
import java.time.format.TextStyle;
import java.time.temporal.ChronoField;
import java.time.temporal.TemporalAccessor;
import java.util.function.Supplier;
import org.apache.kafka.connect.errors.ConnectException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.debezium.connector.postgresql.PostgresValueConverter;
/**
* Transformer for time/date related string representations in replication messages.
*
* @author Jiri Pechanec
*
*/
public interface DateTimeFormat {
public Instant timestampToInstant(final String s);
public OffsetDateTime timestampWithTimeZoneToOffsetDateTime(final String s);
public Instant systemTimestampToInstant(final String s);
public LocalDate date(final String s);
public LocalTime time(final String s);
public OffsetTime timeWithTimeZone(final String s);
public static DateTimeFormat get() {
return new ISODateTimeFormat();
}
public static class ISODateTimeFormat implements DateTimeFormat {
private static final Logger LOGGER = LoggerFactory.getLogger(ISODateTimeFormat.class);
// This formatter is similar to standard Java's ISO_LOCAL_DATE. But this one is
// using 'YEAR_OF_ERA + SignStyle.NEVER' instead of 'YEAR+SignStyle.EXCEEDS_PAD'
// to support ChronoField.ERA at the end of the date string.
private static final DateTimeFormatter NON_ISO_LOCAL_DATE = new DateTimeFormatterBuilder()
.appendValue(ChronoField.YEAR_OF_ERA, 4, 10, SignStyle.NEVER)
.appendLiteral('-')
.appendValue(ChronoField.MONTH_OF_YEAR, 2)
.appendLiteral('-')
.appendValue(ChronoField.DAY_OF_MONTH, 2)
.toFormatter();
private static final String TS_FORMAT_PATTERN_HINT = "y..y-MM-dd HH:mm:ss[.S]";
private static final DateTimeFormatter TS_FORMAT = new DateTimeFormatterBuilder()
.append(NON_ISO_LOCAL_DATE)
.appendLiteral(' ')
.append(DateTimeFormatter.ISO_LOCAL_TIME)
.optionalStart()
.appendLiteral(" ")
.appendText(ChronoField.ERA, TextStyle.SHORT)
.optionalEnd()
.toFormatter();
private static final String TS_TZ_FORMAT_PATTERN_HINT = "y..y-MM-dd HH:mm:ss[.S]X";
private static final DateTimeFormatter TS_TZ_FORMAT = new DateTimeFormatterBuilder()
.append(NON_ISO_LOCAL_DATE)
.appendLiteral(' ')
.append(DateTimeFormatter.ISO_LOCAL_TIME)
.appendOffset("+HH:mm", "")
.optionalStart()
.appendLiteral(" ")
.appendText(ChronoField.ERA, TextStyle.SHORT)
.optionalEnd()
.toFormatter();
private static final DateTimeFormatter TS_TZ_WITH_SECONDS_FORMAT = new DateTimeFormatterBuilder()
.append(NON_ISO_LOCAL_DATE)
.appendLiteral(' ')
.append(DateTimeFormatter.ISO_LOCAL_TIME)
.appendOffset("+HH:MM:SS", "")
.optionalStart()
.appendLiteral(" ")
.appendText(ChronoField.ERA, TextStyle.SHORT)
.optionalEnd()
.toFormatter();
private static final String SYSTEM_TS_FORMAT_PATTERN_HINT = "y..y-MM-dd HH:mm:ss.SSSSSSX";
private static final DateTimeFormatter SYSTEM_TS_FORMAT = new DateTimeFormatterBuilder()
.append(NON_ISO_LOCAL_DATE)
.appendLiteral(' ')
.append(DateTimeFormatter.ISO_LOCAL_TIME)
.appendOffset("+HH:mm", "Z")
.optionalStart()
.appendLiteral(" ")
.appendText(ChronoField.ERA, TextStyle.SHORT)
.optionalEnd()
.toFormatter();
private static final String DATE_FORMAT_OPT_ERA_PATTERN_HINT = "y..y-MM-dd[ GG]";
private static final DateTimeFormatter DATE_FORMAT_OPT_ERA = new DateTimeFormatterBuilder()
.append(NON_ISO_LOCAL_DATE)
.optionalStart()
.appendLiteral(' ')
.appendText(ChronoField.ERA, TextStyle.SHORT)
.optionalEnd()
.toFormatter();
private static final String TIME_FORMAT_PATTERN = "HH:mm:ss[.S]";
private static final DateTimeFormatter TIME_FORMAT = new DateTimeFormatterBuilder()
.appendPattern("HH:mm:ss")
.optionalStart()
.appendFraction(ChronoField.MICRO_OF_SECOND, 0, 6, true)
.optionalEnd()
.toFormatter();
private static final String TIME_TZ_FORMAT_PATTERN = "HH:mm:ss[.S]X";
private static final DateTimeFormatter TIME_TZ_FORMAT = new DateTimeFormatterBuilder()
.append(DateTimeFormatter.ISO_LOCAL_TIME)
.appendOffset("+HH:mm", "")
.toFormatter();
@Override
public LocalDate date(final String s) {
return format(DATE_FORMAT_OPT_ERA_PATTERN_HINT, s, () -> {
if ("infinity".equals(s)) {
return PostgresValueConverter.POSITIVE_INFINITY_LOCAL_DATE;
}
else if ("-infinity".equals(s)) {
return PostgresValueConverter.NEGATIVE_INFINITY_LOCAL_DATE;
}
else {
return LocalDate.parse(s, DATE_FORMAT_OPT_ERA);
}
});
}
@Override
public LocalTime time(final String s) {
return format(TIME_FORMAT_PATTERN, s, () -> LocalTime.parse(s, TIME_FORMAT));
}
@Override
public OffsetTime timeWithTimeZone(final String s) {
return format(TIME_TZ_FORMAT_PATTERN, s, () -> OffsetTime.parse(s, TIME_TZ_FORMAT)).withOffsetSameInstant(ZoneOffset.UTC);
}
private <T> T format(final String pattern, final String s, final Supplier<T> value) {
try {
return value.get();
}
catch (final DateTimeParseException e) {
LOGGER.error("Cannot parse time/date value '{}', expected format '{}'", s, pattern);
throw new ConnectException(e);
}
}
@Override
public Instant timestampToInstant(String s) {
return format(TS_FORMAT_PATTERN_HINT, s, () -> LocalDateTime.from(TS_FORMAT.parse(s)).toInstant(ZoneOffset.UTC));
}
@Override
public OffsetDateTime timestampWithTimeZoneToOffsetDateTime(String s) {
return format(TS_TZ_FORMAT_PATTERN_HINT, s, () -> {
TemporalAccessor parsedTimestamp;
// Usually the timestamp contains only hour offset and optionally minutes
// For very large negative timestamps the offset could contain seconds
// The standard parsing library does not allow both optional minutes and seconds in offset,
// so it is necessary to parse it with optional minutes and if that fails then retyr with
// seconds
try {
parsedTimestamp = TS_TZ_FORMAT.parse(s);
}
catch (DateTimeParseException e) {
parsedTimestamp = TS_TZ_WITH_SECONDS_FORMAT.parse(s);
}
return OffsetDateTime.from(parsedTimestamp);
});
}
@Override
public Instant systemTimestampToInstant(String s) {
return format(SYSTEM_TS_FORMAT_PATTERN_HINT, s, () -> OffsetDateTime.from(SYSTEM_TS_FORMAT.parse(s)).toInstant());
}
}
}
|
package com.wepay.model;
import java.io.IOException;
import org.json.*;
import com.wepay.WePay;
import com.wepay.net.WePayResource;
import com.wepay.exception.WePayException;
import com.wepay.model.data.*;
public class CreditCard extends WePayResource {
protected Long creditCardId;
protected String state;
protected String creditCardName;
protected String userName;
protected String email;
protected Long createTime;
protected String inputSource;
protected String virtualTerminalMode;
protected String referenceId;
protected Integer expirationMonth;
protected Integer expirationYear;
protected String lastFour;
protected Long[] rbits;
public CreditCard(Long creditCardId) {
this.creditCardId = creditCardId;
}
public static CreditCard fetch(Long creditCardId, String accessToken) throws JSONException, IOException, WePayException {
JSONObject params = new JSONObject();
params.put("credit_card_id", creditCardId);
params.put("client_id", WePay.clientId);
params.put("client_secret", WePay.clientSecret);
String response = request("/credit_card", params, accessToken);
CreditCard cc = gson.fromJson(response, CreditCard.class);
return cc;
}
public void authorize(String accessToken) throws JSONException, IOException, WePayException {
JSONObject params = new JSONObject();
params.put("credit_card_id", this.creditCardId);
params.put("client_id", WePay.clientId);
params.put("client_secret", WePay.clientSecret);
request("/credit_card/authorize", params, accessToken);
}
public static CreditCard[] find(CreditCardFindData findData, String accessToken) throws JSONException, IOException, WePayException {
JSONObject params = new JSONObject();
params.put("client_id", WePay.clientId);
params.put("client_secret", WePay.clientSecret);
if (findData != null) {
if (findData.referenceId != null) params.put("reference_id", findData.referenceId);
if (findData.limit != null) params.put("limit", findData.limit);
if (findData.start != null) params.put("start", findData.start);
if (findData.sortOrder != null) params.put("sort_order", findData.sortOrder);
}
JSONArray results = new JSONArray(request("/credit_card/find", params, accessToken));
CreditCard[] found = new CreditCard[results.length()];
for (int i = 0; i < found.length; i++) {
CreditCard cc = gson.fromJson(results.get(i).toString(), CreditCard.class);
found[i] = cc;
}
return found;
}
public void delete(String accessToken) throws JSONException, IOException, WePayException {
JSONObject params = new JSONObject();
params.put("credit_card_id", this.creditCardId);
params.put("client_id", WePay.clientId);
params.put("client_secret", WePay.clientSecret);
request("/credit_card/delete", params, accessToken);
}
public Long getCreditCardId() {
return creditCardId;
}
public String getCreditCardName() {
return creditCardName;
}
public String getState() {
return state;
}
public String getUserName() {
return userName;
}
public String getEmail() {
return email;
}
public long getCreateTime() {
return createTime;
}
public String getInputSource() {
return inputSource;
}
public String getVirtualTerminalMode() {
return virtualTerminalMode;
}
public String getReferenceId() {
return referenceId;
}
public Integer getExpirationMonth() {
return expirationMonth;
}
public Integer getExpirationYear() {
return expirationYear;
}
public String getLastFour() {
return lastFour;
}
public Long[] getRbits() {
return rbits;
}
}
|
package com.mindoo.domino.jna.richtext.conversion;
import com.mindoo.domino.jna.constants.CDRecordType;
import com.mindoo.domino.jna.errors.FormulaCompilationError;
import com.mindoo.domino.jna.errors.NotesError;
import com.mindoo.domino.jna.internal.FormulaCompiler;
import com.mindoo.domino.jna.internal.FormulaDecompiler;
import com.mindoo.domino.jna.internal.NotesConstants;
import com.mindoo.domino.jna.internal.structs.NotesTimeDateStruct;
import com.mindoo.domino.jna.internal.structs.compoundtext.NotesCDFieldStruct;
import com.mindoo.domino.jna.internal.structs.compoundtext.NotesCDPabHideStruct;
import com.mindoo.domino.jna.internal.structs.compoundtext.NotesCDResourceStruct;
import com.mindoo.domino.jna.internal.structs.compoundtext.NotesCdHotspotBeginStruct;
import com.mindoo.domino.jna.richtext.FieldInfo;
import com.mindoo.domino.jna.richtext.ICompoundText;
import com.mindoo.domino.jna.richtext.IRichTextNavigator;
import com.mindoo.domino.jna.utils.NotesStringUtils;
import com.mindoo.domino.jna.utils.StringUtil;
import com.sun.jna.Memory;
import com.sun.jna.Pointer;
/**
* Abstract base class to convert fields in design richtext. Conversion includes field name and description
* change as well as text replacement and recompilation of default value, input translation and
* input validity check formulas.
*
* @author Karsten Lehmann
*/
public abstract class AbstractFieldAndFormulaConversion implements IRichTextConversion {
/** type of field formula */
public static enum FormulaType { DEFAULTVALUE, INPUTTRANSLATION, INPUTVALIDITYCHECK }
/**
* Check here if a formula needs a change
*
* @param fieldName name of current field
* @param type type of formula
* @param formula formula
* @return true if change is required
*/
protected abstract boolean fieldFormulaContainsMatch(String fieldName, FormulaType type, String formula);
/**
* Apply change to formula
*
* @param fieldName name of current field
* @param type type of formula
* @param formula formula
* @return changed formula
*/
protected abstract String replaceAllMatchesInFieldFormula(String fieldName, FormulaType type, String formula);
/**
* Check here if a hide when formula needs a change
*
* @param formula hide when formula
* @return true if change is required
*/
protected abstract boolean hideWhenFormulaContainsMatch(String formula);
/**
* Apply change to hide when formula
*
* @param formula hide when formula
* @return changed formula
*/
protected abstract String replaceAllMatchesInHideWhenFormula(String formula);
/**
* Check here if a hotspot formula needs a change
*
* @param formula hotspot formula
* @return true if change is required
*/
protected abstract boolean hotspotFormulaContainsMatch(String formula);
/**
* Apply change to hotspot formula
*
* @param formula hotspot formula
* @return changed formula
*/
protected abstract String replaceAllMatchesInHotspotFormula(String formula);
/**
* Check here if the field name needs a change
*
* @param fieldName field name
* @return true if change is required
*/
protected abstract boolean fieldNameContainsMatch(String fieldName);
/**
* Apply change to field name
*
* @param fieldName field name
* @return new field name
*/
protected abstract String replaceAllMatchesInFieldName(String fieldName);
/**
* Check here if the field description needs a change
*
* @param fieldName name of current field
* @param fieldDesc field description
* @return true if change is required
*/
protected abstract boolean fieldDescriptionContainsMatch(String fieldName, String fieldDesc);
/**
* Apply change to field description
*
* @param fieldName name of current field
* @param fieldDesc field description
* @return new field description
*/
protected abstract String replaceAllMatchesInFieldDescription(String fieldName, String fieldDesc);
/**
* Override this method to check if a custom change to the CDField record
* is required
*
* @param cdFieldStruct CDField structure
* @return true if change is required, default implementation returns false
*/
protected boolean isCustomFieldChangeRequired(NotesCDFieldStruct cdFieldStruct) {
return false;
}
/**
* Empty method, can be used to apply custom field changes
* @param cdFieldStruct CDField structure
*/
protected void applyCustomFieldChanges(NotesCDFieldStruct cdFieldStruct) {
}
@Override
public boolean isMatch(IRichTextNavigator nav) {
if (nav.gotoFirst()) {
do {
if (CDRecordType.FIELD.getConstant() == nav.getCurrentRecordTypeAsShort()) {
Memory recordData = nav.getCurrentRecordDataWithHeader();
NotesCDFieldStruct cdField = NotesCDFieldStruct.newInstance(recordData);
FieldInfo fieldInfo = new FieldInfo(cdField);
String fieldName = fieldInfo.getName();
if (fieldNameContainsMatch(fieldName)) {
return true;
}
if (!StringUtil.isEmpty(fieldInfo.getDescription()) && fieldDescriptionContainsMatch(fieldName, fieldInfo.getDescription())) {
return true;
}
String defaultValueFormula = fieldInfo.getDefaultValueFormula();
if (!StringUtil.isEmpty(defaultValueFormula) && fieldFormulaContainsMatch(fieldName, FormulaType.DEFAULTVALUE, defaultValueFormula)) {
return true;
}
String itFormula = fieldInfo.getInputTranslationFormula();
if (!StringUtil.isEmpty(itFormula) && fieldFormulaContainsMatch(fieldName, FormulaType.INPUTTRANSLATION, itFormula)) {
return true;
}
String ivFormula = fieldInfo.getInputValidityCheckFormula();
if (!StringUtil.isEmpty(ivFormula) && fieldFormulaContainsMatch(fieldName, FormulaType.INPUTVALIDITYCHECK, ivFormula)) {
return true;
}
}
else if (CDRecordType.PABHIDE.getConstant() == nav.getCurrentRecordTypeAsShort()) {
Memory recordData = nav.getCurrentRecordDataWithHeader();
NotesCDPabHideStruct hideWhenStruct = NotesCDPabHideStruct.newInstance(recordData);
hideWhenStruct.read();
int formulaLen = (int) (recordData.size() - NotesConstants.notesCDPabhideStructSize);
if (formulaLen>0) {
Pointer formulaPtr = recordData.share(NotesConstants.notesCDPabhideStructSize);
String hwFormula = FormulaDecompiler.decompileFormula(formulaPtr);
if (!StringUtil.isEmpty(hwFormula) && hideWhenFormulaContainsMatch(hwFormula)) {
return true;
}
}
}
else if (CDRecordType.HOTSPOTBEGIN.getConstant() == nav.getCurrentRecordTypeAsShort() ||
CDRecordType.V4HOTSPOTBEGIN.getConstant() == nav.getCurrentRecordTypeAsShort()) {
Memory recordData = nav.getCurrentRecordDataWithHeader();
NotesCdHotspotBeginStruct hotspotStruct = NotesCdHotspotBeginStruct.newInstance(recordData);
hotspotStruct.read();
if ((hotspotStruct.Flags & NotesConstants.HOTSPOTREC_RUNFLAG_FORMULA) == NotesConstants.HOTSPOTREC_RUNFLAG_FORMULA) {
int dataLengthAsInt = hotspotStruct.DataLength & 0xffff;
if (dataLengthAsInt > 0) {
Pointer ptrFormula = recordData.share(NotesConstants.notesCDHotspotBeginStructSize);
String formula = FormulaDecompiler.decompileFormula(ptrFormula);
if (!StringUtil.isEmpty(formula) && hotspotFormulaContainsMatch(formula)) {
return true;
}
}
}
}
else if (CDRecordType.HREF.getConstant() == nav.getCurrentRecordTypeAsShort()) {
// e.g. picture element with computed filename
Memory recordData = nav.getCurrentRecordDataWithHeader();
NotesCDResourceStruct resourceStruct = NotesCDResourceStruct.newInstance(recordData);
resourceStruct.read();
int cdResourceSize = NotesConstants.notesCDResourceStructSize;
Pointer ptr = recordData.share(cdResourceSize);
int serverHintLengthAsInt = (int) (resourceStruct.ServerHintLength & 0xffff);
String serverHint="";
if (serverHintLengthAsInt>0) {
serverHint = NotesStringUtils.fromLMBCS(ptr, serverHintLengthAsInt);
ptr = ptr.share(serverHintLengthAsInt);
}
int fileHintLengthAsInt = (int) (resourceStruct.FileHintLength & 0xffff);
String fileHint="";
if (fileHintLengthAsInt>0) {
fileHint = NotesStringUtils.fromLMBCS(ptr, fileHintLengthAsInt);
ptr = ptr.share(fileHintLengthAsInt);
}
if (resourceStruct.Type == NotesConstants.CDRESOURCE_TYPE_URL) {
if((resourceStruct.Flags & NotesConstants.CDRESOURCE_FLAGS_FORMULA) == NotesConstants.CDRESOURCE_FLAGS_FORMULA) {
int formulaLengthAsInt = (int) (resourceStruct.Length1 & 0xffff);
if (formulaLengthAsInt>0) {
String formula = FormulaDecompiler.decompileFormula(ptr);
if (!StringUtil.isEmpty(formula) && hotspotFormulaContainsMatch(formula)) {
return true;
}
}
}
}
else if (resourceStruct.Type == NotesConstants.CDRESOURCE_TYPE_NAMEDELEMENT) {
//DBID to target DB or 0 for current database
NotesTimeDateStruct replicaId = NotesTimeDateStruct.newInstance(ptr);
ptr = ptr.share(NotesConstants.timeDateSize);
if((resourceStruct.Flags & NotesConstants.CDRESOURCE_FLAGS_FORMULA) == NotesConstants.CDRESOURCE_FLAGS_FORMULA) {
int formulaLengthAsInt = (int) (resourceStruct.Length1 & 0xffff);
if (formulaLengthAsInt>0) {
String formula = FormulaDecompiler.decompileFormula(ptr);
if (!StringUtil.isEmpty(formula) && hotspotFormulaContainsMatch(formula)) {
return true;
}
}
}
}
else if (resourceStruct.Type == NotesConstants.CDRESOURCE_TYPE_ACTION) {
if((resourceStruct.Flags & NotesConstants.CDRESOURCE_FLAGS_FORMULA) == NotesConstants.CDRESOURCE_FLAGS_FORMULA) {
int formulaLengthAsInt = (int) (resourceStruct.Length1 & 0xffff);
if (formulaLengthAsInt>0) {
String formula = FormulaDecompiler.decompileFormula(ptr);
if (!StringUtil.isEmpty(formula) && hotspotFormulaContainsMatch(formula)) {
return true;
}
}
}
}
}
}
while (nav.gotoNext());
}
return false;
}
@Override
public void convert(IRichTextNavigator source, ICompoundText target) {
if (source.gotoFirst()) {
do {
if (CDRecordType.FIELD.getConstant() == source.getCurrentRecordTypeAsShort()) {
Memory recordDataWithHeader = source.getCurrentRecordDataWithHeader();
NotesCDFieldStruct cdField = NotesCDFieldStruct.newInstance(recordDataWithHeader);
FieldInfo fieldInfo = new FieldInfo(cdField);
String origFieldName = fieldInfo.getName();
String fieldName = origFieldName;
String fieldDesc = fieldInfo.getDescription();
String defaultValueFormula = fieldInfo.getDefaultValueFormula();
String itFormula = fieldInfo.getInputTranslationFormula();
String ivFormula = fieldInfo.getInputValidityCheckFormula();
boolean hasMatch = false;
if (fieldNameContainsMatch(fieldName)) {
hasMatch = true;
fieldName = replaceAllMatchesInFieldName(fieldName);
}
if (!StringUtil.isEmpty(fieldDesc) && fieldDescriptionContainsMatch(origFieldName, fieldDesc)) {
hasMatch = true;
fieldDesc = replaceAllMatchesInFieldDescription(origFieldName, fieldDesc);
}
if (!StringUtil.isEmpty(itFormula) && fieldFormulaContainsMatch(origFieldName, FormulaType.DEFAULTVALUE, defaultValueFormula)) {
hasMatch = true;
defaultValueFormula = replaceAllMatchesInFieldFormula(origFieldName, FormulaType.DEFAULTVALUE, defaultValueFormula);
}
if (!StringUtil.isEmpty(itFormula) && fieldFormulaContainsMatch(origFieldName, FormulaType.INPUTTRANSLATION, itFormula)) {
hasMatch = true;
itFormula = replaceAllMatchesInFieldFormula(origFieldName, FormulaType.INPUTTRANSLATION, itFormula);
}
if (!StringUtil.isEmpty(ivFormula) && fieldFormulaContainsMatch(origFieldName, FormulaType.INPUTVALIDITYCHECK, ivFormula)) {
hasMatch = true;
ivFormula = replaceAllMatchesInFieldFormula(origFieldName, FormulaType.INPUTVALIDITYCHECK, ivFormula);
}
if (hasMatch) {
//recompile formulas
byte[] compiledDefaultValueFormula;
try {
if (!StringUtil.isEmpty(defaultValueFormula)) {
compiledDefaultValueFormula = FormulaCompiler.compileFormula(defaultValueFormula);
}
else {
compiledDefaultValueFormula = new byte[0];
}
}
catch (FormulaCompilationError e) {
throw new NotesError(0, "Error compiling default value formula of field "+origFieldName, e);
}
byte[] compiledItFormula;
try {
if (!StringUtil.isEmpty(itFormula)) {
compiledItFormula = FormulaCompiler.compileFormula(itFormula);
}
else {
compiledItFormula = new byte[0];
}
}
catch (FormulaCompilationError e) {
throw new NotesError(0, "Error compiling input translation formula of field "+origFieldName, e);
}
byte[] compiledIvFormula;
try {
if (!StringUtil.isEmpty(ivFormula)) {
compiledIvFormula = FormulaCompiler.compileFormula(ivFormula);
}
else {
compiledIvFormula = new byte[0];
}
}
catch (FormulaCompilationError e) {
throw new NotesError(0, "Error compiling input validity check formula of field "+origFieldName, e);
}
int textValueLength = (short) (cdField.TextValueLength & 0xffff);
byte[] textValueData;
if (textValueLength==0) {
textValueData = new byte[0];
}
else {
textValueData = recordDataWithHeader.getByteArray(cdField.size() +
(int) (cdField.DVLength & 0xffff) +
(int) (cdField.ITLength & 0xffff) +
(int) (cdField.IVLength & 0xffff) +
(int) (cdField.NameLength & 0xffff) +
(int) (cdField.DescLength & 0xffff)
, textValueLength);
}
Memory fieldNameMem = NotesStringUtils.toLMBCS(fieldName, false);
Memory fieldDescMem = NotesStringUtils.toLMBCS(fieldDesc, false);
//allocate enough memory for the new CDfield structure and the texts/formulas
Memory newCdFieldStructureWithHeaderMem = new Memory(
NotesConstants.notesCDFieldStructSize +
compiledDefaultValueFormula.length +
compiledItFormula.length +
compiledIvFormula.length +
fieldNameMem.size() +
(fieldDescMem==null ? 0 : fieldDescMem.size()) +
textValueLength
);
//copy the old data for the CDField structure into byte array
byte[] oldCdFieldDataWithHeader = recordDataWithHeader.getByteArray(0, NotesConstants.notesCDFieldStructSize);
//and into newCdFieldStructureWithHeaderMem
newCdFieldStructureWithHeaderMem.write(0, oldCdFieldDataWithHeader, 0, oldCdFieldDataWithHeader.length);
NotesCDFieldStruct newCdField = NotesCDFieldStruct.newInstance(newCdFieldStructureWithHeaderMem);
newCdField.read();
applyCustomFieldChanges(newCdField);
//write new total lengths of CD record including signature
newCdField.Length = (short) (newCdFieldStructureWithHeaderMem.size() & 0xffff);
//write lengths of compiled formulas and name/description
newCdField.DVLength = (short) ((compiledDefaultValueFormula==null ? 0 : compiledDefaultValueFormula.length) & 0xffff);
newCdField.ITLength = (short) ((compiledItFormula==null ? 0 : compiledItFormula.length) & 0xffff);
newCdField.IVLength = (short) ((compiledIvFormula==null ? 0 : compiledIvFormula.length) & 0xffff);
newCdField.NameLength = (short) ((fieldNameMem==null ? 0 : fieldNameMem.size()) & 0xffff);
newCdField.DescLength = (short) ((fieldDescMem==null ? 0 : fieldDescMem.size()) & 0xffff);
newCdField.TextValueLength = (short) (textValueLength & 0xffff);
newCdField.write();
//write flexible data into CD record
int offset = NotesConstants.notesCDFieldStructSize;
if (compiledDefaultValueFormula.length>0) {
newCdFieldStructureWithHeaderMem.write(offset, compiledDefaultValueFormula, 0, compiledDefaultValueFormula.length);
offset += compiledDefaultValueFormula.length;
}
if (compiledItFormula.length>0) {
newCdFieldStructureWithHeaderMem.write(offset, compiledItFormula, 0, compiledItFormula.length);
offset += compiledItFormula.length;
}
if (compiledIvFormula.length>0) {
newCdFieldStructureWithHeaderMem.write(offset, compiledIvFormula, 0, compiledIvFormula.length);
offset += compiledIvFormula.length;
}
newCdFieldStructureWithHeaderMem.write(offset, fieldNameMem.getByteArray(0, (int) fieldNameMem.size()),
0, (int) fieldNameMem.size());
offset += fieldNameMem.size();
if (fieldDescMem!=null) {
newCdFieldStructureWithHeaderMem.write(offset, fieldDescMem.getByteArray(0, (int) fieldDescMem.size()),
0, (int) fieldDescMem.size());
offset += fieldDescMem.size();
}
if (textValueLength>0) {
newCdFieldStructureWithHeaderMem.write(offset, textValueData, 0, textValueData.length);
}
//write new data to target
target.addCDRecords(newCdFieldStructureWithHeaderMem);
}
else {
source.copyCurrentRecordTo(target);
}
}
else if (CDRecordType.PABHIDE.getConstant() == source.getCurrentRecordTypeAsShort()) {
Memory recordData = source.getCurrentRecordDataWithHeader();
NotesCDPabHideStruct hideWhenStruct = NotesCDPabHideStruct.newInstance(recordData);
hideWhenStruct.read();
boolean hasMatch = false;
int formulaLen = (int) (recordData.size() - NotesConstants.notesCDPabhideStructSize);
if (formulaLen>0) {
Pointer formulaPtr = recordData.share(NotesConstants.notesCDPabhideStructSize);
String hwFormula = FormulaDecompiler.decompileFormula(formulaPtr);
if (!StringUtil.isEmpty(hwFormula) && hideWhenFormulaContainsMatch(hwFormula)) {
hwFormula = replaceAllMatchesInHideWhenFormula(hwFormula);
byte[] compiledHwFormula;
try {
if (!StringUtil.isEmpty(hwFormula)) {
compiledHwFormula = FormulaCompiler.compileFormula(hwFormula);
}
else {
compiledHwFormula = new byte[0];
}
}
catch (FormulaCompilationError e) {
throw new NotesError(0, "Error compiling hide when formula", e);
}
int newRecordLength = NotesConstants.notesCDPabhideStructSize + compiledHwFormula.length;
Memory newCdPabHideStructureWithHeaderMem = new Memory(newRecordLength);
//copy old data
newCdPabHideStructureWithHeaderMem.write(0, recordData.getByteArray(0, NotesConstants.notesCDPabhideStructSize), 0, NotesConstants.notesCDPabhideStructSize);
NotesCDPabHideStruct newHideWhenStruct = NotesCDPabHideStruct.newInstance(newCdPabHideStructureWithHeaderMem);
newHideWhenStruct.read();
newHideWhenStruct.Length = (short) (newRecordLength & 0xffff);
newHideWhenStruct.write();
//append new compiled formula
newCdPabHideStructureWithHeaderMem.write(NotesConstants.notesCDPabhideStructSize, compiledHwFormula, 0, compiledHwFormula.length);
//write new data to target
target.addCDRecords(newCdPabHideStructureWithHeaderMem);
hasMatch = true;
}
}
if (!hasMatch) {
source.copyCurrentRecordTo(target);
}
}
else if (CDRecordType.HOTSPOTBEGIN.getConstant() == source.getCurrentRecordTypeAsShort() ||
CDRecordType.V4HOTSPOTBEGIN.getConstant() == source.getCurrentRecordTypeAsShort()) {
Memory recordData = source.getCurrentRecordDataWithHeader();
NotesCdHotspotBeginStruct hotspotStruct = NotesCdHotspotBeginStruct.newInstance(recordData);
hotspotStruct.read();
boolean hasMatch = false;
if ((hotspotStruct.Flags & NotesConstants.HOTSPOTREC_RUNFLAG_FORMULA) == NotesConstants.HOTSPOTREC_RUNFLAG_FORMULA) {
int dataLengthAsInt = hotspotStruct.DataLength & 0xffff;
if (dataLengthAsInt > 0) {
Pointer ptrFormula = recordData.share(NotesConstants.notesCDHotspotBeginStructSize);
String hotspotFormula = FormulaDecompiler.decompileFormula(ptrFormula);
if (!StringUtil.isEmpty(hotspotFormula) && hotspotFormulaContainsMatch(hotspotFormula)) {
hotspotFormula = replaceAllMatchesInHotspotFormula(hotspotFormula);
byte[] compiledHotspotFormula;
try {
if (!StringUtil.isEmpty(hotspotFormula)) {
compiledHotspotFormula = FormulaCompiler.compileFormula(hotspotFormula);
}
else {
compiledHotspotFormula = new byte[0];
}
}
catch (FormulaCompilationError e) {
throw new NotesError(0, "Error compiling hotspot formula", e);
}
int newRecordLength = NotesConstants.notesCDHotspotBeginStructSize + compiledHotspotFormula.length;
Memory newCdHotspotBeginStructureWithHeaderMem = new Memory(newRecordLength);
//copy old data
newCdHotspotBeginStructureWithHeaderMem.write(0, recordData.getByteArray(0, NotesConstants.notesCDHotspotBeginStructSize), 0, NotesConstants.notesCDHotspotBeginStructSize);
NotesCdHotspotBeginStruct newHotspotBeginStruct = NotesCdHotspotBeginStruct.newInstance(newCdHotspotBeginStructureWithHeaderMem);
newHotspotBeginStruct.read();
newHotspotBeginStruct.Length = (short) (newRecordLength & 0xffff);
newHotspotBeginStruct.DataLength = (short) (compiledHotspotFormula.length & 0xffff);
//unsign hotspot
if ((newHotspotBeginStruct.Flags & NotesConstants.HOTSPOTREC_RUNFLAG_SIGNED) == NotesConstants.HOTSPOTREC_RUNFLAG_SIGNED) {
newHotspotBeginStruct.Flags -= NotesConstants.HOTSPOTREC_RUNFLAG_SIGNED;
}
newHotspotBeginStruct.write();
//append new compiled formula
newCdHotspotBeginStructureWithHeaderMem.write(NotesConstants.notesCDHotspotBeginStructSize, compiledHotspotFormula, 0, compiledHotspotFormula.length);
//write new data to target
target.addCDRecords(newCdHotspotBeginStructureWithHeaderMem);
hasMatch = true;
}
}
}
if (!hasMatch) {
source.copyCurrentRecordTo(target);
}
}
else if (CDRecordType.HREF.getConstant() == source.getCurrentRecordTypeAsShort()) {
// e.g. picture element with computed filename
Memory recordData = source.getCurrentRecordDataWithHeader();
NotesCDResourceStruct resourceStruct = NotesCDResourceStruct.newInstance(recordData);
resourceStruct.read();
int cdResourceSize = NotesConstants.notesCDResourceStructSize;
Pointer ptr = recordData.share(cdResourceSize);
int serverHintLengthAsInt = (int) (resourceStruct.ServerHintLength & 0xffff);
String serverHint="";
if (serverHintLengthAsInt>0) {
serverHint = NotesStringUtils.fromLMBCS(ptr, serverHintLengthAsInt);
ptr = ptr.share(serverHintLengthAsInt);
}
int fileHintLengthAsInt = (int) (resourceStruct.FileHintLength & 0xffff);
String fileHint="";
if (fileHintLengthAsInt>0) {
fileHint = NotesStringUtils.fromLMBCS(ptr, fileHintLengthAsInt);
ptr = ptr.share(fileHintLengthAsInt);
}
boolean isMatch = false;
if (resourceStruct.Type == NotesConstants.CDRESOURCE_TYPE_URL) {
if((resourceStruct.Flags & NotesConstants.CDRESOURCE_FLAGS_FORMULA) == NotesConstants.CDRESOURCE_FLAGS_FORMULA) {
int formulaLengthAsInt = (int) (resourceStruct.Length1 & 0xffff);
if (formulaLengthAsInt>0) {
String formula = FormulaDecompiler.decompileFormula(ptr);
if (!StringUtil.isEmpty(formula)) {
String newFormula = replaceAllMatchesInHotspotFormula(formula);
byte[] compiledFormula;
try {
if (!StringUtil.isEmpty(newFormula)) {
compiledFormula = FormulaCompiler.compileFormula(newFormula);
}
else {
compiledFormula = new byte[0];
}
}
catch (FormulaCompilationError e) {
throw new NotesError(0, "Error compiling resource formula", e);
}
int newRecordLengthNoFormula = NotesConstants.notesCDResourceStructSize +
serverHintLengthAsInt +
fileHintLengthAsInt;
int newRecordLengthWithFormula = newRecordLengthNoFormula +
compiledFormula.length;
Memory newRecordDataWithHeader = new Memory(newRecordLengthWithFormula);
//copy header data, server hint and file int
newRecordDataWithHeader.write(0, recordData.getByteArray(0,
newRecordLengthNoFormula), 0, newRecordLengthNoFormula);
newRecordDataWithHeader.write(newRecordLengthNoFormula, compiledFormula, 0, compiledFormula.length);
NotesCDResourceStruct newResourceCDStruct = NotesCDResourceStruct.newInstance(newRecordDataWithHeader);
newResourceCDStruct.read();
newResourceCDStruct.Length = (short) (newRecordLengthWithFormula & 0xffff);
newResourceCDStruct.Length1 = (short) (compiledFormula.length & 0xffff);
newResourceCDStruct.write();
target.addCDRecords(newRecordDataWithHeader);
isMatch = true;
}
}
}
}
else if (resourceStruct.Type == NotesConstants.CDRESOURCE_TYPE_NAMEDELEMENT) {
//DBID to target DB or 0 for current database
NotesTimeDateStruct replicaId = NotesTimeDateStruct.newInstance(ptr);
ptr = ptr.share(NotesConstants.timeDateSize);
if((resourceStruct.Flags & NotesConstants.CDRESOURCE_FLAGS_FORMULA) == NotesConstants.CDRESOURCE_FLAGS_FORMULA) {
int formulaLengthAsInt = (int) (resourceStruct.Length1 & 0xffff);
if (formulaLengthAsInt>0) {
String formula = FormulaDecompiler.decompileFormula(ptr);
if (!StringUtil.isEmpty(formula) && hotspotFormulaContainsMatch(formula)) {
String newFormula = replaceAllMatchesInHotspotFormula(formula);
byte[] compiledFormula;
try {
if (!StringUtil.isEmpty(newFormula)) {
compiledFormula = FormulaCompiler.compileFormula(newFormula);
}
else {
compiledFormula = new byte[0];
}
}
catch (FormulaCompilationError e) {
throw new NotesError(0, "Error compiling resource formula", e);
}
int newRecordLengthNoFormula = NotesConstants.notesCDResourceStructSize +
serverHintLengthAsInt +
fileHintLengthAsInt +
NotesConstants.timeDateSize;
int newRecordLengthWithFormula = newRecordLengthNoFormula +
compiledFormula.length;
Memory newRecordDataWithHeader = new Memory(newRecordLengthWithFormula);
//copy header data, server hint and file int
newRecordDataWithHeader.write(0, recordData.getByteArray(0,
newRecordLengthNoFormula), 0, newRecordLengthNoFormula);
newRecordDataWithHeader.write(newRecordLengthNoFormula, compiledFormula, 0, compiledFormula.length);
NotesCDResourceStruct newResourceCDStruct = NotesCDResourceStruct.newInstance(newRecordDataWithHeader);
newResourceCDStruct.read();
newResourceCDStruct.Length = (short) (newRecordLengthWithFormula & 0xffff);
newResourceCDStruct.Length1 = (short) (compiledFormula.length & 0xffff);
newResourceCDStruct.write();
target.addCDRecords(newRecordDataWithHeader);
isMatch = true;
}
}
}
}
else if (resourceStruct.Type == NotesConstants.CDRESOURCE_TYPE_ACTION) {
if((resourceStruct.Flags & NotesConstants.CDRESOURCE_FLAGS_FORMULA) == NotesConstants.CDRESOURCE_FLAGS_FORMULA) {
int formulaLengthAsInt = (int) (resourceStruct.Length1 & 0xffff);
if (formulaLengthAsInt>0) {
String formula = FormulaDecompiler.decompileFormula(ptr);
if (!StringUtil.isEmpty(formula) && hotspotFormulaContainsMatch(formula)) {
String newFormula = replaceAllMatchesInHotspotFormula(formula);
byte[] compiledFormula;
try {
if (!StringUtil.isEmpty(newFormula)) {
compiledFormula = FormulaCompiler.compileFormula(newFormula);
}
else {
compiledFormula = new byte[0];
}
}
catch (FormulaCompilationError e) {
throw new NotesError(0, "Error compiling resource formula", e);
}
int newRecordLengthNoFormula = NotesConstants.notesCDResourceStructSize +
serverHintLengthAsInt +
fileHintLengthAsInt;
int newRecordLengthWithFormula = newRecordLengthNoFormula +
compiledFormula.length;
Memory newRecordDataWithHeader = new Memory(newRecordLengthWithFormula);
//copy header data, server hint and file int
newRecordDataWithHeader.write(0, recordData.getByteArray(0,
newRecordLengthNoFormula), 0, newRecordLengthNoFormula);
newRecordDataWithHeader.write(newRecordLengthNoFormula, compiledFormula, 0, compiledFormula.length);
NotesCDResourceStruct newResourceCDStruct = NotesCDResourceStruct.newInstance(newRecordDataWithHeader);
newResourceCDStruct.read();
newResourceCDStruct.Length = (short) (newRecordLengthWithFormula & 0xffff);
newResourceCDStruct.Length1 = (short) (compiledFormula.length & 0xffff);
newResourceCDStruct.write();
target.addCDRecords(newRecordDataWithHeader);
isMatch = true;
}
}
}
}
if (!isMatch) {
source.copyCurrentRecordTo(target);
}
}
else {
source.copyCurrentRecordTo(target);
}
}
while (source.gotoNext());
}
}
}
|
package de.tarent.mica.model;
import java.awt.Dimension;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Set;
import de.tarent.mica.model.Field.Element;
import de.tarent.mica.model.ship.AbstractShip;
/**
* Diese Klasse representiert die Spielwelt.
*
* @author rainu
*
*/
public class World {
private Field ownField;
private Field enemyField;
private Field enemyView;
private Collection<AbstractShip> ownShips = new ArrayList<AbstractShip>();
public World(int height, int width) {
ownField = new Field(height, width, Element.WASSER);
enemyField = new Field(height, width);
enemyView = new Field(height, width);
}
public Field getOwnField() {
return ownField;
}
public Field getEnemyField() {
return enemyField;
}
public Field getEnemyView() {
return enemyView;
}
/**
* Platziert ein Schiff auf das eigene Feld.
* @param ship
* @return
*/
public World placeOwnShip(AbstractShip ship){
validateShipPosition(ship);
for(Coord c : ship.getSpace()) ownField.set(c, Element.SCHIFF);
ownShips.add(ship);
return this;
}
void validateShipPosition(AbstractShip ship) {
for(Coord c : ship.getSpace()){
try{
checkOutOfBounce(ownField, c);
}catch(IllegalArgumentException e){
throw new IllegalArgumentException("The given Ship(" + ship + ") is out of bounce!", e);
}
Element e = ownField.get(c);
if(Element.SCHIFF.equals(e)){
throw new IllegalArgumentException("This ship crosses another ship!");
}
}
}
void checkOutOfBounce(Field field, Coord c) {
Dimension dim = field.getDimension();
if(c.getX() < 0 || c.getX() >= dim.width || c.getY() < 0 || c.getX() >= dim.height){
throw new IllegalArgumentException("The given Coord(" + c + ") is out of bounce!");
}
}
public World registerHit(Coord c){
checkOutOfBounce(enemyField, c);
enemyField.set(c, Element.TREFFER);
return this;
}
public World registerShip(Coord c){
checkOutOfBounce(enemyField, c);
enemyField.set(c, Element.SCHIFF);
return this;
}
public World registerMiss(Coord c){
checkOutOfBounce(enemyView, c);
enemyField.set(c, Element.WASSER);
return this;
}
/**
* Liefert Alle bekannten Positionen der Gegnerischen Schiffe.
* Ist keine Position bekannt, wird dennoch ein Set geliefert.
* Dieses ist dann jedoch leer!
*
* @return
*/
public Set<Coord> getShipCoordinates(){
return enemyField.getCoordinatesFor(Element.SCHIFF);
}
public World registerEnemyHit(Coord c){
checkOutOfBounce(enemyView, c);
enemyView.set(c, Element.TREFFER);
AbstractShip ship = getShip(c);
ship.addAttackCoord(c);
return this;
}
public World registerEnemyBurn(Coord c){
registerEnemyHit(c);
AbstractShip ship = getShip(c);
ship.setBurning(true);
return this;
}
public World registerEnemyMiss(Coord c){
checkOutOfBounce(enemyView, c);
enemyView.set(c, Element.WASSER);
return this;
}
public World registerEnemySunk(Coord c){
AbstractShip ship = getShip(c);
for(Coord cc : ship.getSpace()){
registerEnemyHit(cc);
}
return this;
}
public World registerEnemyShip(Coord c){
checkOutOfBounce(enemyView, c);
enemyView.set(c, Element.SCHIFF);
return this;
}
@SuppressWarnings("unchecked")
public Collection<AbstractShip> getOwnShips(){
return Collections.unmodifiableCollection((Collection<AbstractShip>) ownField);
}
/**
* Liefert das eigene Schiff, was an der gegebenen Position stationiert ist.
*
* @param coord
* @return Das eigene Schiff an der gegebenen Koordinate. Null wenn kein Schiff an dieser Koordinate vorhanden ist.
*/
public AbstractShip getShip(Coord coord){
for(AbstractShip ship : ownShips){
if(ship.getSpace().contains(coord)){
return ship;
}
}
return null;
}
public Dimension getWorldDimension() {
return ownField.getDimension();
}
@Override
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append(enemyField.toString());
sb.append("\no)=");
for(int i=0; i < getWorldDimension().getWidth(); i++){
sb.append("==");
}
sb.append("=(o\n\n");
sb.append(ownField.toString());
return sb.toString();
}
}
|
package edu.jhu.gm.data;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.List;
import java.util.Map;
import edu.jhu.gm.Var;
import edu.jhu.gm.Var.VarType;
import edu.jhu.gm.VarConfig;
public class ErmaWriter {
public void writePredictions(File outFile, List<VarConfig> configs, Map<Var,Double> marginals) throws IOException {
Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "UTF-8"));
writePredictions(writer, configs, marginals);
}
private void writePredictions(Writer writer, List<VarConfig> configs, Map<Var,Double> marginals) throws IOException {
int i = 0;
for (VarConfig config : configs) {
writer.write("//example " + i + "\n");
writer.write("example:\n");
for (Var var : config.getVars()) {
writer.write(var.getName());
writer.write(toErmaLetter(var.getType()));
writer.write("=");
writer.write(config.getStateName(var));
writer.write(" ");
writer.write(String.valueOf(marginals.get(var)));
writer.write("\n");
}
i++;
}
}
private String toErmaLetter(VarType type) {
switch(type) {
case OBSERVED:
return "in";
case LATENT:
return "h";
case PREDICTED:
return "o";
default:
throw new RuntimeException("Unhandled type: " + type);
}
}
}
|
package org.grammaticalframework.examples.PhraseDroid;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.view.*;
import android.widget.*;
import java.util.Locale;
import java.util.Arrays;
public abstract class PhrasedroidActivity extends Activity
implements TextToSpeech.OnInitListener,
View.OnClickListener
{
// Preference Keys
public static final String PREFS_NAME = "PhrasedroidPrefs";
public static final String TLANG_PREF_KEY = "targetLanguageCode";
// TTS Intent code
static final int MY_TTS_CHECK_CODE = 2347453;
// Activity menu codes
static final int MENU_CHANGE_LANGUAGE = 1;
private boolean tts_ready = false;
private TextToSpeech mTts;
private Language sLang = Language.ENGLISH;
private Language tLang = Language.FRENCH;
protected PGFThread mPGFThread;
String currentText = "";
// UI elements
TextView resultView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
// Setup languages
// FIXME : do Source language
Locale l = Locale.getDefault();
Language source = Language.fromCode(l.getLanguage());
if (source == null)
source = Language.ENGLISH;
// Target language
String tLangCode = settings.getString(TLANG_PREF_KEY, null);
Language target = Language.fromCode(tLangCode);
if (target == null ||
!Arrays.asList(source.getAvailableTargetLanguages()).contains(target))
target = source.getDefaultTargetLanguage();
this.setupLanguages(source, target);
// Setup TTS
startTTSInit();
// Setup UI
setContentView(R.layout.main);
// Get pointers to the ui elements
resultView = (TextView) findViewById(R.id.result_view);
// setup translate button
((Button) findViewById(R.id.translate_button)).setOnClickListener(this);
// setup speak action
((Button) findViewById(R.id.speak_button)).setOnClickListener(this);
}
public void onDestroy() {
super.onDestroy();
if (mTts != null)
mTts.shutdown();
}
public void setupLanguages(Language sLang, Language tLang) {
this.sLang = sLang;
this.tLang = tLang;
// Setup the thread for the pgf
// FIXME : localize the dialog...
final ProgressDialog progress =
ProgressDialog.show(this, "",
"Loading Grammar. Please wait...", true);
mPGFThread = new PGFThread(this, sLang, tLang);
mPGFThread.onPGFReady(new Runnable() {
public void run() {
runOnUiThread(new Runnable() { public void run() {
progress.dismiss();
}});
}});
mPGFThread.start();
if (this.tts_ready)
mTts.setLanguage(this.tLang.locale);
}
public void changeTargetLanguage(Language l) {
this.setupLanguages(this.sLang, l);
}
// needed by View.onClickListener
public void onClick(View v) {
if (v == findViewById(R.id.translate_button)) {
setText("Translating...", false);
String phrase =
((EditText)findViewById(R.id.phrase)).getText().toString();
mPGFThread.translate(phrase);
} else if (v == findViewById(R.id.speak_button))
say(currentText);
}
public void setText(String t, boolean sayable) {
final String text = t;
if (sayable)
this.currentText = text;
else
this.currentText = "";
runOnUiThread(new Runnable() {
public void run() { resultView.setText(text); }
});
}
/* Creates the menu items */
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, MENU_CHANGE_LANGUAGE, 0, "Change Language");
return true;
}
/* Handles menu item selections */
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_CHANGE_LANGUAGE:
final Language[] tls = this.sLang.getAvailableTargetLanguages();
final String[] items = new String[tls.length];
int i = 0;
for (Language l : tls) {
items[i] = l.getName();
i++ ;
}
AlertDialog.Builder builder = new AlertDialog.Builder(this);
// FIXME: localize...
builder.setTitle("Pick a language");
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
changeTargetLanguage(tls[item]);
SharedPreferences settings =
getSharedPreferences(PREFS_NAME, 0);
settings
.edit().putString(TLANG_PREF_KEY,
tls[item].locale.getLanguage())
.commit();
}
});
AlertDialog alert = builder.create();
alert.show();
return true;
}
return false;
}
public void say(String txt) {
if (this.tts_ready)
this.mTts.speak(txt, TextToSpeech.QUEUE_ADD, null);
}
// Text-To-Speech initialization is done in three (asychronous) steps
// coresponding to the three methods below :
// First : we check if the TTS data is present on the system
public void startTTSInit() {
Intent checkIntent = new Intent();
checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(checkIntent, MY_TTS_CHECK_CODE);
}
// Second: if the data is present, we initialise the TTS engine
// (otherwise we ask to install it)
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == MY_TTS_CHECK_CODE) {
if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
// success, create the TTS instance
mTts = new TextToSpeech(this, this);
} else {
// missing data, install it
Intent installIntent = new Intent();
installIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
startActivity(installIntent);
}
}
}
// Finally: once the TTS engine is initialized, we set-up the language.
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
this.tts_ready = true;
mTts.setLanguage(this.tLang.locale);
}
}
}
|
package io.quarkus.resteasy.runtime.standalone;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.Executor;
import javax.enterprise.inject.Instance;
import javax.enterprise.inject.spi.CDI;
import javax.ws.rs.core.SecurityContext;
import org.jboss.logging.Logger;
import org.jboss.resteasy.core.ResteasyContext;
import org.jboss.resteasy.core.SynchronousDispatcher;
import org.jboss.resteasy.specimpl.ResteasyHttpHeaders;
import org.jboss.resteasy.specimpl.ResteasyUriInfo;
import org.jboss.resteasy.spi.Failure;
import org.jboss.resteasy.spi.ResteasyDeployment;
import io.quarkus.arc.ManagedContext;
import io.quarkus.arc.runtime.BeanContainer;
import io.quarkus.runtime.BlockingOperationControl;
import io.quarkus.security.identity.CurrentIdentityAssociation;
import io.quarkus.vertx.http.runtime.CurrentVertxRequest;
import io.quarkus.vertx.http.runtime.VertxInputStream;
import io.quarkus.vertx.http.runtime.security.QuarkusHttpUser;
import io.vertx.core.Context;
import io.vertx.core.Handler;
import io.vertx.core.Vertx;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.core.http.HttpServerResponse;
import io.vertx.ext.web.RoutingContext;
/**
* @author <a href="mailto:[email protected]">Julien Viet</a>
*/
public class VertxRequestHandler implements Handler<RoutingContext> {
private static final Logger log = Logger.getLogger("io.quarkus.resteasy");
protected final Vertx vertx;
protected final RequestDispatcher dispatcher;
protected final String rootPath;
protected final BufferAllocator allocator;
protected final BeanContainer beanContainer;
protected final CurrentIdentityAssociation association;
protected final CurrentVertxRequest currentVertxRequest;
protected final Executor executor;
protected final long readTimeout;
public VertxRequestHandler(Vertx vertx,
BeanContainer beanContainer,
ResteasyDeployment deployment,
String rootPath,
BufferAllocator allocator, Executor executor, long readTimeout) {
this.vertx = vertx;
this.beanContainer = beanContainer;
this.dispatcher = new RequestDispatcher((SynchronousDispatcher) deployment.getDispatcher(),
deployment.getProviderFactory(), null, Thread.currentThread().getContextClassLoader());
this.rootPath = rootPath;
this.allocator = allocator;
this.executor = executor;
this.readTimeout = readTimeout;
Instance<CurrentIdentityAssociation> association = CDI.current().select(CurrentIdentityAssociation.class);
this.association = association.isResolvable() ? association.get() : null;
currentVertxRequest = CDI.current().select(CurrentVertxRequest.class).get();
}
@Override
public void handle(RoutingContext request) {
// have to create input stream here. Cannot execute in another thread
// otherwise request handlers may not get set up before request ends
InputStream is;
try {
if (request.getBody() != null) {
is = new ByteArrayInputStream(request.getBody().getBytes());
} else {
is = new VertxInputStream(request, readTimeout);
}
} catch (IOException e) {
request.fail(e);
return;
}
if (BlockingOperationControl.isBlockingAllowed()) {
try {
dispatch(request, is, new VertxBlockingOutput(request.request()));
} catch (Throwable e) {
request.fail(e);
}
} else {
executor.execute(new Runnable() {
@Override
public void run() {
try {
dispatch(request, is, new VertxBlockingOutput(request.request()));
} catch (Throwable e) {
request.fail(e);
}
}
});
}
}
private void dispatch(RoutingContext routingContext, InputStream is, VertxOutput output) {
ManagedContext requestContext = beanContainer.requestContext();
requestContext.activate();
routingContext.remove(QuarkusHttpUser.AUTH_FAILURE_HANDLER);
QuarkusHttpUser user = (QuarkusHttpUser) routingContext.user();
if (association != null) {
association.setIdentity(QuarkusHttpUser.getSecurityIdentity(routingContext, null));
}
currentVertxRequest.setCurrent(routingContext);
try {
Context ctx = vertx.getOrCreateContext();
HttpServerRequest request = routingContext.request();
ResteasyUriInfo uriInfo = VertxUtil.extractUriInfo(request, rootPath);
ResteasyHttpHeaders headers = VertxUtil.extractHttpHeaders(request);
HttpServerResponse response = request.response();
VertxHttpResponse vertxResponse = new VertxHttpResponse(request, dispatcher.getProviderFactory(),
request.method(), allocator, output);
// using a supplier to make the remote Address resolution lazy: often it's not needed and it's not very cheap to create.
LazyHostSupplier hostSupplier = new LazyHostSupplier(request);
VertxHttpRequest vertxRequest = new VertxHttpRequest(ctx, routingContext, headers, uriInfo, request.rawMethod(),
hostSupplier,
dispatcher.getDispatcher(), vertxResponse, requestContext);
vertxRequest.setInputStream(is);
try {
ResteasyContext.pushContext(SecurityContext.class, new QuarkusResteasySecurityContext(request, routingContext));
ResteasyContext.pushContext(RoutingContext.class, routingContext);
dispatcher.service(ctx, request, response, vertxRequest, vertxResponse, true);
} catch (Failure e1) {
vertxResponse.setStatus(e1.getErrorCode());
if (e1.isLoggable()) {
log.error(e1);
}
} catch (Throwable ex) {
routingContext.fail(ex);
}
boolean suspended = vertxRequest.getAsyncContext().isSuspended();
boolean requestContextActive = requestContext.isActive();
if (!suspended) {
try {
if (requestContextActive) {
requestContext.terminate();
}
} finally {
try {
vertxResponse.finish();
} catch (IOException e) {
log.debug("IOException writing JAX-RS response", e);
}
}
} else {
//we need the request context to stick around
requestContext.deactivate();
}
} catch (Throwable t) {
try {
routingContext.fail(t);
} finally {
if (requestContext.isActive()) {
requestContext.terminate();
}
}
}
}
}
|
package hudson.plugins.git;
import hudson.EnvVars;
import hudson.Extension;
import hudson.Functions;
import hudson.XmlFile;
import hudson.init.Initializer;
import hudson.model.EnvironmentSpecific;
import hudson.model.Items;
import hudson.model.Node;
import hudson.model.TaskListener;
import hudson.slaves.NodeSpecific;
import hudson.tools.ToolDescriptor;
import hudson.tools.ToolInstallation;
import hudson.tools.ToolProperty;
import hudson.util.FormValidation;
import jenkins.model.Jenkins;
import net.sf.json.JSONObject;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.StaplerRequest;
import javax.servlet.ServletException;
import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import static hudson.init.InitMilestone.PLUGINS_STARTED;
/**
* Information about Git installation.
*
* @author Jyrki Puttonen
*/
public final class GitTool extends ToolInstallation implements NodeSpecific<GitTool>, EnvironmentSpecific<GitTool> {
@DataBoundConstructor
public GitTool(String name, String home, List<? extends ToolProperty<?>> properties) {
super(name, home, properties);
}
public static transient final String DEFAULT = "Default";
public String getGitExe() {
return getHome();
}
private static GitTool[] getInstallations(DescriptorImpl descriptor) {
GitTool[] installations = null;
try {
installations = descriptor.getInstallations();
} catch (NullPointerException e) {
installations = new GitTool[0];
}
return installations;
}
public static GitTool getDefaultInstallation() {
DescriptorImpl gitTools = Jenkins.getInstance().getDescriptorByType(GitTool.DescriptorImpl.class);
return gitTools.getInstallation(GitTool.DEFAULT);
}
public GitTool forNode(Node node, TaskListener log) throws IOException, InterruptedException {
return new GitTool(getName(), translateFor(node, log), Collections.<ToolProperty<?>>emptyList());
}
public GitTool forEnvironment(EnvVars environment) {
return new GitTool(getName(), environment.expand(getHome()), Collections.<ToolProperty<?>>emptyList());
}
@Override
public DescriptorImpl getDescriptor() {
return (DescriptorImpl) Jenkins.getInstance().getDescriptor(GitTool.class);
}
@Initializer(after=PLUGINS_STARTED)
public static void onLoaded() {
//Creates default tool installation if needed. Uses "git" or migrates data from previous versions
DescriptorImpl descriptor = (DescriptorImpl) Jenkins.getInstance().getDescriptor(GitTool.class);
GitTool[] installations = getInstallations(descriptor);
if (installations != null && installations.length > 0) {
//No need to initialize if there's already something
return;
}
String defaultGitExe = Functions.isWindows() ? "git.exe" : "git";
GitTool tool = new GitTool(DEFAULT, defaultGitExe, Collections.<ToolProperty<?>>emptyList());
descriptor.setInstallations(new GitTool[] { tool });
descriptor.save();
}
@Extension
public static class DescriptorImpl extends ToolDescriptor<GitTool> {
public DescriptorImpl() {
super();
load();
}
@Override
public String getDisplayName() {
return "Git";
}
@Override
public boolean configure(StaplerRequest req, JSONObject json) throws FormException {
super.configure(req, json);
save();
return true;
}
public FormValidation doCheckHome(@QueryParameter File value)
throws IOException, ServletException {
Jenkins.getInstance().checkPermission(Jenkins.ADMINISTER);
String path = value.getPath();
return FormValidation.validateExecutable(path);
}
public GitTool getInstallation(String name) {
for(GitTool i : getInstallations()) {
if(i.getName().equals(name)) {
return i;
}
}
return null;
}
}
private static final Logger LOGGER = Logger.getLogger(GitTool.class.getName());
}
|
package it.unitn.ds.rmi;
import it.unitn.ds.Replication;
import it.unitn.ds.entity.Item;
import it.unitn.ds.entity.Node;
import it.unitn.ds.util.MultithreadingUtil;
import it.unitn.ds.util.RemoteUtil;
import it.unitn.ds.util.StorageUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
* Provides an access to remote node via RMI
* <p/>
* Uses read/write locks for manipulation with internal data structure of the node in case of multiple requests
* <p/>
* Read Lock: multiple readers can enter, if not locked for writing
* Write Lock: only one writer can enter, if not locked for reading
*
* @see it.unitn.ds.entity.Item
* @see it.unitn.ds.entity.Node
* @see java.util.concurrent.locks.ReadWriteLock
* @see java.util.concurrent.locks.ReentrantReadWriteLock
*/
public final class NodeRemote extends UnicastRemoteObject implements NodeServer, NodeClient {
private static final Logger logger = LogManager.getLogger();
/**
* Locks nodes TreeMap operations of the node
*/
private static final ReadWriteLock nodesLock = new ReentrantReadWriteLock();
/**
* Locks items TreeMap operations of the node
*/
private static final ReadWriteLock itemsLock = new ReentrantReadWriteLock();
/**
* Locks replication TreeMap operations of the node
*/
private static final ReadWriteLock replicasLock = new ReentrantReadWriteLock();
/**
* Locks client operations of the node
*/
private static final ReadWriteLock clientLock = new ReentrantReadWriteLock();
@NotNull
private final Node node;
public NodeRemote(@NotNull Node node) throws RemoteException {
this.node = node;
}
@NotNull
@Override
public Node getNode() throws RemoteException {
logger.debug("Get node=" + node);
return node;
}
@NotNull
@Override
public Map<Integer, String> getNodes() throws RemoteException {
nodesLock.readLock().lock();
try {
logger.debug("Get nodes=" + Arrays.toString(node.getNodes().entrySet().toArray()));
return node.getNodes();
} finally {
nodesLock.readLock().unlock();
}
}
@Override
public void addNode(int id, @NotNull String host) throws RemoteException {
nodesLock.writeLock().lock();
try {
logger.debug("Add id=" + id + ", host=" + host);
node.putNode(id, host);
logger.debug("Current nodes=" + Arrays.toString(node.getNodes().entrySet().toArray()));
} finally {
nodesLock.writeLock().unlock();
}
}
@Override
public void removeNode(int id) throws RemoteException {
nodesLock.writeLock().lock();
try {
logger.debug("Remove id=" + id);
node.removeNode(id);
logger.debug("Current nodes=" + Arrays.toString(node.getNodes().entrySet().toArray()));
} finally {
nodesLock.writeLock().unlock();
}
}
@Override
public void updateItems(@NotNull List<Item> items) throws RemoteException {
itemsLock.writeLock().lock();
try {
logger.debug("Update items=" + Arrays.toString(items.toArray()));
node.putItems(items);
StorageUtil.write(node);
logger.debug("Current items=" + Arrays.toString(node.getItems().keySet().toArray()));
} finally {
itemsLock.writeLock().unlock();
}
}
@Override
public void removeItems(@NotNull List<Item> items) throws RemoteException {
itemsLock.writeLock().lock();
try {
logger.debug("Remove items=" + Arrays.toString(items.toArray()));
node.removeItems(items);
StorageUtil.write(node);
logger.debug("Current items=" + Arrays.toString(node.getItems().keySet().toArray()));
} finally {
itemsLock.writeLock().unlock();
}
}
@Override
public void updateReplicas(@NotNull List<Item> replicas) throws RemoteException {
replicasLock.writeLock().lock();
try {
logger.debug("Update replicas=" + Arrays.toString(replicas.toArray()));
node.putReplicas(replicas);
StorageUtil.write(node);
logger.debug("Current replicas=" + Arrays.toString(node.getReplicas().keySet().toArray()));
} finally {
replicasLock.writeLock().unlock();
}
}
@Override
public void removeReplicas(@NotNull List<Item> replicas) throws RemoteException {
replicasLock.writeLock().lock();
try {
logger.debug("Remove replicas=" + Arrays.toString(replicas.toArray()));
node.removeReplicas(replicas);
StorageUtil.write(node);
logger.debug("Current replicas=" + Arrays.toString(node.getReplicas().keySet().toArray()));
} finally {
replicasLock.writeLock().unlock();
}
}
@Nullable
@Override
public Item getItem(int key) throws RemoteException {
clientLock.readLock().lock();
try {
logger.debug("Get replica item with key=" + key);
Item item = getLatestVersion(getReplicas(key));
logger.debug("Got replica item=" + item);
return item;
} finally {
clientLock.readLock().unlock();
}
}
@Nullable
@Override
public Item updateItem(int key, @NotNull String value) throws RemoteException {
clientLock.writeLock().lock();
try {
logger.debug("Update replica item with key=" + key + ", value=" + value);
Item item = updateReplicas(key, value);
logger.debug("Updated replica item=" + item);
return item;
} finally {
clientLock.writeLock().unlock();
}
}
/**
* Returns collection of items and replicas
* <p/>
* Replicas are requested concurrently and returned as soon as R replicas replied
*
* @param itemKey of the item
* @return collection of items with the same item key
* @see it.unitn.ds.Replication
* @see it.unitn.ds.ServiceConfiguration
*/
@NotNull
private List<Item> getReplicas(int itemKey) throws RemoteException {
Node nodeForItem = RemoteUtil.getNodeForItem(itemKey, node.getNodes());
Item item = nodeForItem.getItems().get(itemKey);
List<Item> replicas = MultithreadingUtil.getReplicas(itemKey, nodeForItem, item != null, node.getNodes());
if (item != null) {
logger.debug("Got original item=" + item + " from nodeForItem=" + nodeForItem);
replicas.add(item);
}
return replicas;
}
/**
* Creates new item if exists or updates existing item with new value and increased version number
* <p/>
* Replicas are updated concurrently
* <p/>
* Amount of replicas operational must satisfy formula [ Q == max( R , W ) ], where:
* - Q is the number of replicas and items gotten from operational nodes
* - R and W are read and write quorums respectively
*
* @param itemKey of the item
* @param itemValue new value of the item
* @return created or updated item or null if not agreed on WRITE quorum [ Q != max( R , W ) ]
* @see it.unitn.ds.Replication
* @see it.unitn.ds.ServiceConfiguration
*/
@Nullable
private Item updateReplicas(int itemKey, @NotNull String itemValue) throws RemoteException {
List<Item> replicas = getReplicas(itemKey);
if (!replicas.isEmpty() && replicas.size() < Math.max(Replication.R, Replication.W)) {
logger.debug("No can agree on WRITE quorum: Q != max(R,W) as Q=" + replicas.size() + ", R=" + Replication.R + ", W=" + Replication.W);
return null;
}
Item item = createOrUpdate(itemKey, itemValue, replicas);
Node nodeForItem = RemoteUtil.getNodeForItem(itemKey, node.getNodes());
RemoteUtil.getRemoteNode(nodeForItem, NodeServer.class).updateItems(Arrays.asList(item));
logger.debug("Updated item=" + item + " to nodeForItem=" + nodeForItem);
MultithreadingUtil.updateReplicas(item, nodeForItem, node.getNodes());
return item;
}
/**
* Returns new item if exists or updates existing item with new value and increased version number
*
* @param itemKey of the item
* @param itemValue new value of the item
* @param replicas collection of items with the same item key
* @return created or updated item
*/
@NotNull
private Item createOrUpdate(int itemKey, @NotNull String itemValue, @NotNull List<Item> replicas) throws RemoteException {
Item item = getLatestVersion(replicas);
if (item == null) {
return new Item(itemKey, itemValue);
} else {
item.update(itemValue);
return item;
}
}
/**
* Returns latest version of the item among all in the collection
*
* @param replicas collection of items with the same item key
* @return latest version item, or null if collection is empty
*/
@Nullable
private Item getLatestVersion(@NotNull List<Item> replicas) throws RemoteException {
Iterator<Item> iterator = replicas.iterator();
if (iterator.hasNext()) {
Item item = iterator.next();
while (iterator.hasNext()) {
Item replica = iterator.next();
if (replica.getVersion() > item.getVersion()) {
item = replica;
}
}
return item;
}
return null;
}
}
|
package org.schoellerfamily.gedbrowser.geocodecache;
import com.google.maps.model.GeocodingResult;
import com.google.maps.model.Geometry;
import com.google.maps.model.LatLng;
/**
* This class implements a single entry in the geocode cache.
*
* @author Dick Schoeller
*/
public class GeoCodeCacheEntry {
/** The historical place name. */
private final String placeName;
/** A modern place name to use for geo-coding. */
private final String modernPlaceName;
/** The geo-coding result. */
private final GeocodingResult geocodingResult;
/**
* @param placeName a place name to use for both historical and modern name
* @param geocodingResult a geo-coding result
*/
public GeoCodeCacheEntry(final String placeName,
final GeocodingResult geocodingResult) {
this.placeName = placeName;
this.modernPlaceName = placeName;
this.geocodingResult = geocodingResult;
}
/**
* {@inheritDoc}
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + hashCode(geocodingResult);
result = prime * result + hashCode(modernPlaceName);
result = prime * result + hashCode(placeName);
return result;
}
/**
* Get the hash code of the gcResult. 0 if object is null.
*
* @param gcResult the object
* @return its hash code
*/
private int hashCode(final GeocodingResult gcResult) {
if (gcResult == null) {
return 0;
}
// TODO are any other fields useful?
final int prime = 31;
int result = 1;
result = prime * result + hashCode(gcResult.formattedAddress);
result = prime * result + hashCode(gcResult.geometry);
return result;
}
/**
* Get the hash code of the geometry. 0 if object is null.
*
* @param geometry the geometry
* @return the hash code
*/
private int hashCode(final Geometry geometry) {
if (geometry == null) {
return 0;
}
// TODO should I expand to look at more data?
final int prime = 31;
int result = 1;
result = prime * result + hashCode(geometry.location);
return result;
}
/**
* Get the hash code of the location. 0 if object is null.
*
* @param location the location
* @return the hash code
*/
private int hashCode(final LatLng location) {
if (location == null) {
return 0;
}
// TODO should this look at the actual values instead of toString?
return hashCode(location.toString());
}
/**
* Get the hash code of the String. 0 if object is null.
*
* @param o the object
* @return its hash code
*/
private static int hashCode(final String o) {
if (o == null) {
return 0;
}
return o.hashCode();
}
/**
* {@inheritDoc}
*/
@Override
@SuppressWarnings({ "PMD.CyclomaticComplexity",
"PMD.ModifiedCyclomaticComplexity",
"PMD.NPathComplexity",
"PMD.StdCyclomaticComplexity" })
public boolean equals(final Object obj) {
// Suppressed all typical problems that go with an equals method
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final GeoCodeCacheEntry other = (GeoCodeCacheEntry) obj;
if (geocodingResult == null) {
if (other.geocodingResult != null) {
return false;
}
} else if (!equals(geocodingResult, other.geocodingResult)) {
return false;
}
if (modernPlaceName == null) {
if (other.modernPlaceName != null) {
return false;
}
} else if (!modernPlaceName.equals(other.modernPlaceName)) {
return false;
}
if (placeName == null) {
if (other.placeName != null) {
return false;
}
} else if (!placeName.equals(other.placeName)) {
return false;
}
return true;
}
/**
* A relatively shallow equals comparison.
*
* @param result the item
* @param other the item to compare
* @return returns true if they seem equal
*/
@SuppressWarnings({ "PMD.CompareObjectsWithEquals",
"PMD.CyclomaticComplexity",
"PMD.ModifiedCyclomaticComplexity",
"PMD.NPathComplexity",
"PMD.StdCyclomaticComplexity" })
private static boolean equals(final GeocodingResult result,
final GeocodingResult other) {
// Suppressed all typical problems that go with an equals method
if (result == other) {
return true;
}
if (result == null || other == null) {
return false;
}
if (result.formattedAddress == null) {
if (other.formattedAddress != null) {
return false;
}
} else {
if (!result.formattedAddress.equals(other.formattedAddress)) {
return false;
}
}
if (result.geometry == null) {
if (other.geometry != null) {
return false;
}
} else {
if (other.geometry == null) {
return false;
}
if (result.geometry.location == null) {
if (other.geometry.location != null) {
return false;
}
} else {
if (other.geometry.location == null) {
return false;
}
result.geometry.location.toString()
.equals(other.geometry.location.toString());
}
}
return true;
}
/**
* @param placeName the historical place name
* @param modernPlaceName the modern place name to use for geo-coding
* @param geocodingResult the geo-coding result
*/
public GeoCodeCacheEntry(final String placeName,
final String modernPlaceName,
final GeocodingResult geocodingResult) {
this.placeName = placeName;
this.modernPlaceName = modernPlaceName;
this.geocodingResult = geocodingResult;
}
/**
* @param placeName a place name to use for both historical and modern name
*/
public GeoCodeCacheEntry(final String placeName) {
this.placeName = placeName;
this.modernPlaceName = placeName;
this.geocodingResult = null;
}
/**
* @param placeName the historical place name
* @param modernPlaceName the modern place name to use for geo-coding
*/
public GeoCodeCacheEntry(final String placeName,
final String modernPlaceName) {
this.placeName = placeName;
this.modernPlaceName = modernPlaceName;
this.geocodingResult = null;
}
/**
* @return the historical place name
*/
public final String getPlaceName() {
return placeName;
}
/**
* @return the modern place name to use for geo-coding
*/
public final String getModernPlaceName() {
return modernPlaceName;
}
/**
* @return the geo-coding result
*/
public final GeocodingResult getGeocodingResult() {
return geocodingResult;
}
}
|
package jresp.state;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import jresp.protocol.Resp;
import java.nio.charset.Charset;
abstract class ScannableState implements State {
private ByteBuf innerBuffer = Unpooled.directBuffer(1024);
@Override
public boolean decode(ByteBuf in) {
int available = in.readableBytes();
for (int i = 0; i < available; i++) {
byte b = in.readByte();
if (endOfString(b)) {
return true;
} else {
innerBuffer.writeByte(b);
}
}
return false;
}
private boolean endOfString(byte secondByte) {
int idx = innerBuffer.writerIndex();
if (idx == 0) {
return false;
}
if ((innerBuffer.getByte(idx - 1) == Resp.CRLF[0]) &&
(secondByte == Resp.CRLF[1])) {
return true;
} else {
return false;
}
}
protected String bufferAsString() {
String result = innerBuffer.toString(0, innerBuffer.writerIndex() - 1, Charset.forName("UTF-8"));
innerBuffer.release();
return result;
}
}
|
package com.salesforce.samples.contactexplorer;
import org.json.JSONException;
import org.json.JSONObject;
import android.webkit.WebView;
import com.salesforce.androidsdk.util.EventsObservable.Event;
import com.salesforce.androidsdk.util.EventsObservable.EventType;
import com.salesforce.androidsdk.util.HybridInstrumentationTestCase;
/**
* Tests for ContactExplorer
*/
public class ContactExplorerTest extends HybridInstrumentationTestCase {
public void testFetchSfdcAccounts() throws Exception {
interceptExistingJavaScriptFunction(gapWebView, "onSuccessSfdcAccounts");
sendClick(gapWebView, "#link_fetch_sfdc_accounts");
Event evt = waitForEvent(EventType.Other);
validateResponse((String) evt.getData(), "Account");
sendClick(gapWebView, "#link_logout");
waitForEvent(EventType.LogoutComplete);
}
public void testFetchSfdcContacts() throws Exception {
interceptExistingJavaScriptFunction(gapWebView, "onSuccessSfdcContacts");
sendClick(gapWebView, "#link_fetch_sfdc_contacts");
Event evt = waitForEvent(EventType.Other);
validateResponse((String) evt.getData(), "Contact");
sendClick(gapWebView, "#link_logout");
waitForEvent(EventType.LogoutComplete);
}
public void testLogout() throws Exception {
sendClick(gapWebView, "#link_logout");
waitForEvent(EventType.LogoutComplete);
}
private void validateResponse(String data, String expectedType) throws JSONException {
JSONObject response = (new JSONObject(data)).getJSONObject("0"); // we get the arguments dictionary back from javascript
assertTrue("response should have records", response.has("records"));
JSONObject record = response.getJSONArray("records").getJSONObject(0);
assertEquals("record should be an " + expectedType, expectedType, record.getJSONObject("attributes").getString("type"));
}
private void sendClick(WebView webView, String target) {
sendJavaScript(webView, "jQuery('" + target + "').trigger('click')");
}
protected String getTestUsername() {
return "[email protected]";
}
protected String getTestPassword() {
return "123456"; // shouldn't check in
}
}
|
package kr.co.leehana.model;
import lombok.Data;
/**
* @author Hana Lee
* @since 2015-11-13 13-52
*/
@Data
public class Member {
private long id;
private int num;
private String userId;
private String password;
private int mileage;
private String fullName;
private int age;
private String phone;
}
|
package lambda;
import com.google.common.base.Joiner;
import org.junit.Test;
import org.testng.collections.Lists;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class CollectorStreamTest {
@Test
public void test(){
List<String> stringList = Lists.newArrayList("linuxea","l_kimboo","jina","floer","vicky","bonnie");
String string = stringList.stream()
.filter(s -> s.length() > 3)
.filter(s -> s.startsWith("l"))
.collect(Collectors.joining("*"));
System.out.println(string);
String newString = stringList.stream().collect(Collectors.joining("','"));
System.out.println("'" + newString + "'");
}
@Test
public void test2(){
List<String[]> strings = Lists.newArrayList();
strings.add(new String[]{"linuxea","kimboo","jacky"});
strings.add(new String[]{"orange","fruit","pony"});
strings.add(new String[]{"miaoMi","linuxea","kimmy"});
List<String[]> list = strings.stream().distinct().collect(Collectors.toList());
Consumer<String[]> consumer = strArr -> System.out.println(Arrays.toString(strArr));
list.stream().forEach(consumer);
System.out.println("ok");
//thinking...
Function<String[], String> function
= stringArr2 -> Joiner.on(",").join(stringArr2);
strings.stream().map(function).forEach(System.out::println);
}
@Test
public void test3(){
List<String[]> strings = Lists.newArrayList();
strings.add(new String[]{"linuxea","kimboo","jacky"});
strings.add(new String[]{"orange","fruit","pony"});
strings.add(new String[]{"miaoMi","linuxea","kimmy"});
strings.stream().flatMap(Arrays::stream).forEach(System.out::println);
}
/**
* String flatMap
*/
@Test
public void myStringFlatMap(){
List<String[]> strings = Lists.newArrayList();
strings.add(new String[]{"linuxea","kimboo","jacky"});
strings.add(new String[]{"orange","fruit","pony"});
strings.add(new String[]{"miaoMi","linuxea","kimmy"});
Function<String[], Stream<String>> bibiString = stringArray -> Stream.of(stringArray);
Consumer<String[]> consumer = stringArr -> System.out.println(Arrays.toString(stringArr));
strings.stream().flatMap(bibiString).map(s -> s.split("")).forEach(consumer);
}
@Test
public void test4(){
List<String[]> strings = Lists.newArrayList();
strings.add(new String[]{"linuxea","kimboo","jacky"});
strings.add(new String[]{"orange","fruit","pony"});
strings.add(new String[]{"miaoMi","linuxea","kimmy"});
}
@Test
public void test5(){
String[] strings = null;
strings = new String[]{"linuxeaa","kimboo","jacky"};
List<String> stringList = Arrays
.stream(strings)
.map(s -> s.split(""))
.flatMap(Arrays::stream)
.distinct()
.collect(Collectors.toList());
System.out.println(stringList);
}
@Test
public void test8(){
List<String[]> strings = Lists.newArrayList();
strings.add(new String[]{"linuxea","kimboo","jacky"});
strings.add(new String[]{"orange","fruit","pony"});
strings.add(new String[]{"miaoMi","linuxea","kimmy"});
strings
.stream()
.flatMap(Arrays::stream)
.map(s -> s.split(""))
.flatMap(Arrays::stream)
.distinct()
.forEach(System.out::println);
}
}
|
package logbook.internal;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
import javafx.scene.SnapshotParameters;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.effect.ColorAdjust;
import javafx.scene.image.Image;
import javafx.scene.paint.Color;
import logbook.bean.AppConfig;
import logbook.bean.Chara;
import logbook.bean.DeckPortCollection;
import logbook.bean.NdockCollection;
import logbook.bean.Ship;
import logbook.bean.ShipMst;
import logbook.bean.SlotItem;
import logbook.bean.SlotitemMst;
import logbook.bean.SlotitemMstCollection;
class ShipImage {
private static final ReferenceCache<String, Image> BASE_CACHE = new ReferenceCache<>(120);
private static final ReferenceCache<String, Image> COMMON_CACHE = new ReferenceCache<>(32);
private static final ReferenceCache<Double, Image> HPGAUGE_CACHE = new ReferenceCache<>(50);
private static final ReferenceCache<Double, Image> EXPGAUGE_CACHE = new ReferenceCache<>(50);
private static final String[] NORMAL = { "1.png", "1.jpg" };
private static final String[] DAMAGED = { "3.png", "3.jpg", "1.png", "1.jpg" };
private static final String[] STANDING_NORMAL = { "17.png", "17.jpg" };
private static final String[] STANDING_DAMAGED = { "19.png", "19.jpg" };
private static final String MC_BANNER_ICON0 = "common_misc/common_misc_105.png";
private static final String MC_BANNER_ICON1 = "common_misc/common_misc_99.png";
private static final String MC_BANNER_ICON2 = "common_misc/common_misc_109.png";
private static final String MC_BANNER_ICON3 = "common_misc/common_misc_102.png";
private static final String MC_BANNER_ICON4 = "common_misc/common_misc_108.png";
private static final String MC_BANNER_ICON5 = "common_misc/common_misc_100.png";
private static final String MC_BANNER_ICON10 = "common_misc/common_misc_110.png";
private static final String MC_BANNER_SMOKE_IMG0 = "common_misc/common_misc_96.png";
private static final String MC_BANNER_SMOKE_IMG1 = "common_misc/common_misc_97.png";
private static final String MC_BANNER_SMOKE_IMG2 = "common_misc/common_misc_98.png";
private static final String COMMON_MISC_35 = "common_misc/common_misc_35.png";
private static final String COMMON_MISC_112 = "common_misc/common_misc_112.png";
private static final String COMMON_MISC_36 = "common_misc/common_misc_36.png";
private static final String COMMON_MISC_113 = "common_misc/common_misc_113.png";
private static final Layer SLIGHT_DAMAGE_BADGE = new Layer(0, 0, Paths.get("common", MC_BANNER_ICON0));
private static final Layer HALF_DAMAGE_BADGE = new Layer(0, 0, Paths.get("common", MC_BANNER_ICON1));
private static final Layer BADLY_DAMAGE_BADGE = new Layer(0, 0, Paths.get("common", MC_BANNER_ICON2));
private static final Layer LOST_BADGE = new Layer(0, 0, Paths.get("common", MC_BANNER_ICON3));
private static final Layer NDOCK_BADGE = new Layer(0, 0, Paths.get("common", MC_BANNER_ICON4));
private static final Layer MISSION_BADGE = new Layer(0, 0, Paths.get("common", MC_BANNER_ICON5));
private static final Layer ESCAPE_BADGE = new Layer(0, 0, Paths.get("common", MC_BANNER_ICON10));
private static final Layer SLIGHT_DAMAGE_BACKGROUND = new Layer(0, 0, Paths.get("common", MC_BANNER_SMOKE_IMG0));
private static final Layer HALF_DAMAGE_BACKGROUND = new Layer(0, 0, Paths.get("common", MC_BANNER_SMOKE_IMG1));
private static final Layer BADLY_DAMAGE_BACKGROUND = new Layer(0, 0, Paths.get("common", MC_BANNER_SMOKE_IMG2));
private static final Layer ORANGE_BACKGROUND = new Layer(150, 0, Paths.get("common", COMMON_MISC_35));
private static final Layer ORANGE_FACE = new Layer(214, 18, Paths.get("common", COMMON_MISC_112));
private static final Layer RED_BACKGROUND = new Layer(150, 0, Paths.get("common", COMMON_MISC_36));
private static final Layer RED_FACE = new Layer(214, 18, Paths.get("common", COMMON_MISC_113));
private static final String JOIN_BANNER = "common_event/common_event_{0}.png";
private static final int ITEM_ICON_SIZE = 32;
/**
*
*
* @param chara
* @return
*/
static Image get(Chara chara) {
if (chara != null) {
Path base = getPath(chara);
if (base != null) {
return BASE_CACHE.get(base.toUri().toString(), (url, status) -> {
Image image = new Image(url);
status.setDoCache(!image.isError());
return image;
});
}
}
return null;
}
/**
* ()
*
* @param chara
* @return
*/
static Image getBackgroundLoading(Chara chara) {
if (chara != null) {
Path base = getPath(chara);
if (base != null) {
return new Image(base.toUri().toString(), true);
}
}
return null;
}
/**
*
*
* @param chara
* @param addItem
* @param applyState
* @param itemMap Map
* @param escape ID
* @return
*/
static Image get(Chara chara, boolean addItem, boolean applyState,
Map<Integer, SlotItem> itemMap, Set<Integer> escape) {
boolean visibleExpGauge = AppConfig.get().isVisibleExpGauge();
return get(chara, addItem, applyState, true, true, true, visibleExpGauge, itemMap, escape);
}
/**
*
*
* @param chara
* @param addItem
* @param applyState
* @param banner
* @param cond
* @param hpGauge HP
* @param expGauge
* @param itemMap Map
* @param escape ID
* @return
*/
static Image get(Chara chara, boolean addItem, boolean applyState, boolean banner, boolean cond, boolean hpGauge,
boolean expGauge,
Map<Integer, SlotItem> itemMap, Set<Integer> escape) {
Canvas canvas = new Canvas(240, 60);
GraphicsContext gc = canvas.getGraphicsContext2D();
gc.drawImage(get(chara), 0, 0, canvas.getWidth(), canvas.getHeight());
if (chara != null) {
List<Layer> layers = new ArrayList<>();
boolean isShip = chara.isShip();
boolean isOnNdock = applyState && isShip && NdockCollection.get()
.getNdockSet()
.contains(chara.asShip().getId());
boolean isMission = applyState && isShip && DeckPortCollection.get()
.getMissionShips()
.contains(chara.asShip().getId());
boolean isEscape = isShip && Ships.isEscape(chara.asShip(), escape);
if (banner) {
if (isOnNdock) {
layers.add(NDOCK_BADGE);
} else if (isMission) {
layers.add(MISSION_BADGE);
} else if (isEscape) {
layers.add(ESCAPE_BADGE);
gc.applyEffect(new ColorAdjust(0, -1, 0, 0));
} else if (Ships.isSlightDamage(chara)) {
layers.add(SLIGHT_DAMAGE_BADGE);
layers.add(SLIGHT_DAMAGE_BACKGROUND);
} else if (Ships.isHalfDamage(chara)) {
layers.add(HALF_DAMAGE_BADGE);
layers.add(HALF_DAMAGE_BACKGROUND);
} else if (Ships.isBadlyDamage(chara)) {
layers.add(BADLY_DAMAGE_BADGE);
layers.add(BADLY_DAMAGE_BACKGROUND);
} else if (Ships.isLost(chara)) {
layers.add(LOST_BADGE);
gc.applyEffect(new ColorAdjust(0, -1, 0, 0));
}
}
if (cond) {
if (isShip && Ships.isOrange(chara.asShip())) {
layers.add(ORANGE_BACKGROUND);
layers.add(ORANGE_FACE);
} else if (isShip && Ships.isRed(chara.asShip())) {
layers.add(RED_BACKGROUND);
layers.add(RED_FACE);
}
}
if (isShip) {
Ship ship = chara.asShip();
Integer sallyArea = ship.getSallyArea();
if (sallyArea != null && sallyArea.intValue() != 0) {
Path p = Paths.get("common", JOIN_BANNER.replace("{0}", Integer.toString(sallyArea - 1)));
layers.add(new Layer(50, -3, p));
}
}
if (addItem) {
int x = 17;
int y = 24;
if (isShip) {
Ship ship = chara.asShip();
int slotnum = ship.getSlotnum();
for (int i = 0; i < 5; i++) {
if (slotnum > i) {
Integer itemId = ship.getSlot().get(i);
layers.add(new Layer(x, y, ITEM_ICON_SIZE, ITEM_ICON_SIZE, itemIcon(itemId, itemMap)));
}
x += ITEM_ICON_SIZE + 2;
}
if (ship.getSlotEx() != 0) {
layers.add(
new Layer(x, y, ITEM_ICON_SIZE, ITEM_ICON_SIZE, itemIcon(ship.getSlotEx(), itemMap)));
}
} else {
Map<Integer, SlotitemMst> map = SlotitemMstCollection.get()
.getSlotitemMap();
for (Integer itemId : chara.getSlot()) {
Image icon = Items.borderedItemImage(map.get(itemId));
layers.add(new Layer(x, y, ITEM_ICON_SIZE, ITEM_ICON_SIZE, icon));
x += ITEM_ICON_SIZE + 2;
}
}
}
applyLayers(gc, layers);
if (expGauge && chara.isShip()) {
writeExpGauge(chara.asShip(), canvas, gc);
}
if (hpGauge) {
writeHpGauge(chara, canvas, gc);
}
}
SnapshotParameters sp = new SnapshotParameters();
sp.setFill(Color.TRANSPARENT);
return canvas.snapshot(sp, null);
}
/**
* ()
*
* @param ship
* @return
*/
static Image getSupplyGauge(Ship ship) {
Canvas canvas = new Canvas(36, 12);
GraphicsContext gc = canvas.getGraphicsContext2D();
Optional<ShipMst> mstOpt = Ships.shipMst(ship);
if (mstOpt.isPresent()) {
double width = canvas.getWidth();
ShipMst mst = mstOpt.get();
double fuelPer = (double) ship.getFuel() / (double) mst.getFuelMax();
double ammoPer = (double) ship.getBull() / (double) mst.getBullMax();
gc.setFill(Color.GRAY);
gc.fillRect(0, 3, width, 2);
gc.setFill(Color.GRAY);
gc.fillRect(0, 10, width, 2);
Color fuelColor = fuelPer >= 0.5D ? Color.GREEN : fuelPer >= 0.4D ? Color.ORANGE : Color.RED;
Color ammoColor = ammoPer >= 0.5D ? Color.SADDLEBROWN : ammoPer >= 0.4D ? Color.ORANGE : Color.RED;
gc.setFill(fuelColor);
gc.fillRect(0, 0, width * fuelPer, 4);
gc.setFill(ammoColor);
gc.fillRect(0, 7, width * ammoPer, 4);
}
SnapshotParameters sp = new SnapshotParameters();
sp.setFill(Color.TRANSPARENT);
return canvas.snapshot(sp, null);
}
/**
* HP
* @param chara
* @param canvas Canvas
* @param gc GraphicsContext
*/
private static void writeHpGauge(Chara chara, Canvas canvas, GraphicsContext gc) {
double w = canvas.getWidth();
double h = canvas.getHeight();
double gaugeWidth = 7;
double hpPer = (double) chara.getNowhp() / (double) chara.getMaxhp();
gc.drawImage(createGauge(gaugeWidth, h, hpPer, ShipImage::hpGaugeColor, HPGAUGE_CACHE), w - gaugeWidth, 0);
}
/**
*
* @param chara
* @param canvas Canvas
* @param gc GraphicsContext
*/
private static void writeExpGauge(Ship ship, Canvas canvas, GraphicsContext gc) {
double w = canvas.getWidth() - 7;
double h = canvas.getHeight();
double gaugeHeight = 6;
double exp = ship.getExp().get(0);
double next = ship.getExp().get(1);
double expPer;
if (next > 0) {
Integer nowLvExp = ExpTable.get().get(ship.getLv());
Integer nextLvExp = ExpTable.get().get(ship.getLv() + 1);
if (nowLvExp != null && nextLvExp != null) {
expPer = (exp - nowLvExp.doubleValue()) / (nextLvExp.doubleValue() - nowLvExp.doubleValue());
} else {
expPer = 0;
}
} else {
expPer = 0;
}
Color color = Color.TRANSPARENT.interpolate(Color.STEELBLUE, 0.9);
gc.drawImage(createGauge(w, gaugeHeight, expPer, k -> color, EXPGAUGE_CACHE), 0, h - gaugeHeight);
}
/**
*
* @param width
* @param height
* @param per
* @param colorFunc
* @param cache
* @return Image
*/
private static Image createGauge(double width, double height, double per,
Function<Double, Color> colorFunc,
ReferenceCache<Double, Image> cache) {
double fixedPer = (int) (Math.max(width, height) * per) / Math.max(width, height);
return cache.get(fixedPer, key -> {
Canvas canvas = new Canvas(width, height);
GraphicsContext gc = canvas.getGraphicsContext2D();
gc.setFill(Color.TRANSPARENT.interpolate(Color.WHITE, 0.6));
if (width < height) {
gc.fillRect(0, 0, width, height - (height * fixedPer));
} else {
gc.fillRect(width * fixedPer, 0, width - (width * fixedPer), height);
}
gc.setFill(colorFunc.apply(fixedPer));
if (width < height) {
gc.fillRect(0, height - (height * fixedPer), width, height * fixedPer);
} else {
gc.fillRect(0, 0, width * fixedPer, height);
}
SnapshotParameters sp = new SnapshotParameters();
sp.setFill(Color.TRANSPARENT);
return canvas.snapshot(sp, null);
});
}
/**
*
*
* @param gc GraphicsContext
* @param layers
*/
private static void applyLayers(GraphicsContext gc, List<Layer> layers) {
for (Layer layer : layers) {
Image img = null;
if (layer.path != null) {
Path p = Paths.get(AppConfig.get().getResourcesDir()).resolve(layer.path);
img = COMMON_CACHE.get(p.toUri().toString(), (url, status) -> {
Image image = new Image(url);
status.setDoCache(!image.isError());
return image;
});
}
if (layer.img != null) {
img = layer.img;
}
if (img != null) {
if (layer.w > 0) {
gc.drawImage(img, layer.x, layer.y, layer.w, layer.h);
} else {
gc.drawImage(img, layer.x, layer.y);
}
}
}
}
/**
*
* @param chara
* @return
*/
static Path getPath(Chara chara) {
return getBaseImagePath(chara, NORMAL, DAMAGED);
}
/**
* ()
* @param chara
* @return ()
*/
static Path getStandingPosePath(Chara chara) {
return getBaseImagePath(chara, STANDING_NORMAL, STANDING_DAMAGED);
}
/**
*
*
* @param chara
* @return
*/
private static Path getBaseImagePath(Chara chara, String[] normal, String[] damaged) {
Optional<ShipMst> mst = Ships.shipMst(chara);
if (mst.isPresent()) {
Path dir = ShipMst.getResourcePathDir(mst.get());
String[] names;
if ((chara.isShip() || chara.isFriend())
&& (Ships.isHalfDamage(chara) || Ships.isBadlyDamage(chara) || Ships.isLost(chara))) {
names = damaged;
} else {
names = normal;
}
for (String name : names) {
Path p = dir.resolve(name);
if (Files.isReadable(p)) {
return p;
}
}
}
return null;
}
/**
*
*
* @param itemId ID
* @param itemMap Map
*/
private static Image itemIcon(Integer itemId, Map<Integer, SlotItem> itemMap) {
return Items.borderedItemImage(itemMap.get(itemId));
}
/**
* HP
*
* @param per HP
* @return HP
*/
private static Color hpGaugeColor(double per) {
if (per > 0.5) {
return Color.TRANSPARENT.interpolate(Color.ORANGE.interpolate(Color.LIME, (per - 0.5) * 2), 0.9);
} else {
return Color.TRANSPARENT.interpolate(Color.RED.interpolate(Color.ORANGE, per * 2), 0.9);
}
}
private static class Layer {
private final double x;
private final double y;
/** width */
private final double w;
/** height */
private final double h;
private final Path path;
private final Image img;
private Layer(double x, double y, Path path) {
this.x = x;
this.y = y;
this.w = -1;
this.h = -1;
this.path = path;
this.img = null;
}
private Layer(double x, double y, double w, double h, Image img) {
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.path = null;
this.img = img;
}
}
}
|
package me.coley.recaf.util;
import javafx.scene.Group;
import javafx.scene.Node;
import javafx.scene.image.PixelFormat;
import javafx.scene.image.PixelWriter;
import javafx.scene.image.WritableImage;
import me.coley.recaf.ui.controls.IconView;
import me.coley.recaf.workspace.*;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.util.Arrays;
/**
* Utilities for UI functions.
*
* @author Matt
*/
public class UiUtil {
/**
* @param name
* File name.
*
* @return Path to icon based on file extension.
*/
public static String getFileIcon(String name) {
String path = null;
String ext = name.toLowerCase();
if(ext.contains(".")) {
ext = ext.substring(ext.lastIndexOf(".") + 1);
if(Arrays.asList("txt", "mf", "properties").contains(ext))
path = "icons/text.png";
else if(Arrays.asList("json", "xml", "html", "css", "js").contains(ext))
path = "icons/text-code.png";
else if(Arrays.asList("png", "gif", "jpeg", "jpg", "bmp").contains(ext))
path = "icons/image.png";
else if(Arrays.asList("jar", "war").contains(ext))
path = "icons/jar.png";
}
if(path == null)
path = "icons/binary.png";
return path;
}
/**
* @param resource
* Workspace resource instance.
*
* @return Icon path based on the type of resource.
*/
public static String getResourceIcon(JavaResource resource) {
if(resource instanceof DirectoryResource)
return "icons/folder-source.png";
else if(resource instanceof ArchiveResource)
return "icons/jar.png";
else if(resource instanceof ClassResource)
return "icons/binary.png";
else if(resource instanceof UrlResource)
return "icons/link.png";
else if(resource instanceof MavenResource)
return "icons/data.png";
// TODO: Unique debug/agent icon?
else if(resource instanceof DebuggerResource || resource instanceof InstrumentationResource)
return "icons/data.png";
return "icons/binary.png";
}
/**
* @param name
* File name.
*
* @return Icon representing type of file <i>(Based on extension)</i>
*/
public static IconView createFileGraphic(String name) {
return new IconView(getFileIcon(name));
}
/**
* @param access
* Class modifiers.
*
* @return Graphic representing class's attributes.
*/
public static Node createClassGraphic(int access) {
Group g = new Group();
// Root icon
String base = "icons/class/class.png";
if(AccessFlag.isEnum(access))
base = "icons/class/enum.png";
else if(AccessFlag.isAnnotation(access))
base = "icons/class/annotation.png";
else if(AccessFlag.isInterface(access))
base = "icons/class/interface.png";
g.getChildren().add(new IconView(base));
// Add modifiers
if(AccessFlag.isFinal(access) && !AccessFlag.isEnum(access))
g.getChildren().add(new IconView("icons/modifier/final.png"));
if(AccessFlag.isAbstract(access) && !AccessFlag.isInterface(access))
g.getChildren().add(new IconView("icons/modifier/abstract.png"));
if(AccessFlag.isBridge(access) || AccessFlag.isSynthetic(access))
g.getChildren().add(new IconView("icons/modifier/synthetic.png"));
return g;
}
/**
* @param access
* Field modifiers.
*
* @return Graphic representing fields's attributes.
*/
public static Node createFieldGraphic(int access) {
Group g = new Group();
// Root icon
String base = null;
if(AccessFlag.isPublic(access))
base = "icons/modifier/field_public.png";
else if(AccessFlag.isProtected(access))
base = "icons/modifier/field_protected.png";
else if(AccessFlag.isPrivate(access))
base = "icons/modifier/field_private.png";
else
base = "icons/modifier/field_default.png";
g.getChildren().add(new IconView(base));
// Add modifiers
if(AccessFlag.isStatic(access))
g.getChildren().add(new IconView("icons/modifier/static.png"));
if(AccessFlag.isFinal(access))
g.getChildren().add(new IconView("icons/modifier/final.png"));
if(AccessFlag.isBridge(access) || AccessFlag.isSynthetic(access))
g.getChildren().add(new IconView("icons/modifier/synthetic.png"));
return g;
}
/**
* @param access
* Field modifiers.
*
* @return Graphic representing fields's attributes.
*/
public static Node createMethodGraphic(int access) {
Group g = new Group();
// Root icon
String base = null;
if(AccessFlag.isPublic(access))
base = "icons/modifier/method_public.png";
else if(AccessFlag.isProtected(access))
base = "icons/modifier/method_protected.png";
else if(AccessFlag.isPrivate(access))
base = "icons/modifier/method_private.png";
else
base = "icons/modifier/method_default.png";
g.getChildren().add(new IconView(base));
// Add modifiers
if(AccessFlag.isStatic(access))
g.getChildren().add(new IconView("icons/modifier/static.png"));
else if(AccessFlag.isNative(access))
g.getChildren().add(new IconView("icons/modifier/native.png"));
else if(AccessFlag.isAbstract(access))
g.getChildren().add(new IconView("icons/modifier/abstract.png"));
if(AccessFlag.isFinal(access))
g.getChildren().add(new IconView("icons/modifier/final.png"));
if(AccessFlag.isBridge(access) || AccessFlag.isSynthetic(access))
g.getChildren().add(new IconView("icons/modifier/synthetic.png"));
return g;
}
/**
* Convert raw bytes to an image.
*
* @param content
* Some raw bytes of a file.
*
* @return Image instance, if bytes represent a valid image, otherwise {@code null}.
*/
public static BufferedImage toImage(byte[] content) {
try {
return ImageIO.read(new ByteArrayInputStream(content));
} catch(Exception ex) {
return null;
}
}
/**
* Convert a AWT image to a JavaFX image.
*
* @param img
* The image to convert.
*
* @return JavaFX image.
*/
public static WritableImage toFXImage(BufferedImage img) {
// This is a stripped down version of "SwingFXUtils.toFXImage(img, fxImg)"
int w = img.getWidth();
int h = img.getHeight();
// Ensure image type is ARGB.
switch(img.getType()) {
case BufferedImage.TYPE_INT_ARGB:
case BufferedImage.TYPE_INT_ARGB_PRE:
break;
default:
// Convert to ARGB
BufferedImage converted = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB_PRE);
Graphics2D g2d = converted.createGraphics();
g2d.drawImage(img, 0, 0, null);
g2d.dispose();
img = converted;
break;
}
// Even if the image type is ARGB_PRE, we use "getIntArgbInstance()"
// Using "getIntArgbPreInstance()" removes transparency.
WritableImage fxImg = new WritableImage(w, h);
PixelWriter pw = fxImg.getPixelWriter();
int[] data = img.getRGB(0, 0, w, h, null, 0, w);
pw.setPixels(0, 0, w, h, PixelFormat.getIntArgbInstance(), data, 0, w);
return fxImg;
}
}
|
package org.jboss.resteasy.plugins.server.servlet;
import org.jboss.resteasy.core.SynchronousDispatcher;
import org.jboss.resteasy.core.SynchronousExecutionContext;
import org.jboss.resteasy.plugins.providers.FormUrlEncodedProvider;
import org.jboss.resteasy.plugins.server.BaseHttpRequest;
import org.jboss.resteasy.resteasy_jaxrs.i18n.Messages;
import org.jboss.resteasy.specimpl.MultivaluedMapImpl;
import org.jboss.resteasy.specimpl.ResteasyHttpHeaders;
import org.jboss.resteasy.spi.HttpResponse;
import org.jboss.resteasy.spi.ResteasyAsynchronousContext;
import org.jboss.resteasy.spi.ResteasyUriInfo;
import org.jboss.resteasy.util.Encode;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
* Abstraction for an inbound http request on the server, or a response from a server to a client
* <p/>
* We have this abstraction so that we can reuse marshalling objects in a client framework and serverside framework
*
* @author <a href="mailto:[email protected]">Bill Burke</a>
* @version $Revision: 1 $
*/
public class HttpServletInputMessage extends BaseHttpRequest
{
protected ResteasyHttpHeaders httpHeaders;
protected HttpServletRequest request;
protected HttpServletResponse servletResponse;
protected ServletContext servletContext;
protected SynchronousDispatcher dispatcher;
protected HttpResponse httpResponse;
protected String httpMethod;
protected InputStream overridenStream;
protected SynchronousExecutionContext executionContext;
protected boolean wasForwarded;
public HttpServletInputMessage(HttpServletRequest request, HttpServletResponse servletResponse, ServletContext servletContext, HttpResponse httpResponse, ResteasyHttpHeaders httpHeaders, ResteasyUriInfo uri, String httpMethod, SynchronousDispatcher dispatcher)
{
super(uri);
this.request = request;
this.servletResponse = servletResponse;
this.servletContext = servletContext;
this.dispatcher = dispatcher;
this.httpResponse = httpResponse;
this.httpHeaders = httpHeaders;
this.httpMethod = httpMethod;
executionContext = new SynchronousExecutionContext(dispatcher, this, httpResponse);
}
@Override
public MultivaluedMap<String, String> getMutableHeaders()
{
return httpHeaders.getMutableHeaders();
}
public MultivaluedMap<String, String> getPutFormParameters()
{
if (formParameters != null) return formParameters;
if (MediaType.APPLICATION_FORM_URLENCODED_TYPE.isCompatible(getHttpHeaders().getMediaType()))
{
try
{
formParameters = FormUrlEncodedProvider.parseForm(getInputStream());
}
catch (IOException e)
{
throw new RuntimeException(e);
}
}
else
{
throw new IllegalArgumentException(Messages.MESSAGES.requestMediaTypeNotUrlencoded());
}
return formParameters;
}
public MultivaluedMap<String, String> getPutDecodedFormParameters()
{
if (decodedFormParameters != null) return decodedFormParameters;
decodedFormParameters = Encode.decode(getFormParameters());
return decodedFormParameters;
}
@Override
public Object getAttribute(String attribute)
{
return request.getAttribute(attribute);
}
@Override
public void setAttribute(String name, Object value)
{
request.setAttribute(name, value);
}
@Override
public void removeAttribute(String name)
{
request.removeAttribute(name);
}
@Override
public Enumeration<String> getAttributeNames()
{
return request.getAttributeNames();
}
@Override
public MultivaluedMap<String, String> getFormParameters()
{
if (formParameters != null) return formParameters;
// Tomcat does not set getParameters() if it is a PUT request
// so pull it out manually
if (request.getMethod().equals("PUT") && (request.getParameterMap() == null || request.getParameterMap().isEmpty()))
{
return getPutFormParameters();
}
Map<String, String[]> parameterMap = request.getParameterMap();
MultivaluedMap<String, String> queryMap = uri.getQueryParameters();
if (request.getMethod().equals("PUT") && mapEquals(parameterMap, queryMap))
{
return getPutFormParameters();
}
formParameters = Encode.encode(getDecodedFormParameters());
return formParameters;
}
@Override
public MultivaluedMap<String, String> getDecodedFormParameters()
{
if (decodedFormParameters != null) return decodedFormParameters;
// Tomcat does not set getParameters() if it is a PUT request
// so pull it out manually
if (request.getMethod().equals("PUT") && (request.getParameterMap() == null || request.getParameterMap().isEmpty()))
{
return getPutDecodedFormParameters();
}
Map<String, String[]> parameterMap = request.getParameterMap();
MultivaluedMap<String, String> queryMap = uri.getQueryParameters();
if (request.getMethod().equals("PUT") && mapEquals(parameterMap, queryMap))
{
return getPutDecodedFormParameters();
}
decodedFormParameters = new MultivaluedMapImpl<String, String>();
Map<String, String[]> params = request.getParameterMap();
for (Map.Entry<String, String[]> entry : params.entrySet())
{
String name = entry.getKey();
String[] values = entry.getValue();
MultivaluedMap<String, String> queryParams = uri.getQueryParameters();
List<String> queryValues = queryParams.get(name);
if (queryValues == null)
{
for (String val : values) decodedFormParameters.add(name, val);
}
else
{
for (String val : values)
{
if (!queryValues.contains(val))
{
decodedFormParameters.add(name, val);
}
}
}
}
return decodedFormParameters;
}
@Override
public HttpHeaders getHttpHeaders()
{
return httpHeaders;
}
@Override
public InputStream getInputStream()
{
if (overridenStream != null) return overridenStream;
try
{
return request.getInputStream();
}
catch (IOException e)
{
throw new RuntimeException(e);
}
}
@Override
public void setInputStream(InputStream stream)
{
this.overridenStream = stream;
}
@Override
public String getHttpMethod()
{
return httpMethod;
}
@Override
public void setHttpMethod(String method)
{
this.httpMethod = method;
}
@Override
public ResteasyAsynchronousContext getAsyncContext()
{
return executionContext;
}
@Override
public void forward(String path)
{
try
{
wasForwarded = true;
servletContext.getRequestDispatcher(path).forward(request, servletResponse);
}
catch (ServletException e)
{
throw new RuntimeException(e);
}
catch (IOException e)
{
throw new RuntimeException(e);
}
}
@Override
public boolean wasForwarded()
{
return wasForwarded;
}
protected boolean mapEquals(Map<String, String[]> parameterMap, MultivaluedMap<String, String> queryMap)
{
if (parameterMap.size() != queryMap.size())
{
return false;
}
for (Iterator<String> it = parameterMap.keySet().iterator(); it.hasNext(); )
{
String key = it.next();
String[] parameterValues = parameterMap.get(key);
List<String> queryValues = queryMap.get(key);
if (parameterValues.length != queryValues.size())
{
return false;
}
for (int i = 0; i < parameterValues.length; i++)
{
if (!queryValues.contains(parameterValues[i]))
{
return false;
}
}
}
return true;
}
}
|
package me.doubledutch.pikadb;
import java.io.*;
import java.util.*;
import org.json.*;
public class Test{
public static void main(String args[]){
/*for(int l=0;l<20;l++){
System.out.println(Long.toBinaryString(MurmurHash3.getSelectiveBits(l))+", ");
}
if(true)return;*/
String filename="./test.data";
int RECORDS=100000;
try{
System.out.println(" + Writing "+RECORDS+" objects");
String[] firstNames=new String[]{"James","John","Robert","Michael","William","David","Richard","Charles","Joseph","Thomas",
"Mary","Patricia","Linda","Barbara","Elizabeth","Jennifer","Maria","Susan","Margaret","Dorothy",
"Christopher","Daniel","Paul","Mark","Donald","George","Kenneth","Steven","Brian","Anthony",
"Lisa","Nancy","Karen","Betty","Helen","Sandra","Donna","Carol","Ruth","Sharon","Michelle"};
String[] lastNames=new String[]{"Smith","Johnson","Williams","Jones","Brown","Davis","Miller","Wilson","Moore",
"Taylor","Anderson","Thomas","Jackson","White","Harris","Martin","Thompson","Garcia",
"Martinez","Robinson","Clark","Rodriguez","Lewis","Lee","Walker","Hall","Allen","Young",
"Hernandez","King","Wright","Lopez","Hill","Scott","Green","Adams","Baker","Gonzales",
"Nelson","Carter","Mitchell","Perez","Roberts","Turner","Phillips","Campbell","Parker",
"Evans","Edwards","Collins","Stewart","Sanchez","Morriz","Rogers","Reed","Cook","Morgan",
"Bell","Murphy","Bailey","Rivera","Cooper","Richardson","Cox","Howard","Ward","Torres",
"Peterson","Gray","Ramirez","James","Watson","Brooks","Kelly","Sanders","Price","Bennett",
"Wood","Barnes","Ross","Henderson","Coleman","Jenkins","Perry","Powell","Long","Patterson",
"Hughes","Flores","Washington","Butler","Simmons","Foster","Bryant","Alexander","Diaz",
"Myers","Ford","Rice","West","Jordan","Owens","Fisher","Harrison","Gibson","Cruz"};
PikaDB db=new PikaDB(filename);
Table users=db.declareTable("users");
long pre=System.currentTimeMillis();
for(int i=0;i<RECORDS;i++){
JSONObject obj=new JSONObject();
obj.put("record_id",i);
obj.put("id",java.util.UUID.randomUUID().toString());
obj.put("firstName",firstNames[(int)(Math.random()*firstNames.length)]);
obj.put("lastName",lastNames[(int)(Math.random()*lastNames.length)]);
obj.put("username",obj.getString("firstName")+"."+obj.getString("lastName")+"."+i);
obj.put("image","http://some-great-service/img/profile-"+i+".png");
// obj.put("number",3.1415f);
users.add(i,obj);
}
db.save();
db.close();
db=null;
// f.close();
// f=null;
long post=System.currentTimeMillis();
System.out.println(" - Write in "+(post-pre)+"ms "+(int)(RECORDS/((post-pre)/1000.0))+" obj/s");
System.gc();
File ftest=new File(filename);
System.out.println(" - Database size : "+(ftest.length()/1024)+"kb");
ResultSet list=null;
// Do a quick warmup scan
db=new PikaDB(filename);
users=db.declareTable("users");
list=users.select().execute();
db.close();
list=null;
db=null;
System.gc();
System.out.println(" + Reading full objects - 100%");
db=new PikaDB(filename);
users=db.declareTable("users");
pre=System.currentTimeMillis();
list=users.scan();
list.getObjectList();
/*for(int i=0;i<RECORDS;i++){
JSONObject obj=list.get(i);
// System.out.println(obj.toString());
if(obj.getInt("id")!=i){
System.out.println(" - Data error!! at "+i);
System.out.println(obj.toString());
System.exit(0);
}
}*/
db.close();
db=null;
post=System.currentTimeMillis();
System.out.println(" - Read in "+(post-pre)+"ms "+(int)(RECORDS/((post-pre)/1000.0))+" obj/s");
System.gc();
System.out.println(" + Reading full objects - 50%");
db=new PikaDB(filename);
users=db.declareTable("users");
pre=System.currentTimeMillis();
ObjectSet set=new ObjectSet(false);
for(int i=0;i<RECORDS;i++){
if(i%2==0){
set.addOID(i);
}
}
list=users.scan(set);
list.getObjectList();
db.close();
db=null;
post=System.currentTimeMillis();
System.out.println(" - Read in "+(post-pre)+"ms "+(int)((RECORDS/2)/((post-pre)/1000.0))+" obj/s");
System.out.println(" + Reading full objects - 25%");
db=new PikaDB(filename);
users=db.declareTable("users");
pre=System.currentTimeMillis();
set=new ObjectSet(false);
for(int i=0;i<RECORDS;i++){
if(i%4==0){
set.addOID(i);
}
}
list=users.scan(set);
list.getObjectList();
db.close();
db=null;
post=System.currentTimeMillis();
System.out.println(" - Read in "+(post-pre)+"ms "+(int)((RECORDS/4)/((post-pre)/1000.0))+" obj/s");
System.out.println(" + Reading full objects - 5%");
db=new PikaDB(filename);
users=db.declareTable("users");
pre=System.currentTimeMillis();
set=new ObjectSet(false);
for(int i=0;i<RECORDS;i++){
if(i%20==0){
set.addOID(i);
}
}
list=users.scan(set);
list.getObjectList();
db.close();
db=null;
post=System.currentTimeMillis();
System.out.println(" - Read in "+(post-pre)+"ms "+(int)((RECORDS/20)/((post-pre)/1000.0))+" obj/s");
System.out.println(" + Reading full objects - 1%");
db=new PikaDB(filename);
users=db.declareTable("users");
pre=System.currentTimeMillis();
set=new ObjectSet(false);
for(int i=0;i<RECORDS;i++){
if(i%100==0){
set.addOID(i);
}
}
list=users.scan(set);
list.getObjectList();
db.close();
db=null;
post=System.currentTimeMillis();
System.out.println(" - Read in "+(post-pre)+"ms "+(int)((RECORDS/100)/((post-pre)/1000.0))+" obj/s");
System.out.println(" + Reading full objects - 0.1%");
db=new PikaDB(filename);
users=db.declareTable("users");
pre=System.currentTimeMillis();
set=new ObjectSet(false);
for(int i=0;i<RECORDS;i++){
if(i%1000==0){
set.addOID(i);
}
}
list=users.scan(set);
list.getObjectList();
db.close();
db=null;
post=System.currentTimeMillis();
System.out.println(" - Read in "+(post-pre)+"ms "+(int)((RECORDS/1000)/((post-pre)/1000.0))+" obj/s");
System.out.println(" + Reading single objects (bloom test)");
db=new PikaDB(filename);
users=db.declareTable("users");
// Prescan last to exercise bloom and not io
ResultSet obj=users.scan();
pre=System.currentTimeMillis();
obj=users.scan(1);
obj.getObjectList();
post=System.currentTimeMillis();
System.out.println(" - Read early object in "+(post-pre)+"ms");
// System.out.println(obj.getExecutionPlan().toString());
pre=System.currentTimeMillis();
obj=users.scan(RECORDS/2);
obj.getObjectList();
post=System.currentTimeMillis();
System.out.println(" - Read mid object in "+(post-pre)+"ms");
// System.out.println(obj.getExecutionPlan().toString());
pre=System.currentTimeMillis();
obj=users.scan(RECORDS-2);
obj.getObjectList();
post=System.currentTimeMillis();
System.out.println(" - Read late object in "+(post-pre)+"ms");
// System.out.println(obj.getExecutionPlan().toString());
db.close();
db=null;
System.out.println(" + Predicate based queries");
db=new PikaDB(filename);
users=db.declareTable("users");
obj=users.scan();
pre=System.currentTimeMillis();
obj=users.select("id","record_id","username").where("record_id").equalTo(1).execute();
obj.getObjectList();
post=System.currentTimeMillis();
System.out.println(" - Read early object in "+(post-pre)+"ms");
pre=System.currentTimeMillis();
obj=users.select("id","record_id","username").where("record_id").equalTo(RECORDS/2).execute();
obj.getObjectList();
post=System.currentTimeMillis();
System.out.println(" - Read mid object in "+(post-pre)+"ms");
pre=System.currentTimeMillis();
obj=users.select("id","record_id","username").where("record_id").equalTo(RECORDS-2).execute();
obj.getObjectList();
post=System.currentTimeMillis();
System.out.println(" - Read late object in "+(post-pre)+"ms");
// System.out.println(obj.getExecutionPlan().toString(4));
pre=System.currentTimeMillis();
obj=users.select("id","record_id","username").where("record_id").lessThan(1000).execute();
obj.getObjectList();
post=System.currentTimeMillis();
System.out.println(" - Read 1000 early objects in "+(post-pre)+"ms "+(int)((1000)/((post-pre)/1000.0))+" obj/s");
pre=System.currentTimeMillis();
obj=users.select("id","record_id","username").where("record_id").greaterThan(RECORDS-1000).execute();
/*for(JSONObject jobj:obj.getObjectList()){
System.out.println(jobj.toString());
}*/
obj.getObjectList();
post=System.currentTimeMillis();
System.out.println(" - Read 1000 early objects in "+(post-pre)+"ms "+(int)((1000)/((post-pre)/1000.0))+" obj/s");
/*
pre=System.currentTimeMillis();
f=new PageFile(filename);
soup=new Table("users",f,0,false);
System.out.println(" + Reading partial objects");
List<String> columns=new ArrayList<String>();
columns.add("id");
columns.add("username");
list=soup.scan(columns);
for(int i=0;i<RECORDS;i++){
JSONObject obj=list.get(i);
}
f.close();
f=null;
post=System.currentTimeMillis();
System.out.println(" - Read in "+(post-pre)+"ms "+(int)(RECORDS/((post-pre)/1000.0))+" obj/s");
System.gc();
System.out.println(" + Reading a single object - early");
pre=System.currentTimeMillis();
f=new PageFile(filename);
soup=new Table("users",f,0,false);
JSONObject obj=soup.scan(3);
// System.out.println(obj.toString());
post=System.currentTimeMillis();
System.out.println(" - Read in "+(post-pre)+"ms");
System.out.println(" + Reading a single object - mid");
pre=System.currentTimeMillis();
obj=soup.scan(RECORDS/2);
// System.out.println(obj.toString());
post=System.currentTimeMillis();
System.out.println(" - Read in "+(post-pre)+"ms");
System.out.println(" + Reading a single object - late");
pre=System.currentTimeMillis();
obj=soup.scan(RECORDS-1);
System.out.println(obj.toString());
post=System.currentTimeMillis();
System.out.println(" - Read in "+(post-pre)+"ms");
pre=System.currentTimeMillis();
System.out.println(" + Updating a single object");
JSONObject objUpdate=new JSONObject();
objUpdate.put("firstName","Jason");
objUpdate.put("background","#FFB807");
objUpdate.put("SoMuchBoolean",false);
soup.update(RECORDS/2,objUpdate);
f.saveChanges(false);
post=System.currentTimeMillis();
System.out.println(" - Updated in "+(post-pre)+"ms");
obj=soup.scan(RECORDS/2);
System.out.println(obj.toString());
pre=System.currentTimeMillis();
System.out.println(" + Deleting a single object");
soup.delete(RECORDS/2);
f.saveChanges(false);
post=System.currentTimeMillis();
System.out.println(" - Deleted in "+(post-pre)+"ms");
obj=soup.scan(RECORDS/2);
// System.out.println(obj);
f.close();
*/
}catch(Exception e){
e.printStackTrace();
}
try{
File ftest=new File(filename);
if(!ftest.delete()){
System.out.println("Couldn`t delete file");
}
}catch(Exception e){}
}
}
|
package me.mazeika.uconfig;
import me.mazeika.uconfig.parsing.Parser;
import me.mazeika.uconfig.parsing.ParserType;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Optional;
class UConfig extends Config
{
private static final String KEY_INDICES_DELIMITER = "
private static final String KEY_INDICES_ESCAPED_DELIMITER = "\\
private static final String KEY_INDICES_ESCAPE = "\\";
private final File file;
private final Parser parser;
private final ParserType parserType;
private Object data;
public UConfig(File file, boolean lazyLoad)
{
this.file = file;
parser = Parser.create(file.getName());
parserType = parser.getType();
if (! lazyLoad) {
getData();
}
}
@Override
public <T> T getOrDefault(String key, T defaultValue)
{
return getOrDefaultWithIndices(key, defaultValue);
}
@Override
public <T> T getOrDefaultWithIndices(String key, T defaultValue,
int... indices)
{
final String[] parsedKey = parseKey(key, indices);
Object data = getData();
for (int i = 0; i < parsedKey.length; i++) {
String keyPart = parsedKey[i];
// noinspection StringEquality
if (! (data instanceof Map) && ! (data instanceof List)
&& i == parsedKey.length - 1) {
return defaultValue;
}
if (isPositiveInteger(keyPart)) {
if (data instanceof List) {
final int keyPartInt = Integer.parseUnsignedInt(keyPart);
final List list = (List) data;
if (keyPartInt >= list.size()) {
return defaultValue;
}
data = list.get(keyPartInt);
continue;
}
else {
return defaultValue;
}
}
if (keyPart.startsWith(KEY_INDICES_ESCAPE)) {
keyPart = keyPart.substring(1);
}
if (data instanceof Map) {
// noinspection unchecked
if ((data = ((Map<String, Object>) data).get(keyPart))
== null) {
return defaultValue;
}
if (parserType == ParserType.XML && data instanceof Map) {
final Object content;
// noinspection unchecked
if ((content = ((Map<String, Object>) data).get("content"))
!= null) {
data = content;
break;
}
}
}
}
/*
First, check that we're dealing with XML. Next, if we *shouldn't* return
a map and the data *is* a map, return the default value. The reasoning
is that an empty XML element is actually an empty map due to how it's
converted to JSON. So, if we request the key `path.to.value` and the XML
looks like `<path><to><value/></to></path>`, for example, the default
value should be returned.
*/
if (parserType == ParserType.XML && ! (defaultValue instanceof Map)
&& data instanceof Map) {
return defaultValue;
}
/*
Check if the data is a map or list, and if it's an empty map or list,
return the default value.
*/
if ((data instanceof Map && ((Map) data).isEmpty())
|| (data instanceof List && ((List) data).isEmpty())) {
return defaultValue;
}
final String dataStr = data.toString();
/*
Check if the return type should be a string... if so, we'll want to
convert whatever it is we're going to return into a string so that
any other data types don't complain they can't be converted to a string.
*/
if (defaultValue instanceof String) {
// noinspection unchecked
return (T) dataStr;
}
/*
Properties files only give strings when accessing keys. As such, they
will be converted to their correct type if they're requested to be an
int or double.
*/
if (parserType == ParserType.PROPERTIES) {
if (defaultValue instanceof Integer) {
// noinspection unchecked
return (T) (Integer) Integer.parseInt(dataStr);
}
if (defaultValue instanceof Double) {
// noinspection unchecked
return (T) (Double) Double.parseDouble(dataStr);
}
}
// noinspection unchecked
return (T) data;
}
@Override
public <T> Optional<T> get(String key)
{
return getWithIndices(key);
}
@Override
public <T> Optional<T> getWithIndices(String key, int... indices)
{
// noinspection unchecked
return Optional.ofNullable((T) getOrDefaultWithIndices(key, null,
indices));
}
private String[] parseKey(String key, int... indices)
{
key = key.trim();
final String[] tokens = key.split("(?<!\\\\)\\.");
int indicesIndex = 0;
for (int i = 0; i < tokens.length; i++) {
final String token = tokens[i];
tokens[i] = token.replaceAll("(?<!\\\\)\\\\\\.", ".");
if (indices.length > 0) {
if (token.equals(KEY_INDICES_DELIMITER)) {
try {
tokens[i] = String.valueOf(indices[indicesIndex++]);
}
catch (IndexOutOfBoundsException e) {
throw new IllegalArgumentException(
"Insufficient indices supplied for key " + key
+ ", received " + indices.length + ": "
+ Arrays.toString(indices));
}
}
else if (token.equals(KEY_INDICES_ESCAPED_DELIMITER)) {
// '\
tokens[i] = KEY_INDICES_DELIMITER;
}
}
}
return tokens;
}
/**
* Gets the config data. Caches the data and returns the cached data if
* available. Otherwise, performs IO and reads/parses the file.
*
* @return the map
*/
private synchronized Object getData()
{
if (data == null) {
final StringBuilder builder = new StringBuilder();
try (BufferedReader in = new BufferedReader(new FileReader(file))) {
String line;
while ((line = in.readLine()) != null) {
builder.append(line).append('\n');
}
}
catch (IOException e) {
throw new RuntimeException(e);
}
data = parser.parse(builder.toString());
}
return data;
}
/**
* Gets if the given string is a positive integer.
*
* @param str the string to check
*
* @return {@code true} if the given string is a positive integer
*/
private boolean isPositiveInteger(String str)
{
for (char c : str.toCharArray()) {
if (c < '0' || c > '9') {
return false;
}
}
return true;
}
}
|
package me.nallar;
import lombok.Data;
import lombok.Getter;
import lombok.SneakyThrows;
import lombok.val;
import me.nallar.javatransformer.api.JavaTransformer;
import me.nallar.mixin.internal.MixinApplicator;
import me.nallar.modpatcher.tasks.BinaryProcessor;
import me.nallar.modpatcher.tasks.SourceProcessor;
import org.apache.log4j.Logger;
import org.gradle.api.Action;
import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.Task;
import org.gradle.api.tasks.SourceSet;
import java.io.*;
import java.nio.file.*;
import java.util.*;
public class ModPatcherPlugin implements Plugin<Project> {
public static final String RECOMPILE_MC_TASK = "recompileMc";
public static final String SETUP_CI_WORKSPACE_TASK = "setupCiWorkspace";
public static final String COMPILE_JAVA_TASK = "compileJava";
public static final String DEOBF_BINARY_TASK = "deobfMcMCP";
public static final String REMAP_SOURCE_TASK = "remapMcSources";
public static Logger logger = Logger.getLogger("ModPatcher");
public ModPatcherGradleExtension extension = new ModPatcherGradleExtension();
private Project project;
@Getter(lazy = true)
private final JavaTransformer mixinTransformer = makeMixinTransformer();
public static ModPatcherPlugin get(Project project) {
return (ModPatcherPlugin) project.getPlugins().findPlugin("me.nallar.ModPatcherGradle");
}
@Override
public void apply(Project project) {
this.project = project;
project.getPlugins().apply("net.minecraftforge.gradle.forge");
project.getExtensions().add("modpatcher", extension);
project.afterEvaluate(this::afterEvaluate);
}
public JavaTransformer makeMixinTransformer() {
val applicator = new MixinApplicator();
applicator.setNoMixinIsError(extension.noMixinIsError);
for (File file : sourceDirsWithMixins(true)) {
applicator.addSource(file.toPath(), extension.getMixinPackageToUse());
}
return applicator.getMixinTransformer();
}
public void mixinTransform(Path toTransform) {
if (extension.shouldMixin()) {
Path old = toTransform.resolveSibling("bak_" + toTransform.getFileName().toString());
try {
Files.deleteIfExists(old);
Files.move(toTransform, old);
try {
getMixinTransformer().transform(old, toTransform);
} finally {
if (!Files.exists(toTransform)) {
Files.move(old, toTransform);
} else {
Files.delete(old);
}
}
} catch (IOException e) {
throw new IOError(e);
}
}
}
@SuppressWarnings("unchecked")
@SneakyThrows
private List<File> sourceDirsWithMixins(boolean root) {
val results = new ArrayList<File>();
val mixinPackage = extension.getMixinPackageToUse().replace('.', '/');
for (SourceSet s : (Iterable<SourceSet>) project.getProperties().get("sourceSets")) {
for (File javaDir : s.getJava().getSrcDirs()) {
File mixinDir = fileWithChild(javaDir, mixinPackage);
if (mixinDir.isDirectory()) {
if (root)
results.add(javaDir);
else
results.add(mixinDir);
}
}
}
if (results.isEmpty())
throw new FileNotFoundException("Couldn't find any mixin packages! Searched for: " + mixinPackage);
return results;
}
private File fileWithChild(File javaDir, String mixinPackageToUse) {
return mixinPackageToUse == null ? javaDir : new File(javaDir, mixinPackageToUse);
}
public void afterEvaluate(Project project) {
val tasks = project.getTasks();
val mixinDirs = sourceDirsWithMixins(true).toArray();
tasks.getByName(DEOBF_BINARY_TASK).getInputs().files(mixinDirs);
tasks.getByName(REMAP_SOURCE_TASK).getInputs().files(mixinDirs);
tasks.getByName(DEOBF_BINARY_TASK).doLast(new Action<Task>() {
@SneakyThrows
@Override
public void execute(Task task) {
File f = task.getOutputs().getFiles().iterator().next();
BinaryProcessor.process(ModPatcherPlugin.this, f);
}
});
tasks.getByName(REMAP_SOURCE_TASK).doLast(new Action<Task>() {
@SneakyThrows
@Override
public void execute(Task task) {
File f = task.getOutputs().getFiles().iterator().next();
SourceProcessor.process(ModPatcherPlugin.this, f);
}
});
/*
TODO: Fix tasks never being up-to-date?
Via @AbrarSyed:
Adding empty access transformer may solve the problem
Other possiblities:
Instead of doLast, add to Actions list before WriteCacheAction if it's there?
*/
}
@Data
public static class ModPatcherGradleExtension {
public String mixinPackage = "";
public boolean noMixinIsError = false;
public boolean extractGeneratedSources = false;
public boolean generateInheritanceHierarchy = false;
public String getMixinPackageToUse() {
return Objects.equals(mixinPackage, "all") ? null : mixinPackage;
}
public boolean shouldMixin() {
return !"".equals(mixinPackage);
}
}
}
|
package net.xprova.piccolo;
import java.io.BufferedReader;
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.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Scanner;
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) {
runCommand(line);
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();
}
}
}
/**
* 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
*/
public boolean runCommand(String line) {
String[] parts = line.split(" ");
String cmd = parts[0];
String[] args = Arrays.copyOfRange(parts, 1, parts.length);
return runCommand(cmd, args);
}
/**
* Runs a console command
*
* @param methodAlias
* command (method) name
* @param args
* command arguments
* @return true if the command runs successfully and false otherwise
*/
public boolean runCommand(String methodAlias, String args[]) {
MethodData methodData = methodAliases.get(methodAlias);
if (methodData == null) {
return false;
} else {
try {
smartInvoke(methodAlias, methodData.method, methodData.object, args);
return true;
} catch (Exception e) {
System.err.printf("Error while invoking method <%s> ...\n", methodData.method.getName());
e.printStackTrace();
}
return true;
}
}
@Command(aliases = { ":type", ":t" })
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 = { "!" })
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 = { ":quit", ":q" })
public boolean exitConsole() {
exitFlag = 1;
return true;
}
// 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)", method.getName(), 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() {
List<String> resultList = new ArrayList<String>();
for (MethodData md : availMethods) {
ArrayList<String> methodNames = getCommandNames(md.method);
StringBuilder sb = new StringBuilder(methodNames.get(0));
if (methodNames.size() > 1) {
sb.append(" (aliases: ");
int j = methodNames.size() - 1;
for (int i = 1; i < j; i++) {
sb.append(methodNames.get(i)).append(", ");
}
sb.append(methodNames.get(j)).append(")");
}
resultList.add(sb.toString());
}
Collections.sort(resultList);
out.printf("There are %d available commands:\n", resultList.size());
for (String methodName : resultList) {
out.println(methodName);
}
}
/**
* 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);
}
}
}
}
}
}
|
package nl.ovapi.rid.model;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Map;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import nl.ovapi.bison.model.KV17cvlinfo;
import nl.ovapi.bison.model.KV17cvlinfo.Mutation;
import nl.ovapi.bison.model.KV17cvlinfo.Mutation.MutationType;
import nl.ovapi.bison.model.KV6posinfo;
import nl.ovapi.bison.model.KV6posinfo.Type;
import nl.ovapi.exceptions.StopNotFoundException;
import nl.ovapi.exceptions.TooEarlyException;
import nl.ovapi.exceptions.UnknownKV6PosinfoType;
import nl.ovapi.rid.model.JourneyPattern.JourneyPatternPoint;
import nl.ovapi.rid.model.TimeDemandGroup.TimeDemandGroupPoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.collect.Maps;
import com.google.transit.realtime.GtfsRealtime.TripDescriptor;
import com.google.transit.realtime.GtfsRealtime.TripDescriptor.ScheduleRelationship;
import com.google.transit.realtime.GtfsRealtime.TripUpdate;
import com.google.transit.realtime.GtfsRealtime.TripUpdate.StopTimeEvent;
import com.google.transit.realtime.GtfsRealtime.TripUpdate.StopTimeUpdate;
import com.google.transit.realtime.GtfsRealtime.VehicleDescriptor;
@ToString()
public class Journey {
@Getter
@Setter
private Long id;
@Getter
@Setter
private JourneyPattern journeypattern;
@Getter
@Setter
private TimeDemandGroup timedemandgroup;
@Getter
@Setter
private Integer departuretime;
@Getter
@Setter
private Boolean wheelchairaccessible;
@Getter
@Setter
private String agencyId;
@Getter
@Setter
private String operatingDay;
@Getter
@Setter
private KV6posinfo posinfo;
@Getter
@Setter
private boolean isCanceled;
private Map<Integer, ArrayList<Mutation>> mutations;
@Getter
@Setter
private Map<Integer, KV6posinfo> reinforcements;
public Journey() {
mutations = Maps.newHashMap();
reinforcements = Maps.newHashMap();
}
private static final int PUNCTUALITY_FLOOR = 15; // seconds
private static final int DEFAULT_SPEED = (int) (80 / 3.6); // meters per
// seconds
private static final int LONGHAUL_SPEED = (int) (100 / 3.6); // meters per
// seconds
private static final int SHORTHAUL_SPEED = (int) (60 / 3.6); // meters per
// seconds
private static final int MIN_PUNCTUALITY = -300; // Minimum allowed
// punctuality.
private static final Logger _log = LoggerFactory.getLogger(Journey.class);
public TripDescriptor.Builder tripDescriptor(){
TripDescriptor.Builder tripDescriptor = TripDescriptor.newBuilder();
tripDescriptor.setStartDate(operatingDay);
tripDescriptor.setTripId(id.toString());
tripDescriptor.setScheduleRelationship(isCanceled ? ScheduleRelationship.CANCELED : ScheduleRelationship.SCHEDULED);
return tripDescriptor;
}
public StopTimeEvent.Builder stopTimeEventArrival(JourneyPatternPoint pt, int punctuality){
StopTimeEvent.Builder stopTimeEvent = StopTimeEvent.newBuilder();
stopTimeEvent.setDelay(punctuality);
return stopTimeEvent;
}
public boolean hasMutations(){
return mutations.size() > 0 || isCanceled;
}
/**
* @return Whether journey is currently planned to ride or is still riding.
*/
public boolean isCurrent(){
return (System.currentTimeMillis()+24*60*60*1000) > getEndEpoch(); //Whether end-of-trip is 24 hours ago
}
public StopTimeEvent.Builder stopTimeEventDeparture(JourneyPatternPoint pt, int punctuality){
StopTimeEvent.Builder stopTimeEvent = StopTimeEvent.newBuilder();
if (mutations.containsKey(pt.getPointorder())){
for (Mutation m : mutations.get(pt.getPointorder())){
if (m.getMutationtype() == MutationType.LAG){
punctuality = Math.max(punctuality, m.getLagtime());
}
}
}
stopTimeEvent.setDelay(punctuality);
return stopTimeEvent;
}
public long getEndEpoch(){
try {
Calendar c = Calendar.getInstance();
c.setTime(new SimpleDateFormat("yyyy-MM-dd").parse(getOperatingDay()));
c.set(Calendar.HOUR, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
c.add(Calendar.SECOND, getDeparturetime());
c.add(Calendar.SECOND, timedemandgroup.points.get(timedemandgroup.points.size()-1).getTotaldrivetime());
if (posinfo != null && posinfo.getPunctuality() != null){
c.add(Calendar.SECOND, Math.abs(posinfo.getPunctuality()));
}
return c.getTimeInMillis();
} catch (ParseException e) {
return -1;
}
}
public long getDepartureEpoch(){
try {
Calendar c = Calendar.getInstance();
c.setTime(new SimpleDateFormat("yyyy-MM-dd").parse(getOperatingDay()));
c.set(Calendar.HOUR, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
c.add(Calendar.SECOND, getDeparturetime());
return c.getTimeInMillis();
} catch (ParseException e) {
return -1;
}
}
public TripUpdate.Builder updateTimes(KV6posinfo posinfo) {
boolean passed = posinfo.getMessagetype() != KV6posinfo.Type.DELAY;
int punctuality = Math
.max(MIN_PUNCTUALITY, posinfo.getPunctuality() == null ? 0
: posinfo.getPunctuality());
TripUpdate.Builder tripUpdate = TripUpdate.newBuilder();
tripUpdate.setTrip(tripDescriptor());
tripUpdate.setTimestamp(posinfo.getTimestamp());
if (isCanceled){
return tripUpdate;
}
VehicleDescriptor.Builder vehicleDesc = posinfo.getVehicleDescription();
if (vehicleDesc != null)
tripUpdate.setVehicle(vehicleDesc);
switch (posinfo.getMessagetype()) {// These types do not contain // information regarding punctuality
case INIT:
case END:
case OFFROUTE:
return tripUpdate;
default:
break;
}
int passageseq = 0;
int elapsedtime = 0;
boolean nullterminated = false;
for (int i = 0; i < timedemandgroup.points.size(); i++) {
TimeDemandGroupPoint tpt = timedemandgroup.points.get(i);
JourneyPatternPoint pt = journeypattern.getPoint(tpt.pointorder);
if (pt.getOperatorpointref().equals(posinfo.getUserstopcode())) {
if (posinfo.getPassagesequencenumber() - passageseq > 0) {
passageseq++; // Userstop equal but posinfo relates to n-th
// passing
} else {
elapsedtime = tpt.getTotaldrivetime()+tpt.getStopwaittime();
passed = false;
switch (posinfo.getMessagetype()) {
case ARRIVAL:
case ONSTOP:
if ((pt.iswaitpoint || i == 0) && punctuality < 0)
punctuality = 0;
break;
case DEPARTURE:
if ((pt.iswaitpoint || i == 0) && punctuality < 0)
punctuality = 0;
break;
default:
break;
}
}
} else if (!passed) {
StopTimeUpdate.Builder stopTimeUpdate = StopTimeUpdate.newBuilder();
stopTimeUpdate.setStopSequence(tpt.getPointorder());
stopTimeUpdate.setStopId(pt.getPointref().toString());
stopTimeUpdate.setArrival(stopTimeEventArrival(pt,punctuality));
boolean stopcanceled = isCanceled;
if (mutations.containsKey(tpt.getPointorder())){ // Check if mutation exists with cancel
for (Mutation m : mutations.get(tpt.getPointorder())){
if (m.getMutationtype() == MutationType.SHORTEN){
stopcanceled = true;
}
}
}
stopTimeUpdate.setScheduleRelationship(
stopcanceled ? StopTimeUpdate.ScheduleRelationship.SKIPPED
: StopTimeUpdate.ScheduleRelationship.SCHEDULED);
if (pt.getIswaitpoint() && punctuality < 0)
punctuality = 0;
if (tpt.getStopwaittime() != 0) {
int stopwaittime = tpt.getStopwaittime();
if (stopwaittime > 20 && punctuality > 0) {
punctuality -= Math.max(0, stopwaittime - 20);
punctuality = Math.max(0, punctuality);
}
}
stopTimeUpdate.setDeparture(stopTimeEventDeparture(pt,punctuality));
if (!nullterminated || Math.abs(punctuality) > 0 || stopcanceled){
if (punctuality == 0){
nullterminated = true;
}
tripUpdate.addStopTimeUpdate(stopTimeUpdate);
}
punctuality = stopTimeUpdate.getDeparture().getDelay();
if (punctuality > 0 && i != timedemandgroup.points.size() - 1) {
TimeDemandGroupPoint ntpt = timedemandgroup.points.get(i+1);
JourneyPatternPoint npt = journeypattern.getPoint(ntpt.pointorder);
int distanceToNext = npt.getDistancefromstartroute() - pt.getDistancefromstartroute();
int secondsToNext = ntpt.getTotaldrivetime() - (tpt.getTotaldrivetime()+tpt.getStopwaittime());
int speed = DEFAULT_SPEED;
if (distanceToNext > 10000) {
speed = LONGHAUL_SPEED;
} else if (distanceToNext < 1000) {
speed = SHORTHAUL_SPEED;
}
int fastest = distanceToNext / speed;
punctuality -= (secondsToNext - fastest);
if (punctuality < 0) {
punctuality = 0;
}
} else if (punctuality < 0 && i != timedemandgroup.points.size() - 1) {
punctuality = decayeddelay(punctuality,
tpt.getTotaldrivetime() - elapsedtime);
}
if (Math.abs(punctuality) < PUNCTUALITY_FLOOR) {
punctuality = 0;
}
}
}
return tripUpdate;
}
public int decayeddelay(int delay, int elapsedtime) {
if (delay == 0)
return 0;
double vlamba = 1.0 / 500.0;
double decay = Math.exp(-vlamba * elapsedtime);
int decayeddelay = (int) (decay * delay);
return decayeddelay;
}
private void parseMutateJourney(Long timestamp, Mutation m) {
switch (m.getMutationtype()) {
case CANCEL:
isCanceled = true;
break;
case RECOVER:
isCanceled = false;
break;
default:
break;
}
}
private JourneyPatternPoint getJourneyStop (String userstopcode,int passageSequencenumber){
for (int i = 0; i < timedemandgroup.points.size(); i++) {
TimeDemandGroupPoint tpt = timedemandgroup.points.get(i);
JourneyPatternPoint pt = journeypattern.getPoint(tpt.pointorder);
if (pt.getOperatorpointref().equals(userstopcode)){
if (passageSequencenumber > 0){
passageSequencenumber
}else{
return pt;
}
}
}
return null;
}
private void parseMutateJourneyStop(Long timestamp, Mutation m)
throws StopNotFoundException {
JourneyPatternPoint pst = getJourneyStop(m.getUserstopcode(),m.getPassagesequencenumber());
if (pst == null) {
throw new StopNotFoundException(m.toString());
}
mutations.put(pst.getPointorder(), new ArrayList<Mutation>());
switch (m.getMutationtype()) {
case CHANGEDESTINATION:
break;
case CHANGEPASSTIMES:
mutations.get(pst.getPointorder()).add(m);
break;
case LAG:
mutations.get(pst.getPointorder()).add(m);
break;
case MUTATIONMESSAGE:
mutations.get(pst.getPointorder()).add(m);
break;
case SHORTEN:
mutations.get(pst.getPointorder()).add(m);
break;
case RECOVER:
case CANCEL:
default:
break;
}
}
public TripUpdate.Builder update(ArrayList<KV17cvlinfo> cvlinfos) {
long timestamp = 0;
if (cvlinfos.size() == 0){
return null;
}
mutations.clear();
for (KV17cvlinfo cvlinfo : cvlinfos) {
for (Mutation mut : cvlinfo.getMutations()) {
try {
timestamp = Math.max(timestamp, cvlinfo.getTimestamp());
switch (mut.getMessagetype()) {
case KV17MUTATEJOURNEY:
parseMutateJourney(cvlinfo.getTimestamp(), mut);
break;
case KV17MUTATEJOURNEYSTOP:
parseMutateJourneyStop(cvlinfo.getTimestamp(), mut);
break;
default:
break;
}
} catch (Exception e) {
_log.error("Error applying KV17",e);
}
}
}
int posinfoAge = (posinfo == null) ? Integer.MAX_VALUE :
(int)((System.currentTimeMillis()-posinfo.getTimestamp()) / 1000);
if (posinfo != null && posinfoAge < 120){
TripUpdate.Builder timeUpdate = updateTimes(posinfo);
timeUpdate.setTimestamp(cvlinfos.get(0).getTimestamp());
return timeUpdate;
}else{
KV6posinfo posinfo = new KV6posinfo();
posinfo.setMessagetype(Type.DELAY); //Fake KV6posinfo to get things moving
posinfo.setPunctuality(0);
posinfo.setTimestamp(cvlinfos.get(0).getTimestamp());
return updateTimes(posinfo);
}
}
public TripUpdate.Builder update(KV6posinfo posinfo) throws StopNotFoundException,UnknownKV6PosinfoType, TooEarlyException {
long departureTime = getDepartureEpoch();
if (System.currentTimeMillis() < departureTime){
int timeDeltaSeconds = (int)((departureTime- System.currentTimeMillis())/1000);
if (timeDeltaSeconds>=3600){
switch(posinfo.getMessagetype()){
case INIT:
case ARRIVAL:
case ONSTOP:
case DELAY:
break;
default:
throw new TooEarlyException(posinfo.toString());
}
}
}
if (posinfo.getUserstopcode() != null
&& !journeypattern.contains(posinfo.getUserstopcode())) {
throw new StopNotFoundException(posinfo.toString());
}
return updateTimes(posinfo);
}
}
|
package it.unibz.krdb.obda.gui.swing.panel;
import it.unibz.krdb.obda.gui.swing.IconLoader;
import it.unibz.krdb.obda.gui.swing.utils.CustomTraversalPolicy;
import it.unibz.krdb.obda.gui.swing.utils.DatasourceSelectorListener;
import it.unibz.krdb.obda.model.OBDADataSource;
import it.unibz.krdb.obda.model.OBDAException;
import it.unibz.krdb.obda.model.OBDAModel;
import it.unibz.krdb.obda.model.OBDAModelListener;
import it.unibz.krdb.obda.model.impl.OBDADataFactoryImpl;
import it.unibz.krdb.obda.model.impl.RDBMSourceParameterConstants;
import it.unibz.krdb.sql.JDBCConnectionManager;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.net.URI;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Vector;
import javax.swing.JOptionPane;
public class DatasourceParameterEditorPanel extends javax.swing.JPanel implements DatasourceSelectorListener {
private static final long serialVersionUID = 3506358479342412849L;
private OBDADataSource selectedDataSource;
private OBDAModel obdaModel;
private DatasourceSelector selector;
private ComboBoxItemListener comboListener;
/**
* Creates new form DatasourceParameterEditorPanel
*/
public DatasourceParameterEditorPanel(OBDAModel model) {
initComponents();
this.comboListener = new ComboBoxItemListener();
txtJdbcDriver.addItemListener(comboListener);
setDatasourcesController(model);
enableFields(false);
Vector<Component> order = new Vector<Component>(7);
order.add(pnlDataSourceParameters);
order.add(txtJdbcUrl);
order.add(txtDatabaseUsername);
order.add(txtDatabasePassword);
order.add(txtJdbcDriver);
order.add(cmdTestConnection);
this.setFocusTraversalPolicy(new CustomTraversalPolicy(order));
lblSourcesNumber.setText(Integer.toString(obdaModel.getSources().size()));
model.addSourcesListener(new OBDAModelListener() {
private static final long serialVersionUID = -415753131971100104L;
@Override
public void datasourceUpdated(String oldname, OBDADataSource currendata) {
// NO OP
}
@Override
public void datasourceDeleted(OBDADataSource source) {
lblSourcesNumber.setText(Integer.toString(obdaModel.getSources().size()));
}
@Override
public void datasourceAdded(OBDADataSource source) {
lblSourcesNumber.setText(Integer.toString(obdaModel.getSources().size()));
}
@Override
public void datasourcParametersUpdated() {
// NO OP
}
@Override
public void alldatasourcesDeleted() {
lblSourcesNumber.setText(Integer.toString(obdaModel.getSources().size()));
}
});
}
private class ComboBoxItemListener implements ItemListener {
private boolean notify = false;
@Override
public void itemStateChanged(ItemEvent e) {
if (notify) {
fieldChangeHandler(null);
}
}
public void setNotify(boolean notify) {
this.notify = notify;
}
}
public void setDatasourcesController(OBDAModel model) {
obdaModel = model;
addDataSourceSelector();
resetTextFields();
}
private void addDataSourceSelector() {
selector = new DatasourceSelector(obdaModel);
selector.addDatasourceListListener(this);
pnlDataSourceSelector.add(selector, BorderLayout.CENTER);
}
private void resetTextFields() {
txtJdbcUrl.setText("");
txtDatabasePassword.setText("");
txtDatabaseUsername.setText("");
comboListener.setNotify(false);
txtJdbcDriver.setSelectedIndex(0);
comboListener.setNotify(true);
}
private void enableFields(boolean value) {
txtJdbcUrl.setEnabled(value);
txtDatabasePassword.setEnabled(value);
txtDatabaseUsername.setEnabled(value);
txtJdbcDriver.setEnabled(value);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed"
// <editor-fold defaultstate="collapsed"
// <editor-fold defaultstate="collapsed"
// <editor-fold defaultstate="collapsed"
// desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
pnlOBDAModelData = new javax.swing.JPanel();
lblSources = new javax.swing.JLabel();
lblSourcesNumber = new javax.swing.JLabel();
jPanel1 = new javax.swing.JPanel();
pnlDataSourceParameters = new javax.swing.JPanel();
txtJdbcUrl = new javax.swing.JTextField();
txtDatabaseUsername = new javax.swing.JTextField();
txtDatabasePassword = new javax.swing.JPasswordField();
txtJdbcDriver = new javax.swing.JComboBox();
cmdTestConnection = new javax.swing.JButton();
lblDataSourceName = new javax.swing.JLabel();
lblJdbcUrl = new javax.swing.JLabel();
lblDatabaseUsername = new javax.swing.JLabel();
lblDatabasePassword = new javax.swing.JLabel();
lblJdbcDriver = new javax.swing.JLabel();
lblConnectionStatus = new javax.swing.JLabel();
pnlDataSourceSelector = new javax.swing.JPanel();
pnlCommandButton = new javax.swing.JPanel();
cmdNew = new javax.swing.JButton();
cmdRemove = new javax.swing.JButton();
pnlInformation = new javax.swing.JPanel();
setFocusable(false);
setMinimumSize(new java.awt.Dimension(640, 480));
setPreferredSize(new java.awt.Dimension(640, 480));
setLayout(new java.awt.GridBagLayout());
pnlOBDAModelData.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "OBDA Model information",
javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font(
"Lucida Grande", 0, 13), new java.awt.Color(53, 113, 163))); // NOI18N
pnlOBDAModelData.setForeground(new java.awt.Color(53, 113, 163));
pnlOBDAModelData.setLayout(new java.awt.GridBagLayout());
lblSources.setFont(new java.awt.Font("Dialog", 1, 12)); // NOI18N
lblSources.setForeground(new java.awt.Color(53, 113, 163));
lblSources.setText("Number of sources:");
lblSources.setFocusTraversalKeysEnabled(false);
lblSources.setFocusable(false);
lblSources.setMaximumSize(new java.awt.Dimension(120, 24));
lblSources.setMinimumSize(new java.awt.Dimension(120, 24));
lblSources.setPreferredSize(new java.awt.Dimension(130, 24));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
gridBagConstraints.insets = new java.awt.Insets(0, 10, 10, 20);
pnlOBDAModelData.add(lblSources, gridBagConstraints);
lblSourcesNumber.setFont(new java.awt.Font("Courier New", 1, 13)); // NOI18N
lblSourcesNumber.setText("0");
lblSourcesNumber.setFocusable(false);
lblSourcesNumber.setPreferredSize(new java.awt.Dimension(150, 24));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
gridBagConstraints.insets = new java.awt.Insets(0, 10, 10, 20);
pnlOBDAModelData.add(lblSourcesNumber, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
pnlOBDAModelData.add(jPanel1, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
add(pnlOBDAModelData, gridBagConstraints);
pnlDataSourceParameters.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Connection parameters",
javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font(
"Lucida Grande", 0, 13), new java.awt.Color(53, 113, 163))); // NOI18N
pnlDataSourceParameters.setForeground(new java.awt.Color(53, 113, 163));
pnlDataSourceParameters.setAlignmentX(5.0F);
pnlDataSourceParameters.setAlignmentY(5.0F);
pnlDataSourceParameters.setAutoscrolls(true);
pnlDataSourceParameters.setFocusable(false);
pnlDataSourceParameters.setMaximumSize(new java.awt.Dimension(32767, 23));
pnlDataSourceParameters.setMinimumSize(new java.awt.Dimension(0, 0));
pnlDataSourceParameters.setPreferredSize(new java.awt.Dimension(1, 230));
pnlDataSourceParameters.setLayout(new java.awt.GridBagLayout());
txtJdbcUrl.setFont(new java.awt.Font("Courier New", 1, 13)); // NOI18N
txtJdbcUrl.setMaximumSize(new java.awt.Dimension(25, 2147483647));
txtJdbcUrl.setMinimumSize(new java.awt.Dimension(180, 24));
txtJdbcUrl.setPreferredSize(new java.awt.Dimension(180, 24));
txtJdbcUrl.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
fieldChangeHandler(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(10, 0, 2, 10);
pnlDataSourceParameters.add(txtJdbcUrl, gridBagConstraints);
txtDatabaseUsername.setFont(new java.awt.Font("Courier New", 1, 13)); // NOI18N
txtDatabaseUsername.setMaximumSize(new java.awt.Dimension(25, 2147483647));
txtDatabaseUsername.setMinimumSize(new java.awt.Dimension(180, 24));
txtDatabaseUsername.setPreferredSize(new java.awt.Dimension(180, 24));
txtDatabaseUsername.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
fieldChangeHandler(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(3, 0, 2, 10);
pnlDataSourceParameters.add(txtDatabaseUsername, gridBagConstraints);
txtDatabasePassword.setFont(new java.awt.Font("Courier New", 1, 13)); // NOI18N
txtDatabasePassword.setMinimumSize(new java.awt.Dimension(180, 24));
txtDatabasePassword.setPreferredSize(new java.awt.Dimension(180, 24));
txtDatabasePassword.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
fieldChangeHandler(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH;
gridBagConstraints.insets = new java.awt.Insets(3, 0, 2, 10);
pnlDataSourceParameters.add(txtDatabasePassword, gridBagConstraints);
txtJdbcDriver.setEditable(true);
txtJdbcDriver.setFont(new java.awt.Font("Courier New", 1, 13)); // NOI18N
txtJdbcDriver.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "select or type the name of the driver...",
"org.postgresql.Driver", "com.mysql.jdbc.Driver", "org.h2.Driver", "com.ibm.db2.jcc.DB2Driver",
"oracle.jdbc.driver.OracleDriver", "com.microsoft.sqlserver.jdbc.SQLServerDriver" }));
txtJdbcDriver.setMinimumSize(new java.awt.Dimension(180, 24));
txtJdbcDriver.setPreferredSize(new java.awt.Dimension(180, 24));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH;
gridBagConstraints.insets = new java.awt.Insets(3, 0, 2, 10);
pnlDataSourceParameters.add(txtJdbcDriver, gridBagConstraints);
cmdTestConnection.setIcon(IconLoader.getImageIcon("images/execute.png"));
cmdTestConnection.setText("Test Connection");
cmdTestConnection.setBorder(javax.swing.BorderFactory.createEtchedBorder());
cmdTestConnection.setContentAreaFilled(false);
cmdTestConnection.setIconTextGap(5);
cmdTestConnection.setMaximumSize(new java.awt.Dimension(110, 25));
cmdTestConnection.setMinimumSize(new java.awt.Dimension(110, 25));
cmdTestConnection.setPreferredSize(new java.awt.Dimension(110, 25));
cmdTestConnection.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cmdTestConnectionActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 5;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH;
gridBagConstraints.insets = new java.awt.Insets(8, 10, 10, 20);
pnlDataSourceParameters.add(cmdTestConnection, gridBagConstraints);
lblDataSourceName.setBackground(new java.awt.Color(153, 153, 153));
lblDataSourceName.setFont(new java.awt.Font("Dialog", 1, 12)); // NOI18N
lblDataSourceName.setForeground(new java.awt.Color(53, 113, 163));
lblDataSourceName.setText("Datasource Name: ");
lblDataSourceName.setFocusTraversalKeysEnabled(false);
lblDataSourceName.setFocusable(false);
lblDataSourceName.setMaximumSize(new java.awt.Dimension(120, 27));
lblDataSourceName.setMinimumSize(new java.awt.Dimension(120, 27));
lblDataSourceName.setPreferredSize(new java.awt.Dimension(120, 27));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
gridBagConstraints.insets = new java.awt.Insets(0, 10, 0, 0);
pnlDataSourceParameters.add(lblDataSourceName, gridBagConstraints);
lblJdbcUrl.setFont(new java.awt.Font("Dialog", 1, 12)); // NOI18N
lblJdbcUrl.setForeground(new java.awt.Color(53, 113, 163));
lblJdbcUrl.setText("Connection URL:");
lblJdbcUrl.setFocusTraversalKeysEnabled(false);
lblJdbcUrl.setFocusable(false);
lblJdbcUrl.setMaximumSize(new java.awt.Dimension(130, 24));
lblJdbcUrl.setMinimumSize(new java.awt.Dimension(130, 24));
lblJdbcUrl.setPreferredSize(new java.awt.Dimension(130, 24));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH;
gridBagConstraints.insets = new java.awt.Insets(10, 10, 2, 20);
pnlDataSourceParameters.add(lblJdbcUrl, gridBagConstraints);
lblDatabaseUsername.setFont(new java.awt.Font("Dialog", 1, 12)); // NOI18N
lblDatabaseUsername.setForeground(new java.awt.Color(53, 113, 163));
lblDatabaseUsername.setText("Database Username:");
lblDatabaseUsername.setFocusTraversalKeysEnabled(false);
lblDatabaseUsername.setFocusable(false);
lblDatabaseUsername.setMaximumSize(new java.awt.Dimension(130, 24));
lblDatabaseUsername.setMinimumSize(new java.awt.Dimension(130, 24));
lblDatabaseUsername.setPreferredSize(new java.awt.Dimension(130, 24));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH;
gridBagConstraints.insets = new java.awt.Insets(3, 10, 2, 20);
pnlDataSourceParameters.add(lblDatabaseUsername, gridBagConstraints);
lblDatabasePassword.setFont(new java.awt.Font("Dialog", 1, 12)); // NOI18N
lblDatabasePassword.setForeground(new java.awt.Color(53, 113, 163));
lblDatabasePassword.setText("Database Password:");
lblDatabasePassword.setFocusTraversalKeysEnabled(false);
lblDatabasePassword.setFocusable(false);
lblDatabasePassword.setMaximumSize(new java.awt.Dimension(130, 24));
lblDatabasePassword.setMinimumSize(new java.awt.Dimension(130, 24));
lblDatabasePassword.setPreferredSize(new java.awt.Dimension(130, 24));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH;
gridBagConstraints.insets = new java.awt.Insets(3, 10, 2, 20);
pnlDataSourceParameters.add(lblDatabasePassword, gridBagConstraints);
lblJdbcDriver.setFont(new java.awt.Font("Dialog", 1, 12)); // NOI18N
lblJdbcDriver.setForeground(new java.awt.Color(53, 113, 163));
lblJdbcDriver.setText("JDBC Driver name:");
lblJdbcDriver.setFocusTraversalKeysEnabled(false);
lblJdbcDriver.setFocusable(false);
lblJdbcDriver.setMaximumSize(new java.awt.Dimension(130, 24));
lblJdbcDriver.setMinimumSize(new java.awt.Dimension(130, 24));
lblJdbcDriver.setPreferredSize(new java.awt.Dimension(130, 24));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH;
gridBagConstraints.insets = new java.awt.Insets(3, 10, 2, 20);
pnlDataSourceParameters.add(lblJdbcDriver, gridBagConstraints);
lblConnectionStatus.setFont(new java.awt.Font("Courier New", 1, 13)); // NOI18N
lblConnectionStatus.setFocusTraversalKeysEnabled(false);
lblConnectionStatus.setFocusable(false);
lblConnectionStatus.setMaximumSize(new java.awt.Dimension(180, 24));
lblConnectionStatus.setMinimumSize(new java.awt.Dimension(180, 24));
lblConnectionStatus.setPreferredSize(new java.awt.Dimension(180, 24));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 5;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH;
gridBagConstraints.insets = new java.awt.Insets(8, 0, 10, 10);
pnlDataSourceParameters.add(lblConnectionStatus, gridBagConstraints);
pnlDataSourceSelector.setFocusable(false);
pnlDataSourceSelector.setMinimumSize(new java.awt.Dimension(300, 27));
pnlDataSourceSelector.setPreferredSize(new java.awt.Dimension(300, 27));
pnlDataSourceSelector.setLayout(new java.awt.BorderLayout());
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
pnlDataSourceParameters.add(pnlDataSourceSelector, gridBagConstraints);
pnlCommandButton.setFocusable(false);
pnlCommandButton.setMinimumSize(new java.awt.Dimension(210, 27));
pnlCommandButton.setPreferredSize(new java.awt.Dimension(210, 27));
pnlCommandButton.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 2));
cmdNew.setIcon(IconLoader.getImageIcon("images/plus.png"));
cmdNew.setText("Create New...");
cmdNew.setBorder(javax.swing.BorderFactory.createEtchedBorder());
cmdNew.setContentAreaFilled(false);
cmdNew.setIconTextGap(5);
cmdNew.setMargin(new java.awt.Insets(0, 0, 0, 0));
cmdNew.setMaximumSize(new java.awt.Dimension(105, 25));
cmdNew.setMinimumSize(new java.awt.Dimension(105, 25));
cmdNew.setPreferredSize(new java.awt.Dimension(105, 25));
cmdNew.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cmdNewActionPerformed(evt);
}
});
pnlCommandButton.add(cmdNew);
cmdRemove.setIcon(IconLoader.getImageIcon("images/minus.png"));
cmdRemove.setText("Remove");
cmdRemove.setBorder(javax.swing.BorderFactory.createEtchedBorder());
cmdRemove.setContentAreaFilled(false);
cmdRemove.setIconTextGap(5);
cmdRemove.setMaximumSize(new java.awt.Dimension(85, 25));
cmdRemove.setMinimumSize(new java.awt.Dimension(85, 25));
cmdRemove.setPreferredSize(new java.awt.Dimension(85, 25));
cmdRemove.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cmdRemoveActionPerformed(evt);
}
});
pnlCommandButton.add(cmdRemove);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_END;
pnlDataSourceParameters.add(pnlCommandButton, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
gridBagConstraints.weightx = 1.0;
add(pnlDataSourceParameters, gridBagConstraints);
pnlInformation.setFocusable(false);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
add(pnlInformation, gridBagConstraints);
}// </editor-fold>//GEN-END:initComponents
private void cmdNewActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_cmdNewActionPerformed
while (true) {
String name = JOptionPane.showInputDialog(this, "Insert an identifier for the new data source:", null);
if (name == null) {
return;
}
if (!name.isEmpty()) {
URI uri = createUri(name);
if (uri != null) {
if (!obdaModel.containsSource(uri)) {
OBDADataSource source = OBDADataFactoryImpl.getInstance().getDataSource(uri);
obdaModel.addSource(source);
selector.set(source);
return;
} else {
JOptionPane.showMessageDialog(this, "The data source ID is already taken!", "Warning", JOptionPane.WARNING_MESSAGE);
}
}
} else {
JOptionPane.showMessageDialog(this, "The data source ID cannot be blank", "Warning", JOptionPane.WARNING_MESSAGE);
}
}
}// GEN-LAST:event_cmdNewActionPerformed
private void cmdRemoveActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_cmdRemoveActionPerformed
OBDADataSource ds = selector.getSelectedDataSource();
if (ds == null) {
JOptionPane.showMessageDialog(this, "Select a data source to proceed", "Warning", JOptionPane.WARNING_MESSAGE);
return;
}
int answer = JOptionPane.showConfirmDialog(this, "Are you sure want to delete this data source?", "Delete Confirmation",
JOptionPane.OK_CANCEL_OPTION);
if (answer == JOptionPane.OK_OPTION) {
obdaModel.removeSource(ds.getSourceID());
}
}// GEN-LAST:event_cmdRemoveActionPerformed
private void cmdTestConnectionActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_cmdTestConnectionActionPerformed
OBDADataSource ds = selector.getSelectedDataSource();
if (ds == null) {
JOptionPane.showMessageDialog(this, "Select a data source to proceed", "Warning", JOptionPane.WARNING_MESSAGE);
return;
}
JDBCConnectionManager connm = JDBCConnectionManager.getJDBCConnectionManager();
try {
Connection conn = connm.getConnection(selectedDataSource);
if (conn == null)
throw new SQLException("Error connecting to the database");
lblConnectionStatus.setForeground(Color.GREEN);
lblConnectionStatus.setText("Connection is OK");
} catch (SQLException e) { // if fails
lblConnectionStatus.setForeground(Color.RED);
lblConnectionStatus.setText(String.format("%s (ERR-CODE: %s)", e.getMessage(), e.getErrorCode()));
}
}// GEN-LAST:event_cmdTestConnectionActionPerformed
private URI createUri(String name) {
URI uri = null;
try {
uri = URI.create(name);
} catch (IllegalArgumentException e) {
JOptionPane.showMessageDialog(null, "Invalid identifier string", "Warning", JOptionPane.WARNING_MESSAGE);
}
return uri;
}
private void fieldChangeHandler(java.awt.event.KeyEvent evt) {// GEN-FIRST:event_fieldChangeHandler
if (selectedDataSource == null) {
JOptionPane.showMessageDialog(this, "Select a data source to proceed", "Warning", JOptionPane.WARNING_MESSAGE);
return;
}
JDBCConnectionManager man = JDBCConnectionManager.getJDBCConnectionManager();
try {
man.closeConnection(selectedDataSource);
} catch (OBDAException e) {
// do nothing
} catch (SQLException e) {
// do nothing
}
selectedDataSource.setParameter(RDBMSourceParameterConstants.DATABASE_USERNAME, txtDatabaseUsername.getText());
selectedDataSource.setParameter(RDBMSourceParameterConstants.DATABASE_PASSWORD, new String(txtDatabasePassword.getPassword()));
selectedDataSource.setParameter(RDBMSourceParameterConstants.DATABASE_DRIVER, txtJdbcDriver.getSelectedItem() == null ? "" : (String) txtJdbcDriver.getSelectedItem());
selectedDataSource.setParameter(RDBMSourceParameterConstants.DATABASE_URL, txtJdbcUrl.getText());
obdaModel.fireSourceParametersUpdated();
}// GEN-LAST:event_fieldChangeHandler
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton cmdNew;
private javax.swing.JButton cmdRemove;
private javax.swing.JButton cmdTestConnection;
private javax.swing.JPanel jPanel1;
private javax.swing.JLabel lblConnectionStatus;
private javax.swing.JLabel lblDataSourceName;
private javax.swing.JLabel lblDatabasePassword;
private javax.swing.JLabel lblDatabaseUsername;
private javax.swing.JLabel lblJdbcDriver;
private javax.swing.JLabel lblJdbcUrl;
private javax.swing.JLabel lblSources;
private javax.swing.JLabel lblSourcesNumber;
private javax.swing.JPanel pnlCommandButton;
private javax.swing.JPanel pnlDataSourceParameters;
private javax.swing.JPanel pnlDataSourceSelector;
private javax.swing.JPanel pnlInformation;
private javax.swing.JPanel pnlOBDAModelData;
private javax.swing.JPasswordField txtDatabasePassword;
private javax.swing.JTextField txtDatabaseUsername;
private javax.swing.JComboBox txtJdbcDriver;
private javax.swing.JTextField txtJdbcUrl;
// End of variables declaration//GEN-END:variables
private void currentDatasourceChange(OBDADataSource previousdatasource, OBDADataSource currentsource) {
comboListener.setNotify(false);
if (currentsource == null) {
selectedDataSource = null;
txtJdbcDriver.setSelectedIndex(0);
txtDatabaseUsername.setText("");
txtDatabasePassword.setText("");
txtJdbcUrl.setText("");
txtJdbcDriver.setEnabled(false);
txtDatabaseUsername.setEnabled(false);
txtDatabasePassword.setEnabled(false);
txtJdbcUrl.setEnabled(false);
lblConnectionStatus.setText("");
} else {
selectedDataSource = currentsource;
txtJdbcDriver.setSelectedItem(currentsource.getParameter(RDBMSourceParameterConstants.DATABASE_DRIVER));
txtDatabaseUsername.setText(currentsource.getParameter(RDBMSourceParameterConstants.DATABASE_USERNAME));
txtDatabasePassword.setText(currentsource.getParameter(RDBMSourceParameterConstants.DATABASE_PASSWORD));
txtJdbcUrl.setText(currentsource.getParameter(RDBMSourceParameterConstants.DATABASE_URL));
txtJdbcDriver.setEnabled(true);
txtDatabaseUsername.setEnabled(true);
txtDatabasePassword.setEnabled(true);
txtJdbcUrl.setEnabled(true);
lblConnectionStatus.setText("");
}
comboListener.setNotify(true);
}
@Override
public void datasourceChanged(OBDADataSource oldSource, OBDADataSource newSource) {
currentDatasourceChange(oldSource, newSource);
if (newSource == null) {
enableFields(false);
} else {
enableFields(true);
}
}
}
|
package org.mcupdater.util;
import org.apache.commons.io.FileUtils;
import org.mcupdater.MCUApp;
import java.io.*;
import java.nio.file.Path;
import java.util.List;
import java.util.jar.Attributes;
import java.util.jar.JarEntry;
import java.util.jar.JarOutputStream;
import java.util.jar.Manifest;
import java.util.logging.Level;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
//import java.io.BufferedOutputStream;
//import java.util.ArrayList;
public class Archive {
public static void extractZip(File archive, File destination) {
extractZip(archive, destination, false);
}
public static void extractZip(File archive, File destination, Boolean keepMeta) {
try{
ZipInputStream zis = new ZipInputStream(new FileInputStream(archive));
ZipEntry entry;
entry = zis.getNextEntry();
while(entry != null) {
String entryName = entry.getName();
if(entry.isDirectory()) {
File newDir = destination.toPath().resolve(entryName).toFile();
newDir.mkdirs();
MCUpdater.apiLogger.finest(" Directory: " + newDir.getPath());
} else {
if (!keepMeta && entryName.contains("META-INF")) {
zis.closeEntry();
entry = zis.getNextEntry();
continue;
}
if (entryName.contains("aux.class")) {
entryName = "mojangDerpyClass1.class";
}
File outFile = destination.toPath().resolve(entryName).toFile();
outFile.getParentFile().mkdirs();
MCUpdater.apiLogger.finest(" Extract: " + outFile.getPath());
FileOutputStream fos = new FileOutputStream(outFile);
int len;
byte[] buf = new byte[1024];
while((len = zis.read(buf, 0, 1024)) > -1) {
fos.write(buf, 0, len);
}
fos.close();
}
zis.closeEntry();
entry = zis.getNextEntry();
}
zis.close();
} catch (FileNotFoundException fnf) {
MCUpdater.apiLogger.log(Level.SEVERE, "File not found", fnf);
} catch (IOException ioe) {
MCUpdater.apiLogger.log(Level.SEVERE, "I/O error", ioe);
}
}
public static void createZip(File archive, List<File> files, Path mCFolder, MCUApp parent) throws IOException
{
if(!archive.getParentFile().exists()){
archive.getParentFile().mkdirs();
}
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(archive));
int fileCount = files.size();
int filePos = 0;
for (File entry : files) {
filePos++;
parent.setStatus("Writing backup: (" + filePos + "/" + fileCount + ")");
String relPath = entry.getPath().replace(mCFolder.toString(), "");
MCUpdater.apiLogger.finest(relPath);
if (entry.isDirectory()) {
out.putNextEntry(new ZipEntry(relPath + "/"));
out.closeEntry();
} else {
FileInputStream in = new FileInputStream(entry);
out.putNextEntry(new ZipEntry(relPath));
byte[] buf = new byte[1024];
int count;
while ((count = in.read(buf)) > 0) {
out.write(buf, 0, count);
}
in.close();
out.closeEntry();
}
}
out.close();
parent.setStatus("Backup written");
}
public static void addToZip(File archive, List<File> files, File basePath) throws IOException
{
File tempFile = File.createTempFile(archive.getName(), null);
tempFile.delete();
if(!archive.exists())
{
archive.getParentFile().mkdirs();
archive.createNewFile();
}
byte[] buf = new byte[1024];
boolean renameStatus = archive.renameTo(tempFile);
if (!renameStatus)
{
throw new RuntimeException("could not rename the file " + archive.getAbsolutePath() + " to " + tempFile.getAbsolutePath());
}
ZipInputStream zis = new ZipInputStream(new FileInputStream(tempFile));
ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(archive));
ZipEntry entry = zis.getNextEntry();
while (entry != null)
{
String name = entry.getName();
boolean notInFiles = true;
for (File f : files) {
if (f.getName().equals(name)) {
notInFiles = false;
break;
}
}
if (notInFiles) {
zos.putNextEntry(new ZipEntry(name));
int len;
while ((len = zis.read(buf)) > 0) {
zos.write(buf,0,len);
}
}
entry = zis.getNextEntry();
}
zis.close();
for (File f : files) {
if (f.isDirectory()) {
MCUpdater.apiLogger.finer("addToZip: " + f.getPath().replace(basePath.getPath(), "") + "/");
zos.putNextEntry(new ZipEntry(f.getPath().replace(basePath.getPath(), "") + "/"));
zos.closeEntry();
} else {
InputStream in = new FileInputStream(f);
MCUpdater.apiLogger.finer("addToZip: " + f.getPath().replace(basePath.getPath(), ""));
zos.putNextEntry(new ZipEntry(f.getPath().replace(basePath.getPath(), "")));
int len;
while ((len = in.read(buf)) > 0) {
zos.write(buf, 0, len);
}
zos.closeEntry();
in.close();
}
}
zos.close();
tempFile.delete();
}
public static void createJar(File outJar, List<File> inputFiles, String basePath, boolean doManifest) throws IOException {
Manifest manifest = new Manifest();
manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
try {
JarOutputStream jos;
if (doManifest) {
jos = new JarOutputStream(new FileOutputStream(outJar), manifest);
} else {
jos = new JarOutputStream(new FileOutputStream(outJar));
}
BufferedInputStream in;
for (File entry : inputFiles) {
// On some systems, the first entry provided is the root directory, but it is missing
// the path separator - making it not caught by the replace() call below, and added
// as a full path entry, malforming the created .JAR.
if (basePath.startsWith(entry.getPath())) {
continue;
}
String path = entry.getPath().replace(basePath, "").replace("\\", "/");
if (entry.isDirectory()) {
if (!path.isEmpty()) {
if (!path.endsWith("/")) {
path += "/";
}
JarEntry jEntry = new JarEntry(path);
jEntry.setTime(entry.lastModified());
jos.putNextEntry(jEntry);
jos.closeEntry();
}
} else {
if (path.contains("mojangDerpyClass1.class")) {
path = path.replace("mojangDerpyClass1.class", "aux.class");
}
JarEntry jEntry = new JarEntry(path);
jEntry.setTime(entry.lastModified());
jos.putNextEntry(jEntry);
in = new BufferedInputStream(new FileInputStream(entry));
byte[] buffer = new byte[1024];
int count;
while ((count = in.read(buffer)) > -1) {
jos.write(buffer, 0, count);
}
jos.closeEntry();
in.close();
}
}
jos.close();
} catch (FileNotFoundException e) {
MCUpdater.apiLogger.log(Level.SEVERE, "File not found", e);
} catch (IOException e) {
throw e;
}
}
public static void updateArchive(File zipFile, File[] files) throws IOException {
File tempFile = File.createTempFile(zipFile.getName(), null);
tempFile.delete();
boolean renameOk=zipFile.renameTo(tempFile);
if (!renameOk)
{
FileUtils.copyFile(zipFile, tempFile);
zipFile.delete();
}
byte[] buf = new byte[1024];
ZipInputStream zin = new ZipInputStream(new FileInputStream(tempFile));
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFile));
ZipEntry entry = zin.getNextEntry();
while (entry != null) {
String name = entry.getName();
boolean notInFiles = true;
for (File f : files) {
if (f.getName().equals(name)) {
notInFiles = false;
break;
}
}
if (notInFiles) {
// Add ZIP entry to output stream.
out.putNextEntry(new ZipEntry(name));
// Transfer bytes from the ZIP file to the output file
int len;
while ((len = zin.read(buf)) > 0) {
out.write(buf, 0, len);
}
}
entry = zin.getNextEntry();
}
// Close the streams
zin.close();
// Compress the files
for (File file : files) {
InputStream in = new FileInputStream(file);
// Add ZIP entry to output stream.
out.putNextEntry(new ZipEntry(file.getName()));
// Transfer bytes from the file to the ZIP file
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
// Complete the entry
out.closeEntry();
in.close();
}
// Complete the ZIP file
out.close();
tempFile.delete();
}
}
|
package org.mvel.ast;
import org.mvel.*;
import org.mvel.integration.VariableResolverFactory;
import static org.mvel.optimizers.OptimizerFactory.getThreadAccessorOptimizer;
import org.mvel.util.ArrayTools;
/**
* @author Christopher Brock
*/
public class NewObjectNode extends ASTNode {
private Accessor newObjectOptimizer;
private String FQCN;
public NewObjectNode(char[] expr, int fields) {
super(expr, fields);
if ((fields & COMPILE_IMMEDIATE) != 0) {
int endRange = ArrayTools.findFirst('(', expr);
String name;
if (endRange == -1) {
name = new String(expr);
}
else {
name = new String(expr, 0, ArrayTools.findFirst('(', expr));
}
ParserContext pCtx = AbstractParser.getCurrentThreadParserContext();
if (pCtx != null && pCtx.hasImport(name)) {
egressType = pCtx.getImport(name);
}
else {
try {
egressType = Class.forName(name);
}
catch (ClassNotFoundException e) {
throw new CompileException("class not found: " + name, e);
}
}
FQCN = egressType.getName();
if (!name.equals(FQCN)) {
int idx = FQCN.lastIndexOf('$');
if (idx != -1 && name.lastIndexOf('$') == -1) {
this.name = (FQCN.substring(0, idx + 1) + new String(this.name)).toCharArray();
}
else {
this.name = (FQCN.substring(0, FQCN.lastIndexOf('.') + 1) + new String(this.name)).toCharArray();
}
}
}
}
public Object getReducedValueAccelerated(Object ctx, Object thisValue, VariableResolverFactory factory) {
if (newObjectOptimizer == null) {
newObjectOptimizer = getThreadAccessorOptimizer().optimizeObjectCreation(name, ctx, thisValue, factory);
}
return newObjectOptimizer.getValue(ctx, thisValue, factory);
}
public Object getReducedValue(Object ctx, Object thisValue, VariableResolverFactory factory) {
return getReducedValueAccelerated(ctx, thisValue, factory);
}
public Accessor getNewObjectOptimizer() {
return newObjectOptimizer;
}
}
|
package seedu.doit.model.item;
import java.util.Objects;
import seedu.doit.commons.util.CollectionUtil;
import seedu.doit.model.tag.UniqueTagList;
/**
* Represents a Task in the task manager. Guarantees: details are present and
* not null, field values are validated.
*/
public class Task implements ReadOnlyTask, Comparable<ReadOnlyTask> {
private Name name;
private Priority priority;
private StartTime startTime;
private EndTime endTime;
private Description description;
private UniqueTagList tags;
/**
* Event Constructor where every field must be present and not null.
*/
public Task(Name name, Priority priority, StartTime startTime, EndTime endTime, Description description,
UniqueTagList tags) {
assert !CollectionUtil.isAnyNull(name, priority, startTime, endTime, description, tags);
this.name = name;
this.priority = priority;
this.startTime = startTime;
this.endTime = endTime;
this.description = description;
this.tags = new UniqueTagList(tags); // protect internal tags from
// changes in the arg list
}
/**
* Task Constructor every field must be present except for startTime.
*/
public Task(Name name, Priority priority, EndTime endTime, Description description, UniqueTagList tags) {
assert !CollectionUtil.isAnyNull(name, priority, endTime, description, tags);
this.name = name;
this.priority = priority;
this.startTime = new StartTime();
this.endTime = endTime;
this.description = description;
this.tags = new UniqueTagList(tags); // protect internal tags from
// changes in the arg list
}
/**
* Task Constructor every field must be present except for startTime and
* endTime.
*/
public Task(Name name, Priority priority, Description description, UniqueTagList tags) {
assert !CollectionUtil.isAnyNull(name, priority, description, tags);
this.name = name;
this.priority = priority;
this.startTime = new StartTime();
this.endTime = new EndTime();
this.description = description;
this.tags = new UniqueTagList(tags); // protect internal tags from
// changes in the arg list
}
/**
* Creates a copy of the given ReadOnlyTask.
*/
public Task(ReadOnlyTask source) {
this(source.getName(), source.getPriority(), source.getDescription(), source.getTags());
this.startTime = source.getStartTime();
this.endTime = source.getEndTime();
}
@Override
public Name getName() {
return this.name;
}
public void setName(Name name) {
assert name != null;
this.name = name;
}
@Override
public Priority getPriority() {
return this.priority;
}
public void setPriority(Priority priority) {
assert priority != null;
this.priority = priority;
}
@Override
public StartTime getStartTime() {
return this.startTime;
}
public void setStartTime(StartTime startTime) {
assert startTime != null;
this.startTime = startTime;
}
@Override
public EndTime getEndTime() {
return this.endTime;
}
public void setEndTime(EndTime endTime) {
assert endTime != null;
this.endTime = endTime;
}
@Override
public Description getDescription() {
return this.description;
}
public void setDescription(Description description) {
assert description != null;
this.description = description;
}
@Override
public boolean hasStartTime() {
if (this.startTime == null) {
return false;
} else if (this.startTime.value == null) {
return false;
}
return true;
}
@Override
public boolean hasEndTime() {
if (this.endTime == null) {
return false;
} else if (this.endTime.value == null) {
return false;
}
return true;
}
@Override
public UniqueTagList getTags() {
return new UniqueTagList(this.tags);
}
/**
* Replaces this task's tags with the tags in the argument tag list.
*/
public void setTags(UniqueTagList replacement) {
this.tags.setTags(replacement);
}
/**
* Indicates if this item is an event
*/
@Override
public boolean isEvent() {
return (hasStartTime() && hasEndTime());
}
/**
* Indicates if this item is a floatingTask
*/
@Override
public boolean isFloatingTask() {
return (!hasStartTime() && !hasEndTime());
}
/**
* Indicates if this item is a task
*/
@Override
public boolean isTask() {
return (!hasStartTime() && hasEndTime());
}
/**
* Updates this task with the details of {@code replacement}.
*/
public void resetData(ReadOnlyTask replacement) {
assert replacement != null;
this.setName(replacement.getName());
this.setPriority(replacement.getPriority());
this.setStartTime(replacement.getStartTime());
this.setEndTime(replacement.getEndTime());
this.setDescription(replacement.getDescription());
this.setTags(replacement.getTags());
}
@Override
public boolean equals(Object other) {
return (other == this // short circuit if same object
) || ((other instanceof ReadOnlyTask // instanceof handles nulls
) && this.isSameStateAs((ReadOnlyTask) other));
}
/**
* Compares the current task with another Task other. The current task is
* considered to be less than the other task if 1) This item has a earlier
* start time associated 2) both items are not events but this item has a
* later end time 3) but this task has a lexicographically smaller name
* (useful when sorting tasks in testing)
*/
@Override
public int compareTo(ReadOnlyTask other) {
return compareItems(other);
}
private int compareName(ReadOnlyTask other) {
return this.getName().toString().compareTo(other.getName().toString());
}
public int compareItems(ReadOnlyTask other) {
if (this.isTask() && other.isTask()) {
return compareName(other);
} else if (this.isTask() && other.isEvent()) {
return -1;
} else if (this.isTask() && other.isFloatingTask()) {
return -1;
}
if (this.isEvent() && other.isEvent()) {
return compareName(other);
} else if (this.isEvent() && other.isTask()) {
return 1;
} else if (this.isEvent() && other.isFloatingTask()) {
return -1;
}
if (this.isFloatingTask() && other.isFloatingTask()) {
return compareName(other);
} else if (this.isFloatingTask() && other.isTask()) {
return 1;
} else if (this.isFloatingTask() && other.isEvent()) {
return 1;
}
// Should never reach this
return 0;
}
@Override
public int hashCode() {
// use this method for custom fields hashing instead of implementing
// your own
return Objects.hash(this.name, this.priority, this.endTime, this.description, this.tags);
}
@Override
public String toString() {
return getAsText();
}
}
|
package seedu.toDoList.ui;
import java.util.List;
import javafx.beans.binding.Bindings;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.StringProperty;
import javafx.fxml.FXML;
import javafx.scene.Node;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.Region;
import javafx.scene.layout.StackPane;
import javafx.scene.text.Font;
import seedu.toDoList.model.task.ReadOnlyTask;
public class TaskCard extends UiPart{
private static final String FXML = "TaskListCard.fxml";
@FXML
private HBox cardPane;
@FXML
private Label name;
@FXML
private Label id;
@FXML
private Label date;
@FXML
private Label done;
@FXML
private Label recurring;
@FXML
private Label frequency;
@FXML
private Label tags;
@FXML
private ImageView priority;
private ReadOnlyTask task;
private int displayedIndex;
private Image priorityImage;
private int priorityLevel;
public TaskCard(){
}
public static TaskCard load(ReadOnlyTask task, int displayedIndex){
TaskCard card = new TaskCard();
card.task = task;
card.displayedIndex = displayedIndex;
return UiPartLoader.loadUiPart(card);
}
@FXML
public void initialize() {
HBox.setHgrow(id, Priority.ALWAYS);
id.setText(displayedIndex + ". ");
id.setWrapText(false);
id.setPrefWidth(Region.USE_COMPUTED_SIZE);
name.setText(task.getName().taskName);
name.setWrapText(true);
name.setPrefWidth(Region.USE_COMPUTED_SIZE);
date.setText(task.getDate().getValue());
date.setWrapText(true);
if(task.isDone())
{
cardPane.setStyle("-fx-background-color: #c2c0c0;");
}
done.setText(task.isDone() ? "DONE" : "");
if(!task.tagsString().equals(""))
tags.setText("Tags: " + task.tagsString());
tags.setWrapText(true);
recurring.setText(task.isRecurring()? "recurring":"");
recurring.setWrapText(true);
frequency.setText(task.isRecurring()?task.getRecurring().recurringFrequency:"");
frequency.setWrapText(true);
priorityLevel = task.getPriorityLevel().priorityLevel;
if(priorityLevel == 1)
{
priorityImage = new Image("/images/thunderbolt.png");
priority.setImage(priorityImage);
priority.setFitWidth(21.0);
priority.setFitHeight(40.0);
}
else if(priorityLevel == 2)
{
priorityImage = new Image("/images/thunderbolt2.png");
priority.setImage(priorityImage);
priority.setFitWidth(36.0);
priority.setFitHeight(40.0);
}
else if(priorityLevel == 3)
{
priorityImage = new Image("/images/thunderbolt3.png");
priority.setImage(priorityImage);
priority.setFitWidth(48.0);
priority.setFitHeight(40.0);
}
}
public HBox getLayout() {
return cardPane;
}
@Override
public void setNode(Node node) {
cardPane = (HBox)node;
}
@Override
public String getFxmlPath() {
return FXML;
}
}
|
package si.mazi.rescu;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import si.mazi.rescu.utils.AssertUtil;
import si.mazi.rescu.utils.HttpUtils;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSocketFactory;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.*;
import java.util.HashMap;
import java.util.Map;
import java.util.zip.GZIPInputStream;
/**
* Various HTTP utility methods
*/
class HttpTemplate {
public final static String CHARSET_UTF_8 = "UTF-8";
private final Logger log = LoggerFactory.getLogger(HttpTemplate.class);
/**
* Default request header fields
*/
private final Map<String, String> defaultHttpHeaders = new HashMap<String, String>();
private final int connTimeout;
private final int readTimeout;
private final Proxy proxy;
private final SSLSocketFactory sslSocketFactory;
private final HostnameVerifier hostnameVerifier;
/**
* Constructor
*/
public HttpTemplate(int readTimeout, String proxyHost, Integer proxyPort,
SSLSocketFactory sslSocketFactory, HostnameVerifier hostnameVerifier) {
this(0, readTimeout, proxyHost, proxyPort, sslSocketFactory, hostnameVerifier);
}
/**
* Constructor
*/
public HttpTemplate(int connTimeout,int readTimeout, String proxyHost, Integer proxyPort,
SSLSocketFactory sslSocketFactory, HostnameVerifier hostnameVerifier) {
this.connTimeout = connTimeout;
this.readTimeout = readTimeout;
this.sslSocketFactory = sslSocketFactory;
this.hostnameVerifier = hostnameVerifier;
defaultHttpHeaders.put("Accept-Charset", CHARSET_UTF_8);
// defaultHttpHeaders.put("Content-Type", "application/x-www-form-urlencoded");
defaultHttpHeaders.put("Accept", "application/json");
// 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
if (proxyHost == null || proxyPort == null) {
proxy = Proxy.NO_PROXY;
} else {
proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
log.info("Using proxy {}", proxy);
}
}
/**
* Requests JSON via an HTTP POST
*
* @param urlString A string representation of a URL
* @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)
*/
public InvocationResult executeRequest(String urlString, String requestBody,
Map<String, String> httpHeaders, HttpMethod method)
throws IOException {
HttpURLConnection connection = send(urlString, requestBody, httpHeaders, method);
return receive(connection);
}
public HttpURLConnection send(String urlString, String requestBody, Map<String, String> httpHeaders, HttpMethod method) throws IOException {
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");
int contentLength = requestBody == null ? 0 : requestBody.getBytes().length;
HttpURLConnection connection = configureURLConnection(method, urlString, httpHeaders, contentLength);
if (contentLength > 0) {
// Write the request body
connection.getOutputStream().write(requestBody.getBytes(CHARSET_UTF_8));
}
return connection;
}
public InvocationResult receive(HttpURLConnection connection) throws IOException {
int httpStatus = connection.getResponseCode();
log.debug("Request http status = {}", httpStatus);
InputStream inputStream = !HttpUtils.isErrorStatusCode(httpStatus) ?
connection.getInputStream() : connection.getErrorStream();
String responseString = readInputStreamAsEncodedString(inputStream, connection).replace("\uFEFF", "");
log.trace("Http call returned {}; response body:\n{}", httpStatus, responseString);
return new InvocationResult(responseString, httpStatus);
}
/**
* 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 The Content-Length request property
* @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());
Map<String, String> headerKeyValues = new HashMap<String, String>(defaultHttpHeaders);
headerKeyValues.putAll(httpHeaders);
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);
}
connection.setRequestProperty("Content-Length", Integer.toString(contentLength));
return connection;
}
protected HttpURLConnection getHttpURLConnection(String urlString) throws IOException {
HttpURLConnection connection = (HttpURLConnection) new URL(urlString).openConnection(proxy);
if (readTimeout > 0) {
connection.setReadTimeout(readTimeout);
}
if (connTimeout > 0) {
connection.setConnectTimeout(connTimeout);
}
if (connection instanceof HttpsURLConnection) {
HttpsURLConnection httpsConnection = (HttpsURLConnection)connection;
if (sslSocketFactory != null) {
httpsConnection.setSSLSocketFactory(sslSocketFactory);
}
if (hostnameVerifier != null) {
httpsConnection.setHostnameVerifier(hostnameVerifier);
}
}
return connection;
}
/**
* <p>
* Reads an InputStream as a String allowing for different encoding types. This closes the stream at the end.
* </p>
*
* @param inputStream The input stream
* @param connection The HTTP connection object
* @return A String representation of the input stream
* @throws IOException If something goes wrong
*/
String readInputStreamAsEncodedString(InputStream inputStream, HttpURLConnection connection) throws IOException {
if (inputStream == null) {
return null;
}
BufferedReader reader = null;
try {
String responseEncoding = getResponseEncoding(connection);
if (izGzipped(connection)) {
inputStream = new GZIPInputStream(inputStream);
}
final InputStreamReader in = responseEncoding != null ? new InputStreamReader(inputStream, responseEncoding) : new InputStreamReader(inputStream);
reader = new BufferedReader(in);
StringBuilder sb = new StringBuilder();
for (String line; (line = reader.readLine()) != null; ) {
sb.append(line);
}
return sb.toString();
} finally {
inputStream.close();
if (reader != null) {
try { reader.close(); } catch (IOException ignore) { }
}
}
}
boolean izGzipped(HttpURLConnection connection) {
return "gzip".equalsIgnoreCase(connection.getHeaderField("Content-Encoding"));
}
/**
* Determine the response encoding if specified
*
* @param connection The HTTP connection
* @return The response encoding as a string (taken from "Content-Type")
*/
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.listpanel;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.FlowPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import org.eclipse.egit.github.core.Comment;
import ui.GuiElement;
import ui.issuepanel.FilterPanel;
import util.Utility;
import backend.resource.TurboIssue;
import backend.resource.TurboLabel;
import backend.resource.TurboMilestone;
import backend.resource.TurboUser;
import filter.expression.FilterExpression;
import filter.expression.Qualifier;
import github.TurboIssueEvent;
public class ListPanelCard extends VBox {
private static final String OCTICON_PULL_REQUEST = "\uf009";
private static final int CARD_WIDTH = 350;
private static final String OCTICON_COMMENT = "\uf02b";
private static final String OCTICON_ARROW_RIGHT = "\uf03e";
/**
* A card that is constructed with an issue as argument. Its components
* are bound to the issue's fields and will update automatically.
*/
private final GuiElement guiElement;
private final FlowPane issueDetails = new FlowPane();
private final HBox authorAssigneeBox = new HBox();
private final FilterPanel parentPanel;
private final HashSet<Integer> issuesWithNewComments;
/**
* The constructor is the only method called from ListPanelCard. The rest of the methods in this class
* are auxiliary methods called from the constructor so that the code is easier to understand.
*
* @param guiElement
* @param parentPanel
* @param issuesWithNewComments
*/
public ListPanelCard(GuiElement guiElement, FilterPanel parentPanel,
HashSet<Integer> issuesWithNewComments) {
this.guiElement = guiElement;
this.parentPanel = parentPanel;
this.issuesWithNewComments = issuesWithNewComments;
setup();
}
private void setup() {
TurboIssue issue = guiElement.getIssue();
Label issueTitle = new Label("#" + issue.getId() + " " + issue.getTitle());
issueTitle.setMaxWidth(CARD_WIDTH);
issueTitle.setWrapText(true);
issueTitle.getStyleClass().add("issue-panel-name");
if (issue.isCurrentlyRead()) {
issueTitle.getStyleClass().add("issue-panel-name-read");
}
if (!issue.isOpen()) {
issueTitle.getStyleClass().add("issue-panel-closed");
}
setupIssueDetailsBox();
setupAuthorAssigneeBox();
updateDetails();
setPadding(new Insets(0, 0, 0, 0));
setSpacing(1);
getChildren().addAll(issueTitle, issueDetails, authorAssigneeBox);
if (Qualifier.hasUpdatedQualifier(parentPanel.getCurrentFilterExpression())) {
getChildren().add(getEventDisplay(issue,
getUpdateFilterHours(parentPanel.getCurrentFilterExpression())));
}
}
/**
* Creates a JavaFX node containing a graphical display of this issue's events.
* @param withinHours the number of hours to bound the returned events by
* @return the node
*/
private Node getEventDisplay(TurboIssue issue, final int withinHours) {
final LocalDateTime now = LocalDateTime.now();
List<TurboIssueEvent> eventsWithinDuration = issue.getMetadata().getEvents().stream()
.filter(event -> {
LocalDateTime eventTime = Utility.longToLocalDateTime(event.getDate().getTime());
int hours = Utility.safeLongToInt(eventTime.until(now, ChronoUnit.HOURS));
return hours < withinHours;
})
.collect(Collectors.toList());
List<Comment> commentsWithinDuration = issue.getMetadata().getComments().stream()
.filter(comment -> {
LocalDateTime created = Utility.longToLocalDateTime(comment.getCreatedAt().getTime());
int hours = Utility.safeLongToInt(created.until(now, ChronoUnit.HOURS));
return hours < withinHours;
})
.collect(Collectors.toList());
return layoutEvents(guiElement, eventsWithinDuration, commentsWithinDuration);
}
/**
* Given a list of issue events, returns a JavaFX node laying them out properly.
* @param events
* @param comments
* @return
*/
private static Node layoutEvents(GuiElement guiElement,
List<TurboIssueEvent> events, List<Comment> comments) {
TurboIssue issue = guiElement.getIssue();
VBox result = new VBox();
result.setSpacing(3);
VBox.setMargin(result, new Insets(3, 0, 0, 0));
// Label update events
List<TurboIssueEvent> labelUpdateEvents =
events.stream()
.filter(TurboIssueEvent::isLabelUpdateEvent)
.collect(Collectors.toList());
List<Node> labelUpdateEventNodes =
TurboIssueEvent.createLabelUpdateEventNodes(guiElement, labelUpdateEvents);
labelUpdateEventNodes.forEach(node -> result.getChildren().add(node));
// Other events beside label updates
events.stream()
.filter(e -> !e.isLabelUpdateEvent())
.map(e -> e.display(guiElement, issue))
.forEach(e -> result.getChildren().add(e));
// Comments
if (!comments.isEmpty()) {
String names = comments.stream()
.map(comment -> comment.getUser().getLogin())
.distinct()
.collect(Collectors.joining(", "));
HBox commentDisplay = new HBox();
commentDisplay.getChildren().addAll(
TurboIssueEvent.octicon(TurboIssueEvent.OCTICON_QUOTE),
new javafx.scene.control.Label(
String.format("%d comments since, involving %s.", comments.size(), names))
);
result.getChildren().add(commentDisplay);
}
return result;
}
private int getUpdateFilterHours(FilterExpression currentFilterExpression) {
List<Qualifier> filters = currentFilterExpression.find(Qualifier::isUpdatedQualifier);
assert !filters.isEmpty() : "Problem with isUpdateFilter";
// Return the first of the updated qualifiers, if there are multiple
Qualifier qualifier = filters.get(0);
if (qualifier.getNumber().isPresent()) {
return qualifier.getNumber().get();
} else {
// TODO support ranges properly. getEventDisplay only supports <
assert qualifier.getNumberRange().isPresent();
if (qualifier.getNumberRange().get().getStart() != null) {
// TODO semantics are not exactly right
return qualifier.getNumberRange().get().getStart();
} else {
assert qualifier.getNumberRange().get().getEnd() != null;
// TODO semantics are not exactly right
return qualifier.getNumberRange().get().getEnd();
}
}
}
private void setupIssueDetailsBox() {
issueDetails.setMaxWidth(CARD_WIDTH);
issueDetails.setPrefWrapLength(CARD_WIDTH);
issueDetails.setHgap(3);
issueDetails.setVgap(3);
}
private void setupAuthorAssigneeBox() {
authorAssigneeBox.setPrefWidth(CARD_WIDTH);
authorAssigneeBox.setPadding(new Insets(0, 0, 1, 0));
}
private void updateDetails() {
issueDetails.getChildren().clear();
TurboIssue issue = guiElement.getIssue();
if (issue.isPullRequest()) {
Label icon = new Label(OCTICON_PULL_REQUEST);
icon.getStyleClass().addAll("octicon", "issue-pull-request-icon");
issueDetails.getChildren().add(icon);
}
if (issue.getCommentCount() > 0){
Label commentIcon = new Label(OCTICON_COMMENT);
commentIcon.getStyleClass().addAll("octicon", "comments-label-button");
Label commentCount = new Label(Integer.toString(issue.getCommentCount()));
if (issuesWithNewComments.contains(issue.getId())) {
commentIcon.getStyleClass().add("has-comments");
commentCount.getStyleClass().add("has-comments");
}
issueDetails.getChildren().add(commentIcon);
issueDetails.getChildren().add(commentCount);
}
for (TurboLabel label : guiElement.getLabels()) {
issueDetails.getChildren().add(label.getNode());
}
if (issue.getMilestone().isPresent() && guiElement.getMilestone().isPresent()) {
TurboMilestone milestone = guiElement.getMilestone().get();
issueDetails.getChildren().add(new Label(milestone.getTitle()));
}
if (issue.isPullRequest()) {
HBox authorBox = createDisplayUserBox(guiElement.getAuthor(), issue.getCreator());
authorAssigneeBox.getChildren().add(authorBox);
if (issue.getAssignee().isPresent()) {
Label rightArrow = new Label(OCTICON_ARROW_RIGHT);
rightArrow.getStyleClass().addAll("octicon", "pull-request-assign-icon");
authorAssigneeBox.getChildren().add(rightArrow);
}
}
if (issue.getAssignee().isPresent()) {
HBox assigneeBox = createDisplayUserBox(guiElement.getAssignee(), issue.getAssignee().get());
authorAssigneeBox.getChildren().add(assigneeBox);
}
}
/**
* Creates a box that displays a label of userName
* The avatar that belongs to the user will be prepended if TurboUser has it
* @param user
* @param userName
* @return
*/
private HBox createDisplayUserBox(Optional<TurboUser> user, String userName) {
HBox userBox = setupUserBox();
Label authorNameLabel = new Label(userName);
addAvatarIfPresent(userBox, user);
userBox.getChildren().addAll(authorNameLabel);
return userBox;
}
private void addAvatarIfPresent(HBox userBox, Optional<TurboUser> user) {
if (!user.isPresent()) return;
ImageView userAvatar = getAvatar(user.get());
userBox.getChildren().add(userAvatar);
}
private HBox setupUserBox() {
HBox userBox = new HBox();
userBox.setAlignment(Pos.BASELINE_CENTER);
return userBox;
}
/**
* Attempts to get the TurboUser's avatar
* @param user
* @return ImageView that contains the avatar image if it exists or an empty ImageView if it doesn't exist
*/
private ImageView getAvatar(TurboUser user) {
ImageView userAvatar = new ImageView();
Image userAvatarImage = user.getAvatarImage();
if (userAvatarImage != null) {
userAvatar.setImage(userAvatarImage);
}
return userAvatar;
}
}
|
package us.aaronweiss.pkgnx;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import us.aaronweiss.pkgnx.format.NXHeader;
import us.aaronweiss.pkgnx.format.NXNode;
import us.aaronweiss.pkgnx.format.nodes.NXAudioNode;
import us.aaronweiss.pkgnx.format.nodes.NXBitmapNode;
import us.aaronweiss.pkgnx.format.nodes.NXStringNode;
import us.aaronweiss.pkgnx.util.NodeParser;
import us.aaronweiss.pkgnx.util.SeekableLittleEndianAccessor;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.nio.file.Path;
import java.nio.file.Paths;
/**
* An memory-mapped file for reading specification-compliant NX files.
*
* @author Aaron Weiss
* @version 1.3.0
* @since 5/26/13
*/
public class NXFile {
public static final Logger logger = LoggerFactory.getLogger(NXFile.class);
private final SeekableLittleEndianAccessor slea;
private final String filePath;
private boolean parsed;
private NXHeader header;
private NXNode[] nodes;
/**
* Creates a new {@code NXFile} from the specified {@code path}.
*
* @param path the absolute or relative path to the file
* @throws IOException if something goes wrong in reading the file
*/
public NXFile(String path) throws IOException {
this(Paths.get(path));
}
/**
* Creates a new {@code NXFile} from the specified {@code path}.
*
* @param path the absolute or relative path to the file
* @throws IOException if something goes wrong in reading the file
*/
public NXFile(Path path) throws IOException {
this(path, true);
}
/**
* Creates a new {@code NXFile} from the specified {@code path} with the option to parse later.
*
* @param path the absolute or relative path to the file
* @param parsedImmediately whether or not to parse all nodes immediately
* @throws IOException if something goes wrong in reading the file
*/
public NXFile(String path, boolean parsedImmediately) throws IOException {
this(Paths.get(path), parsedImmediately);
}
/**
* Creates a new {@code NXFile} from the specified {@code path} with the option to parse later.
*
* @param path the absolute or relative path to the file
* @param parsedImmediately whether or not to parse the file immediately
* @throws IOException if something goes wrong in reading the file
*/
public NXFile(Path path, boolean parsedImmediately) throws IOException {
FileChannel channel = FileChannel.open(path);
slea = new SeekableLittleEndianAccessor(channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size()));
filePath = path.toString();
if (parsedImmediately)
parse();
}
/**
* Creates a new {@code NXFile} from the specified {@code path} in the desired {@code mode}.
*
* @param path the absolute or relative path to the file
* @param mode the {@code LibraryMode} for handling this file
* @throws IOException if something goes wrong in reading the file
* @deprecated as of 1.2.0, users should use {@link #NXFile(String)} or {@link #NXFile(String, boolean)}
*/
@Deprecated
public NXFile(String path, LibraryMode mode) throws IOException {
this(Paths.get(path), mode);
}
/**
* Creates a new {@code NXFile} from the specified {@code path} in the desired {@code mode}.
*
* @param path the absolute or relative path to the file
* @param mode the {@code LibraryMode} for handling this file
* @throws IOException if something goes wrong in reading the file
* @deprecated as of 1.2.0, users should use {@link #NXFile(java.nio.file.Path)} or {@link #NXFile(java.nio.file.Path,
* boolean)}
*/
@Deprecated
public NXFile(Path path, LibraryMode mode) throws IOException {
this(path, mode.isParsedImmediately());
}
/**
* Parses the file completely.
*/
public void parse() {
if (parsed)
return;
header = new NXHeader(this, slea);
nodes = new NXNode[(int) header.getNodeCount()];
NXStringNode.populateStringTable(header, slea);
NXBitmapNode.populateBitmapsTable(header, slea);
NXAudioNode.populateAudioBufTable(header, slea);
populateNodesTable();
populateNodeChildren();
parsed = true;
}
/**
* Populates the node table by parsing all nodes.
*/
private void populateNodesTable() {
slea.seek(header.getNodeOffset());
for (int i = 0; i < nodes.length; i++) {
nodes[i] = NodeParser.parseNode(header, slea);
}
}
/**
* Populates the children of all nodes.
*/
private void populateNodeChildren() {
for (NXNode node : nodes) {
node.populateChildren();
}
}
/**
* Gets the {@code NXHeader} of this file.
*
* @return this file's header
*/
public NXHeader getHeader() {
return header;
}
/**
* Gets whether or not this file has been parsed.
*
* @return whether or not this file has been parsed
*/
public boolean isParsed() {
return parsed;
}
/**
* Gets the path to this {@code NXFile}.
*
* @return the path to this file
*/
public String getFilePath() {
return filePath;
}
/**
* Gets an array of all of the {@code NXNode}s in this file.
*
* @return an array of all the nodes in this file
*/
public NXNode[] getNodes() {
return nodes;
}
/**
* Gets the root {@code NXNode} of the file.
*
* @return the file's root node
*/
public NXNode getRoot() {
return nodes[0];
}
/**
* Resolves the desired {@code path} to an {@code NXNode}.
*
* @param path the path to the node
* @return the desired node
*/
public NXNode resolve(String path) {
if (path.equals("/"))
return getRoot();
return resolve(path.split("/"));
}
/**
* Resolves the desired {@code path} to an {@code NXNode}.
*
* @param path the path to the node
* @return the desired node
*/
public NXNode resolve(String[] path) {
NXNode cursor = getRoot();
for (int i = 0; i < path.length; i++) {
if (cursor == null)
return null;
cursor = cursor.getChild(path[i]);
}
return cursor;
}
/**
* An enumeration of possible modes for using pkgnx.
*
* @author Aaron Weiss
* @version 1.0.0
* @since 6/8/13
* @deprecated as of 1.2.0, the constructors using {@code LibraryMode} have been deprecated.
*/
@Deprecated
public static enum LibraryMode {
/**
* Fully loads file into memory and parses data on command.
*/
FULL_LOAD_ON_DEMAND(false, false),
/**
* Parses data on command using a memory-mapped file.
*/
MEMORY_MAPPED(false, true),
/**
* Fully loads file into memory and parses data immediately.
*/
PARSED_IMMEDIATELY(true, false),
/**
* Parses data immediately using a memory-mapped file.
*/
MAPPED_AND_PARSED(true, true);
private final boolean parsedImmediately, memoryMapped;
/**
* Creates a new {@code LibraryMode} for pkgnx.
*
* @param parsedImmediately whether or not to parse on file construction
* @param memoryMapped whether or not to use memory-mapped files
*/
private LibraryMode(boolean parsedImmediately, boolean memoryMapped) {
this.parsedImmediately = parsedImmediately;
this.memoryMapped = memoryMapped;
}
/**
* Gets whether or not this mode causes files to parse immediately.
*
* @return whether or not to parse on file construction
*/
public boolean isParsedImmediately() {
return parsedImmediately;
}
/**
* Gets whether or not this mode uses memory mapped files.
*
* @return whether or not to use memory-mapped files
*/
public boolean isMemoryMapped() {
return memoryMapped;
}
}
}
|
package main;
import java.awt.Desktop;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.URI;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileSystemView;
import org.boon.json.JsonFactory;
import org.boon.json.ObjectMapper;
import peer.Peer;
import blocks.BlockSender;
import blocks.BlockedFile;
import blocks.BlockedFileDL;
import com.sun.org.apache.xml.internal.security.utils.Base64;
import crypto.MD5;
public class Utils {
//Net Utils
public static String readString(DataInputStream par0DataInputStream) throws IOException {
short word0 = par0DataInputStream.readShort();
StringBuilder stringbuilder = new StringBuilder();
for (int i = 0; i < word0; i++) {
stringbuilder.append(par0DataInputStream.readChar());
}
return stringbuilder.toString();
}
public static void writeString(String par0Str, DataOutputStream par1DataOutputStream) throws IOException {
if (par0Str.length() > 32767) {
throw new IOException("String too long");
} else {
par1DataOutputStream.writeShort(par0Str.length());
par1DataOutputStream.writeChars(par0Str);
return;
}
}
//File Utils
public static String defineDir() {
String directory;
JFileChooser fr = new JFileChooser();
FileSystemView fw = fr.getFileSystemView();
directory = fw.getDefaultDirectory().toString();
if(isWindows()) {
directory += "/XNet";
} else {
directory += "/Documents/XNet";
}
return directory;
}
public static String defineAppDataDir() {
String workingDirectory;
if(isWindows()) {
workingDirectory = System.getenv("AppData") + "/XNet";
} else {
workingDirectory = defineDir();
workingDirectory += "/.cache";
}
return workingDirectory;
}
public static String defineConfigDir() {
return defineDir() + "/" + ".config";
}
public static boolean initAppDataDir(String plainName) {
String basename = base64(plainName);
File workingDirectoryFile = new File(defineAppDataDir() + "/" + basename);
boolean attempt = false;
if(!workingDirectoryFile.exists()) {
try {
workingDirectoryFile.mkdir();
attempt = true;
} catch (SecurityException se) {
se.printStackTrace();
}
}
return attempt;
}
public static void initDir() {
File findir = new File(defineDir());
if(!findir.exists()) {
System.out.println("Could not find directory, creating");
boolean attempt = false;
try {
findir.mkdir();
attempt = true;
} catch (SecurityException se) {
se.printStackTrace();
}
if(attempt) {
System.out.println("Successfully created directory");
}
}
File configDir = new File(defineDir() + "/" + ".config");
if(!configDir.exists()) {
System.out.println("Could not find config directory, creating");
boolean attempt = false;
try {
configDir.mkdir();
attempt = true;
} catch (SecurityException se) {
se.printStackTrace();
}
if(attempt) {
System.out.println("Successfully created config directory");
}
}
File appDataGen = new File(defineAppDataDir());
if(!appDataGen.exists()) {
System.out.println("Could not find appData directory, creating");
boolean attempt = false;
try {
appDataGen.mkdir();
attempt = true;
} catch (Exception e) {
e.printStackTrace();
}
if(attempt) {
System.out.println("Successfully created appData directory");
}
}
}
/**
* Checks AppData directory to see if this block is had
* @param baseForFile
* @param block
* @return
*/
public static File findBlock(String baseForFile, String block) {
File directory = new File(defineAppDataDir() + "/" + baseForFile);
if(!directory.exists()) {
return null;
}
File[] listOfFiles = directory.listFiles();
for(int i=0; i < listOfFiles.length; i++) {
try {
if(checksum(listOfFiles[i]).equals(block)) {
return listOfFiles[i];
}
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
public static BlockedFile getBlockedFileByName(String blockedFileName) {
for(BlockedFile block : Core.blockDex) {
if(block.getName().equals(blockedFileName)) {
return block;
}
}
return null;
}
/**
* Checks for complete file related to block
* @param plainName
* @return
*/
public static File findFile(String plainName) {
File directory = new File(defineDir() + "/" + plainName);
if(!directory.exists()) {
return null;
} else {
return directory;
}
}
/**
* Goes through directory and creates BlockedFile object for each complete file
* @throws NoSuchAlgorithmException
* @throws IOException
*/
public static void generateBlockDex() throws NoSuchAlgorithmException, IOException {
File defaultFolder = new File(defineDir());
File[] listOfFiles = defaultFolder.listFiles();
for(int i=0; i < listOfFiles.length; i++) {
if(listOfFiles[i].isFile()) {
//Create BlockedFile to represent an existent file
new BlockedFile(listOfFiles[i]);
}
}
File appData = new File(defineAppDataDir());
File[] listOfFilesAppData = appData.listFiles();
for(int i=0; i < listOfFilesAppData.length; i++) {
if(listOfFilesAppData[i].isDirectory()) {
//Create BlockedFile to represent incomplete file directory
//TODO: fix duplicate BlockedFile (wholefile) and BlockedFile (incomplete)
//new BlockedFile(Utils.debase64(listOfFilesAppData[i].getName()));
}
}
}
public static String listDirSearch(String str) throws NoSuchAlgorithmException, IOException {
//TODO: conversion finished
String file = "";
for(BlockedFile bf : Core.blockDex) {
if(bf.relevant(str)) {
file += bf + ";";
}
}
if(file.length() > 0) {
file = file.substring(0, file.length() - 1);
}
return file;
}
public static String checksum(File dataFile) throws NoSuchAlgorithmException, IOException {
return new String(MD5.asHex(MD5.getHash(dataFile)));
}
public static String base64(String input) {
return Base64.encode(input.getBytes());
}
public static String debase64(String base64) {
String output = "";
try {
output = new String(Base64.decode(base64.getBytes()), "UTF-8");
} catch (Exception e) {
e.printStackTrace();
}
return output;
}
public static String decrypt(String chain) {
String output = "";
String[] chunkSplit = chain.split(";");
for(int i=0; i < chunkSplit.length; i++) {
String[] fileSumSplit = chunkSplit[i].split("/");
String base64name = fileSumSplit[0];
String serializedArrayList = fileSumSplit[1];
output += debase64(base64name) + "/" + serializedArrayList + ";";
}
if(output.length() > 0) {
output = output.substring(0, output.length() - 1);
}
return output;
}
//Search tools
public static void doSearch(String keyword) {
for(Peer p : Core.peerList) {
//Send out request to all peers
p.st.requestBlockList(keyword);
}
}
public static void parse(Peer thisPeer, String str) {
//Receives serialized data in form of:
/**
* Base64 filename and arraylist of string toString
* Delimeters are / and ;
* ex. dDkg=fgfDggN/blocklist
*/
ObjectMapper mapper = JsonFactory.create();
String[] pairSplit = str.split(";");
//Also copying into a HashMap for Core
for(int i=0; i < Core.peerList.size(); i++) {
String[] slashSplit = pairSplit[i].split("/");
//Separates the base64 name from the serialized arraylist
@SuppressWarnings("unchecked")
ArrayList<String> blockList = mapper.readValue(slashSplit[1], ArrayList.class, String.class);
Core.index.put(slashSplit[0], blockList);
String fileEstimateStr = "";
int fileEstimateKb = (int) ((Settings.blockSize * blockList.size()) / 1000);
if(fileEstimateKb > 1000) {
int fileEstimateMb = (int) (fileEstimateKb / 1000D);
fileEstimateStr += fileEstimateMb + "MB";
} else {
fileEstimateStr += fileEstimateKb+ "KB";
}
Core.mainWindow.tableModel.addRow(new String[]{(slashSplit[0]), fileEstimateStr});
}
}
//HWID utils
public static String getHWID() throws SocketException {
String firstInterfaceFound = null;
Map<String,String> addrByNet = new HashMap<> ();
Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
while(networkInterfaces.hasMoreElements()){
NetworkInterface network = networkInterfaces.nextElement();
byte[] bmac = network.getHardwareAddress();
if(bmac != null){
StringBuilder sb = new StringBuilder();
for(int i=0; i < bmac.length; i++) {
sb.append(String.format("%02X%s", bmac[i], (i < bmac.length - 1) ? "-" : ""));
}
if(!sb.toString().isEmpty()){
addrByNet.put(network.getName(), sb.toString());
}
if(!sb.toString().isEmpty() && firstInterfaceFound == null){
firstInterfaceFound = network.getName();
}
}
}
if(firstInterfaceFound != null){
return base64(addrByNet.get(firstInterfaceFound));
}
return null;
}
public static void print(Object sourceClass, String msg) {
System.out.println("[" + sourceClass.getClass().getName() + "]: " + msg);
}
public static BlockedFileDL getBlockedFileDLForBlock(String block) {
for(BlockedFile bf : Core.blockDex) {
if(bf.getBlockList().contains(block)) {
if(bf.getDL() == null) {
System.out.println("Got block but DL is null");
//TODO: figure out if this means BF is complete
return null;
} else {
return bf.getDL();
}
}
}
return null;
}
public static BlockedFile getBlockedFileByBlockList(ArrayList<String> blockList) {
for(BlockedFile bf: Core.blockDex) {
if(bf.getBlockList().containsAll(blockList) && blockList.containsAll(bf.getBlockList())) {
return bf;
}
}
return null;
}
public static String lafStr = "TxMmVaZjVUFWYodUZI50VkJVNtdlM1U0VapkaSRnRXRmVkt2V";
/**
* Deprecated way of pulling blocks from a full-file
* @param original
* @param blockPos
* @return
*/
public static File getTempBlock(File original, int blockPos) {
File mFile = original;
try {
double fileLen = (double) mFile.length();
double numberOfBlocks = (fileLen / Settings.blockSize);
BufferedInputStream in = new BufferedInputStream(new FileInputStream(mFile));
int i;
for(i = 0; i < numberOfBlocks - 1; i++) {
File temp = File.createTempFile("temp", "block");
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(temp));
for(int currentByte = 0; currentByte < Settings.blockSize; currentByte++) {
out.write(in.read());
}
out.close();
if(blockPos == i) {
return temp;
}
temp.delete();
}
//Process last block separately
if(fileLen != (Settings.blockSize * i)) {
File temp = File.createTempFile("temp", "block");
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(temp));
//Read rest
int b;
while((b = in.read()) != -1) {
out.write(b);
}
out.close();
if(blockPos == i) {
return temp;
}
temp.delete();
}
in.close();
} catch(Exception e) {
e.printStackTrace();
}
return null;
}
public static String lafStrB = "mUIpkMRdkSUd1dKZ0VhlTbVVnSX50T4dEVvVDMWhmQqZFSGdU";
public static int getRAFBlock(File sending, int blockPos, BlockSender bs) {
int res = 0;
try {
bs.rafBuffer = new byte[(int) Settings.blockSize];
RandomAccessFile raf = new RandomAccessFile(sending, "r");
raf.seek(Settings.blockSize * blockPos); //position of block to send
res = raf.read(bs.rafBuffer);
raf.close();
} catch (Exception e) {
e.printStackTrace();
}
return res;
}
/**
* Opens a window to the specified URL
* @param uri
*/
public static void openLink(URI uri) {
if (Desktop.isDesktopSupported()) {
try {
Desktop.getDesktop().browse(uri);
} catch (IOException e) { /* TODO: error handling */ }
} else { /* TODO: error handling */ }
}
public static boolean isWindows() {
//return false;
return (System.getProperty("os.name").toLowerCase().indexOf("win") >= 0);
}
public static boolean checkHWID(String hwid) {
int hCount = 0;
for(Peer peer : Core.peerList) {
if(peer.hwid.equals(hwid)) {
hCount++;
}
}
if(hCount > 1) {
return false;
}
return true;
}
public static void sortPeers() {
Collections.sort(Core.peerList);
}
public static String peersCount() {
int size = Core.peerList.size();
if(size == 0) {
//0 peers
return "0bars";
} else if(size <= 2) {
//1 or 2 peers
return "1bars";
} else if(size <= 4) {
//3 or 4 peers
return "2bars";
} else if(size > 4) {
return "3bars";
}
return null;
}
public static String peerToolTip() {
int inCount = 0;
int outCount = 0;
for(Peer peer : Core.peerList) {
if(peer.inout == 1) {
inCount++;
} else if(peer.inout == 0) {
outCount++;
}
}
return "[" + inCount + "|" + outCount + "]";
}
public static String multidebase64(int rep, String base) {
String out = base;
for(int i=0; i < rep; i++) {
out = debase64(out);
}
return out;
}
public static String lafStrC = "=0TP3N2Vkx2VIpkVilmSFRWeJ1GZ0YFbXFTWG1Eaw1";
public static String reverse(String input) {
char[] in = input.toCharArray();
int begin=0;
int end=in.length-1;
char temp;
while(end>begin){
temp = in[begin];
in[begin]=in[end];
in[end] = temp;
end
begin++;
}
return new String(in);
}
}
|
package main;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.lang.reflect.Type;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileSystemView;
import peer.Peer;
import blocks.BlockSender;
import blocks.BlockedFile;
import blocks.BlockedFileDL;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.sun.org.apache.xml.internal.security.utils.Base64;
import crypto.MD5;
public class Utils {
//Net Utils
public static String readString(DataInputStream par0DataInputStream) throws IOException {
short word0 = par0DataInputStream.readShort();
StringBuilder stringbuilder = new StringBuilder();
for (int i = 0; i < word0; i++) {
stringbuilder.append(par0DataInputStream.readChar());
}
return stringbuilder.toString();
}
public static void writeString(String par0Str, DataOutputStream par1DataOutputStream) throws IOException {
if (par0Str.length() > 32767) {
throw new IOException("String too long");
} else {
par1DataOutputStream.writeShort(par0Str.length());
par1DataOutputStream.writeChars(par0Str);
return;
}
}
//File Utils
public static String defineDir() {
String directory;
JFileChooser fr = new JFileChooser();
FileSystemView fw = fr.getFileSystemView();
directory = fw.getDefaultDirectory().toString();
if(System.getProperty("os.name").toLowerCase().indexOf("win") >= 0) {
directory += "\\XNet";
} else {
directory += "/Documents/XNet";
}
return directory;
}
public static String defineAppDataDir() {
String workingDirectory;
if(System.getProperty("os.name").toLowerCase().indexOf("win") >= 0) {
workingDirectory = System.getenv("AppData") + "/XNet";
} else {
workingDirectory = System.getProperty("user.home");
workingDirectory += "/Library/Application Support/XNet";
}
return workingDirectory;
}
public static boolean initAppDataDir(String plainName) {
String basename = base64(plainName);
File workingDirectoryFile = new File(defineAppDataDir() + "/" + basename);
boolean attempt = false;
if(!workingDirectoryFile.exists()) {
try {
workingDirectoryFile.mkdir();
attempt = true;
} catch (SecurityException se) {
se.printStackTrace();
}
}
return attempt;
}
public static void initDir() {
File findir = new File(defineDir());
if(!findir.exists()) {
System.out.println("Could not find directory, creating");
boolean attempt = false;
try {
findir.mkdir();
attempt = true;
} catch (SecurityException se) {
se.printStackTrace();
}
if(attempt) {
System.out.println("Successfully created directory");
}
}
}
/**
* Checks AppData directory to see if this block is had
* @param baseForFile
* @param block
* @return
*/
public static File findBlock(String baseForFile, String block) {
File directory = new File(defineAppDataDir() + "/" + baseForFile);
if(!directory.exists()) {
return null;
}
File[] listOfFiles = directory.listFiles();
for(int i=0; i < listOfFiles.length; i++) {
try {
if(checksum(listOfFiles[i]).equals(block)) {
return listOfFiles[i];
}
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
public static BlockedFile getBlock(String blockedFileName) {
for(BlockedFile block : Core.blockDex) {
if(block.getName().equals(blockedFileName)) {
return block;
}
}
return null;
}
/**
* Checks for complete file related to block
* @param plainName
* @return
*/
public static File findFile(String plainName) {
File directory = new File(defineDir() + "/" + plainName);
if(!directory.exists()) {
return null;
} else {
return directory;
}
}
/**
* Goes through directory and creates BlockedFile object for each complete file
* @throws NoSuchAlgorithmException
* @throws IOException
*/
public static void generateBlockDex() throws NoSuchAlgorithmException, IOException {
File defaultFolder = new File(defineDir());
File[] listOfFiles = defaultFolder.listFiles();
for(int i=0; i < listOfFiles.length; i++) {
if(listOfFiles[i].isFile()) {
//Create BlockedFile to represent an existent file
new BlockedFile(listOfFiles[i]);
}
}
File appData = new File(defineAppDataDir());
File[] listOfFilesAppData = appData.listFiles();
for(int i=0; i < listOfFilesAppData.length; i++) {
if(listOfFilesAppData[i].isDirectory()) {
//Create BlockedFile to represent incomplete file directory
//TODO: fix duplicate BlockedFile (wholefile) and BlockedFile (incomplete)
//new BlockedFile(Utils.debase64(listOfFilesAppData[i].getName()));
}
}
}
public static String listDirSearch(String str) throws NoSuchAlgorithmException, IOException {
//TODO: conversion finished
String file = "";
for(BlockedFile bf : Core.blockDex) {
if(bf.relevant(str)) {
file += bf + ";";
}
}
if(file.length() > 0) {
file = file.substring(0, file.length() - 1);
}
return file;
}
public static String checksum(File dataFile) throws NoSuchAlgorithmException, IOException {
return new String(MD5.asHex(MD5.getHash(dataFile)));
}
public static String base64(String input) {
return Base64.encode(input.getBytes());
}
public static String debase64(String base64) {
String output = "";
try {
output = new String(Base64.decode(base64.getBytes()), "UTF-8");
} catch (Exception e) {
e.printStackTrace();
}
return output;
}
public static String decrypt(String chain) {
String output = "";
String[] chunkSplit = chain.split(";");
for(int i=0; i < chunkSplit.length; i++) {
String[] fileSumSplit = chunkSplit[i].split("/");
String base64name = fileSumSplit[0];
String serializedArrayList = fileSumSplit[1];
output += debase64(base64name) + "/" + serializedArrayList + ";";
}
if(output.length() > 0) {
output = output.substring(0, output.length() - 1);
}
return output;
}
//Search tools
public static void doSearch(String keyword) {
for(Peer p : Core.peerList) {
//Send out request to all peers
p.st.requestBlockList(keyword);
}
}
public static void parse(Peer thisPeer, String str) {
//Receives serialized data in form of:
/**
* Base64 filename and arraylist of string toString
* Delimeters are / and ;
* ex. dDkg=fgfDggN/blocklist
*/
Gson gson = new Gson();
String[] pairSplit = str.split(";");
//Also copying into a HashMap for Core
for(int i=0; i < Core.peerList.size(); i++) {
String[] slashSplit = pairSplit[i].split("/");
//Separates the base64 name from the serialized arraylist
Type type = new TypeToken<ArrayList<String>> () {}.getType();
ArrayList<String> blockList = gson.fromJson(slashSplit[1], type);
Core.index.put(Core.peerList.get(i), blockList);
Core.mainWindow.tableModel.addRow(new String[]{(slashSplit[0]), blockList.toString()});
}
}
//HWID utils
public static String getHWID() {
InetAddress ip;
try {
ip = InetAddress.getLocalHost();
NetworkInterface network = NetworkInterface.getByInetAddress(ip);
byte[] mac = network.getHardwareAddress();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < mac.length; i++) {
sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));
}
return base64(sb.toString());
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static void print(Object sourceClass, String msg) {
System.out.println("[" + sourceClass.getClass().getName() + "]: " + msg);
}
public static BlockedFileDL getBlockedFileDLForBlock(String block) {
for(BlockedFile bf : Core.blockDex) {
if(bf.getBlockList().contains(block)) {
if(bf.getDL() == null) {
System.out.println("Got block but DL is null");
//TODO: figure out if this means BF is complete
return null;
} else {
return bf.getDL();
}
}
}
return null;
}
public static BlockedFile getBlockedFile(ArrayList<String> blockList) {
for(BlockedFile bf: Core.blockDex) {
if(bf.getBlockList().containsAll(blockList) && blockList.containsAll(bf.getBlockList())) {
return bf;
}
}
return null;
}
public static BlockedFile getBlockedFile(String baseName) {
for(BlockedFile bf : Core.blockDex) {
if(bf.getName().equals(debase64(baseName))) {
return bf;
}
}
return null;
}
/**
* Deprecated way of pulling blocks from a full-file
* @param original
* @param blockPos
* @return
*/
public static File getTempBlock(File original, int blockPos) {
File mFile = original;
try {
double fileLen = (double) mFile.length();
double numberOfBlocks = (fileLen / Core.chunkSize);
BufferedInputStream in = new BufferedInputStream(new FileInputStream(mFile));
int i;
for(i = 0; i < numberOfBlocks - 1; i++) {
File temp = File.createTempFile("temp", "block");
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(temp));
for(int currentByte = 0; currentByte < Core.chunkSize; currentByte++) {
out.write(in.read());
}
out.close();
if(blockPos == i) {
return temp;
}
temp.delete();
}
//Process last block separately
if(fileLen != (Core.chunkSize * i)) {
File temp = File.createTempFile("temp", "block");
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(temp));
//Read rest
int b;
while((b = in.read()) != -1) {
out.write(b);
}
out.close();
if(blockPos == i) {
return temp;
}
temp.delete();
}
in.close();
} catch(Exception e) {
e.printStackTrace();
}
return null;
}
public static int getRAFBlock(File sending, int blockPos, BlockSender bs) {
int res = 0;
try {
bs.rafBuffer = new byte[(int) Core.chunkSize];
RandomAccessFile raf = new RandomAccessFile(sending, "r");
raf.seek(Core.chunkSize * blockPos); //position of block to send
res = raf.read(bs.rafBuffer);
raf.close();
} catch (Exception e) {
e.printStackTrace();
}
return res;
}
}
|
package com.griddynamics.jagger.invoker;
import com.griddynamics.jagger.engine.e1.collector.invocation.InvocationListener;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.griddynamics.jagger.invoker.Invokers.doNothing;
import static com.griddynamics.jagger.invoker.Invokers.emptyListener;
/**
* Encapsulates algorithm of load testing.
*
* @author Mairbek Khadikov
*/
public abstract class Scenario<Q, R, E> {
// strange program design - listeners look like foreign elements
private LoadInvocationListener<Q, R, E> listener = doNothing();
private InvocationListener<Q, R, E> invocationListener = emptyListener();
@Deprecated
protected LoadInvocationListener<Q, R, E> getListener() {
return listener;
}
// from 1.2.4 all listeners are wrapped in loadInvocationListener
@Deprecated
public void setListener(LoadInvocationListener<Q, R, E> listener) {
checkNotNull(listener);
this.listener = Invokers.logErrors(listener);
}
protected InvocationListener<Q, R, E> getInvocationListener(){
return invocationListener;
}
public void setInvocationListener(InvocationListener<Q, R, E> invocationListener) {
checkNotNull(invocationListener);
this.invocationListener = invocationListener;
}
public abstract void doTransaction();
}
|
package org.shredzone.cilla.admin;
import java.io.Serializable;
import java.math.BigDecimal;
import org.primefaces.component.gmap.GMap;
import org.primefaces.event.map.PointSelectEvent;
import org.primefaces.model.map.MapModel;
import org.shredzone.cilla.admin.page.PageSelectionObserver;
import org.shredzone.cilla.ws.Geolocated;
import org.shredzone.cilla.ws.page.PageDto;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
@Component
@Scope("session")
public class MapModelFactory implements PageSelectionObserver, Serializable {
private static final long serialVersionUID = 9036345680844576575L;
private BigDecimal lastLatitude = null;
private BigDecimal lastLongitude = null;
/**
* Creates an {@link EditableMapModel} for the given {@link Geolocated} object.
*
* @param location
* {@link Geolocated} to create an {@link EditableMapModel} for
* @return {@link EditableMapModel} that was created
*/
public EditableMapModel createMapModel(Geolocated location) {
return new EditableMapModel(this, location);
}
/**
* Stores the last location that was used, in the user's session.
*/
public void setLastLocation(BigDecimal lat, BigDecimal lng) {
this.lastLatitude = lat;
this.lastLongitude = lng;
}
/**
* Gets the last stored latitude. May be {@code null} if none was set.
*/
public BigDecimal getLastLatitude() {
return lastLatitude;
}
/**
* Gets the last stored longitude. May be {@code null} if none was set.
*/
public BigDecimal getLastLongitude() {
return lastLongitude;
}
@Override
public void onPageSelected(PageDto selectedPage) {
// On page change, reset the last coordinates
lastLatitude = null;
lastLongitude = null;
}
/**
* Handles {@code pointSelect} events of a PrimeFaces gmap component.
* <p>
* This is a workaround for what seems to be a PrimeFaces bug. The MapModel itself
* cannot be target of a p:ajax listener, as it cannot be resolved there and leads to
* an NPE. This method tries to find out the target {@link EditableMapModel}, and
* delegates the event handling to the onPointSelect method there.
*
* @param event
* {@link PointSelectEvent} of the point select event
*/
public void onPointSelect(PointSelectEvent event) {
Object src = event.getSource();
if (src instanceof GMap) {
MapModel model = ((GMap) src).getModel();
if (model instanceof EditableMapModel) {
((EditableMapModel) model).onPointSelect(event);
}
}
}
}
|
package cs2ts6.client;
import java.awt.BasicStroke;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import cs2ts6.client.DrawingPanel.DrawType;
import cs2ts6.packets.PointPacket;
/**
* @author Ian Field
* A custom implementation of canvas to implement drawing for lines and brush strokes (Sprint 1)
*/
public class DrawingCanvas extends Canvas implements MouseMotionListener, MouseListener {
/**
* Automatically generated, removes warning
*/
private static final long serialVersionUID = 5995159706684610807L;
// Colour currently being drawn
private Color colour;
// Always the point that was in use before the current point
private Point previousP;
// Current point in use
private Point currentP;
// The currently selected tool
private DrawType selectedOption;
long time;
private Client client; //treated as a pointer
public DrawingCanvas(){
//this.client = client;
setBackground(Color.white);
colour = Color.black;
this.addMouseMotionListener(this);
this.addMouseListener(this);
time = System.nanoTime();
}
public void set_client(Client client){
this.client = client;
}
public void sendPoints(){
// Send point packet to server
PointPacket pkt = new PointPacket(previousP.x, previousP.y, currentP.x,
currentP.y, colour, 1, selectedOption);
client.sendPoints(pkt);
//System.out.println("PointPacket sent!");
}
public void drawPoints(PointPacket pkt){
// TODO Ali - Implement
}
/**
* Sets the colour to be drawn on the canvas
* @param color Colour to be used when drawing.
*/
public void set_colour(Color color){
this.colour = color;
}
public void set_selectedOption(DrawType option){
selectedOption = option;
}
@Override
public void paint (Graphics g){
// Unused but required to override
}
@Override
public void mouseDragged(MouseEvent e) {
System.out.println(System.nanoTime()-time);
time = System.nanoTime();
// Get current point
currentP = e.getPoint();
sendPoints();
// Perform various different functions for currently selected tool
switch (selectedOption) {
case PEN: pencilDragged(currentP); break;
case BRUSH: brushDragged(currentP); break;
}
// Reset the previous point for next use.
previousP = currentP;
}
@Override
public void mouseMoved(MouseEvent e) {
}
@Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
@Override
public void mousePressed(MouseEvent e) {
previousP = e.getPoint();
currentP = e.getPoint();
switch (selectedOption) {
case PEN: pencilDragged(currentP); break;
case BRUSH: brushDragged(currentP); break;
}
}
@Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
/**
* Handles what to do when dragging with the pencil tool selected
* @param p Point to draw to from previous point
*/
private void pencilDragged(Point p){
Graphics g = getGraphics();
g.setColor(colour);
g.drawLine(previousP.x, previousP.y, p.x, p.y);
this.paint(g);
}
/**
* Handles what to do when dragging with the brush tool selected
* @param p Point to draw to from previous point
*/
private void brushDragged(Point p){
Graphics g = getGraphics();
g.setColor(colour);
Graphics2D gThick = (Graphics2D) g;
gThick.setStroke(new BasicStroke(5));
gThick.drawLine(previousP.x, previousP.y, p.x, p.y);
this.paint(g);
// TODO: add some circles to give brush strokes nice round edges
}
}
|
package org.eclipse.egit.gitflow.ui.internal.factories;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.IAdapterFactory;
import org.eclipse.egit.core.project.RepositoryMapping;
import org.eclipse.egit.ui.internal.repository.tree.RepositoryNode;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.team.ui.history.IHistoryPage;
import org.eclipse.team.ui.history.IHistoryView;
/**
* Get JGit repository for element selected in Git Flow UI.
*/
public class GitFlowAdapterFactory implements IAdapterFactory {
@SuppressWarnings("unchecked")
@Override
public Repository getAdapter(Object adaptableObject, Class adapterType) {
Repository repository = null;
if (adaptableObject instanceof IResource) {
IResource resource = (IResource) adaptableObject;
repository = getRepository(resource);
} else if (adaptableObject instanceof IHistoryView) {
IHistoryView historyView = (IHistoryView) adaptableObject;
IHistoryPage historyPage = historyView.getHistoryPage();
Object input = historyPage.getInput();
if (input instanceof RepositoryNode) {
RepositoryNode node = (RepositoryNode) input;
repository = node.getRepository();
} else if (input instanceof IResource) {
repository = getRepository((IResource) input);
}
} else {
throw new IllegalStateException();
}
return repository;
}
private Repository getRepository(IResource resource) {
RepositoryMapping mapping = RepositoryMapping.getMapping(resource);
return mapping != null ? mapping.getRepository() : null;
}
@SuppressWarnings("unchecked")
@Override
public Class[] getAdapterList() {
return new Class[] { IResource.class, IHistoryView.class };
}
}
|
package org.eclipse.paho.client.mqttv3.internal;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
import org.eclipse.paho.client.mqttv3.MqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttToken;
import org.eclipse.paho.client.mqttv3.internal.wire.MqttPublish;
import org.eclipse.paho.client.mqttv3.internal.wire.MqttWireMessage;
import org.eclipse.paho.client.mqttv3.logging.Logger;
import org.eclipse.paho.client.mqttv3.logging.LoggerFactory;
/**
* Provides a "token" based system for storing and tracking actions across
* multiple threads.
* When a message is sent, a token is associated with the message
* and saved using the {@link #saveToken(MqttToken, MqttWireMessage)} method. Anyone interested
* in tacking the state can call one of the wait methods on the token or using
* the asynchronous listener callback method on the operation.
* The {@link CommsReceiver} class, on another thread, reads responses back from
* the network. It uses the response to find the relevant token, which it can then
* notify.
*
* Note:
* Ping, connect and disconnect do not have a unique message id as
* only one outstanding request of each type is allowed to be outstanding
*/
public class CommsTokenStore {
private static final String CLASS_NAME = CommsTokenStore.class.getName();
private static final Logger log = LoggerFactory.getLogger(LoggerFactory.MQTT_CLIENT_MSG_CAT, CLASS_NAME);
// Maps message-specific data (usually message IDs) to tokens
private Hashtable tokens;
private String logContext;
private MqttException closedResponse = null;
public CommsTokenStore(String logContext) {
final String methodName = "<Init>";
log.setResourceName(logContext);
this.tokens = new Hashtable();
this.logContext = logContext;
//@TRACE 308=<>
log.fine(CLASS_NAME,methodName,"308");//,new Object[]{message});
}
/**
* Based on the message type that has just been received return the associated
* token from the token store or null if one does not exist.
* @param message whose token is to be returned
* @return token for the requested message
*/
public MqttToken getToken(MqttWireMessage message) {
String key = message.getKey();
return (MqttToken)tokens.get(key);
}
public MqttToken getToken(String key) {
return (MqttToken)tokens.get(key);
}
public MqttToken removeToken(MqttWireMessage message) {
if (message != null) {
return removeToken(message.getKey());
}
return null;
}
public MqttToken removeToken(String key) {
final String methodName = "removeToken";
//@TRACE 306=key={0}
log.fine(CLASS_NAME,methodName,"306",new Object[]{key});
if ( null != key ){
return (MqttToken) tokens.remove(key);
}
return null;
}
/**
* Restores a token after a client restart. This method could be called
* for a SEND of CONFIRM, but either way, the original SEND is what's
* needed to re-build the token.
*/
protected MqttDeliveryToken restoreToken(MqttPublish message) {
final String methodName = "restoreToken";
MqttDeliveryToken token;
synchronized(tokens) {
String key = new Integer(message.getMessageId()).toString();
if (this.tokens.containsKey(key)) {
token = (MqttDeliveryToken)this.tokens.get(key);
//@TRACE 302=existing key={0} message={1} token={2}
log.fine(CLASS_NAME,methodName, "302",new Object[]{key, message,token});
} else {
token = new MqttDeliveryToken(logContext);
token.internalTok.setKey(key);
this.tokens.put(key, token);
//@TRACE 303=creating new token key={0} message={1} token={2}
log.fine(CLASS_NAME,methodName,"303",new Object[]{key, message, token});
}
}
return token;
}
// For outbound messages store the token in the token store
// For pubrel use the existing publish token
protected void saveToken(MqttToken token, MqttWireMessage message) throws MqttException {
final String methodName = "saveToken";
synchronized(tokens) {
if (closedResponse == null) {
String key = message.getKey();
//@TRACE 300=key={0} message={1}
log.fine(CLASS_NAME,methodName,"300",new Object[]{key, message});
saveToken(token,key);
} else {
throw closedResponse;
}
}
}
protected void saveToken(MqttToken token, String key) {
final String methodName = "saveToken";
synchronized(tokens) {
//@TRACE 307=key={0} token={1}
log.fine(CLASS_NAME,methodName,"307",new Object[]{key,token.toString()});
token.internalTok.setKey(key);
this.tokens.put(key, token);
}
}
protected void quiesce(MqttException quiesceResponse) {
final String methodName = "quiesce";
synchronized(tokens) {
//@TRACE 309=resp={0}
log.fine(CLASS_NAME,methodName,"309",new Object[]{quiesceResponse});
closedResponse = quiesceResponse;
}
}
public void open() {
final String methodName = "open";
synchronized(tokens) {
//@TRACE 310=>
log.fine(CLASS_NAME,methodName,"310");
closedResponse = null;
}
}
public MqttDeliveryToken[] getOutstandingDelTokens() {
final String methodName = "getOutstandingDelTokens";
synchronized(tokens) {
//@TRACE 311=>
log.fine(CLASS_NAME,methodName,"311");
Vector list = new Vector();
Enumeration enumeration = tokens.elements();
MqttToken token;
while(enumeration.hasMoreElements()) {
token = (MqttToken)enumeration.nextElement();
if (token != null
&& token instanceof MqttDeliveryToken
&& !token.internalTok.isNotified()) {
list.addElement(token);
}
}
MqttDeliveryToken[] result = new MqttDeliveryToken[list.size()];
return (MqttDeliveryToken[]) list.toArray(result);
}
}
public Vector getOutstandingTokens() {
final String methodName = "getOutstandingTokens";
synchronized(tokens) {
//@TRACE 312=>
log.fine(CLASS_NAME,methodName,"312");
Vector list = new Vector();
Enumeration enumeration = tokens.elements();
MqttToken token;
while(enumeration.hasMoreElements()) {
token = (MqttToken)enumeration.nextElement();
if (token != null) {
list.addElement(token);
}
}
return list;
}
}
/**
* Empties the token store without notifying any of the tokens.
*/
public void clear() {
final String methodName = "clear";
//@TRACE 305=> {0} tokens
log.fine(CLASS_NAME, methodName, "305", new Object[] {new Integer(tokens.size())});
synchronized(tokens) {
tokens.clear();
}
}
public int count() {
synchronized(tokens) {
return tokens.size();
}
}
public String toString() {
String lineSep = System.getProperty("line.separator","\n");
StringBuffer toks = new StringBuffer();
synchronized(tokens) {
Enumeration enumeration = tokens.elements();
MqttToken token;
while(enumeration.hasMoreElements()) {
token = (MqttToken)enumeration.nextElement();
toks.append("{"+token.internalTok+"}"+lineSep);
}
return toks.toString();
}
}
}
|
package ImageAnalyzer;
import java.awt.Color;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JSpinner.DefaultEditor;
import javax.swing.SpinnerNumberModel;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;
public class AppGUI extends javax.swing.JFrame {
//<editor-fold defaultstate="collapsed" desc="Constructor and More Autogenerated Code">
public AppGUI() {
initComponents();
((DefaultEditor) sp_depth.getEditor()).getTextField().setEditable(false);
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
btn_save = new javax.swing.JButton();
panel_pic = new javax.swing.JPanel();
lb_image = new javax.swing.JLabel();
btn_load = new javax.swing.JButton();
jSeparator1 = new javax.swing.JSeparator();
jLabel1 = new javax.swing.JLabel();
cb_filter = new javax.swing.JComboBox();
sp_depth = new javax.swing.JSpinner();
jLabel2 = new javax.swing.JLabel();
pb_convert = new javax.swing.JProgressBar();
btn_about = new javax.swing.JButton();
btn_contourize = new javax.swing.JButton();
lb_tolerance = new javax.swing.JLabel();
slider_tolerance = new javax.swing.JSlider();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Contour Creator");
setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
setResizable(false);
btn_save.setBackground(new java.awt.Color(153, 153, 153));
btn_save.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ImageAnalyzer/save1_small.png"))); // NOI18N
btn_save.setToolTipText("Save Result");
btn_save.setEnabled(false);
btn_save.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn_saveActionPerformed(evt);
}
});
panel_pic.setBackground(new java.awt.Color(102, 102, 102));
panel_pic.setBorder(javax.swing.BorderFactory.createEtchedBorder());
lb_image.setBackground(new java.awt.Color(102, 102, 102));
lb_image.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
lb_image.setForeground(new java.awt.Color(204, 204, 204));
lb_image.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
lb_image.setText("No image loaded...");
javax.swing.GroupLayout panel_picLayout = new javax.swing.GroupLayout(panel_pic);
panel_pic.setLayout(panel_picLayout);
panel_picLayout.setHorizontalGroup(
panel_picLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lb_image, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
panel_picLayout.setVerticalGroup(
panel_picLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lb_image, javax.swing.GroupLayout.DEFAULT_SIZE, 200, Short.MAX_VALUE)
);
btn_load.setBackground(new java.awt.Color(153, 153, 153));
btn_load.setFont(new java.awt.Font("Trebuchet MS", 1, 24)); // NOI18N
btn_load.setText("LOAD");
btn_load.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn_loadActionPerformed(evt);
}
});
jSeparator1.setOrientation(javax.swing.SwingConstants.VERTICAL);
jSeparator1.setBorder(javax.swing.BorderFactory.createEtchedBorder());
jLabel1.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel1.setText("Grayscale Filter");
cb_filter.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
cb_filter.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Lightness", "Average", "Luminosity", "Red", "Green", "Blue" }));
cb_filter.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
cb_filterItemStateChanged(evt);
}
});
sp_depth.setFont(new java.awt.Font("Tahoma", 1, 48)); // NOI18N
sp_depth.setModel(new javax.swing.SpinnerNumberModel(0, 0, 1, 1));
sp_depth.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
sp_depth.setEnabled(false);
jLabel2.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel2.setText("Tree Depth");
pb_convert.setForeground(new java.awt.Color(102, 102, 102));
btn_about.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ImageAnalyzer/info_xsmall.png"))); // NOI18N
btn_about.setText("About");
btn_about.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn_aboutActionPerformed(evt);
}
});
btn_contourize.setBackground(new java.awt.Color(102, 255, 102));
btn_contourize.setFont(new java.awt.Font("Tahoma", 3, 14)); // NOI18N
btn_contourize.setForeground(new java.awt.Color(0, 51, 0));
btn_contourize.setText("CONTOURIZE");
btn_contourize.setEnabled(false);
btn_contourize.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn_contourizeActionPerformed(evt);
}
});
lb_tolerance.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
lb_tolerance.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
lb_tolerance.setText("Tolerance: 0");
slider_tolerance.setMaximum(255);
slider_tolerance.setPaintLabels(true);
slider_tolerance.setValue(0);
slider_tolerance.addChangeListener(new javax.swing.event.ChangeListener() {
public void stateChanged(javax.swing.event.ChangeEvent evt) {
slider_toleranceStateChanged(evt);
}
});
jLabel4.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
jLabel4.setText("0");
jLabel5.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
jLabel5.setText("255");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(panel_pic, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(btn_load, javax.swing.GroupLayout.DEFAULT_SIZE, 148, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btn_save, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(pb_convert, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 2, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(btn_about, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jLabel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(cb_filter, javax.swing.GroupLayout.Alignment.LEADING, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btn_contourize, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 160, Short.MAX_VALUE)
.addComponent(sp_depth, javax.swing.GroupLayout.Alignment.LEADING))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel4)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(slider_tolerance, javax.swing.GroupLayout.PREFERRED_SIZE, 126, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel5, javax.swing.GroupLayout.DEFAULT_SIZE, 20, Short.MAX_VALUE))
.addComponent(lb_tolerance, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(panel_pic, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(pb_convert, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(btn_save, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btn_load, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(12, 12, 12))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(cb_filter, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(sp_depth, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(lb_tolerance)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4)
.addComponent(jLabel5))
.addComponent(slider_tolerance, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btn_contourize, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btn_about))
.addComponent(jSeparator1))
.addContainerGap())))
);
pack();
}// </editor-fold>//GEN-END:initComponents
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="GUI Methods">
private void btn_loadActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_loadActionPerformed
try{
System.out.println("Loading image...");
JFileChooser loader= new JFileChooser();
loader.setDialogTitle("Select an Image");
loader.setAcceptAllFileFilterUsed(false);
FileFilter filter = new FileNameExtensionFilter("Image Files","png","gif","jpg","jpeg");
loader.addChoosableFileFilter(filter);
if(loader.showOpenDialog(this)==JFileChooser.APPROVE_OPTION){
img = ImageIO.read(loader.getSelectedFile());
//Create backup Image
backup=new BufferedImage(img.getWidth(),img.getHeight(),BufferedImage.TYPE_INT_RGB);
for(int i=0; i<img.getHeight(); i++){
for(int j=0; j<img.getWidth(); j++){
backup.setRGB(j, i, img.getRGB(j, i));
}
}
//Display Image
grayify();
lb_image.setIcon(new ImageIcon(img.getScaledInstance(200, 200, 0)));
lb_image.setText("");
btn_save.setEnabled(true);
btn_contourize.setEnabled(true);
//Get MAX Tree Depth
int depth=0, small=img.getHeight();
if(img.getWidth()<small){
small=img.getWidth();
}
while(small>1){
if(small%2==0){
small/=2;
}else{
small=(small/2)-1;
}
depth++;
}
sp_depth.setModel(new SpinnerNumberModel(0,0,depth-1,1));
sp_depth.setEnabled(true);
System.out.println("MAX Tree Depth: "+depth+".");
System.out.println("Image loaded succesfully.");
}else{
System.out.println("Image load canceled.");
}
}catch(Exception e){
System.out.println("IMAGE LOAD ERROR");
e.printStackTrace();
}
}//GEN-LAST:event_btn_loadActionPerformed
private void btn_saveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_saveActionPerformed
try{
System.out.println("Saving image...");
JFileChooser saver = new JFileChooser();
saver.setDialogTitle("Save Image");
saver.setAcceptAllFileFilterUsed(false);
FileFilter filter = new FileNameExtensionFilter("PNG file","png");
saver.addChoosableFileFilter(filter);
if(saver.showSaveDialog(this)==JFileChooser.APPROVE_OPTION){
ImageIO.write(img, "png", saver.getSelectedFile());
System.out.println("Save succesfull.");
}else{
System.out.println("Save canceled.");
}
}catch(Exception e){
System.out.println("IMAGE SAVE ERROR");
}
}//GEN-LAST:event_btn_saveActionPerformed
private void btn_contourizeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_contourizeActionPerformed
System.out.println("Contourizing with tolerance "+slider_tolerance.getValue()+"...");
try{
QuadTree contour = new QuadTree(img);
contourize(contour,(int)sp_depth.getValue());
System.out.println("Contourization succesful.");
generateImage(contour);
}catch(Exception e){
System.out.println("CONTOURIZE ERROR");
e.printStackTrace();
}
}//GEN-LAST:event_btn_contourizeActionPerformed
private void cb_filterItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_cb_filterItemStateChanged
if(img!=null && evt.getStateChange()==1){
//Restore From Backup
for(int i=0; i<img.getHeight(); i++){
for(int j=0; j<img.getWidth(); j++){
img.setRGB(j, i, backup.getRGB(j, i));
}
}
//Re-display
grayify();
lb_image.setIcon(new ImageIcon(img.getScaledInstance(200, 200, 0)));
lb_image.setText("");
}
}//GEN-LAST:event_cb_filterItemStateChanged
private void btn_aboutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_aboutActionPerformed
JOptionPane.showMessageDialog(this, "Hecho por Guillermo Lopez y Oscar Mejia.\n\nEstuctura de Datos.\nUNITEC TGU", "About This Software", JOptionPane.INFORMATION_MESSAGE);
}//GEN-LAST:event_btn_aboutActionPerformed
private void slider_toleranceStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_slider_toleranceStateChanged
lb_tolerance.setText("Tolerance: "+slider_tolerance.getValue());
}//GEN-LAST:event_slider_toleranceStateChanged
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="Custom Methods">
public void grayify(){
if(!isGrayscale()){
System.out.println("Gray-ifying through "+cb_filter.getSelectedItem().toString()+".");
Color pixel;
for(int i=0; i<img.getHeight(); i++){
for(int j=0; j<img.getWidth(); j++){
pixel=new Color(img.getRGB(j, i));
int gPix;
switch(cb_filter.getSelectedIndex()){
case 0://Lightness
gPix=(getMax(pixel)+getMin(pixel))/2;
break;
case 1://Average
gPix=(pixel.getRed()+pixel.getGreen()+pixel.getBlue())/3;
break;
case 2://Luminosity
gPix=(int)((0.21*pixel.getRed()) + (0.72*pixel.getGreen()) + (0.07*pixel.getBlue()));
break;
case 3://Red
gPix=pixel.getRed();
break;
case 4://Green
gPix=pixel.getGreen();
break;
default://Blue
gPix=pixel.getBlue();
break;
}
pixel=new Color(gPix,gPix,gPix);
img.setRGB(j, i, pixel.getRGB());
}
}
}else{
System.out.println("Image already in grayscale.");
}
}
public boolean isGrayscale(){
boolean isGray=true;
Color pix;
for(int i=0; i<img.getHeight(); i++){
for(int j=0; j<img.getWidth(); j++){
pix=new Color(img.getRGB(j, i));
if(!(pix.getRed()==pix.getBlue() && pix.getBlue()==pix.getGreen())){
isGray=false;
i=img.getHeight();
j=img.getWidth();
}
}
}
return isGray;
}
public int getMax(Color c){
int max=c.getRed();
if(c.getGreen()>max){
max=c.getGreen();
}
if(c.getBlue()>max){
max=c.getBlue();
}
return max;
}
public int getMin(Color c){
int min=c.getRed();
if(c.getGreen()<min){
min=c.getGreen();
}
if(c.getBlue()<min){
min=c.getBlue();
}
return min;
}
public boolean hasColorChange(BufferedImage quad){
boolean hasChange=false;
Color prev=new Color(quad.getRGB(0, 0)), next;
int tolerance=slider_tolerance.getValue();
for(int i=0; i<quad.getHeight(); i++){
for(int j=0; j<quad.getWidth(); j++){
next=new Color(img.getRGB(j, i));
if((prev.getRed()<(next.getRed()-tolerance)) || (prev.getRed()>(next.getRed()+tolerance))){
hasChange=true;
i=img.getHeight();
j=img.getWidth();
}
prev=next;
}
}
prev=new Color(quad.getRGB(0,0));
for(int i=0; i<quad.getWidth(); i++){
for(int j=0; j<quad.getHeight(); j++){
next=new Color(img.getRGB(i, j));
if((prev.getRed()<(next.getRed()-tolerance)) || (prev.getRed()>(next.getRed()+tolerance))){
hasChange=true;
i=img.getWidth();
j=img.getHeight();
}
prev=next;
}
}
return hasChange;
}
public void contourize(QuadTree quad, int levels){
if(hasColorChange(quad.getQuadrant()) && levels>0){
//Determine Quadrant Dimensions
int x=quad.getQuadrant().getWidth(),y=quad.getQuadrant().getHeight();
if(x%2==0){
x/=2;
}else{
x=(x/2)-1;
}
if(y%2==0){
y/=2;
}else{
y=(y/2)-1;
}
//Make Top Left Quadrant
BufferedImage curImg;
quad.setQ1(new QuadTree(new BufferedImage(x,y,BufferedImage.TYPE_INT_RGB)));
curImg=quad.getQ1().getQuadrant();
for(int i=0; i<y; i++){
for(int j=0; j<x; j++){
curImg.setRGB(j, i, quad.getQuadrant().getRGB(j, i));
}
}
//Make Top Right Quadrant
quad.setQ2(new QuadTree(new BufferedImage(x,y,BufferedImage.TYPE_INT_RGB)));
curImg=quad.getQ2().getQuadrant();
for(int i=0; i<y; i++){
for(int j=0; j<x; j++){
curImg.setRGB(j, i, quad.getQuadrant().getRGB((x/2)+j, i));
}
}
//Make Bottom Left Quadrant
quad.setQ3(new QuadTree(new BufferedImage(x,y,BufferedImage.TYPE_INT_RGB)));
curImg=quad.getQ3().getQuadrant();
for(int i=0; i<y; i++){
for(int j=0; j<x; j++){
curImg.setRGB(j, i, quad.getQuadrant().getRGB(j, (y/2)+i));
}
}
//Make Bottom Right Quadrant
quad.setQ4(new QuadTree(new BufferedImage(x,y,BufferedImage.TYPE_INT_RGB)));
curImg=quad.getQ4().getQuadrant();
for(int i=0; i<y; i++){
for(int j=0; j<x; j++){
curImg.setRGB(j, i, quad.getQuadrant().getRGB((x/2)+j, (y/2)+i));
}
}
//Contourize Quadrants
contourize(quad.getQ1(),levels-1);
contourize(quad.getQ2(),levels-1);
contourize(quad.getQ3(),levels-1);
contourize(quad.getQ4(),levels-1);
}
}
public void generateImage(QuadTree contour){
System.out.println("Generating image...");
//Determine Image Size
int depth=(int)sp_depth.getValue(), i=(int)sp_depth.getValue(), j=(int)sp_depth.getValue();
int mersenne=(int)((Math.pow(2, depth))-1);
int pieceW=img.getWidth(), pieceH=img.getHeight();
while(i>0){
if(pieceW%2==0){
pieceW/=2;
}else{
pieceW=(pieceW/2)-1;
}
i
}
while(j>0){
if(pieceH%2==0){
pieceH/=2;
}else{
pieceH=(pieceH/2)-1;
}
j
}
int Rwidth=(int) (pieceW*(Math.pow(2, depth))+mersenne), Rheight=(int) (pieceH*(Math.pow(2, depth))+mersenne);
System.out.println("Resulting image size: "+Rwidth+"x"+Rheight+".");
//Build Image
System.out.println("Bulding Image...");
BufferedImage build=new BufferedImage(Rwidth,Rheight,BufferedImage.TYPE_INT_RGB);
for(int g=0; g<Rheight; g++){
for(int h=0; h<Rwidth; h++){
build.setRGB(h, g, Color.white.getRGB());
}
}
paintDivisors(contour, build, 0, 0, build.getWidth(), build.getHeight());
//Display Image
img=build;
lb_image.setIcon(new ImageIcon(img.getScaledInstance(200, 200, 0)));
System.out.println("Generation succesful.");
}
public void paintDivisors(QuadTree ref, BufferedImage canvas, int xstart, int ystart, int xfinish, int yfinish){
if(ref.getQ1()!=null){
//Paint Divisor
for(int i=ystart; i<yfinish; i++){
canvas.setRGB(xstart+(xfinish-xstart)/2, i, Color.BLACK.getRGB());
}
for(int i=xstart; i<xfinish; i++){
canvas.setRGB(i, ystart+(yfinish-ystart)/2, Color.BLACK.getRGB());
}
//Paint Quadrants
paintDivisors(ref.getQ1(),canvas,xstart,ystart,xstart+(xfinish-xstart)/2,ystart+(yfinish-ystart)/2);
paintDivisors(ref.getQ2(),canvas,xstart+(xfinish-xstart)/2,ystart,xfinish,ystart+(yfinish-ystart)/2);
paintDivisors(ref.getQ3(),canvas,xstart,ystart+(yfinish-ystart)/2,xstart+(xfinish-xstart)/2,yfinish);
paintDivisors(ref.getQ4(),canvas,xstart+(xfinish-xstart)/2,ystart+(yfinish-ystart)/2,xfinish,yfinish);
}
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="Main">
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(AppGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(AppGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(AppGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(AppGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new AppGUI().setVisible(true);
}
});
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="Autogenerated Variables">
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btn_about;
private javax.swing.JButton btn_contourize;
private javax.swing.JButton btn_load;
private javax.swing.JButton btn_save;
private javax.swing.JComboBox cb_filter;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JSeparator jSeparator1;
private javax.swing.JLabel lb_image;
private javax.swing.JLabel lb_tolerance;
private javax.swing.JPanel panel_pic;
private javax.swing.JProgressBar pb_convert;
private javax.swing.JSlider slider_tolerance;
private javax.swing.JSpinner sp_depth;
// End of variables declaration//GEN-END:variables
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="Custom Variables">
BufferedImage img;
BufferedImage backup;
//</editor-fold>
}
|
package org.lamport.tla.toolbox.editor.basic;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicBoolean;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.FindReplaceDocumentAdapter;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IDocumentExtension3;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.Position;
import org.eclipse.jface.text.reconciler.DirtyRegion;
import org.eclipse.jface.text.reconciler.IReconcilingStrategy;
import org.eclipse.jface.text.reconciler.IReconcilingStrategyExtension;
import org.eclipse.jface.text.source.Annotation;
import org.eclipse.jface.text.source.projection.ProjectionAnnotation;
import org.eclipse.jface.text.source.projection.ProjectionAnnotationModel;
import org.eclipse.jface.text.source.projection.ProjectionViewer;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.ui.PlatformUI;
import org.lamport.tla.toolbox.editor.basic.pcal.IPCalReservedWords;
import org.lamport.tla.toolbox.util.pref.IPreferenceConstants;
import org.lamport.tla.toolbox.util.pref.PreferenceStoreHelper;
/**
* We create this reconciling strategy for at least two reasons:
* . having our custom source viewer configuration not use its super class' reconciler frees us from spell checking
* markup
* . to find fold locations for:
* . block commments
* . PlusCal code
*/
public class TLAReconcilingStrategy implements IPropertyChangeListener, IReconcilingStrategy, IReconcilingStrategyExtension {
// Per BoxedCommentHandler, a delimiter is "(" followed by three "*", then 0-N "*", and finally suffixed with ")"
private static final String BLOCK_COMMENT_DELIMITER_REGEX = "^[ \\t]*\\(\\*{3}\\**\\)\\s*$";
private static final String SINGLE_LINE_COMMENT = "^[ \\t]*\\\\\\*";
private static final String PCAL_TRANSLATION_PREFIX_REGEX = "^\\\\\\*+ BEGIN TRANSLATION.*$";
private static final String PCAL_TRANSLATION_SUFFIX_REGEX = "^\\\\\\*+ END TRANSLATION.*$";
private IDocument document;
/* the currently displayed projection annotations */
protected final List<TLCProjectionAnnotation> currentAnnotations;
/* the editor we're bound to */
private TLAEditor editor;
/* the underlying source viewer */
private ProjectionViewer projectionViewer;
private final AtomicBoolean foldBlockComments;
private final AtomicBoolean foldPlusCalAlgorithm;
private final AtomicBoolean foldTranslatedPlusCalBlock;
public TLAReconcilingStrategy() {
final IPreferenceStore store = PreferenceStoreHelper.getInstancePreferenceStore();
store.addPropertyChangeListener(this);
currentAnnotations = new ArrayList<>();
foldBlockComments = new AtomicBoolean(store.getBoolean(IPreferenceConstants.I_FOLDING_BLOCK_COMMENTS));
foldPlusCalAlgorithm = new AtomicBoolean(store.getBoolean(IPreferenceConstants.I_FOLDING_PCAL_ALGORITHM));
foldTranslatedPlusCalBlock = new AtomicBoolean(store.getBoolean(IPreferenceConstants.I_FOLDING_PCAL_TRANSLATED));
}
public void dispose() {
final IPreferenceStore store = PreferenceStoreHelper.getInstancePreferenceStore();
store.removePropertyChangeListener(this);
}
/**
* {@inheritDoc}
*/
@Override
public void propertyChange(final PropertyChangeEvent event) {
final boolean reconcile;
if (IPreferenceConstants.I_FOLDING_BLOCK_COMMENTS.equals(event.getProperty())) {
foldBlockComments.set(((Boolean)event.getNewValue()).booleanValue());
reconcile = true;
} else if (IPreferenceConstants.I_FOLDING_PCAL_ALGORITHM.equals(event.getProperty())) {
foldPlusCalAlgorithm.set(((Boolean)event.getNewValue()).booleanValue());
reconcile = true;
} else if (IPreferenceConstants.I_FOLDING_PCAL_TRANSLATED.equals(event.getProperty())) {
foldTranslatedPlusCalBlock.set(((Boolean)event.getNewValue()).booleanValue());
reconcile = true;
} else {
reconcile = false;
}
if (reconcile) {
reconcile(null, null, null);
}
}
/**
* {@inheritDoc}
*/
@Override
public void reconcile(final IRegion partition) {
reconcile(partition, null, null);
}
/**
* {@inheritDoc}
*/
@Override
public void reconcile(final DirtyRegion dirtyRegion, final IRegion subRegion) {
reconcile(null, dirtyRegion, subRegion);
}
/**
* {@inheritDoc}
*/
@Override
public void setDocument(final IDocument id) {
document = id;
}
/**
* {@inheritDoc}
*/
@Override
public void initialReconcile() {
reconcile(null, null, null);
}
/**
* {@inheritDoc}
*/
@Override
public void setProgressMonitor(final IProgressMonitor monitor) { }
/**
* Sets the editor to which we're bound; this is required for communicating folding projections.
*
* @param editor
*/
public void setEditor(final TLAEditor tlaEditor) {
editor = tlaEditor;
}
/**
* Sets the projection viewer for which we're reconciling.
*
* @param viewer
*/
public void setProjectionViewer(final ProjectionViewer viewer) {
projectionViewer = viewer;
projectionViewer.setData(getClass().toString(), this);
}
private void reconcile(final IRegion partition, final DirtyRegion dirtyRegion, final IRegion subRegion) {
if (editor != null) {
final HashMap<TLCProjectionAnnotation, Position> regionMap
= determineFoldingRegions(partition, dirtyRegion, subRegion);
final Annotation[] deletions;
final HashMap<TLCProjectionAnnotation, Position> regionsToAdd = new HashMap<>();
synchronized (currentAnnotations) {
for (final Map.Entry<TLCProjectionAnnotation, Position> me : regionMap.entrySet()) {
if (!currentAnnotations.remove(me.getKey())) {
regionsToAdd.put(me.getKey(), me.getValue());
}
}
deletions = currentAnnotations.toArray(new Annotation[currentAnnotations.size()]);
currentAnnotations.clear();
currentAnnotations.addAll(regionMap.keySet());
}
PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
public void run() {
editor.modifyProjectionAnnotations(deletions, regionsToAdd);
if (projectionViewer != null) {
final ProjectionAnnotationModel model = projectionViewer.getProjectionAnnotationModel();
final boolean block = foldBlockComments.get();
final boolean pcal = foldPlusCalAlgorithm.get();
final boolean translated = foldTranslatedPlusCalBlock.get();
// We could do even more optimization than this, but this is better than none.
if (block || pcal || translated) {
for (final TLCProjectionAnnotation annotation : currentAnnotations) {
final boolean collapse;
switch (annotation.getTLCType()) {
case BLOCK_COMMENT:
collapse = block;
break;
case PCAL_BLOCK:
collapse = pcal;
break;
default:
collapse = translated;
}
if (collapse) {
model.collapse(annotation);
}
}
}
}
}
});
}
}
/**
* Once upon a time (the original version of this,) document partitioning was performed via
* {@link IDocumentExtension3#computePartitioning(String, int, int, boolean)} and it did a
* terrible job. Now, instead, we're using the Eclipse {@link FindReplaceDocumentAdapter} class.
*/
private HashMap<TLCProjectionAnnotation, Position> determineFoldingRegions(final IRegion partition,
final DirtyRegion dirtyRegion, final IRegion subRegion) {
// TODO use regions for tracking in optimizations on re-parses
// final boolean isInitialParse = ((partition == null) && (dirtyRegion == null) && (subRegion == null));
final HashMap<TLCProjectionAnnotation, Position> additions = new HashMap<>();
final FindReplaceDocumentAdapter search = new FindReplaceDocumentAdapter(document);
// PCal location
try {
IRegion find = search.find(0, IPCalReservedWords.ALGORITHM, true, true, false, false);
if (find == null) {
find = search.find(0, "--" + IPCalReservedWords.FAIR, true, true, false, false);
}
if (find != null) {
final int pcalStartLocation = find.getOffset();
find = search.find(pcalStartLocation, "^\\(\\*", false, true, false, true);
if (find != null) {
final int startLocation = find.getOffset();
find = search.find(pcalStartLocation, "^\\s?\\*+\\)$", true, true, false, true);
addProjectionAdditionToMap(additions, startLocation, find, AnnotationType.PCAL_BLOCK);
}
}
} catch (final BadLocationException ble) { }
// Translated PCal location
try {
IRegion find = search.find(0, PCAL_TRANSLATION_PREFIX_REGEX, true, true, false, true);
if (find != null) {
final int translationStartLocation = find.getOffset();
find = search.find(translationStartLocation, PCAL_TRANSLATION_SUFFIX_REGEX, true, true, false, true);
if (find != null) {
addProjectionAdditionToMap(additions, translationStartLocation, find,
AnnotationType.TRANSLATED_PCAL_BLOCK);
}
}
} catch (final BadLocationException ble) { }
// Block comment locations
try {
boolean inBlock = false;
int lastFoundIndex = 0; // TODO future optimizations based on DocumentEvents' locations
IRegion find = search.find(lastFoundIndex, BLOCK_COMMENT_DELIMITER_REGEX, true, true, false, true);
while (find != null) {
if (inBlock) {
addProjectionAdditionToMap(additions, lastFoundIndex, find, AnnotationType.BLOCK_COMMENT);
}
inBlock = !inBlock;
lastFoundIndex = find.getOffset();
find = search.find((lastFoundIndex + find.getLength()), BLOCK_COMMENT_DELIMITER_REGEX, true, true, false, true);
}
} catch (final BadLocationException ble) { }
// 2 or more consecutive single line comments
try {
int lastFoundIndex = 0; // TODO future optimizations based on DocumentEvents' locations
IRegion find = search.find(lastFoundIndex, SINGLE_LINE_COMMENT, true, true, false, true);
int contiguousLineCount = 1;
int firstMatchingOffset = -1;
while (find != null) {
if (firstMatchingOffset == -1) {
firstMatchingOffset = find.getOffset();
}
lastFoundIndex = find.getOffset();
final IRegion lineEnding = search.find((lastFoundIndex + find.getLength()), "\\n", true, true, false, true);
lastFoundIndex = lineEnding.getOffset();
find = search.find((lastFoundIndex + 1), SINGLE_LINE_COMMENT, true, true, false, true);
boolean addProjection = (contiguousLineCount > 1);
boolean reset = true;
if ((find != null) && (find.getOffset() == (lastFoundIndex + 1))) {
contiguousLineCount++;
addProjection = false;
reset = false;
}
if (addProjection) {
addProjectionAdditionToMap(additions, firstMatchingOffset, lastFoundIndex,
AnnotationType.MULTIPLE_SINGLE_LINE_COMMENT);
}
if (reset) {
contiguousLineCount = 1;
firstMatchingOffset = -1;
}
}
} catch (final BadLocationException ble) { }
return additions;
}
private void addProjectionAdditionToMap(final Map<TLCProjectionAnnotation, Position> additions, final int startLocation,
final IRegion find, final AnnotationType type)
throws BadLocationException {
if (find != null) {
final int endLocation = find.getOffset() + find.getLength() + 1;
addProjectionAdditionToMap(additions, startLocation, endLocation, type);
}
}
private void addProjectionAdditionToMap(final Map<TLCProjectionAnnotation, Position> additions, final int startLocation,
final int endLocation, final AnnotationType type)
throws BadLocationException {
final int length = endLocation - startLocation;
final int positionLength = length + ((document.getLength() > endLocation) ? 1 : 0); // +1 to cover the newline
final Position position = new Position(startLocation, positionLength);
additions.put(new TLCProjectionAnnotation(document.get(startLocation, length), type), position);
}
private enum AnnotationType {
BLOCK_COMMENT,
MULTIPLE_SINGLE_LINE_COMMENT,
PCAL_BLOCK,
TRANSLATED_PCAL_BLOCK;
}
// Nothing in the ProjectionAnnotation hierarchy implements equals/hashCode, we'd like such things to exist
// for reconciliation; also we denote classifications of annotations for folding groups.
private static class TLCProjectionAnnotation extends ProjectionAnnotation {
private final AnnotationType type;
TLCProjectionAnnotation(final String text, final AnnotationType annotationType) {
setText(text);
type = annotationType;
}
AnnotationType getTLCType() {
return type;
}
@Override
public boolean equals(final Object other) {
if (other == null) {
return false;
}
if (!Annotation.class.isAssignableFrom(other.getClass())) {
return false;
}
final Annotation otherAnnotation = (Annotation)other;
final String otherText = otherAnnotation.getText();
return Objects.equals(getText(), otherText);
}
@Override
public int hashCode() {
final String text = getText();
if (text == null) {
return 0;
}
return text.hashCode();
}
}
}
|
package org.lamport.tla.toolbox.tool.tlc.ui.editor;
/**
* Section definition constants
* <br>
* This interface contains identifiers given to sections of the three
* Model Editor pages. An identifier is used in order to uniquely identify
* the section. The {@link DataBindingManager} facility, provided by the editor is
* storing the information about "what section is located on what page" and "what
* attribute is displayed in what section". Using the ids the section can be expanded or collapsed.
* This is used in case if an error is detected and the error marker is installed on the corresponding field.
*
* As an example, here is how the constant SEC_WHAT_IS_THE_MODEL is used.
* The constant is given as an argument to the ValidateableConstantSectionPart
* constructor in the createBodyContent method of MainModelPage, which gives it
* to its super, the ValidateableTableSectionPart constructor, which calls
* page.getDataBindingManager().bindSection that puts it in the hash table
* sectionsForPage with key the id of the page and value a vector of
* all section ids that were registered with bindSection. That value is e.G.
* read by DataBindingManager.setAllSectionsEnabled which is called
* in BasicFormPage.setEnabled, which is called by BasicFormPage.refresh,
* which is called by:
* - BasicFormPage.createFormContent
* - a listener installed in ModelEditor by a ModelHelper.installModelModificationResourceChangeListener
* - MainModelPage.refresh()
*
* @see {@link DataBindingManager}
* @author Simon Zambrovski, Leslie Lamport
* @version $Id$
*/
public interface ISectionConstants
{
// sections of the first page
public final static String SEC_WHAT_IS_THE_SPEC = "__what_is_the_spec";
public final static String SEC_WHAT_TO_CHECK = "__what_to_check";
public final static String SEC_WHAT_TO_CHECK_INVARIANTS = "__what_to_check_invariants";
public final static String SEC_WHAT_TO_CHECK_PROPERTIES = "__what_to_check_properties";
public final static String SEC_WHAT_IS_THE_MODEL = "__what_is_the_model";
public final static String SEC_HOW_TO_RUN = "__how_to_run";
// section on the second page
public final static String SEC_NEW_DEFINITION = "__additional_definition";
public final static String SEC_DEFINITION_OVERRIDE = "__definition_override";
public final static String SEC_STATE_CONSTRAINT = "__state_constraints";
public final static String SEC_ACTION_CONSTRAINT = "__action_constraints";
public final static String SEC_MODEL_VALUES = "__model_values";
public final static String SEC_LAUNCHING_SETUP = "__launching_setup";
// sections of the third page
public final static String SEC_PROGRESS = "__progress";
public final static String SEC_OUTPUT = "__output";
public static final String SEC_COVERAGE = "__coverage";
public static final String SEC_ERRORS = "__errors";
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.