repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15
values |
|---|---|---|---|---|
wuiidl/Thesis | Bakk-Askalon-Installer/src/org/askalon/installer/businesslogic/io/writer/TextfileWriter.java | 2430 | /**
* @author Walter Gugenberger
* @date 17.02.2014 13:50:46
* @version
* Bakk-Askalon-Installer.org.askalon.installer.businesslogic.io.writer.TextfileWriter
* @description
*/
package org.askalon.installer.businesslogic.io.writer;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import org.apache.log4j.Logger;
/**
* The Class TextfileWriter.
*/
public class TextfileWriter {
private static Logger log = Logger.getLogger(TextfileWriter.class);
/** The writer. */
private BufferedWriter writer;
/** The file. */
private final File file;
/**
* Instantiates a new textfile writer.
*
* @param path
* the path
* @param append
* the append
* @throws IOException
* Signals that an I/O exception has occurred.
*/
public TextfileWriter(String path, boolean append) throws IOException {
this.file = new File(path);
if (!this.file.exists()) {
if (this.file.createNewFile()) {
this.writer = new BufferedWriter(new FileWriter(this.file,
false));
} else {
try {
throw new IOException();
} catch (IOException e) {
log.error("Could not create new file to write.", e);
}
}
} else {
this.writer = new BufferedWriter(new FileWriter(this.file, true));
}
}
/**
* Instantiates a new textfile writer.
*
* @param file
* the file
* @param append
* the append
* @throws IOException
* Signals that an I/O exception has occurred.
*/
public TextfileWriter(File file, boolean append) throws IOException {
this.file = file;
if (!this.file.exists()) {
if (this.file.createNewFile()) {
this.writer = new BufferedWriter(new FileWriter(this.file,
false));
} else {
try {
throw new IOException();
} catch (IOException e) {
log.error("Could not create new file to write.", e);
}
}
} else {
this.writer = new BufferedWriter(new FileWriter(this.file, true));
}
}
/**
* Write.
*
* @param msg
* the msg
*/
public void write(String msg) {
try {
log.debug("writing " + msg);
this.writer.write(msg);
this.writer.flush();
} catch (IOException e) {
log.error("Problem while writing to file.", e);
} finally {
try {
this.writer.close();
} catch (IOException e) {
log.error("Problem while closing the writer.");
}
}
}
} | gpl-3.0 |
andersonbui/audio_stream_java_corba | src/sop_corba/BufferHolder.java | 741 | package sop_corba;
/**
* sop_corba/BufferHolder.java .
* Generated by the IDL-to-Java compiler (portable), version "3.2"
* from audio_stream.idl
* lunes 12 de junio de 2017 10:40:30 PM UTC
*/
public final class BufferHolder implements org.omg.CORBA.portable.Streamable
{
public byte value[] = null;
public BufferHolder ()
{
}
public BufferHolder (byte[] initialValue)
{
value = initialValue;
}
public void _read (org.omg.CORBA.portable.InputStream i)
{
value = sop_corba.BufferHelper.read (i);
}
public void _write (org.omg.CORBA.portable.OutputStream o)
{
sop_corba.BufferHelper.write (o, value);
}
public org.omg.CORBA.TypeCode _type ()
{
return sop_corba.BufferHelper.type ();
}
}
| gpl-3.0 |
eschwert/DL-Learner | components-core/src/test/java/org/dllearner/algorithms/qtl/experiments/QTLEvaluation.java | 80727 | /**
*
*/
package org.dllearner.algorithms.qtl.experiments;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Random;
import java.util.Set;
import java.util.SortedSet;
import java.util.Stack;
import java.util.TreeSet;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import org.aksw.jena_sparql_api.cache.core.QueryExecutionFactoryCacheEx;
import org.aksw.jena_sparql_api.core.QueryExecutionFactory;
import org.apache.commons.math3.random.RandomDataGenerator;
import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics;
import org.apache.commons.math3.stat.descriptive.SynchronizedDescriptiveStatistics;
import org.apache.commons.math3.util.Pair;
import org.apache.log4j.FileAppender;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.SimpleLayout;
import org.dllearner.algorithms.qtl.QTL2Disjunctive;
import org.dllearner.algorithms.qtl.QueryTreeUtils;
import org.dllearner.algorithms.qtl.datastructures.impl.EvaluatedRDFResourceTree;
import org.dllearner.algorithms.qtl.datastructures.impl.RDFResourceTree;
import org.dllearner.algorithms.qtl.heuristics.QueryTreeHeuristic;
import org.dllearner.algorithms.qtl.heuristics.QueryTreeHeuristicSimple;
import org.dllearner.algorithms.qtl.impl.QueryTreeFactoryBase;
import org.dllearner.algorithms.qtl.operations.lgg.LGGGenerator;
import org.dllearner.algorithms.qtl.operations.lgg.LGGGeneratorSimple;
import org.dllearner.algorithms.qtl.util.Entailment;
import org.dllearner.algorithms.qtl.util.filters.PredicateExistenceFilter;
import org.dllearner.algorithms.qtl.util.filters.PredicateExistenceFilterDBpedia;
import org.dllearner.algorithms.qtl.util.statistics.TimeMonitors;
import org.dllearner.core.ComponentAnn;
import org.dllearner.core.ComponentInitException;
import org.dllearner.kb.sparql.ConciseBoundedDescriptionGenerator;
import org.dllearner.kb.sparql.ConciseBoundedDescriptionGeneratorImpl;
import org.dllearner.learningproblems.Heuristics;
import org.dllearner.learningproblems.Heuristics.HeuristicType;
import org.dllearner.learningproblems.PosNegLPStandard;
import org.dllearner.utilities.QueryUtils;
import org.semanticweb.owlapi.io.ToStringRenderer;
import org.semanticweb.owlapi.model.IRI;
import org.semanticweb.owlapi.model.OWLIndividual;
import uk.ac.manchester.cs.owl.owlapi.OWLNamedIndividualImpl;
import uk.ac.manchester.cs.owlapi.dlsyntax.DLSyntaxObjectRenderer;
import com.google.common.base.Charsets;
import com.google.common.base.Function;
import com.google.common.collect.ComparisonChain;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.HashMultiset;
import com.google.common.collect.Lists;
import com.google.common.collect.Multimap;
import com.google.common.collect.Multiset;
import com.google.common.collect.Ordering;
import com.google.common.collect.Sets;
import com.google.common.hash.HashFunction;
import com.google.common.hash.Hashing;
import com.google.common.io.Files;
import com.hp.hpl.jena.datatypes.RDFDatatype;
import com.hp.hpl.jena.datatypes.xsd.XSDDatatype;
import com.hp.hpl.jena.datatypes.xsd.XSDDateTime;
import com.hp.hpl.jena.datatypes.xsd.impl.XSDAbstractDateTimeType;
import com.hp.hpl.jena.graph.Node;
import com.hp.hpl.jena.graph.NodeFactory;
import com.hp.hpl.jena.graph.Triple;
import com.hp.hpl.jena.query.ParameterizedSparqlString;
import com.hp.hpl.jena.query.Query;
import com.hp.hpl.jena.query.QueryExecution;
import com.hp.hpl.jena.query.QueryFactory;
import com.hp.hpl.jena.query.QuerySolution;
import com.hp.hpl.jena.query.ResultSet;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.rdf.model.Statement;
import com.hp.hpl.jena.sparql.core.BasicPattern;
import com.hp.hpl.jena.sparql.core.TriplePath;
import com.hp.hpl.jena.sparql.core.Var;
import com.hp.hpl.jena.sparql.expr.E_Equals;
import com.hp.hpl.jena.sparql.expr.E_LessThanOrEqual;
import com.hp.hpl.jena.sparql.expr.E_LogicalOr;
import com.hp.hpl.jena.sparql.expr.E_NotEquals;
import com.hp.hpl.jena.sparql.expr.E_NotExists;
import com.hp.hpl.jena.sparql.expr.E_NumAbs;
import com.hp.hpl.jena.sparql.expr.E_Str;
import com.hp.hpl.jena.sparql.expr.E_Subtract;
import com.hp.hpl.jena.sparql.expr.Expr;
import com.hp.hpl.jena.sparql.expr.ExprAggregator;
import com.hp.hpl.jena.sparql.expr.ExprVar;
import com.hp.hpl.jena.sparql.expr.NodeValue;
import com.hp.hpl.jena.sparql.expr.aggregate.AggCountVarDistinct;
import com.hp.hpl.jena.sparql.syntax.Element;
import com.hp.hpl.jena.sparql.syntax.ElementFilter;
import com.hp.hpl.jena.sparql.syntax.ElementGroup;
import com.hp.hpl.jena.sparql.syntax.ElementOptional;
import com.hp.hpl.jena.sparql.syntax.ElementPathBlock;
import com.hp.hpl.jena.sparql.syntax.ElementTriplesBlock;
import com.hp.hpl.jena.sparql.syntax.ElementUnion;
import com.hp.hpl.jena.sparql.syntax.ElementVisitorBase;
import com.hp.hpl.jena.sparql.syntax.ElementWalker;
import com.hp.hpl.jena.util.iterator.Filter;
import com.hp.hpl.jena.vocabulary.RDF;
import com.jamonapi.MonitorFactory;
/**
* @author Lorenz Buehmann
*
*/
public class QTLEvaluation {
private static final Logger logger = Logger.getLogger(QTLEvaluation.class.getName());
private static final ParameterizedSparqlString superClassesQueryTemplate2 = new ParameterizedSparqlString(
"PREFIX rdfs:<http://www.w3.org/2000/01/rdf-schema#> PREFIX owl: <http://www.w3.org/2002/07/owl#> "
+ "SELECT ?sup WHERE {"
+ "?sub ((rdfs:subClassOf|owl:equivalentClass)|^owl:equivalentClass)+ ?sup .}");
private static final ParameterizedSparqlString superClassesQueryTemplate = new ParameterizedSparqlString(
"PREFIX rdfs:<http://www.w3.org/2000/01/rdf-schema#> PREFIX owl: <http://www.w3.org/2002/07/owl#> "
+ "SELECT ?sup WHERE {"
+ "?sub (rdfs:subClassOf|owl:equivalentClass)+ ?sup .}");
enum NoiseMethod {
RANDOM, SIMILAR, SIMILARITY_PARAMETERIZED
}
enum Baseline {
RANDOM, MOST_POPULAR_TYPE_IN_KB, MOST_FREQUENT_TYPE_IN_EXAMPLES, MOST_INFORMATIVE_EDGE_IN_EXAMPLES, LGG, MOST_FREQUENT_EDGE_IN_EXAMPLES
}
NoiseMethod noiseMethod = NoiseMethod.RANDOM;
static Map<String, String> prefixes = new HashMap<String, String>();
static {
prefixes.put("sider", "http://www4.wiwiss.fu-berlin.de/sider/resource/sider/");
prefixes.put("side_effects", "http://www4.wiwiss.fu-berlin.de/sider/resource/side_effects/");
prefixes.put("drug", "http://www4.wiwiss.fu-berlin.de/drugbank/resource/drugbank/");
prefixes.put("diseasome", "http://www4.wiwiss.fu-berlin.de/diseasome/resource/diseasome/");
prefixes.put("dbo", "http://dbpedia.org/ontology/");
prefixes.put("dbpedia", "http://dbpedia.org/resource/");
}
List<String> questionFiles;
QueryExecutionFactory qef;
String cacheDirectory = "./cache/qtl";
int minNrOfPositiveExamples = 9;
int maxDepth = 3;
private org.dllearner.algorithms.qtl.impl.QueryTreeFactory queryTreeFactory;
private ConciseBoundedDescriptionGenerator cbdGen;
RandomDataGenerator rnd = new RandomDataGenerator();
private EvaluationDataset dataset;
private Map<String, List<String>> cache = new HashMap<String, List<String>>();
private int kbSize;
private boolean splitComplexQueries = true;
PredicateExistenceFilter filter = new PredicateExistenceFilterDBpedia(null);
// List<String> noiseExamples = new ArrayList<String>();
// private Map<OWLIndividual, RDFResourceTree> generatedExamples;
// private List<String> correctExamples;
// the directory where all files, results etc. are maintained
private File benchmarkDirectory;
// whether to write eval results to a database
private boolean write2DB;
private Connection conn;
private PreparedStatement psInsertOverallEval;
private PreparedStatement psInsertDetailEval;
// max. runtime for each QTL
private int maxExecutionTimeInSeconds = 30;
// whether to override existing results
private boolean override = false;
private boolean failed;
public QTLEvaluation(EvaluationDataset dataset, File benchmarkDirectory, boolean write2DB, boolean override) throws ComponentInitException {
this.dataset = dataset;
this.benchmarkDirectory = benchmarkDirectory;
this.write2DB = write2DB;
this.override = override;
queryTreeFactory = new QueryTreeFactoryBase();
queryTreeFactory.setMaxDepth(maxDepth);
// add some filters to avoid resources with namespaces like http://dbpedia.org/property/
queryTreeFactory.addDropFilters((Filter<Statement>[]) dataset.getQueryTreeFilters().toArray(new Filter[]{}));
qef = dataset.getKS().getQueryExecutionFactory();
cbdGen = new ConciseBoundedDescriptionGeneratorImpl(qef);
cbdGen.setRecursionDepth(maxDepth);
rnd.reSeed(123);
kbSize = getKBSize();
if(write2DB) {
setupDatabase();
}
}
private void setupDatabase() {
try {
Properties config = new Properties();
config.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("org/dllearner/algorithms/qtl/qtl-eval-config.properties"));
String url = config.getProperty("url");
String username = config.getProperty("username");
String password = config.getProperty("password");
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection(url, username, password);
String sql = "CREATE TABLE IF NOT EXISTS eval_overall (" +
"heuristic VARCHAR(100), " +
"heuristic_measure VARCHAR(100), " +
"nrOfExamples TINYINT, " +
"noise DOUBLE, " +
"avg_fscore_best_returned DOUBLE, " +
"avg_precision_best_returned DOUBLE, " +
"avg_recall_best_returned DOUBLE, " +
"avg_predacc_best_returned DOUBLE, " +
"avg_mathcorr_best_returned DOUBLE, " +
"avg_position_best DOUBLE, " +
"avg_fscore_best DOUBLE, " +
"avg_precision_best DOUBLE, " +
"avg_recall_best DOUBLE, " +
"avg_predacc_best DOUBLE, " +
"avg_mathcorr_best DOUBLE, " +
"avg_fscore_baseline DOUBLE, " +
"avg_precision_baseline DOUBLE, " +
"avg_recall_baseline DOUBLE, " +
"avg_predacc_baseline DOUBLE, " +
"avg_mathcorr_baseline DOUBLE, " +
"PRIMARY KEY(heuristic, heuristic_measure, nrOfExamples, noise))";
java.sql.Statement stmt = conn.createStatement();
stmt.execute(sql);
sql = "CREATE TABLE IF NOT EXISTS eval_detailed (" +
"target_query VARCHAR(500)," +
"nrOfExamples TINYINT, " +
"noise DOUBLE, " +
"heuristic VARCHAR(100), " +
"heuristic_measure VARCHAR(100), " +
"query_top VARCHAR(5000), " +
"fscore_top DOUBLE, " +
"precision_top DOUBLE, " +
"recall_top DOUBLE, " +
"best_query TEXT," +
"best_rank TINYINT, " +
"best_fscore DOUBLE, " +
"best_precision DOUBLE, " +
"best_recall DOUBLE, " +
"baseline_query TEXT," +
"baseline_fscore DOUBLE, " +
"baseline_precision DOUBLE, " +
"baseline_recall DOUBLE, " +
"PRIMARY KEY(target_query, nrOfExamples, noise, heuristic, heuristic_measure)) ENGINE=MyISAM";
stmt = conn.createStatement();
stmt.execute(sql);
sql = "INSERT INTO eval_overall ("
+ "heuristic, heuristic_measure, nrOfExamples, noise, "
+ "avg_fscore_best_returned, avg_precision_best_returned, avg_recall_best_returned,"
+ "avg_predacc_best_returned, avg_mathcorr_best_returned, "
+ "avg_position_best, avg_fscore_best, avg_precision_best, avg_recall_best, avg_predacc_best, avg_mathcorr_best,"
+ "avg_fscore_baseline, avg_precision_baseline, avg_recall_baseline, avg_predacc_baseline, avg_mathcorr_baseline"
+ ")" +
"VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
psInsertOverallEval = conn.prepareStatement(sql);
sql = "INSERT INTO eval_detailed ("
+ "target_query, nrOfExamples, noise, heuristic, heuristic_measure, "
+ "query_top, fscore_top, precision_top, recall_top,"
+ "best_query, best_rank, best_fscore, best_precision, best_recall, "
+ "baseline_query,baseline_fscore, baseline_precision, baseline_recall)" +
"VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
psInsertDetailEval = conn.prepareStatement(sql);
} catch (Exception e) {
e.printStackTrace();
}
}
private int getKBSize() {
String query = "SELECT (COUNT(*) AS ?cnt) WHERE {[] a ?type . ?type a <http://www.w3.org/2002/07/owl#Class> .}";
QueryExecution qe = qef.createQueryExecution(query);
ResultSet rs = qe.execSelect();
int size = rs.next().get("cnt").asLiteral().getInt();
qe.close();
return size;
}
private List<String> getSparqlQueries(File queriesFile) throws IOException {
List<String> sparqlQueries = new ArrayList<String>();
for (String queryString : Files.readLines(queriesFile, Charsets.UTF_8)) {
Query q = QueryFactory.create(queryString);
int subjectObjectJoinDepth = QueryUtils.getSubjectObjectJoinDepth(q, q.getProjectVars().get(0));
if(subjectObjectJoinDepth < maxDepth) {
sparqlQueries.add(queryString);
}
}
return sparqlQueries;
}
public void run(File queriesFile) throws Exception{
List<String> sparqlQueries = getSparqlQueries(queriesFile);
sparqlQueries = sparqlQueries.subList(0, 10);
logger.info("Total number of queries: " + sparqlQueries.size());
// parameters
int[] nrOfExamplesIntervals = {
// 5,
10,
// 15,
// 20,
// 25,
30
};
double[] noiseIntervals = {
0.0,
// 0.1,
0.2,
// 0.3,
0.4,
// 0.6
};
QueryTreeHeuristic[] heuristics = {
new QueryTreeHeuristicSimple(),
// new QueryTreeHeuristicComplex(qef)
};
HeuristicType[] measures = {
HeuristicType.PRED_ACC,
// HeuristicType.FMEASURE,
// HeuristicType.MATTHEWS_CORRELATION
};
// loop over heuristics
for(final QueryTreeHeuristic heuristic : heuristics) {
final String heuristicName = heuristic.getClass().getAnnotation(ComponentAnn.class).shortName();
// loop over heuristics measures
for (HeuristicType measure : measures) {
final String measureName = measure.toString();
double[][] data = new double[nrOfExamplesIntervals.length][noiseIntervals.length];
// loop over number of positive examples
for (int i = 0; i < nrOfExamplesIntervals.length; i++) {
final int nrOfExamples = nrOfExamplesIntervals[i];
// loop over noise value
for (int j = 0; j < noiseIntervals.length; j++) {
final double noise = noiseIntervals[j];
// check if not already processed
File logFile = new File(benchmarkDirectory, "qtl2-" + nrOfExamples + "-" + noise + "-" + heuristicName + "-" + measureName + ".log");
File statsFile = new File(benchmarkDirectory, "qtl2-" + nrOfExamples + "-" + noise + "-" + heuristicName + "-" + measureName + ".stats");
if(!override && logFile.exists() && statsFile.exists()) {
logger.info("Eval config already processed. For re-running please remove corresponding output files.");
continue;
}
FileAppender appender = null;
try {
appender = new FileAppender(new SimpleLayout(), logFile.getPath(), false);
Logger.getRootLogger().addAppender(appender);
} catch (IOException e) {
e.printStackTrace();
}
logger.info("#examples: " + nrOfExamples + " noise: " + noise);
final DescriptiveStatistics nrOfReturnedSolutionsStats = new SynchronizedDescriptiveStatistics();
final DescriptiveStatistics baselinePrecisionStats = new SynchronizedDescriptiveStatistics();
final DescriptiveStatistics baselineRecallStats = new SynchronizedDescriptiveStatistics();
final DescriptiveStatistics baselineFMeasureStats = new SynchronizedDescriptiveStatistics();
final DescriptiveStatistics baselinePredAccStats = new SynchronizedDescriptiveStatistics();
final DescriptiveStatistics baselineMathCorrStats = new SynchronizedDescriptiveStatistics();
final DescriptiveStatistics bestReturnedSolutionPrecisionStats = new SynchronizedDescriptiveStatistics();
final DescriptiveStatistics bestReturnedSolutionRecallStats = new SynchronizedDescriptiveStatistics();
final DescriptiveStatistics bestReturnedSolutionFMeasureStats = new SynchronizedDescriptiveStatistics();
final DescriptiveStatistics bestReturnedSolutionPredAccStats = new SynchronizedDescriptiveStatistics();
final DescriptiveStatistics bestReturnedSolutionMathCorrStats = new SynchronizedDescriptiveStatistics();
final DescriptiveStatistics bestSolutionPrecisionStats = new SynchronizedDescriptiveStatistics();
final DescriptiveStatistics bestSolutionRecallStats = new SynchronizedDescriptiveStatistics();
final DescriptiveStatistics bestSolutionFMeasureStats = new SynchronizedDescriptiveStatistics();
final DescriptiveStatistics bestSolutionPredAccStats = new SynchronizedDescriptiveStatistics();
final DescriptiveStatistics bestSolutionMathCorrStats = new SynchronizedDescriptiveStatistics();
final DescriptiveStatistics bestSolutionPositionStats = new SynchronizedDescriptiveStatistics();
MonitorFactory.getTimeMonitor(TimeMonitors.CBD_RETRIEVAL.name()).reset();
MonitorFactory.getTimeMonitor(TimeMonitors.TREE_GENERATION.name()).reset();
ExecutorService tp = Executors.newFixedThreadPool(1);
// indicates if the execution for some of the queries failed
final AtomicBoolean failed = new AtomicBoolean(false);
// if(nrOfExamples != 7) continue;
// loop over SPARQL queries
for (final String sparqlQuery : sparqlQueries) {
// if(!sparqlQuery.contains("MilitaryPerson"))continue;
tp.submit(new Runnable(){
@Override
public void run() {
logger.info("##############################################################");
logger.info("Processing query\n" + sparqlQuery);
// some queries can return less examples
int possibleNrOfExamples = Math.min(getResultCount(sparqlQuery), nrOfExamples);
try {
ExamplesWrapper examples = generateExamples(sparqlQuery, possibleNrOfExamples, noise);
// compute baseline
logger.info("Computing baseline...");
RDFResourceTree baselineSolution = applyBaseLine(examples, Baseline.MOST_FREQUENT_TYPE_IN_EXAMPLES);
logger.info("done. \nBaseline solution:\n" + QueryTreeUtils.toOWLClassExpression(baselineSolution));
logger.info("Evaluating baseline...");
Score baselineScore = computeScore(sparqlQuery, baselineSolution, noise);
logger.info("Baseline score:\n" + baselineScore);
String baseLineQuery = QueryTreeUtils.toSPARQLQueryString(
baselineSolution, dataset.getBaseIRI(), dataset.getPrefixMapping());
baselinePrecisionStats.addValue(baselineScore.precision);
baselineRecallStats.addValue(baselineScore.recall);
baselineFMeasureStats.addValue(baselineScore.fmeasure);
baselinePredAccStats.addValue(baselineScore.predAcc);
baselineMathCorrStats.addValue(baselineScore.mathCorr);
// compute or load cached solutions
List<EvaluatedRDFResourceTree> solutions = generateSolutions(examples, noise, heuristic);
nrOfReturnedSolutionsStats.addValue(solutions.size());
// the best returned solution by QTL
EvaluatedRDFResourceTree bestSolution = solutions.get(0);
logger.info("Got " + solutions.size() + " query trees.");
logger.info("Best computed solution:\n" + bestSolution.asEvaluatedDescription());
logger.info("QTL Score:\n" + bestSolution.getTreeScore());
// convert to SPARQL query
RDFResourceTree tree = bestSolution.getTree();
// filter.filter(tree);
String learnedSPARQLQuery = QueryTreeUtils.toSPARQLQueryString(
tree, dataset.getBaseIRI(), dataset.getPrefixMapping());
// compute score
Score score = computeScore(sparqlQuery, tree, noise);
bestReturnedSolutionPrecisionStats.addValue(score.precision);
bestReturnedSolutionRecallStats.addValue(score.recall);
bestReturnedSolutionFMeasureStats.addValue(score.fmeasure);
bestReturnedSolutionPredAccStats.addValue(score.predAcc);
bestReturnedSolutionMathCorrStats.addValue(score.mathCorr);
logger.info(score);
// find the extensionally best matching tree in the list
Pair<EvaluatedRDFResourceTree, Score> bestMatchingTreeWithScore = findBestMatchingTreeFast(solutions, sparqlQuery, noise, examples);
EvaluatedRDFResourceTree bestMatchingTree = bestMatchingTreeWithScore.getFirst();
Score bestMatchingScore = bestMatchingTreeWithScore.getSecond();
// position of best tree in list of solutions
int positionBestScore = solutions.indexOf(bestMatchingTree);
bestSolutionPositionStats.addValue(positionBestScore);
Score bestScore = score;
if (positionBestScore > 0) {
logger.info("Position of best covering tree in list: " + positionBestScore);
logger.info("Best covering solution:\n" + bestMatchingTree.asEvaluatedDescription());
logger.info("Tree score: " + bestMatchingTree.getTreeScore());
bestScore = bestMatchingScore;
logger.info(bestMatchingScore);
} else {
logger.info("Best returned solution was also the best covering solution.");
}
bestSolutionRecallStats.addValue(bestScore.recall);
bestSolutionPrecisionStats.addValue(bestScore.precision);
bestSolutionFMeasureStats.addValue(bestScore.fmeasure);
bestSolutionPredAccStats.addValue(bestScore.predAcc);
bestSolutionMathCorrStats.addValue(bestScore.mathCorr);
String bestQuery = QueryFactory.create(QueryTreeUtils.toSPARQLQueryString(
filter.filter(bestMatchingTree.getTree()),
dataset.getBaseIRI(), dataset.getPrefixMapping())).toString();
if(write2DB) {
write2DB(sparqlQuery, nrOfExamples, examples, noise,
baseLineQuery, baselineScore,
heuristicName, measureName,
QueryFactory.create(learnedSPARQLQuery).toString(), score,
bestQuery, positionBestScore, bestScore);
}
} catch (Exception e) {
failed.set(true);
logger.error("Error occured.", e);
// System.exit(0);
}
}
});
}
tp.shutdown();
tp.awaitTermination(1, TimeUnit.HOURS);
Logger.getRootLogger().removeAppender(appender);
if(!failed.get()) {
String result = "";
result += "\nBaseline Precision:\n" + baselinePrecisionStats;
result += "\nBaseline Recall:\n" + baselineRecallStats;
result += "\nBaseline F-measure:\n" + baselineFMeasureStats;
result += "\nBaseline PredAcc:\n" + baselinePredAccStats;
result += "\nBaseline MathCorr:\n" + baselineMathCorrStats;
result += "#Returned solutions:\n" + nrOfReturnedSolutionsStats;
result += "\nOverall Precision:\n" + bestReturnedSolutionPrecisionStats;
result += "\nOverall Recall:\n" + bestReturnedSolutionRecallStats;
result += "\nOverall F-measure:\n" + bestReturnedSolutionFMeasureStats;
result += "\nOverall PredAcc:\n" + bestReturnedSolutionPredAccStats;
result += "\nOverall MathCorr:\n" + bestReturnedSolutionMathCorrStats;
result += "\nPositions of best solution:\n" + Arrays.toString(bestSolutionPositionStats.getValues());
result += "\nPosition of best solution stats:\n" + bestSolutionPositionStats;
result += "\nOverall Precision of best solution:\n" + bestSolutionPrecisionStats;
result += "\nOverall Recall of best solution:\n" + bestSolutionRecallStats;
result += "\nOverall F-measure of best solution:\n" + bestSolutionFMeasureStats;
result += "\nCBD generation time(total):\t" + MonitorFactory.getTimeMonitor(TimeMonitors.CBD_RETRIEVAL.name()).getTotal() + "\n";
result += "CBD generation time(avg):\t" + MonitorFactory.getTimeMonitor(TimeMonitors.CBD_RETRIEVAL.name()).getAvg() + "\n";
result += "Tree generation time(total):\t" + MonitorFactory.getTimeMonitor(TimeMonitors.TREE_GENERATION.name()).getTotal() + "\n";
result += "Tree generation time(avg):\t" + MonitorFactory.getTimeMonitor(TimeMonitors.TREE_GENERATION.name()).getAvg() + "\n";
logger.info(result);
try {
Files.write(result, statsFile, Charsets.UTF_8);
} catch (IOException e) {
e.printStackTrace();
}
data[i][j] = bestReturnedSolutionFMeasureStats.getMean();
if(write2DB) {
write2DB(heuristicName, measureName, nrOfExamples, noise,
bestReturnedSolutionFMeasureStats.getMean(),
bestReturnedSolutionPrecisionStats.getMean(),
bestReturnedSolutionRecallStats.getMean(),
bestReturnedSolutionPredAccStats.getMean(),
bestReturnedSolutionMathCorrStats.getMean(),
bestSolutionPositionStats.getMean(),
bestSolutionFMeasureStats.getMean(),
bestSolutionPrecisionStats.getMean(),
bestSolutionRecallStats.getMean(),
bestSolutionPredAccStats.getMean(),
bestSolutionMathCorrStats.getMean(),
baselineFMeasureStats.getMean(),
baselinePrecisionStats.getMean(),
baselineRecallStats.getMean(),
baselinePredAccStats.getMean(),
baselineMathCorrStats.getMean()
);
}
}
}
}
String content = "###";
String separator = "\t";
for(int j = 0; j < noiseIntervals.length; j++) {
content += separator + noiseIntervals[j];
}
content += "\n";
for(int i = 0; i < nrOfExamplesIntervals.length; i++) {
content += nrOfExamplesIntervals[i];
for(int j = 0; j < noiseIntervals.length; j++) {
content += separator + data[i][j];
}
content += "\n";
}
File examplesVsNoise = new File(benchmarkDirectory, "examplesVsNoise-" + heuristicName + "-" + measureName + ".txt");
try {
Files.write(content, examplesVsNoise, Charsets.UTF_8);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/*
* Compute a baseline solution.
*
* From simple to more complex:
*
* 1. random type
* 2. most popular type in KB
* 3. most frequent type in pos. examples
* 4. most informative edge, e.g. based on information gain
* 5. LGG of all pos. examples
*
*/
private RDFResourceTree applyBaseLine(ExamplesWrapper examples, Baseline baselineApproach) {
Collection<RDFResourceTree> posExamples = examples.posExamplesMapping.values();
switch (baselineApproach) {
case RANDOM:// 1.
String query = "SELECT ?cls WHERE {?cls a owl:Class .} ORDER BY RAND() LIMIT 1";
QueryExecution qe = qef.createQueryExecution(query);
ResultSet rs = qe.execSelect();
if(rs.hasNext()) {
QuerySolution qs = rs.next();
Resource cls = qs.getResource("cls");
RDFResourceTree solution = new RDFResourceTree();
solution.addChild(new RDFResourceTree(cls.asNode()), RDF.type.asNode());
return solution;
}
case MOST_POPULAR_TYPE_IN_KB:// 2.
query = "SELECT ?cls WHERE {?cls a owl:Class . ?s a ?cls .} ORDER BY DESC(COUNT(?s)) LIMIT 1";
qe = qef.createQueryExecution(query);
rs = qe.execSelect();
if(rs.hasNext()) {
QuerySolution qs = rs.next();
Resource cls = qs.getResource("cls");
RDFResourceTree solution = new RDFResourceTree();
solution.addChild(new RDFResourceTree(cls.asNode()), RDF.type.asNode());
return solution;
}
case MOST_FREQUENT_TYPE_IN_EXAMPLES:// 3.
Multiset<Node> types = HashMultiset.create();
for (RDFResourceTree ex : posExamples) {
List<RDFResourceTree> children = ex.getChildren(RDF.type.asNode());
for (RDFResourceTree child : children) {
types.add(child.getData());
}
}
Node mostFrequentType = Ordering.natural().onResultOf(new Function<Multiset.Entry<Node>, Integer>() {
public Integer apply(Multiset.Entry<Node> entry) {
return entry.getCount();
}
}).max(types.entrySet()).getElement();
RDFResourceTree solution = new RDFResourceTree();
solution.addChild(new RDFResourceTree(mostFrequentType), RDF.type.asNode());
return solution;
case MOST_FREQUENT_EDGE_IN_EXAMPLES:// 4.
Multiset<Pair<Node, Node>> pairs = HashMultiset.create();
for (RDFResourceTree ex : posExamples) {
SortedSet<Node> edges = ex.getEdges();
for (Node edge : edges) {
List<RDFResourceTree> children = ex.getChildren(edge);
for (RDFResourceTree child : children) {
pairs.add(new Pair<Node, Node>(edge, child.getData()));
}
}
}
Pair<Node, Node> mostFrequentPair = Ordering.natural().onResultOf(new Function<Multiset.Entry<Pair<Node, Node>>, Integer>() {
public Integer apply(Multiset.Entry<Pair<Node, Node>> entry) {
return entry.getCount();
}
}).max(pairs.entrySet()).getElement();
solution = new RDFResourceTree();
solution.addChild(new RDFResourceTree(mostFrequentPair.getValue()), mostFrequentPair.getKey());
return solution;
case MOST_INFORMATIVE_EDGE_IN_EXAMPLES:
break;
case LGG:
LGGGenerator lggGenerator = new LGGGeneratorSimple();
RDFResourceTree lgg = lggGenerator.getLGG(Lists.newArrayList(posExamples));
return lgg;
default:
break;
}
return null;
}
private List<EvaluatedRDFResourceTree> generateSolutions(ExamplesWrapper examples, double noise, QueryTreeHeuristic heuristic) throws ComponentInitException {
// run QTL
PosNegLPStandard lp = new PosNegLPStandard();
lp.setPositiveExamples(examples.posExamplesMapping.keySet());
lp.setNegativeExamples(examples.negExamplesMapping.keySet());
// lp.init();
QTL2Disjunctive la = new QTL2Disjunctive(lp, qef);
la.setReasoner(dataset.getReasoner());
la.setEntailment(Entailment.RDFS);
la.setTreeFactory(queryTreeFactory);
la.setPositiveExampleTrees(examples.posExamplesMapping);
la.setNegativeExampleTrees(examples.negExamplesMapping);
la.setNoise(noise);
la.setHeuristic(heuristic);
la.setMaxExecutionTimeInSeconds(maxExecutionTimeInSeconds);
la.init();
la.start();
List<EvaluatedRDFResourceTree> solutions = new ArrayList<EvaluatedRDFResourceTree>(la.getSolutions());
return solutions;
}
private void solutionsFromCache(String sparqlQuery, int possibleNrOfExamples, double noise) {
HashFunction hf = Hashing.md5();
String hash = hf.newHasher()
.putString(sparqlQuery, Charsets.UTF_8)
.putInt(possibleNrOfExamples)
.putDouble(noise)
.hash().toString();
File file = new File(cacheDirectory, hash + "-data.ttl");
if(file.exists()) {
}
}
private Pair<EvaluatedRDFResourceTree, Score> findBestMatchingTree(Collection<EvaluatedRDFResourceTree> trees,
String targetSPARQLQuery, double noise) throws Exception {
logger.info("Finding best matching query tree...");
//get the tree with the highest fMeasure
EvaluatedRDFResourceTree bestTree = null;
Score bestScore = null;
double bestFMeasure = -1;
for (EvaluatedRDFResourceTree evalutedTree : trees) {
RDFResourceTree tree = evalutedTree.getTree();
// compute score
Score score = computeScore(targetSPARQLQuery, tree, noise);
double fMeasure = score.fmeasure;
// we can stop if f-score is 1
if(fMeasure == 1.0){
return new Pair<>(evalutedTree, score);
}
if(fMeasure > bestFMeasure){
bestFMeasure = fMeasure;
bestTree = evalutedTree;
bestScore = score;
}
}
return new Pair<>(bestTree, bestScore);
}
/**
* find best query tree by searching for the tree which covers
* (1) most of the correct positive examples and
* (2) none of the noise positive examples
* @throws Exception
*/
private Pair<EvaluatedRDFResourceTree, Score> findBestMatchingTreeFast(
Collection<EvaluatedRDFResourceTree> trees, String targetSPARQLQuery, double noise,
ExamplesWrapper examples) throws Exception{
logger.info("Finding best matching query tree...");
Set<RDFResourceTree> correctPositiveExampleTrees = new HashSet<RDFResourceTree>();
for (String ex : examples.correctPosExamples) {
correctPositiveExampleTrees.add(examples.posExamplesMapping.get(new OWLNamedIndividualImpl(IRI.create(ex))));
}
Set<RDFResourceTree> noisyPositiveExampleTrees = new HashSet<RDFResourceTree>();
for (String ex : examples.noisePosExamples) {
noisyPositiveExampleTrees.add(examples.posExamplesMapping.get(new OWLNamedIndividualImpl(IRI.create(ex))));
}
EvaluatedRDFResourceTree bestTree = null;
int coveredNoiseTreesBest = 0;
int coveredCorrectTreesBest = 0;
for (EvaluatedRDFResourceTree evalutedTree : trees) {
RDFResourceTree tree = evalutedTree.getTree();
int coveredNoiseTrees = 0;
for (RDFResourceTree noiseTree : noisyPositiveExampleTrees) {
if(QueryTreeUtils.isSubsumedBy(noiseTree, tree)) {
coveredNoiseTrees++;
}
}
int coveredCorrectTrees = 0;
for (RDFResourceTree correctTree : correctPositiveExampleTrees) {
if(QueryTreeUtils.isSubsumedBy(correctTree, tree)) {
coveredCorrectTrees++;
}
}
// System.err.println("+" + coveredCorrectTrees + "|-" + coveredNoiseTrees);
// this is obviously the most perfect solution according to the input
if(coveredNoiseTrees == 0 && coveredCorrectTrees == correctPositiveExampleTrees.size()) {
bestTree = evalutedTree;
break;
}
if(coveredCorrectTrees > coveredCorrectTreesBest || coveredNoiseTrees < coveredNoiseTreesBest) {
bestTree = evalutedTree;
coveredCorrectTreesBest = coveredCorrectTrees;
coveredNoiseTreesBest = coveredNoiseTrees;
}
}
// compute score
String learnedSPARQLQuery = QueryTreeUtils.toSPARQLQueryString(bestTree.getTree(), dataset.getBaseIRI(), dataset.getPrefixMapping());
System.out.println(learnedSPARQLQuery);
Score score = computeScore(targetSPARQLQuery, bestTree.getTree(), noise);
return new Pair<>(bestTree, score);
}
private ExamplesWrapper generateExamples(String sparqlQuery, int maxNrOfExamples, double noise) throws Exception{
Random randomGen = new Random(123);
// get all resources returned by the query
List<String> resources = getResult(sparqlQuery, false);
// pick some random positive examples from the list
Collections.shuffle(resources, randomGen);
List<String> examples = resources.subList(0, Math.min(maxNrOfExamples, resources.size()));
logger.info("Pos. examples: " + examples);
// add noise if enabled
Pair<List<String>, List<String>> examplesSet;
if(noise > 0) {
examplesSet = generateNoise(examples, sparqlQuery, noise, randomGen);
} else {
examplesSet = new Pair<List<String>, List<String>>(new ArrayList<String>(examples), new ArrayList<String>());
}
// build query trees
Map<OWLIndividual, RDFResourceTree> posQueryTrees = new HashMap<>();
for (String ex : examples) {
try {
RDFResourceTree queryTree = getQueryTree(ex);
posQueryTrees.put(new OWLNamedIndividualImpl(IRI.create(ex)), queryTree);
} catch (Exception e) {
throw e;
}
}
List<String> negativeExamples = new NegativeExampleSPARQLQueryGenerator().getNegativeExamples(sparqlQuery, maxNrOfExamples);
Map<OWLIndividual, RDFResourceTree> negQueryTrees = new HashMap<>();
for (String ex : negativeExamples) {
try {
RDFResourceTree queryTree = getQueryTree(ex);
negQueryTrees.put(new OWLNamedIndividualImpl(IRI.create(ex)), queryTree);
} catch (Exception e) {
throw e;
}
}
// add noise by modifying the query trees
// generateNoiseAttributeLevel(sparqlQuery, queryTrees, noise);
return new ExamplesWrapper(examplesSet.getFirst(), examplesSet.getSecond(), negativeExamples, posQueryTrees, negQueryTrees);
}
private RDFResourceTree getSimilarTree(RDFResourceTree tree, String property, int maxTreeDepth){
String query = "SELECT ?o WHERE {?s <" + property + "> ?o. FILTER(isURI(?o) && ?o != <" + tree.getData() + ">)} LIMIT 1";
QueryExecution qe = qef.createQueryExecution(query);
ResultSet rs = qe.execSelect();
if(rs.hasNext()){
Resource object = rs.next().getResource("o");
Model cbd = cbdGen.getConciseBoundedDescription(object.getURI(), maxTreeDepth);
RDFResourceTree similarTree = queryTreeFactory.getQueryTree(object, cbd);
similarTree.setData(object.asNode());
return similarTree;
}
return null;
}
private Pair<List<String>, List<String>> generateNoise(List<String> examples, String sparqlQuery, double noise, Random randomGen) {
// generate noise example candidates
List<String> noiseCandidateExamples = null;
switch(noiseMethod) {
case RANDOM: noiseCandidateExamples = generateNoiseCandidatesRandom(examples, 20);
break;
case SIMILAR:noiseCandidateExamples = generateNoiseCandidatesSimilar(examples, sparqlQuery);
break;
case SIMILARITY_PARAMETERIZED://TODO implement configurable noise method
break;
default:noiseCandidateExamples = generateNoiseCandidatesRandom(examples, 20);
break;
}
Collections.shuffle(noiseCandidateExamples, randomGen);
// add some noise by using instances close to the positive examples
// we have two ways of adding noise t_n
// 1: iterate over pos. examples and if random number is below t_n, replace the example
// 2: replace the (#posExamples * t_n) randomly chosen pos. examples by randomly chosen negative examples
boolean probabilityBased = false;
if (probabilityBased) {
// 1. way
List<String> newExamples = new ArrayList<String>();
for (Iterator<String> iterator = examples.iterator(); iterator.hasNext();) {
String posExample = iterator.next();
double rnd = randomGen.nextDouble();
if (rnd <= noise) {
// remove the positive example
iterator.remove();
// add one of the negative examples
String negExample = noiseCandidateExamples.remove(0);
newExamples.add(negExample);
logger.info("Replacing " + posExample + " by " + negExample);
}
}
examples.addAll(newExamples);
return null;
} else {
// 2. way
// replace at least 1 but not more than half of the examples
int upperBound = examples.size() / 2;
int nrOfPosExamples2Replace = (int) Math.ceil(noise * examples.size());
nrOfPosExamples2Replace = Math.min(nrOfPosExamples2Replace, upperBound);
logger.info("replacing " + nrOfPosExamples2Replace + "/" + examples.size() + " examples to introduce noise");
List<String> posExamples2Replace = new ArrayList<>(examples.subList(0, nrOfPosExamples2Replace));
examples.removeAll(posExamples2Replace);
List<String> negExamples4Replacement = noiseCandidateExamples.subList(0, nrOfPosExamples2Replace);
List<String> noiseExamples = new ArrayList<String>(negExamples4Replacement);
List<String> correctExamples = new ArrayList<String>(examples);
examples.addAll(negExamples4Replacement);
logger.info("replaced " + posExamples2Replace + " by " + negExamples4Replacement);
return new Pair<>(correctExamples, noiseExamples);
}
}
/**
* Randomly pick {@code n} instances from KB that do not belong to given positive examples {@code examples}.
* @param examples the examples that must not be contained in the returned list
* @param n the number of random examples
* @return
*/
private List<String> generateNoiseCandidatesRandom(List<String> examples, int n) {
List<String> noiseExamples = new ArrayList<>();
rnd.reSeed(123);
// get max number of instances in KB
String query = "SELECT (COUNT(*) AS ?cnt) WHERE {[] a ?type . ?type a <http://www.w3.org/2002/07/owl#Class> .}";
QueryExecution qe = qef.createQueryExecution(query);
ResultSet rs = qe.execSelect();
int max = rs.next().get("cnt").asLiteral().getInt();
// generate random instances
while(noiseExamples.size() < n) {
int offset = rnd.nextInt(0, max);
query = "SELECT ?s WHERE {?s a [] .} LIMIT 1 OFFSET " + offset;
qe = qef.createQueryExecution(query);
rs = qe.execSelect();
String resource = rs.next().getResource("s").getURI();
if(!examples.contains(resource) && !resource.contains("__")) {
noiseExamples.add(resource);
}
qe.close();
}
return noiseExamples;
}
private List<String> generateNoiseCandidatesSimilar(List<String> examples, String queryString){
Query query = QueryFactory.create(queryString);
QueryUtils queryUtils = new QueryUtils();
Set<Triple> triplePatterns = queryUtils.extractTriplePattern(query);
Set<String> negExamples = new HashSet<String>();
if(triplePatterns.size() == 1){
Triple tp = triplePatterns.iterator().next();
Node var = NodeFactory.createVariable("var");
Triple newTp = Triple.create(tp.getSubject(), tp.getPredicate(), var);
ElementTriplesBlock triplesBlock = new ElementTriplesBlock();
triplesBlock.addTriple(newTp);
ElementFilter filter = new ElementFilter(new E_NotEquals(new ExprVar(var), NodeValue.makeNode(tp.getObject())));
ElementGroup eg = new ElementGroup();
eg.addElement(triplesBlock);
eg.addElementFilter(filter);
Query q = new Query();
q.setQuerySelectType();
q.setDistinct(true);
q.addProjectVars(query.getProjectVars());
q.setQueryPattern(eg);
// System.out.println(q);
List<String> result = getResult(q.toString());
negExamples.addAll(result);
} else {
// we modify each triple pattern <s p o> by <s p ?var> . ?var != o
Set<Set<Triple>> powerSet = new TreeSet<>(new Comparator<Set<Triple>>() {
@Override
public int compare(Set<Triple> o1, Set<Triple> o2) {
return ComparisonChain.start().compare(o1.size(), o2.size()).compare(o1.hashCode(), o2.hashCode()).result();
}
});
powerSet.addAll(Sets.powerSet(triplePatterns));
for (Set<Triple> set : powerSet) {
if(!set.isEmpty() && set.size() != triplePatterns.size()){
List<Triple> existingTriplePatterns = new ArrayList<>(triplePatterns);
List<Triple> newTriplePatterns = new ArrayList<>();
List<ElementFilter> filters = new ArrayList<ElementFilter>();
int cnt = 0;
for (Triple tp : set) {
if(tp.getObject().isURI() || tp.getObject().isLiteral()){
Node var = NodeFactory.createVariable("var" + cnt++);
Triple newTp = Triple.create(tp.getSubject(), tp.getPredicate(), var);
existingTriplePatterns.remove(tp);
newTriplePatterns.add(newTp);
ElementTriplesBlock triplesBlock = new ElementTriplesBlock();
triplesBlock.addTriple(tp);
ElementGroup eg = new ElementGroup();
eg.addElement(triplesBlock);
ElementFilter filter = new ElementFilter(new E_NotExists(eg));
filters.add(filter);
}
}
Query q = new Query();
q.setQuerySelectType();
q.setDistinct(true);
q.addProjectVars(query.getProjectVars());
List<Triple> allTriplePatterns = new ArrayList<Triple>(existingTriplePatterns);
allTriplePatterns.addAll(newTriplePatterns);
ElementTriplesBlock tripleBlock = new ElementTriplesBlock(BasicPattern.wrap(allTriplePatterns));
ElementGroup eg = new ElementGroup();
eg.addElement(tripleBlock);
for (ElementFilter filter : filters) {
eg.addElementFilter(filter);
}
q.setQueryPattern(eg);
// System.out.println(q);
List<String> result = getResult(q.toString());
result.removeAll(examples);
if(result.isEmpty()){
q = new Query();
q.setQuerySelectType();
q.setDistinct(true);
q.addProjectVars(query.getProjectVars());
tripleBlock = new ElementTriplesBlock(BasicPattern.wrap(existingTriplePatterns));
eg = new ElementGroup();
eg.addElement(tripleBlock);
for (ElementFilter filter : filters) {
eg.addElementFilter(filter);
}
q.setQueryPattern(eg);
// System.out.println(q);
result = getResult(q.toString());
result.removeAll(examples);
}
negExamples.addAll(result);
}
}
}
negExamples.removeAll(examples);
if(negExamples.isEmpty()){
logger.error("Found no negative example.");
System.exit(0);
}
return new ArrayList<>(negExamples);
}
private List<RDFResourceTree> getQueryTrees(List<String> resources){
List<RDFResourceTree> trees = new ArrayList<RDFResourceTree>();
for (String resource : resources) {
trees.add(getQueryTree(resource));
}
return trees;
}
private RDFResourceTree getQueryTree(String resource){
// get CBD
MonitorFactory.getTimeMonitor(TimeMonitors.CBD_RETRIEVAL.name()).start();
Model cbd = cbdGen.getConciseBoundedDescription(resource);
MonitorFactory.getTimeMonitor(TimeMonitors.CBD_RETRIEVAL.name()).stop();
// rewrite NAN to NaN to avoid parse exception
try(ByteArrayOutputStream baos = new ByteArrayOutputStream()){
cbd.write(baos, "N-TRIPLES", null);
String modelAsString = new String(baos.toByteArray());
modelAsString = modelAsString.replace("NAN", "NaN");
Model newModel = ModelFactory.createDefaultModel();
newModel.read(new StringReader(modelAsString), null, "TURTLE");
cbd = newModel;
} catch (IOException e) {
e.printStackTrace();
}
// generate tree
MonitorFactory.getTimeMonitor(TimeMonitors.TREE_GENERATION.name()).start();
RDFResourceTree tree = queryTreeFactory.getQueryTree(resource, cbd);
MonitorFactory.getTimeMonitor(TimeMonitors.TREE_GENERATION.name()).stop();
return tree;
}
private List<String> getResult(String sparqlQuery){
return getResult(sparqlQuery, true);
}
private List<String> getResult(String sparqlQuery, boolean useCache){
logger.trace(sparqlQuery);
List<String> resources = cache.get(sparqlQuery);
if(resources == null || !useCache) {
resources = new ArrayList<String>();
// sparqlQuery = getPrefixedQuery(sparqlQuery);
// we assume a single projection var
Query query = QueryFactory.create(sparqlQuery);
String projectVar = query.getProjectVars().get(0).getName();
ResultSet rs = qef.createQueryExecution(sparqlQuery).execSelect();
QuerySolution qs;
while(rs.hasNext()){
qs = rs.next();
if(qs.get(projectVar).isURIResource()){
resources.add(qs.getResource(projectVar).getURI());
} else if(qs.get(projectVar).isLiteral()){
resources.add(qs.getLiteral(projectVar).toString());
}
}
cache.put(sparqlQuery, resources);
}
return resources;
}
/**
* Split the SPARQL query and join the result set of each split. This
* allows for the execution of more complex queries.
* @param sparqlQuery
* @return
*/
private List<String> getResultSplitted(String sparqlQuery){
Query query = QueryFactory.create(sparqlQuery);
logger.trace("Getting result set for\n" + query);
QueryUtils queryUtils = new QueryUtils();
Set<Triple> triplePatterns = queryUtils.extractTriplePattern(query);
// remove triple patterns with unbound object vars
if(triplePatterns.size() > 10) {
query = removeUnboundObjectVarTriples(query);
triplePatterns = queryUtils.extractTriplePattern(query);
}
// Virtuoso bug workaround with literals of type xsd:float and xsd:double
for (Iterator<Triple> iterator = triplePatterns.iterator(); iterator.hasNext();) {
Node object = iterator.next().getObject();
if(object.isLiteral() && object.getLiteralDatatype() != null
&& (object.getLiteralDatatype().equals(XSDDatatype.XSDfloat) || object.getLiteralDatatype().equals(XSDDatatype.XSDdouble))){
iterator.remove();
}
}
Var targetVar = query.getProjectVars().get(0); // should be ?x0
Multimap<Var, Triple> var2TriplePatterns = HashMultimap.create();
for (Triple tp : triplePatterns) {
var2TriplePatterns.put(Var.alloc(tp.getSubject()), tp);
}
// we keep only the most specific types for each var
filterOutGeneralTypes(var2TriplePatterns);
// 1. get the outgoing triple patterns of the target var that do not have
// outgoing triple patterns
Set<Triple> fixedTriplePatterns = new HashSet<Triple>();
Set<Set<Triple>> clusters = new HashSet<Set<Triple>>();
Collection<Triple> targetVarTriplePatterns = var2TriplePatterns.get(targetVar);
boolean useSplitting = false;
for (Triple tp : targetVarTriplePatterns) {
Node object = tp.getObject();
if(object.isConcrete() || !var2TriplePatterns.containsKey(Var.alloc(object))){
fixedTriplePatterns.add(tp);
} else {
Set<Triple> cluster = new TreeSet<>(new Comparator<Triple>() {
@Override
public int compare(Triple o1, Triple o2) {
return ComparisonChain.start().
compare(o1.getSubject().toString(), o2.getSubject().toString()).
compare(o1.getPredicate().toString(), o2.getPredicate().toString()).
compare(o1.getObject().toString(), o2.getObject().toString()).
result();
}
});
cluster.add(tp);
clusters.add(cluster);
useSplitting = true;
}
}
if(!useSplitting){
clusters.add(Sets.newHashSet(fixedTriplePatterns));
} else {
logger.trace("Query too complex. Splitting...");
// 2. build clusters for other
for (Set<Triple> cluster : clusters) {
Triple representative = cluster.iterator().next();
cluster.addAll(var2TriplePatterns.get(Var.alloc(representative.getObject())));
cluster.addAll(fixedTriplePatterns);
}
}
// again split clusters to have only a maximum number of triple patterns
int maxNrOfTriplePatternsPerQuery = 20;// number of outgoing triple patterns form the target var in each executed query
Set<Set<Triple>> newClusters = new HashSet<Set<Triple>>();
for (Set<Triple> cluster : clusters) {
int cnt = 0;
for (Triple triple : cluster) {
if(triple.getSubject().matches(targetVar)) {
cnt++;
}
}
if(cnt > maxNrOfTriplePatternsPerQuery) {
Set<Triple> newCluster = new HashSet<Triple>();
for (Triple triple : cluster) {
if(triple.getSubject().matches(targetVar)) {
newCluster.add(triple);
}
if(newCluster.size() == maxNrOfTriplePatternsPerQuery) {
newClusters.add(newCluster);
newCluster = new HashSet<Triple>();
}
}
if(!newCluster.isEmpty()) {
newClusters.add(newCluster);
}
}
}
for (Set<Triple> cluster : newClusters) {
for(int i = 1; i < maxDepth; i++) {
Set<Triple> additionalTriples = new HashSet<Triple>();
for (Triple triple : cluster) {
if(triple.getObject().isVariable()){
additionalTriples.addAll(var2TriplePatterns.get(Var.alloc(triple.getObject())));
}
}
cluster.addAll(additionalTriples);
}
}
// clusters = newClusters;
Set<String> resources = null;
// 3. run query for each cluster
for (Set<Triple> cluster : clusters) {
Query q = new Query();
q.addProjectVars(Collections.singleton(targetVar));
ElementTriplesBlock el = new ElementTriplesBlock();
for (Triple triple : cluster) {
el.addTriple(triple);
}
q.setQuerySelectType();
q.setDistinct(true);
q.setQueryPattern(el);
q = rewriteForVirtuosoDateLiteralBug(q);
// q = rewriteForVirtuosoFloatingPointIssue(q);
logger.trace(q);
// sparqlQuery = getPrefixedQuery(sparqlQuery);
System.out.println(q);
List<String> partialResult = getResult(q.toString());
Set<String> resourcesTmp = new HashSet<String>(partialResult);
if(resourcesTmp.isEmpty()) {
System.err.println("Empty query result");
System.err.println(q);
// System.exit(0);
return Collections.EMPTY_LIST;
}
if(resources == null){
resources = resourcesTmp;
} else {
resources.retainAll(resourcesTmp);
}
}
return new ArrayList<String>(resources);
}
private Query removeUnboundObjectVarTriples(Query query) {
QueryUtils queryUtils = new QueryUtils();
Set<Triple> triplePatterns = queryUtils.extractTriplePattern(query);
Multimap<Var, Triple> var2TriplePatterns = HashMultimap.create();
for (Triple tp : triplePatterns) {
var2TriplePatterns.put(Var.alloc(tp.getSubject()), tp);
}
Iterator<Triple> iterator = triplePatterns.iterator();
while (iterator.hasNext()) {
Triple triple = iterator.next();
Node object = triple.getObject();
if(object.isVariable() && !var2TriplePatterns.containsKey(Var.alloc(object))) {
iterator.remove();
}
}
Query newQuery = new Query();
newQuery.addProjectVars(query.getProjectVars());
ElementTriplesBlock el = new ElementTriplesBlock();
for (Triple triple : triplePatterns) {
el.addTriple(triple);
}
newQuery.setQuerySelectType();
newQuery.setDistinct(true);
newQuery.setQueryPattern(el);
return newQuery;
}
private void filterOutGeneralTypes(Multimap<Var, Triple> var2Triples) {
// keep the most specific types for each subject
for (Var subject : var2Triples.keySet()) {
Collection<Triple> triplePatterns = var2Triples.get(subject);
Collection<Triple> triplesPatterns2Remove = new HashSet<Triple>();
for (Triple tp : triplePatterns) {
if (tp.getObject().isURI() && !triplesPatterns2Remove.contains(tp)) {
// get all super classes for the triple object
Set<Node> superClasses = getSuperClasses(tp.getObject());
// remove triple patterns that have one of the super classes as object
for (Triple tp2 : triplePatterns) {
if(tp2 != tp && superClasses.contains(tp2.getObject())) {
triplesPatterns2Remove.add(tp2);
}
}
}
}
// remove triple patterns
triplePatterns.removeAll(triplesPatterns2Remove);
}
}
private Set<Node> getSuperClasses(Node cls){
Set<Node> superClasses = new HashSet<Node>();
superClassesQueryTemplate.setIri("sub", cls.getURI());
String query = superClassesQueryTemplate.toString();
try {
QueryExecution qe = qef.createQueryExecution(query);
ResultSet rs = qe.execSelect();
while(rs.hasNext()){
QuerySolution qs = rs.next();
superClasses.add(qs.getResource("sup").asNode());
}
qe.close();
} catch (Exception e) {
System.out.println(query);
throw e;
}
return superClasses;
}
private int getResultCount(String sparqlQuery){
sparqlQuery = "PREFIX owl: <http://www.w3.org/2002/07/owl#> " + sparqlQuery;
int cnt = 0;
QueryExecution qe = qef.createQueryExecution(sparqlQuery);
ResultSet rs = qe.execSelect();
while(rs.hasNext()){
rs.next();
cnt++;
}
qe.close();
return cnt;
}
private Query rewriteForVirtuosoFloatingPointIssue(Query query){
QueryUtils queryUtils = new QueryUtils();
Set<Triple> triplePatterns = queryUtils.extractTriplePattern(query);
Set<Triple> newTriplePatterns = new TreeSet<>(new Comparator<Triple>() {
@Override
public int compare(Triple o1, Triple o2) {
return ComparisonChain.start().
compare(o1.getSubject().toString(), o2.getSubject().toString()).
compare(o1.getPredicate().toString(), o2.getPredicate().toString()).
compare(o1.getObject().toString(), o2.getObject().toString()).
result();
}
});
List<ElementFilter> filters = new ArrayList<>();
int cnt = 0;
// <s p o>
for (Iterator<Triple> iter = triplePatterns.iterator(); iter.hasNext();) {
Triple tp = iter.next();
if(tp.getObject().isLiteral()){
RDFDatatype dt = tp.getObject().getLiteralDatatype();
if(dt != null && (dt.equals(XSDDatatype.XSDfloat) || dt.equals(XSDDatatype.XSDdouble))){
iter.remove();
// new triple pattern <s p ?var>
Node objectVar = NodeFactory.createVariable("floatVal" + cnt++);
newTriplePatterns.add(Triple.create(
tp.getSubject(),
tp.getPredicate(),
objectVar)
);
// add FILTER(STR(?var) = lexicalform(o))
System.out.println(tp.getObject());
double epsilon = 0.00001;
Expr filterExpr = new E_LessThanOrEqual(
new E_NumAbs(
new E_Subtract(
new ExprVar(objectVar),
NodeValue.makeNode(tp.getObject())
)
),
NodeValue.makeDouble(epsilon)
);
ElementFilter filter = new ElementFilter(filterExpr);
filters.add(filter);
}
}
}
newTriplePatterns.addAll(triplePatterns);
Query q = new Query();
q.addProjectVars(query.getProjectVars());
ElementTriplesBlock tripleBlock = new ElementTriplesBlock();
for (Triple triple : newTriplePatterns) {
tripleBlock.addTriple(triple);
}
ElementGroup eg = new ElementGroup();
eg.addElement(tripleBlock);
for (ElementFilter filter : filters) {
eg.addElementFilter(filter);
}
q.setQuerySelectType();
q.setDistinct(true);
q.setQueryPattern(eg);
return q;
}
private Query rewriteForVirtuosoDateLiteralBug(Query query){
final Query copy = QueryFactory.create(query);
final Element queryPattern = copy.getQueryPattern();
final List<ElementFilter> filters = new ArrayList<>();
ElementWalker.walk(queryPattern, new ElementVisitorBase() {
int cnt = 0;
@Override
public void visit(ElementGroup el) {
super.visit(el);
}
@Override
public void visit(ElementTriplesBlock el) {
Set<Triple> newTriplePatterns = new TreeSet<>(new Comparator<Triple>() {
@Override
public int compare(Triple o1, Triple o2) {
return ComparisonChain.start().compare(o1.getSubject().toString(), o2.getSubject().toString())
.compare(o1.getPredicate().toString(), o2.getPredicate().toString())
.compare(o1.getObject().toString(), o2.getObject().toString()).result();
}
});
Iterator<Triple> iterator = el.patternElts();
while (iterator.hasNext()) {
Triple tp = iterator.next();
if (tp.getObject().isLiteral()) {
RDFDatatype dt = tp.getObject().getLiteralDatatype();
if (dt != null && dt instanceof XSDAbstractDateTimeType) {
iterator.remove();
// new triple pattern <s p ?var>
Node objectVar = NodeFactory.createVariable("date" + cnt++);
newTriplePatterns.add(Triple.create(tp.getSubject(), tp.getPredicate(), objectVar));
String lit = tp.getObject().getLiteralLexicalForm();
Object literalValue = tp.getObject().getLiteralValue();
Expr filterExpr = new E_Equals(new E_Str(new ExprVar(objectVar)), NodeValue.makeString(lit));
if (literalValue instanceof XSDDateTime) {
Calendar calendar = ((XSDDateTime) literalValue).asCalendar();
Date date = new Date(calendar.getTimeInMillis() + TimeUnit.HOURS.toMillis(2));
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
String inActiveDate = format1.format(date);
filterExpr = new E_LogicalOr(filterExpr, new E_Equals(
new E_Str(new ExprVar(objectVar)), NodeValue.makeString(inActiveDate)));
}
ElementFilter filter = new ElementFilter(filterExpr);
filters.add(filter);
}
}
}
for (Triple tp : newTriplePatterns) {
el.addTriple(tp);
}
for (ElementFilter filter : filters) {
((ElementGroup)queryPattern).addElementFilter(filter);
}
}
@Override
public void visit(ElementPathBlock el) {
Set<Triple> newTriplePatterns = new TreeSet<>(new Comparator<Triple>() {
@Override
public int compare(Triple o1, Triple o2) {
return ComparisonChain.start().compare(o1.getSubject().toString(), o2.getSubject().toString())
.compare(o1.getPredicate().toString(), o2.getPredicate().toString())
.compare(o1.getObject().toString(), o2.getObject().toString()).result();
}
});
Iterator<TriplePath> iterator = el.patternElts();
while (iterator.hasNext()) {
Triple tp = iterator.next().asTriple();
if (tp.getObject().isLiteral()) {
RDFDatatype dt = tp.getObject().getLiteralDatatype();
if (dt != null && dt instanceof XSDAbstractDateTimeType) {
iterator.remove();
// new triple pattern <s p ?var>
Node objectVar = NodeFactory.createVariable("date" + cnt++);
newTriplePatterns.add(Triple.create(tp.getSubject(), tp.getPredicate(), objectVar));
String lit = tp.getObject().getLiteralLexicalForm();
Object literalValue = tp.getObject().getLiteralValue();
Expr filterExpr = new E_Equals(new E_Str(new ExprVar(objectVar)), NodeValue.makeString(lit));
if (literalValue instanceof XSDDateTime) {
Calendar calendar = ((XSDDateTime) literalValue).asCalendar();
Date date = new Date(calendar.getTimeInMillis() + TimeUnit.HOURS.toMillis(2));
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
String inActiveDate = format1.format(date);
filterExpr = new E_LogicalOr(filterExpr, new E_Equals(
new E_Str(new ExprVar(objectVar)), NodeValue.makeString(inActiveDate)));
}
ElementFilter filter = new ElementFilter(filterExpr);
filters.add(filter);
}
}
}
for (Triple tp : newTriplePatterns) {
el.addTriple(tp);
}
}
});
for (ElementFilter filter : filters) {
((ElementGroup)queryPattern).addElementFilter(filter);
}
return copy;
}
private Score computeScore(String referenceSparqlQuery, RDFResourceTree tree, double noise) throws Exception{
// apply some filters
QueryTreeUtils.removeVarLeafs(tree);
QueryTreeUtils.prune(tree, null, Entailment.RDF);
String learnedSPARQLQuery = QueryTreeUtils.toSPARQLQueryString(tree, dataset.getBaseIRI(), dataset.getPrefixMapping());
if(QueryUtils.getTriplePatterns(QueryFactory.create(learnedSPARQLQuery)).size() < 25) {
return computeScoreBySparqlCount(referenceSparqlQuery, tree, noise);
}
// get the reference resources
List<String> referenceResources = getResult(referenceSparqlQuery);
if (referenceResources.isEmpty()) {
logger.error("Reference SPARQL query returns no result.\n" + referenceSparqlQuery);
return new Score();
}
// if query is most general one P=|TARGET|/|KB| R=1
if (learnedSPARQLQuery.equals(QueryTreeUtils.EMPTY_QUERY_TREE_QUERY)) {
int tp = referenceResources.size();
int fp = kbSize - tp;
int tn = 0;
int fn = 0;
return score(tp, fp, tn, fn);
}
// get the learned resources
List<String> learnedResources = splitComplexQueries ? getResultSplitted(learnedSPARQLQuery) : getResult(learnedSPARQLQuery);
if (learnedResources.isEmpty()) {
logger.error("Learned SPARQL query returns no result.\n" + learnedSPARQLQuery);
return new Score();
}
// get the overlapping resources
int overlap = Sets.intersection(Sets.newHashSet(referenceResources), Sets.newHashSet(learnedResources)).size();
int tp = overlap;
int fp = Sets.difference(Sets.newHashSet(learnedResources), Sets.newHashSet(referenceResources)).size();
int fn = Sets.difference(Sets.newHashSet(referenceResources), Sets.newHashSet(learnedResources)).size();
int tn = kbSize - tp - fp - fn;
return score(tp, fp, tn, fn);
}
private Score computeScoreBySparqlCount(String referenceSparqlQuery, RDFResourceTree tree, double noise) throws Exception{
String learnedSPARQLQuery = QueryTreeUtils.toSPARQLQueryString(tree, dataset.getBaseIRI(), dataset.getPrefixMapping());
final ExprVar s = new ExprVar("s");
Var cntVar = Var.alloc("cnt");
// Q1
Query q1 = QueryFactory.create(referenceSparqlQuery);
Query q1Count = QueryFactory.create();
q1Count.setQuerySelectType();
q1Count.getProject().add(cntVar, new ExprAggregator(s.asVar(), new AggCountVarDistinct(s)));
q1Count.setQueryPattern(q1.getQueryPattern());
QueryExecution qe = qef.createQueryExecution(q1Count);
ResultSet rs = qe.execSelect();
QuerySolution qs = rs.next();
int referenceCnt = qs.getLiteral(cntVar.getName()).getInt();
qe.close();
// if query is most general one P=|TARGET|/|KB| R=1
if (learnedSPARQLQuery.equals(QueryTreeUtils.EMPTY_QUERY_TREE_QUERY)) {
int tp = referenceCnt;
int fp = kbSize - tp;
int tn = 0;
int fn = 0;
return score(tp, fp, tn, fn);
}
// Q2
Query q2 = QueryFactory.create(learnedSPARQLQuery);
Query q2Count = QueryFactory.create();
q2Count.setQuerySelectType();
q2Count.getProject().add(cntVar, new ExprAggregator(s.asVar(), new AggCountVarDistinct(s)));
q2Count.setQueryPattern(q2.getQueryPattern());
logger.info("Learned query:\n" + q2Count);
q2Count = rewriteForVirtuosoDateLiteralBug(q2Count);
qe = qef.createQueryExecution(q2Count);
rs = qe.execSelect();
qs = rs.next();
int learnedCnt = qs.getLiteral(cntVar.getName()).getInt();
qe.close();
// Q1 ∪ Q2
// if noise = 0 then Q1 ∪ Q2 = Q2
int overlap = Math.min(learnedCnt, referenceCnt);
if(noise > 0) {
Query q12 = QueryFactory.create();
q12.setQuerySelectType();
q12.getProject().add(cntVar, new ExprAggregator(s.asVar(), new AggCountVarDistinct(s)));
ElementGroup whereClause = new ElementGroup();
for (Element el : ((ElementGroup)q1.getQueryPattern()).getElements()) {
whereClause.addElement(el);
}
for (Element el : ((ElementGroup)q2.getQueryPattern()).getElements()) {
whereClause.addElement(el);
}
q12.setQueryPattern(whereClause);
logger.info("Combined query:\n" + q12);
q12 = rewriteForVirtuosoDateLiteralBug(q12);
qe = qef.createQueryExecution(q12);
rs = qe.execSelect();
qs = rs.next();
overlap = qs.getLiteral(cntVar.getName()).getInt();
qe.close();
}
int tp = overlap;
int fp = learnedCnt - overlap;
int fn = referenceCnt - overlap;
int tn = kbSize - tp - fp - fn;
return score(tp, fp, tn, fn);
}
private Score score(int tp, int fp, int tn, int fn) throws Exception {
// P
double precision = (tp == 0 && fp == 0) ? 1.0 : (double) tp / (tp + fp);
// R
double recall = (tp == 0 && fn == 0) ? 1.0 : (double) tp / (tp + fn);
//F_1
double fMeasure = Heuristics.getFScore(recall, precision);
// pred. acc
double predAcc = (tp + tn) / (double)((tp + fn) + (tn + fp));
BigDecimal denominator = BigDecimal.valueOf(tp + fp).
multiply(BigDecimal.valueOf(tp + fn)).
multiply(BigDecimal.valueOf(tn + fp)).
multiply(BigDecimal.valueOf(tn + fn));
// Mathews CC
double mathCorr = denominator.doubleValue() == 0 ? 0 : (tp * tn - fp * fn) / Math.sqrt(denominator.doubleValue());
if(Double.isNaN(predAcc) || Double.isNaN(mathCorr)){
throw new Exception(Double.isNaN(predAcc) ? ("PredAcc") : ("MC") + " not a number.");
}
return new Score(precision, recall, fMeasure, predAcc, mathCorr);
}
private void write2DB(String targetQuery, int nrOfExamples, ExamplesWrapper examples,
double noise, String baseLineQuery, Score baselineScore, String heuristicName, String heuristicMeasure,
String returnedQuery, Score returnedQueryScore, String bestQuery, int bestQueryPosition,
Score bestQueryScore) {
try {
psInsertDetailEval.setString(1, targetQuery);
psInsertDetailEval.setInt(2, nrOfExamples);
psInsertDetailEval.setDouble(3, noise);
psInsertDetailEval.setString(4, heuristicName);
psInsertDetailEval.setString(5, heuristicMeasure);
psInsertDetailEval.setString(6, returnedQuery);
psInsertDetailEval.setDouble(7, returnedQueryScore.fmeasure);
psInsertDetailEval.setDouble(8, returnedQueryScore.precision);
psInsertDetailEval.setDouble(9, returnedQueryScore.recall);
psInsertDetailEval.setString(10, bestQuery);
psInsertDetailEval.setInt(11, bestQueryPosition);
psInsertDetailEval.setDouble(12, bestQueryScore.fmeasure);
psInsertDetailEval.setDouble(13, bestQueryScore.precision);
psInsertDetailEval.setDouble(14, bestQueryScore.recall);
psInsertDetailEval.setString(15, baseLineQuery);
psInsertDetailEval.setDouble(16, baselineScore.fmeasure);
psInsertDetailEval.setDouble(17, baselineScore.precision);
psInsertDetailEval.setDouble(18, baselineScore.recall);
System.out.println(psInsertDetailEval);
psInsertDetailEval.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}
}
private synchronized void write2DB(
String heuristic, String heuristicMeasure, int nrOfExamples, double noise,
double fmeasure, double precision, double recall, double predAcc, double mathCorr,
double bestSolutionPosition, double bestSolutionFmeasure, double bestSolutionPrecision, double bestSolutionRecall, double bestSolutionPredAcc, double bestSolutionMathCorr,
double baselineFmeasure, double baselinePrecision, double baselineRecall, double baselinePredAcc, double baselineMathCorr
) {
try {
psInsertOverallEval.setString(1, heuristic);
psInsertOverallEval.setString(2, heuristicMeasure);
psInsertOverallEval.setInt(3, nrOfExamples);
psInsertOverallEval.setDouble(4, noise);
psInsertOverallEval.setDouble(5, fmeasure);
psInsertOverallEval.setDouble(6, precision);
psInsertOverallEval.setDouble(7, recall);
psInsertOverallEval.setDouble(8, predAcc);
psInsertOverallEval.setDouble(9, mathCorr);
psInsertOverallEval.setDouble(10, bestSolutionPosition);
psInsertOverallEval.setDouble(11, bestSolutionFmeasure);
psInsertOverallEval.setDouble(12, bestSolutionPrecision);
psInsertOverallEval.setDouble(13, bestSolutionRecall);
psInsertOverallEval.setDouble(14, bestSolutionPredAcc);
psInsertOverallEval.setDouble(15, bestSolutionMathCorr);
psInsertOverallEval.setDouble(16, baselineFmeasure);
psInsertOverallEval.setDouble(17, baselinePrecision);
psInsertOverallEval.setDouble(18, baselineRecall);
psInsertOverallEval.setDouble(19, baselinePredAcc);
psInsertOverallEval.setDouble(20, baselineMathCorr);
System.out.println(psInsertOverallEval);
psInsertOverallEval.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception {
ToStringRenderer.getInstance().setRenderer(new DLSyntaxObjectRenderer());
Logger.getLogger(QTLEvaluation.class).addAppender(
new FileAppender(new SimpleLayout(), "log/qtl-qald.log", false));
Logger.getRootLogger().setLevel(Level.INFO);
Logger.getLogger(QTL2Disjunctive.class).setLevel(Level.INFO);
Logger.getLogger(QTLEvaluation.class).setLevel(Level.INFO);
Logger.getLogger(QueryExecutionFactoryCacheEx.class).setLevel(Level.INFO);
if(args.length < 4) {
System.out.println("Usage: QTLEvaluation <path/to/benchmark> <path/to/benchmark-queries> <write2Database> <overrideLocalResults>");
System.exit(0);
}
File benchmarkDirectory = new File(args[0]);
File queries = new File(args[1]);
boolean write2DB = Boolean.valueOf(args[2]);
boolean override = Boolean.valueOf(args[3]);
new QTLEvaluation(new DBpediaEvaluationDataset(), benchmarkDirectory, write2DB, override).run(queries);
// new QALDExperiment(Dataset.BIOMEDICAL).run();
}
class Score {
int tp, fp, tn, fn = 0;
double precision, recall, fmeasure, predAcc, mathCorr = 0;
public Score() {}
public Score(double precision, double recall, double fmeasure, double predAcc, double mathCorr) {
this.precision = precision;
this.recall = recall;
this.fmeasure = fmeasure;
this.predAcc = predAcc;
this.mathCorr = mathCorr;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return String.format("P=%f\nR=%f\nF-score=%f\nPredAcc=%f\nMC=%f", precision, recall, fmeasure, predAcc, mathCorr);
}
}
class NegativeExampleSPARQLQueryGenerator extends ElementVisitorBase{
private boolean inOptionalClause;
private Stack<ElementGroup> parentGroup = new Stack<>();
private QueryUtils triplePatternExtractor = new QueryUtils();
private Triple triple;
Random randomGen = new Random(123);
public List<String> getNegativeExamples(String targetQuery, int size) {
List<String> negExamples = new ArrayList<String>();
// remove triple patterns as long as enough neg examples have been found
Query query = QueryFactory.create(targetQuery);
List<Query> queries = generateQueries(query);
while(negExamples.size() < size && !queries.isEmpty()) {
Query q = queries.remove(0);
q.setLimit(size);
// System.err.println(q);
QueryExecution qe = qef.createQueryExecution(q);
ResultSet rs = qe.execSelect();
while(rs.hasNext()) {
QuerySolution qs = rs.next();
String example = qs.getResource(query.getProjectVars().get(0).getName()).getURI();
negExamples.add(example);
}
qe.close();
}
return negExamples;
}
private ElementFilter getNotExistsFilter(Element el){
return new ElementFilter(new E_NotExists(el));
}
private List<Query> generateQueries(Query query) {
List<Query> queries = new ArrayList<Query>();
// extract paths
Node source = query.getProjectVars().get(0).asNode();
List<List<Triple>> paths = getPaths(new ArrayList<Triple>(), query, source);
int index = 0;
for (List<Triple> path : paths) {
if(path.size() == 1 && path.get(0).getPredicate().equals(RDF.type.asNode())) {
index = paths.indexOf(path);
}
}
List<Triple> path1 = paths.get(index == 0 ? 1 : 0);
List<Triple> typePath = paths.get(index);
// get last tp first
if(path1.size() == 2) {
// remove last edge
ElementGroup eg = new ElementGroup();
ElementTriplesBlock existsBlock = new ElementTriplesBlock();
existsBlock.addTriple(path1.get(0));
existsBlock.addTriple(typePath.get(0));
eg.addElement(existsBlock);
ElementTriplesBlock notExistsBlock = new ElementTriplesBlock();
notExistsBlock.addTriple(path1.get(1));
ElementGroup notExistsGroup = new ElementGroup();
notExistsGroup.addElement(notExistsBlock);
eg.addElementFilter(getNotExistsFilter(notExistsGroup));
Query newQuery = QueryFactory.create();
newQuery.setQuerySelectType();
newQuery.setQueryPattern(eg);
newQuery.addProjectVars(query.getProjectVars());
newQuery.setDistinct(true);
queries.add(newQuery);
//remove both edges
eg = new ElementGroup();
existsBlock = new ElementTriplesBlock();
existsBlock.addTriple(typePath.get(0));
eg.addElement(existsBlock);
notExistsBlock = new ElementTriplesBlock();
notExistsBlock.addTriple(path1.get(0));
notExistsBlock.addTriple(path1.get(1));
notExistsGroup = new ElementGroup();
notExistsGroup.addElement(notExistsBlock);
eg.addElementFilter(getNotExistsFilter(notExistsGroup));
newQuery = QueryFactory.create();
newQuery.setQuerySelectType();
newQuery.setQueryPattern(eg);
newQuery.addProjectVars(query.getProjectVars());
newQuery.setDistinct(true);
queries.add(newQuery);
} else {
//remove both edges
ElementGroup eg = new ElementGroup();
ElementTriplesBlock existsBlock = new ElementTriplesBlock();
existsBlock.addTriple(typePath.get(0));
eg.addElement(existsBlock);
ElementTriplesBlock notExistsBlock = new ElementTriplesBlock();
notExistsBlock.addTriple(path1.get(0));
ElementGroup notExistsGroup = new ElementGroup();
notExistsGroup.addElement(notExistsBlock);
eg.addElementFilter(getNotExistsFilter(notExistsGroup));
Query newQuery = QueryFactory.create();
newQuery.setQuerySelectType();
newQuery.setQueryPattern(eg);
newQuery.addProjectVars(query.getProjectVars());
newQuery.setDistinct(true);
queries.add(newQuery);
}
return queries;
}
private List<List<Triple>> getPaths(List<Triple> path, Query query, Node source) {
List<List<Triple>> paths = new ArrayList<List<Triple>>();
Set<Triple> outgoingTriplePatterns = QueryUtils.getOutgoingTriplePatterns(query, source);
for (Triple tp : outgoingTriplePatterns) {
List<Triple> newPath = new ArrayList<Triple>(path);
newPath.add(tp);
if(tp.getObject().isVariable()) {
paths.addAll(getPaths(newPath, query, tp.getObject()));
} else {
paths.add(newPath);
}
}
return paths;
}
/**
* Returns a modified SPARQL query such that it is similar but different by choosing one of the triple patterns and use
* the negation of its existence.
* @param query
*/
public Query generateSPARQLQuery(Query query){
//choose a random triple for the modification
List<Triple> triplePatterns = new ArrayList<Triple>(triplePatternExtractor.extractTriplePattern(query));
Collections.shuffle(triplePatterns, randomGen);
triple = triplePatterns.get(0);
Query modifiedQuery = query.cloneQuery();
modifiedQuery.getQueryPattern().visit(this);
logger.info("Negative examples query:\n" + modifiedQuery.toString());
return modifiedQuery;
}
@Override
public void visit(ElementGroup el) {
parentGroup.push(el);
for (Iterator<Element> iterator = new ArrayList<Element>(el.getElements()).iterator(); iterator.hasNext();) {
Element e = iterator.next();
e.visit(this);
}
parentGroup.pop();
}
@Override
public void visit(ElementOptional el) {
inOptionalClause = true;
el.getOptionalElement().visit(this);
inOptionalClause = false;
}
@Override
public void visit(ElementTriplesBlock el) {
for (Iterator<Triple> iterator = el.patternElts(); iterator.hasNext();) {
Triple t = iterator.next();
if(inOptionalClause){
} else {
if(t.equals(triple)){
ElementGroup parent = parentGroup.peek();
ElementTriplesBlock elementTriplesBlock = new ElementTriplesBlock();
elementTriplesBlock.addTriple(t);
ElementGroup eg = new ElementGroup();
eg.addElement(elementTriplesBlock);
parent.addElement(new ElementFilter(new E_NotExists(eg)));
iterator.remove();
}
}
}
}
@Override
public void visit(ElementPathBlock el) {
for (Iterator<TriplePath> iterator = el.patternElts(); iterator.hasNext();) {
TriplePath tp = iterator.next();
if(inOptionalClause){
} else {
if(tp.asTriple().equals(triple)){
ElementGroup parent = parentGroup.peek();
ElementPathBlock elementTriplesBlock = new ElementPathBlock();
elementTriplesBlock.addTriple(tp);
ElementGroup eg = new ElementGroup();
eg.addElement(elementTriplesBlock);
parent.addElement(new ElementFilter(new E_NotExists(eg)));
iterator.remove();
}
}
}
}
@Override
public void visit(ElementUnion el) {
for (Iterator<Element> iterator = el.getElements().iterator(); iterator.hasNext();) {
Element e = iterator.next();
e.visit(this);
}
}
@Override
public void visit(ElementFilter el) {
}
}
class ExamplesWrapper {
List<String> correctPosExamples;
List<String> noisePosExamples;
List<String> correctNegExamples;
Map<OWLIndividual, RDFResourceTree> posExamplesMapping;
Map<OWLIndividual, RDFResourceTree> negExamplesMapping;
public ExamplesWrapper(List<String> correctPosExamples, List<String> noisePosExamples,List<String> correctNegExamples,
Map<OWLIndividual, RDFResourceTree> posExamplesMapping, Map<OWLIndividual, RDFResourceTree> negExamplesMapping) {
super();
this.correctPosExamples = correctPosExamples;
this.noisePosExamples = noisePosExamples;
this.correctNegExamples = correctNegExamples;
this.posExamplesMapping = posExamplesMapping;
this.negExamplesMapping = negExamplesMapping;
}
}
}
| gpl-3.0 |
nullfer/nfweixin | src/java/com/myapp/sales/mybatis/mapper/MessageMapper.java | 1463 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.myapp.sales.mybatis.mapper;
import com.myapp.sales.mybatis.entity.EventMsgEntity;
import com.myapp.sales.mybatis.entity.ImgMsgEntity;
import com.myapp.sales.mybatis.entity.LinkMsgEntity;
import com.myapp.sales.mybatis.entity.LocMsgEntity;
import com.myapp.sales.mybatis.entity.MessageEntity;
import com.myapp.sales.mybatis.entity.TxtMsgEntity;
import com.myapp.sales.mybatis.entity.VoiceMsgEntity;
import java.util.List;
/**
*
* @author citysky
*/
public interface MessageMapper {
public void saveMessage(MessageEntity message);
public void saveTxtMessage(TxtMsgEntity message);
public void saveImgMessage(ImgMsgEntity message);
public void saveLinkMessage(LinkMsgEntity message);
public void saveLocationMessage(LocMsgEntity message);
public void saveVoiceMessage(VoiceMsgEntity message);
public void saveEventMessage(EventMsgEntity message);
public MessageEntity getMessage(String msgId);
public List<MessageEntity> getAllMessage();
public List<TxtMsgEntity> getAllTxtMessage();
public TxtMsgEntity getTxtMessage(String msgId);
public void getImgMessage(String msgId);
public void getLinkMessage(String msgId);
public void getLocationMessage(String msgId);
public void getVoiceMessage(String msgId);
public void getEventMessage(String msgId);
}
| gpl-3.0 |
dieuph/index-database-portlet | docroot/WEB-INF/service/vn/edu/ctu/index/database/service/ClpSerializer.java | 7155 | /**
* Copyright (c) 2000-2013 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package vn.edu.ctu.index.database.service;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.io.unsync.UnsyncByteArrayInputStream;
import com.liferay.portal.kernel.io.unsync.UnsyncByteArrayOutputStream;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.util.ClassLoaderObjectInputStream;
import com.liferay.portal.kernel.util.PropsUtil;
import com.liferay.portal.kernel.util.Validator;
import com.liferay.portal.model.BaseModel;
import vn.edu.ctu.index.database.model.EntityClp;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
/**
* @author $author$
*/
public class ClpSerializer {
public static String getServletContextName() {
if (Validator.isNotNull(_servletContextName)) {
return _servletContextName;
}
synchronized (ClpSerializer.class) {
if (Validator.isNotNull(_servletContextName)) {
return _servletContextName;
}
try {
ClassLoader classLoader = ClpSerializer.class.getClassLoader();
Class<?> portletPropsClass = classLoader.loadClass(
"com.liferay.util.portlet.PortletProps");
Method getMethod = portletPropsClass.getMethod("get",
new Class<?>[] { String.class });
String portletPropsServletContextName = (String)getMethod.invoke(null,
"index-database-portlet-deployment-context");
if (Validator.isNotNull(portletPropsServletContextName)) {
_servletContextName = portletPropsServletContextName;
}
}
catch (Throwable t) {
if (_log.isInfoEnabled()) {
_log.info(
"Unable to locate deployment context from portlet properties");
}
}
if (Validator.isNull(_servletContextName)) {
try {
String propsUtilServletContextName = PropsUtil.get(
"index-database-portlet-deployment-context");
if (Validator.isNotNull(propsUtilServletContextName)) {
_servletContextName = propsUtilServletContextName;
}
}
catch (Throwable t) {
if (_log.isInfoEnabled()) {
_log.info(
"Unable to locate deployment context from portal properties");
}
}
}
if (Validator.isNull(_servletContextName)) {
_servletContextName = "index-database-portlet";
}
return _servletContextName;
}
}
public static Object translateInput(BaseModel<?> oldModel) {
Class<?> oldModelClass = oldModel.getClass();
String oldModelClassName = oldModelClass.getName();
if (oldModelClassName.equals(EntityClp.class.getName())) {
return translateInputEntity(oldModel);
}
return oldModel;
}
public static Object translateInput(List<Object> oldList) {
List<Object> newList = new ArrayList<Object>(oldList.size());
for (int i = 0; i < oldList.size(); i++) {
Object curObj = oldList.get(i);
newList.add(translateInput(curObj));
}
return newList;
}
public static Object translateInputEntity(BaseModel<?> oldModel) {
EntityClp oldClpModel = (EntityClp)oldModel;
BaseModel<?> newModel = oldClpModel.getEntityRemoteModel();
newModel.setModelAttributes(oldClpModel.getModelAttributes());
return newModel;
}
public static Object translateInput(Object obj) {
if (obj instanceof BaseModel<?>) {
return translateInput((BaseModel<?>)obj);
}
else if (obj instanceof List<?>) {
return translateInput((List<Object>)obj);
}
else {
return obj;
}
}
public static Object translateOutput(BaseModel<?> oldModel) {
Class<?> oldModelClass = oldModel.getClass();
String oldModelClassName = oldModelClass.getName();
if (oldModelClassName.equals(
"vn.edu.ctu.index.database.model.impl.EntityImpl")) {
return translateOutputEntity(oldModel);
}
return oldModel;
}
public static Object translateOutput(List<Object> oldList) {
List<Object> newList = new ArrayList<Object>(oldList.size());
for (int i = 0; i < oldList.size(); i++) {
Object curObj = oldList.get(i);
newList.add(translateOutput(curObj));
}
return newList;
}
public static Object translateOutput(Object obj) {
if (obj instanceof BaseModel<?>) {
return translateOutput((BaseModel<?>)obj);
}
else if (obj instanceof List<?>) {
return translateOutput((List<Object>)obj);
}
else {
return obj;
}
}
public static Throwable translateThrowable(Throwable throwable) {
if (_useReflectionToTranslateThrowable) {
try {
UnsyncByteArrayOutputStream unsyncByteArrayOutputStream = new UnsyncByteArrayOutputStream();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(unsyncByteArrayOutputStream);
objectOutputStream.writeObject(throwable);
objectOutputStream.flush();
objectOutputStream.close();
UnsyncByteArrayInputStream unsyncByteArrayInputStream = new UnsyncByteArrayInputStream(unsyncByteArrayOutputStream.unsafeGetByteArray(),
0, unsyncByteArrayOutputStream.size());
Thread currentThread = Thread.currentThread();
ClassLoader contextClassLoader = currentThread.getContextClassLoader();
ObjectInputStream objectInputStream = new ClassLoaderObjectInputStream(unsyncByteArrayInputStream,
contextClassLoader);
throwable = (Throwable)objectInputStream.readObject();
objectInputStream.close();
return throwable;
}
catch (SecurityException se) {
if (_log.isInfoEnabled()) {
_log.info("Do not use reflection to translate throwable");
}
_useReflectionToTranslateThrowable = false;
}
catch (Throwable throwable2) {
_log.error(throwable2, throwable2);
return throwable2;
}
}
Class<?> clazz = throwable.getClass();
String className = clazz.getName();
if (className.equals(PortalException.class.getName())) {
return new PortalException();
}
if (className.equals(SystemException.class.getName())) {
return new SystemException();
}
if (className.equals("vn.edu.ctu.index.database.NoSuchEntityException")) {
return new vn.edu.ctu.index.database.NoSuchEntityException();
}
return throwable;
}
public static Object translateOutputEntity(BaseModel<?> oldModel) {
EntityClp newModel = new EntityClp();
newModel.setModelAttributes(oldModel.getModelAttributes());
newModel.setEntityRemoteModel(oldModel);
return newModel;
}
private static Log _log = LogFactoryUtil.getLog(ClpSerializer.class);
private static String _servletContextName;
private static boolean _useReflectionToTranslateThrowable = true;
} | gpl-3.0 |
KaiKikuchi/BetterKits | src/main/java/net/kaikk/mc/betterkits/bukkit/Kit.java | 4051 | package net.kaikk.mc.betterkits.bukkit;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.block.Block;
import org.bukkit.configuration.serialization.ConfigurationSerializable;
import org.bukkit.configuration.serialization.SerializableAs;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.ItemStack;
import net.kaikk.mc.betterkits.common.CommonKit;
@SerializableAs("Kit")
public class Kit extends CommonKit implements InventoryHolder, ConfigurationSerializable {
private Inventory cachedInventory;
private ItemStack[] cachedContents;
private String cachedTitle;
public Kit(String name, String world, int x, int y, int z, int cooldown, List<String> commands) {
super(name, world, x, y, z, cooldown, commands);
}
public Kit(String name, Block block) {
super(name, block.getWorld().getName(), block.getLocation().getBlockX(), block.getLocation().getBlockY(), block.getLocation().getBlockZ(), 0, Collections.emptyList());
}
public Block getBlock() {
return Bukkit.getWorld(this.world).getBlockAt(x, y, z);
}
public Inventory getChestInventory() {
return ((InventoryHolder) this.getBlock().getState()).getInventory();
}
public void give(Player player) {
Map<Integer,ItemStack> map = player.getInventory().addItem(this.getContents());
for (ItemStack is : map.values()) {
player.getWorld().dropItem(player.getLocation(), is);
}
for (String cmd : this.getCommands()) {
try {
Bukkit.dispatchCommand(Bukkit.getConsoleSender(), cmd.replace("%name", player.getName()).replace("%uuid", player.getUniqueId().toString()));
} catch (Throwable e) {
e.printStackTrace();
}
}
}
public void refill(InventoryHolder inventoryHolder) {
inventoryHolder.getInventory().clear();
inventoryHolder.getInventory().addItem(this.getContents());
}
public void openKitPreview(Player player) {
player.openInventory(this.getInventory());
}
public ItemStack[] getContents() {
if (cachedContents == null) {
List<ItemStack> itemStacks = new ArrayList<ItemStack>(this.getChestInventory().getContents().length);
for (ItemStack is : this.getChestInventory().getContents()) {
if (is != null) {
itemStacks.add(is);
}
}
cachedContents = itemStacks.toArray(new ItemStack[itemStacks.size()]);
}
return cachedContents;
}
@Override
public Inventory getInventory() {
if (cachedInventory == null) {
cachedInventory = Bukkit.createInventory(this, this.shortestInventorySize(), this.getCachedTitle());
cachedInventory.addItem(this.getContents());
}
return cachedInventory;
}
public String getCachedTitle() {
if (this.cachedTitle == null) {
this.cachedTitle = ChatColor.translateAlternateColorCodes('&', BetterKits.instance().config().kitTitleFormat.replace("%name", this.getName()));
if (this.cachedTitle.length() > 32) {
this.cachedTitle = this.cachedTitle.substring(0, 32);
}
}
return this.cachedTitle;
}
public int shortestInventorySize() {
return this.getContents().length % 9 == 0 ? this.getContents().length : (((int)(this.getContents().length / 9)) * 9) + 9;
}
public void clearCache() {
cachedInventory = null;
cachedContents = null;
cachedTitle = null;
}
@Override
public Map<String, Object> serialize() {
Map<String, Object> map = new LinkedHashMap<String, Object>();
map.put("name", this.name);
map.put("world", this.world);
map.put("x", this.x);
map.put("y", this.y);
map.put("z", this.z);
map.put("cooldown", this.cooldown);
map.put("commands", this.commands);
return map;
}
@SuppressWarnings("unchecked")
public static Kit deserialize(Map<String, Object> map) {
return new Kit((String)map.get("name"), (String)map.get("world"), (int)map.get("x"), (int)map.get("y"), (int)map.get("z"), (int)map.get("cooldown"), (List<String>)map.get("commands"));
}
}
| gpl-3.0 |
EasyinnovaSL/DPFManager | src/main/java/dpfmanager/shell/modules/messages/messages/JacpExceptionMessage.java | 2072 | /**
* <h1>JacpExceptionMessage.java</h1> <p> This program is free software: you can redistribute it
* and/or modify it under the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any later version; or,
* at your choice, under the terms of the Mozilla Public License, v. 2.0. SPDX GPL-3.0+ or MPL-2.0+.
* </p> <p> This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
* PURPOSE. See the GNU General Public License and the Mozilla Public License for more details. </p>
* <p> You should have received a copy of the GNU General Public License and the Mozilla Public
* License along with this program. If not, see <a href="http://www.gnu.org/licenses/">http://www.gnu.org/licenses/</a>
* and at <a href="http://mozilla.org/MPL/2.0">http://mozilla.org/MPL/2.0</a> . </p> <p> NB: for the
* © statement, include Easy Innova SL or other company/Person contributing the code. </p> <p> ©
* 2015 Easy Innova, SL </p>
*
* @author Adria Llorens
* @version 1.0
* @since 23/7/2015
*/
package dpfmanager.shell.modules.messages.messages;
import dpfmanager.shell.core.DPFManagerProperties;
import dpfmanager.shell.core.messages.DpfMessage;
import java.util.ResourceBundle;
/**
* Created by Adria Llorens on 06/04/2016.
*/
public class JacpExceptionMessage extends DpfMessage {
private String title;
private String header;
private String content;
private Throwable throwable;
public JacpExceptionMessage(Throwable t){
ResourceBundle bundle = DPFManagerProperties.getBundle();
title = bundle.getString("guiException");
header = bundle.getString("guiError");
content = t.getMessage();
throwable = t;
}
public String getTitle(){
return title;
}
public String getHeader(){
return header;
}
public String getContent(){
return content;
}
public Throwable getThrowable(){
return throwable;
}
}
| gpl-3.0 |
lucasgueiros/variados | Registro/src/usuario/Main.java | 939 | package usuario;
import dao.PessoaDAO;
import dominio.Pessoa;
import javax.swing.*;
/**
* Created by lucas on 01/04/16.
*/
public class Main {
PessoaDAO daoPessoa = new PessoaDAO();
public static void main(String [] args) {
new Main().menu();
}
private void menu() {
int option = 0;
do{
option = Integer.parseInt(JOptionPane.showInputDialog("" +
"Escolha uma opção:\n" +
" 1 - Adicionar usuário\n"));
switch (option) {
case 1: daoPessoa.insert(readPessoa()); break;
}
} while(option!=0);
}
public Pessoa readPessoa() {
String nome, cpf, nomeDaMae;
nome = JOptionPane.showInputDialog("Nome");
cpf = JOptionPane.showInputDialog("Cpf");
nomeDaMae = JOptionPane.showInputDialog("Nome da mae");
return new Pessoa(nome,cpf,nomeDaMae);
}
}
| gpl-3.0 |
starlis/EMC-CraftBukkit | src/main/java/org/spigotmc/timings/SpigotTimings.java | 3840 | package org.spigotmc.timings;
import net.minecraft.server.*;
import org.bukkit.plugin.Plugin;
import org.bukkit.scheduler.BukkitTask;
import org.bukkit.craftbukkit.scheduler.CraftTask;
public final class SpigotTimings {
public static final Timing playerListTimer = Timings.ofSafe("Player List");
public static final Timing connectionTimer = Timings.ofSafe("Connection Handler");
public static final Timing tickablesTimer = Timings.ofSafe("Tickables");
public static final Timing schedulerTimer = Timings.ofSafe("Scheduler");
public static final Timing chunkIOTickTimer = Timings.ofSafe("ChunkIOTick");
public static final Timing timeUpdateTimer = Timings.ofSafe("Time Update");
public static final Timing serverCommandTimer = Timings.ofSafe("Server Command");
public static final Timing worldSaveTimer = Timings.ofSafe("World Save");
public static final Timing tickEntityTimer = Timings.ofSafe("## tickEntity");
public static final Timing tickTileEntityTimer = Timings.ofSafe("## tickTileEntity");
public static final Timing processQueueTimer = Timings.ofSafe("processQueue");
public static final Timing playerCommandTimer = Timings.ofSafe("playerCommand");
public static final Timing entityActivationCheckTimer = Timings.ofSafe("entityActivationCheck");
public static final Timing checkIfActiveTimer = Timings.ofSafe("checkIfActive");
public static final Timing antiXrayUpdateTimer = Timings.ofSafe("anti-xray - update");
public static final Timing antiXrayObfuscateTimer = Timings.ofSafe("anti-xray - obfuscate");
private SpigotTimings() {}
/**
* Gets a timer associated with a plugins tasks.
* @param bukkitTask
* @param period
* @return
*/
public static Timing getPluginTaskTimings(BukkitTask bukkitTask, long period) {
if (!bukkitTask.isSync()) {
return null;
}
Plugin plugin;
Runnable task = ((CraftTask) bukkitTask).task;
final Class<? extends Runnable> taskClass = task.getClass();
if (bukkitTask.getOwner() != null) {
plugin = bukkitTask.getOwner();
} else {
plugin = TimingsManager.getPluginByClassloader(taskClass);
}
final String taskname;
if (taskClass.isAnonymousClass()) {
taskname = taskClass.getName();
} else {
taskname = taskClass.getCanonicalName();
}
String name = "Task: " +taskname;
if (period > 0) {
name += " (interval:" + period +")";
} else {
name += " (Single)";
}
if (plugin == null) {
return Timings.ofSafe(null, name, TimingsManager.PLUGIN_GROUP_HANDLER);
}
return Timings.ofSafe(plugin, name);
}
/**
* Get a named timer for the specified entity type to track type specific timings.
* @param entity
* @return
*/
public static Timing getEntityTimings(Entity entity) {
String entityType = entity.getClass().getName();
return Timings.ofSafe("Minecraft", "## tickEntity - " + entityType, tickEntityTimer);
}
/**
* Get a named timer for the specified tile entity type to track type specific timings.
* @param entity
* @return
*/
public static Timing getTileEntityTimings(TileEntity entity) {
String entityType = entity.getClass().getName();
return Timings.ofSafe("Minecraft", "## tickTileEntity - " + entityType, tickTileEntityTimer);
}
public static Timing getCancelTasksTimer() {
return Timings.ofSafe("Cancel Tasks");
}
public static Timing getCancelTasksTimer(Plugin plugin) {
return Timings.ofSafe(plugin, "Cancel Tasks");
}
public static void stopServer() {
TimingsManager.stopServer();
}
}
| gpl-3.0 |
mkodekar/Fennece-Browser | tests/background/junit4/src/org/mozilla/gecko/browserid/test/TestDSACryptoImplementation.java | 5186 | /* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */
package org.mozilla.gecko.browserid.test;
import java.math.BigInteger;
import junit.framework.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mozilla.gecko.browserid.BrowserIDKeyPair;
import org.mozilla.gecko.browserid.DSACryptoImplementation;
import org.mozilla.gecko.sync.ExtendedJSONObject;
import org.robolectric.RobolectricGradleTestRunner;
@RunWith(RobolectricGradleTestRunner.class)
public class TestDSACryptoImplementation {
@Test
public void testToJSONObject() throws Exception {
BigInteger p = new BigInteger("fca682ce8e12caba26efccf7110e526db078b05edecbcd1eb4a208f3ae1617ae01f35b91a47e6df63413c5e12ed0899bcd132acd50d99151bdc43ee737592e17", 16);
BigInteger q = new BigInteger("962eddcc369cba8ebb260ee6b6a126d9346e38c5", 16);
BigInteger g = new BigInteger("678471b27a9cf44ee91a49c5147db1a9aaf244f05a434d6486931d2d14271b9e35030b71fd73da179069b32e2935630e1c2062354d0da20a6c416e50be794ca4", 16);
BigInteger x = new BigInteger("9516d860392003db5a4f168444903265467614db", 16);
BigInteger y = new BigInteger("455152a0e499f5c9d11f9f1868c8b868b1443ca853843226a5a9552dd909b4bdba879acc504acb690df0348d60e63ea37e8c7f075302e0df5bcdc76a383888a0", 16);
BrowserIDKeyPair keyPair = new BrowserIDKeyPair(
DSACryptoImplementation.createPrivateKey(x, p, q, g),
DSACryptoImplementation.createPublicKey(y, p, q, g));
ExtendedJSONObject o = new ExtendedJSONObject("{\"publicKey\":{\"g\":\"678471b27a9cf44ee91a49c5147db1a9aaf244f05a434d6486931d2d14271b9e35030b71fd73da179069b32e2935630e1c2062354d0da20a6c416e50be794ca4\",\"q\":\"962eddcc369cba8ebb260ee6b6a126d9346e38c5\",\"p\":\"fca682ce8e12caba26efccf7110e526db078b05edecbcd1eb4a208f3ae1617ae01f35b91a47e6df63413c5e12ed0899bcd132acd50d99151bdc43ee737592e17\",\"y\":\"455152a0e499f5c9d11f9f1868c8b868b1443ca853843226a5a9552dd909b4bdba879acc504acb690df0348d60e63ea37e8c7f075302e0df5bcdc76a383888a0\",\"algorithm\":\"DS\"},\"privateKey\":{\"g\":\"678471b27a9cf44ee91a49c5147db1a9aaf244f05a434d6486931d2d14271b9e35030b71fd73da179069b32e2935630e1c2062354d0da20a6c416e50be794ca4\",\"q\":\"962eddcc369cba8ebb260ee6b6a126d9346e38c5\",\"p\":\"fca682ce8e12caba26efccf7110e526db078b05edecbcd1eb4a208f3ae1617ae01f35b91a47e6df63413c5e12ed0899bcd132acd50d99151bdc43ee737592e17\",\"x\":\"9516d860392003db5a4f168444903265467614db\",\"algorithm\":\"DS\"}}");
Assert.assertEquals(o.getObject("privateKey"), keyPair.toJSONObject().getObject("privateKey"));
Assert.assertEquals(o.getObject("publicKey"), keyPair.toJSONObject().getObject("publicKey"));
}
@Test
public void testFromJSONObject() throws Exception {
BigInteger p = new BigInteger("fca682ce8e12caba26efccf7110e526db078b05edecbcd1eb4a208f3ae1617ae01f35b91a47e6df63413c5e12ed0899bcd132acd50d99151bdc43ee737592e17", 16);
BigInteger q = new BigInteger("962eddcc369cba8ebb260ee6b6a126d9346e38c5", 16);
BigInteger g = new BigInteger("678471b27a9cf44ee91a49c5147db1a9aaf244f05a434d6486931d2d14271b9e35030b71fd73da179069b32e2935630e1c2062354d0da20a6c416e50be794ca4", 16);
BigInteger x = new BigInteger("9516d860392003db5a4f168444903265467614db", 16);
BigInteger y = new BigInteger("455152a0e499f5c9d11f9f1868c8b868b1443ca853843226a5a9552dd909b4bdba879acc504acb690df0348d60e63ea37e8c7f075302e0df5bcdc76a383888a0", 16);
BrowserIDKeyPair keyPair = new BrowserIDKeyPair(
DSACryptoImplementation.createPrivateKey(x, p, q, g),
DSACryptoImplementation.createPublicKey(y, p, q, g));
ExtendedJSONObject o = new ExtendedJSONObject("{\"publicKey\":{\"g\":\"678471b27a9cf44ee91a49c5147db1a9aaf244f05a434d6486931d2d14271b9e35030b71fd73da179069b32e2935630e1c2062354d0da20a6c416e50be794ca4\",\"q\":\"962eddcc369cba8ebb260ee6b6a126d9346e38c5\",\"p\":\"fca682ce8e12caba26efccf7110e526db078b05edecbcd1eb4a208f3ae1617ae01f35b91a47e6df63413c5e12ed0899bcd132acd50d99151bdc43ee737592e17\",\"y\":\"455152a0e499f5c9d11f9f1868c8b868b1443ca853843226a5a9552dd909b4bdba879acc504acb690df0348d60e63ea37e8c7f075302e0df5bcdc76a383888a0\",\"algorithm\":\"DS\"},\"privateKey\":{\"g\":\"678471b27a9cf44ee91a49c5147db1a9aaf244f05a434d6486931d2d14271b9e35030b71fd73da179069b32e2935630e1c2062354d0da20a6c416e50be794ca4\",\"q\":\"962eddcc369cba8ebb260ee6b6a126d9346e38c5\",\"p\":\"fca682ce8e12caba26efccf7110e526db078b05edecbcd1eb4a208f3ae1617ae01f35b91a47e6df63413c5e12ed0899bcd132acd50d99151bdc43ee737592e17\",\"x\":\"9516d860392003db5a4f168444903265467614db\",\"algorithm\":\"DS\"}}");
Assert.assertEquals(keyPair.getPublic().toJSONObject(), DSACryptoImplementation.createPublicKey(o.getObject("publicKey")).toJSONObject());
Assert.assertEquals(keyPair.getPrivate().toJSONObject(), DSACryptoImplementation.createPrivateKey(o.getObject("privateKey")).toJSONObject());
}
@Test
public void testRoundTrip() throws Exception {
BrowserIDKeyPair keyPair = DSACryptoImplementation.generateKeyPair(512);
ExtendedJSONObject o = keyPair.toJSONObject();
BrowserIDKeyPair keyPair2 = DSACryptoImplementation.fromJSONObject(o);
Assert.assertEquals(o, keyPair2.toJSONObject());
}
}
| mpl-2.0 |
bubulemaster/openjill | open-jill-object-background/src/main/java/org/jill/game/entities/ObjectEntityImpl.java | 7448 | package org.jill.game.entities;
import org.jill.game.entities.obj.player.PalyerActionPerState;
import org.jill.game.entities.obj.player.PlayerAction;
import org.jill.game.entities.obj.util.UtilityObjectEntity;
import org.jill.jn.ObjectItem;
import org.jill.jn.ObjectItemImpl;
import org.jill.openjill.core.api.entities.BackgroundEntity;
import org.jill.openjill.core.api.entities.ObjectEntity;
import org.jill.openjill.core.api.entities.ObjectParam;
import org.jill.openjill.core.api.keyboard.KeyboardLayout;
import org.jill.openjill.core.api.manager.TileManager;
import org.jill.openjill.core.api.message.MessageDispatcher;
import java.awt.*;
import java.awt.image.BufferedImage;
/**
* Background object for catch update/draw/... message
*
* @author Emeric MARTINEAU
*/
public abstract class ObjectEntityImpl extends ObjectItemImpl
implements ObjectEntity {
/**
* Background objects e.g. torches, stalags.
*/
protected static final int F_BACK = 512;
/**
* Fireball kills it (objs).
*/
protected static final int F_FIREBALL = 4096;
/**
* Puts object in foreground.
*/
protected static final int F_FRONT = 128;
/**
* Text inside (objs).
*/
protected static final int F_INSIDE = 64;
/**
* Laser or rock kills it (objs).
*/
protected static final int F_KILLABLE = 2048;
//-- WORK
//-- DON'T wORK OR NOT IMPLEMENTED
/**
* Touch routine? (blocks & objs).
*/
protected static final int F_MSGTOUCH = 8;
/**
* Pad triggers it (objs).
*/
protected static final int F_TRIGGER = 256;
/**
* Is a weapon (objs).
*/
protected static final int F_WEAPON = 16384;
/**
* Max value (in original game -1).
*/
protected static final int MAX_INT_VALUE = -1;
/**
* If object can e write on background and never update (write once,
* kill after create).
*/
protected boolean writeOnBackGround = false;
/**
* Picture manager.
*/
protected TileManager pictureCache;
/**
* If object must be always on screen (like MAP/DEMO).
*/
protected boolean alwaysOnScreen = false;
/**
* To dispatch message for any object in game.
*/
protected MessageDispatcher messageDispatcher;
/**
* True if player object.
*/
protected boolean playerObject = false;
/**
* Remove object out of screen.
*/
private boolean removeOutOfVisibleScreen = false;
/**
* True if checkpoint.
*/
private boolean checkpointObject = false;
/**
* True if object is killable.
*/
private boolean killabgeObject = false;
/**
* Default constructor.
*
* @param objectParam object parameter
*/
@Override
public void init(final ObjectParam objectParam) {
this.pictureCache = objectParam.getPictureCache();
this.messageDispatcher = objectParam.getMessageDispatcher();
final ObjectItem object = objectParam.getObject();
type = object.getType();
x = object.getX();
y = object.getY();
xSpeed = object.getxSpeed();
ySpeed = object.getySpeed();
width = object.getWidth();
height = object.getHeight();
state = object.getState();
subState = object.getSubState();
stateCount = object.getStateCount();
counter = object.getCounter();
flags = object.getFlags();
pointer = object.getPointer();
info1 = object.getInfo1();
zapHold = object.getZapHold();
setStringStackEntry(object.getStringStackEntry());
}
/**
* Write on background.
*
* @return writeOnBackGround
*/
@Override
public final boolean isWriteOnBackGround() {
return writeOnBackGround;
}
/**
* if olways on screen.
*
* @return alwaysOnScreen
*/
@Override
public final boolean isAlwaysOnScreen() {
return alwaysOnScreen;
}
/**
* Call to update.
*/
@Override
public void msgUpdate(KeyboardLayout keyboardLayout) {
// Nothing
}
/**
* Call when player touche object.
*
* @param obj object
*/
@Override
public void msgTouch(final ObjectEntity obj, KeyboardLayout keyboardLayout) {
// Nothing
}
/**
* When weapon kill object or ennemy kill player.
*
* @param sender sender
* @param nbLife number life to decrease
* @param typeOfDeath tyep of death (for player)
*/
@Override
public void msgKill(final ObjectEntity sender,
final int nbLife, final int typeOfDeath) {
// nothing
}
/**
* When background kill object.
*
* @param sender sender
* @param nbLife number life to decrease
* @param typeOfDeath tyep of death (for player)
*/
@Override
public void msgKill(final BackgroundEntity sender,
final int nbLife, final int typeOfDeath) {
// nothing
}
/**
* To know if object is checkpoint.
*
* @return if is chack point
*/
@Override
public final boolean isCheckPoint() {
return checkpointObject;
}
/**
* Setup chackpoint status.
*
* @param checkpoint true if chackpoint
*/
protected final void setCheckPoint(final boolean checkpoint) {
this.checkpointObject = checkpoint;
}
/**
* If player object.
*
* @return true/false
*/
@Override
public final boolean isPlayer() {
return playerObject;
}
/**
* If object is killable.
*
* @return true/false
*/
@Override
public final boolean isKillableObject() {
return killabgeObject;
}
/**
* Killable.
*
* @param killabge killable
*/
protected final void setKillabgeObject(final boolean killabge) {
this.killabgeObject = killabge;
}
@Override
public boolean isRemoveOutOfVisibleScreen() {
return this.removeOutOfVisibleScreen;
}
/**
* Remove object out of screen.
*
* @param remove true to remove
*/
protected final void setRemoveOutOfVisibleScreen(final boolean remove) {
this.removeOutOfVisibleScreen = remove;
}
/**
* If player can fire (with standard method).
*
* @return true/false
*/
@Override
public boolean canFire() {
return PalyerActionPerState.canDo(getState(),
PlayerAction.CANFIRE);
}
/**
* Short way to draw.
*
* @param g2d graphic
* @param img image
* @param x x
* @param y y
*/
protected static void draw(Graphics g2d, Image img, int x, int y) {
UtilityObjectEntity.draw(g2d, img, x, y);
}
/**
* Short way to draw.
*
* @param dest image
* @param src
* @param x x
* @param y y
*/
protected static void drawFromImage(BufferedImage dest, Image src, int x, int y) {
UtilityObjectEntity.drawFromImage(dest, src, x, y);
}
}
| mpl-2.0 |
scauwe/Generic-File-Driver-for-IDM | shim/src/main/java/info/vancauwenberge/filedriver/filestart/ForceCloseJob.java | 2435 | /*******************************************************************************
* Copyright (c) 2007, 2018 Stefaan Van Cauwenberge
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0 (the "License"). If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
* the specific language governing rights and limitations under the License.
*
* The Initial Developer of the Original Code is
* Stefaan Van Cauwenberge. Portions created by
* the Initial Developer are Copyright (C) 2007, 2018 by
* Stefaan Van Cauwenberge. All Rights Reserved.
*
* Contributor(s): none so far.
* Stefaan Van Cauwenberge: Initial API and implementation
*******************************************************************************/
package info.vancauwenberge.filedriver.filestart;
import info.vancauwenberge.filedriver.api.ISubscriberShim;
import info.vancauwenberge.filedriver.exception.WriteException;
import info.vancauwenberge.filedriver.util.TraceLevel;
import info.vancauwenberge.filedriver.util.Util;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import com.novell.nds.dirxml.driver.Trace;
public class ForceCloseJob implements org.quartz.Job{
public static final String JOBMAP_SUBSCRIBER = "callback";
public static final String JOBMAP_BASICNEWFILEDECIDER = "BasicNewFileDecider";
public ForceCloseJob(){
}
public void execute(JobExecutionContext arg0)
throws JobExecutionException {
Trace trace = new Trace("CronJob");
trace.trace("Cron triggered.");
try{
ISubscriberShim subscriberShim = (ISubscriberShim) arg0.getJobDetail().getJobDataMap().get(JOBMAP_SUBSCRIBER);
BasicNewFileDecider master = (BasicNewFileDecider) arg0.getJobDetail().getJobDataMap().get(JOBMAP_BASICNEWFILEDECIDER);
trace.trace("Cron executing");
try{
if (subscriberShim.finishFile())
trace.trace("Closed file due to cron "+master.getCronExpression());
} catch (WriteException e) {
trace.trace("Unable to close file:"+e.getMessage());
Util.printStackTrace(trace, e);
}
}catch (RuntimeException e) {
Util.printStackTrace(trace, e);
throw e;
}
trace.trace("Cron finished.",TraceLevel.TRACE);
}
}
| mpl-2.0 |
sthaiya/muzima-android | app/src/main/java/com/muzima/utils/audio/AudioIntent.java | 10438 | /*
* Copyright (c) The Trustees of Indiana University, Moi University
* and Vanderbilt University Medical Center. All Rights Reserved.
*
* This version of the code is licensed under the MPL 2.0 Open Source license
* with additional health care disclaimer.
* If the user is an entity intending to commercialize any application that uses
* this code in a for-profit venture, please contact the copyright holder.
*/
package com.muzima.utils.audio;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.MediaStore.Audio;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.muzima.R;
import com.muzima.utils.LanguageUtil;
import com.muzima.utils.MediaUtils;
import com.muzima.utils.ThemeUtils;
import java.io.File;
import static com.muzima.utils.Constants.APP_AUDIO_DIR;
public class AudioIntent extends Activity {
public static final String KEY_AUDIO_PATH = "audioPath";
public static final String KEY_AUDIO_CAPTION = "audioCaption";
public static final String KEY_SECTION_NAME = "sectionName";
private final int AUDIO_CHOOSE = 2;
private String AUDIO_FOLDER;
private boolean isNewAudio;
private TextView mNoAudioMessage;
private ImageView mAudioThumbnail;
private EditText mAudioCaption;
private View mAudioPreview;
private View mAudioAcceptContainer;
private View mAudioRecordContainer;
private String mSectionName;
private String mBinaryName;
private String mBinaryDescription;
private final ThemeUtils themeUtils = new ThemeUtils();
private final LanguageUtil languageUtil = new LanguageUtil();
public void onCreate(Bundle savedInstanceState) {
themeUtils.onCreate(this);
languageUtil.onCreate(this);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_audio);
Intent i = getIntent();
String audioPath = i.getStringExtra(KEY_AUDIO_PATH);
mBinaryDescription = i.getStringExtra(KEY_AUDIO_CAPTION);
mSectionName = i.getStringExtra(KEY_SECTION_NAME);
// we are not using formUuid in the media path anymore
AUDIO_FOLDER = APP_AUDIO_DIR;
if (savedInstanceState != null) {
if (savedInstanceState.containsKey(KEY_AUDIO_PATH))
mBinaryName = savedInstanceState.getString(KEY_AUDIO_PATH);
} else {
if (audioPath != null) {
File audio = new File(audioPath);
if (audio.exists())
mBinaryName = audio.getName();
}
}
if (savedInstanceState != null) {
if (savedInstanceState.containsKey(KEY_AUDIO_PATH))
mBinaryName = savedInstanceState.getString(KEY_AUDIO_PATH);
if (savedInstanceState.containsKey(KEY_AUDIO_CAPTION))
mBinaryDescription = savedInstanceState.getString(KEY_AUDIO_CAPTION);
if (savedInstanceState.containsKey(KEY_SECTION_NAME))
mSectionName = savedInstanceState.getString(KEY_SECTION_NAME);
} else {
if (audioPath != null) {
File audio = new File(audioPath);
if (audio.exists()) {
mBinaryName = audio.getName();
isNewAudio = false;
}
}
}
mNoAudioMessage = findViewById(R.id.noAudioMessage);
mAudioPreview = findViewById(R.id.audioPreview);
mAudioCaption = findViewById(R.id.audioCaption);
mAudioThumbnail = findViewById(R.id.audioThumbnail);
mAudioAcceptContainer = findViewById(R.id.audioAcceptContainer);
mAudioRecordContainer = findViewById(R.id.audioRecordContainer);
refreshAudioView();
}
public void acceptAudio(View view) {
String caption = mAudioCaption.getText().toString();
if (caption == null || caption.length() < 1){
Toast.makeText(getApplicationContext(),getString(R.string.hint_audio_caption), Toast.LENGTH_SHORT).show();
return;
}
String audioUri = AUDIO_FOLDER + File.separator + mBinaryName;
if (mBinaryName != null) {
Intent i = new Intent();
i.putExtra(KEY_SECTION_NAME, mSectionName);
i.putExtra(KEY_AUDIO_PATH, audioUri);
i.putExtra(KEY_AUDIO_CAPTION, caption);
setResult(RESULT_OK, i);
}
finish();
}
public void rejectAudio(View view) {
if (isNewAudio)
deleteMedia();
mBinaryName=null;
refreshAudioView();
}
public void recordAudio(View view) {
isNewAudio = true;
Intent i = new Intent(Audio.Media.RECORD_SOUND_ACTION);
i.putExtra(MediaStore.EXTRA_OUTPUT,
Audio.Media.EXTERNAL_CONTENT_URI.toString());
try {
int AUDIO_CAPTURE = 1;
startActivityForResult(i, AUDIO_CAPTURE);
} catch (ActivityNotFoundException e) {
Toast.makeText(this,getString(R.string.error_audio_record_activity_find), Toast.LENGTH_SHORT).show();
}
}
public void chooseAudio(View view) {
isNewAudio = false;
Intent i;
i = new Intent(Intent.ACTION_GET_CONTENT, MediaStore.Audio.Media.EXTERNAL_CONTENT_URI);
i.addCategory(Intent.CATEGORY_OPENABLE);
try {
i.setType("audio/*");
startActivityForResult(i,AUDIO_CHOOSE);
} catch (ActivityNotFoundException e) {
Log.d(getClass().getSimpleName(),e.getMessage(), e);
Toast.makeText(this,getString(R.string.error_audio_chose_activity_find), Toast.LENGTH_SHORT).show();
}
}
public void playAudio(View view) {
Intent i = new Intent("android.intent.action.VIEW");
File f = new File(AUDIO_FOLDER + File.separator + mBinaryName);
i.setDataAndType(Uri.fromFile(f), "audio/*");
try {
startActivity(i);
} catch (ActivityNotFoundException e) {
Toast.makeText(AudioIntent.this,getString(R.string.error_audio_play_activity_find), Toast.LENGTH_SHORT).show();
}
}
private void refreshAudioView() {
if (mBinaryName != null) {
// show preview with thumbnail view
mAudioPreview.setVisibility(View.VISIBLE);
// show accept view
mAudioAcceptContainer.setVisibility(View.VISIBLE);
// show caption view
mAudioCaption.setVisibility(View.VISIBLE);
//hide record view
mAudioRecordContainer.setVisibility(View.GONE);
//hide no message view
mNoAudioMessage.setVisibility(View.GONE);
if (mBinaryDescription != null)
mAudioCaption.setText(mBinaryDescription);
} else {
mAudioThumbnail.setImageBitmap(null);
// hide preview with thumbnail view
mAudioPreview.setVisibility(View.GONE);
// hide accept view
mAudioAcceptContainer.setVisibility(View.GONE);
// hide caption view
mAudioCaption.setVisibility(View.GONE);
//show record view
mAudioRecordContainer.setVisibility(View.VISIBLE);
//show no message view
mNoAudioMessage.setVisibility(View.VISIBLE);
}
}
private void deleteMedia() {
//delete from media provider
int del = MediaUtils.deleteAudioFileFromMediaProvider(this, AUDIO_FOLDER + File.separator + mBinaryName);
Log.i(getClass().getSimpleName(), "Deleted " + del + " rows from media content provider");
}
private void saveAudio(String audioPath) {
if (mBinaryName != null)
deleteMedia();
String extension = audioPath.substring(audioPath.lastIndexOf("."));
String destAudioPath = AUDIO_FOLDER + File.separator + System.currentTimeMillis() + extension;
File source = new File(audioPath);
File newAudio = new File(destAudioPath);
if (MediaUtils.folderExists(AUDIO_FOLDER))
MediaUtils.copyFile(source, newAudio);
if (newAudio.exists())
mBinaryName = newAudio.getName();
else
Log.e(getClass().getSimpleName(), "Inserting Audio file FAILED");
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (intent != null) {
boolean openDocument = false;
if (requestCode == AUDIO_CHOOSE)
openDocument = true;
// get the file path and create a copy in the instance folder
String audioPath = getPathFromUri(intent.getData(), openDocument);
saveAudio(audioPath);
refreshAudioView();
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString(KEY_SECTION_NAME, mSectionName);
outState.putString(KEY_AUDIO_PATH, mBinaryName);
outState.putString(KEY_AUDIO_CAPTION, mBinaryDescription);
}
private String getPathFromUri(Uri uri, boolean isOpenDocument) {
if (uri.toString().startsWith("file"))
return uri.toString().substring(6);
else {
String[] audioProjection = {Audio.Media.DATA };
String audioSelection = null;
Cursor c = null;
try {
if (isOpenDocument) {
String id = uri.getLastPathSegment().split(":")[1];
audioSelection = Audio.Media._ID + "=" + id;
uri = getUri();
}
c = getContentResolver().query(uri, audioProjection, audioSelection, null, null);
int column_index = c.getColumnIndexOrThrow(Audio.Media.DATA);
String audioPath = null;
if (c.getCount() > 0) {
c.moveToFirst();
audioPath = c.getString(column_index);
}
return audioPath;
} finally {
if (c != null)
c.close();
}
}
}
// Get the Uri of Internal/External Storage for Media
private Uri getUri() {
String state = Environment.getExternalStorageState();
if(!state.equalsIgnoreCase(Environment.MEDIA_MOUNTED))
return MediaStore.Audio.Media.INTERNAL_CONTENT_URI;
return MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
}
| mpl-2.0 |
openmrs/openmrs-module-dataintegrityworkflow | api/src/main/java/org/openmrs/module/dataintegrityworkflow/IntegrityRecordComment.java | 1847 | /**
* The contents of this file are subject to the OpenMRS Public License
* Version 1.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://license.openmrs.org
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations
* under the License.
*
* Copyright (C) OpenMRS, LLC. All Rights Reserved.
*/
package org.openmrs.module.dataintegrityworkflow;
import org.openmrs.BaseOpenmrsMetadata;
/**
* @author: harsz89
*/
/**
* Pojo class for keep comment data associate with a workflow record
*/
public class IntegrityRecordComment extends BaseOpenmrsMetadata{
private Integer integrityRecordCommentId;
private IntegrityWorkflowRecord integrityWorkflowRecord;
private String comment;
public Integer getId() {
return this.getIntegrityRecordCommentId();
}
public void setId(Integer integrityRecordCommentId) {
this.setIntegrityRecordCommentId(integrityRecordCommentId);
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public Integer getIntegrityRecordCommentId() {
return integrityRecordCommentId;
}
public void setIntegrityRecordCommentId(Integer integrityRecordCommentId) {
this.integrityRecordCommentId = integrityRecordCommentId;
}
public IntegrityWorkflowRecord getIntegrityWorkflowRecord() {
return integrityWorkflowRecord;
}
public void setIntegrityWorkflowRecord(IntegrityWorkflowRecord integrityWorkflowRecord) {
this.integrityWorkflowRecord = integrityWorkflowRecord;
}
}
| mpl-2.0 |
cFerg/MineJava | src/main/java/minejava/reg/collect/FilteredEntrySetMultimap.java | 1092 | package minejava.reg.collect;
import minejava.reg.util.Map.Entry;
import minejava.reg.util.Set;
import minejava.reg.annotations.GwtCompatible;
import minejava.reg.base.Predicate;
@GwtCompatible
final class FilteredEntrySetMultimap<K, V> extends FilteredEntryMultimap<K, V> implements FilteredSetMultimap<K, V>{
FilteredEntrySetMultimap(SetMultimap<K, V> unfiltered, Predicate<? super Entry<K, V>> predicate){
super(unfiltered, predicate);
}
@Override
public SetMultimap<K, V> unfiltered(){
return (SetMultimap<K, V>) unfiltered;
}
@Override
public Set<V> get(K key){
return (Set<V>) super.get(key);
}
@Override
public Set<V> removeAll(Object key){
return (Set<V>) super.removeAll(key);
}
@Override
public Set<V> replaceValues(K key, Iterable<? extends V> values){
return (Set<V>) super.replaceValues(key, values);
}
@Override
Set<Entry<K, V>> createEntries(){
return Sets.filter(unfiltered().entries(), entryPredicate());
}
@Override
public Set<Entry<K, V>> entries(){
return (Set<Entry<K, V>>) super.entries();
}
} | mpl-2.0 |
ajschult/etomica | etomica-apps/src/main/java/etomica/normalmode/NormalModesMolecular.java | 8144 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package etomica.normalmode;
import java.io.IOException;
import java.io.PrintWriter;
import etomica.api.IBox;
import etomica.api.IMolecule;
import etomica.api.IMoleculeList;
import etomica.api.IPotentialMaster;
import etomica.api.IVector;
import etomica.api.IVectorMutable;
import etomica.atom.AtomPositionCOM;
import etomica.lattice.crystal.Primitive;
import etomica.models.water.SpeciesWater4P;
import etomica.normalmode.LatticeSumMolecularCrystal.AtomicTensorAtomicPair;
import etomica.space.ISpace;
import etomica.space.Tensor;
import etomica.space3d.Tensor3D;
import etomica.spaceNd.TensorND;
/**
* Uses analysis of 2nd derivatives to compute the normal modes for a Bravais lattice with a basis,
* occupied by atoms that interact with a simple, spherically-symmetric soft potential.
*/
public class NormalModesMolecular implements NormalModes {
public NormalModesMolecular(SpeciesWater4P species, boolean waveVectorMethod ,IPotentialMaster potentialMaster,IBox box, int[] nUniyCellsInSupBox, Primitive primitive, int basisDim, AtomicTensorAtomicPair atomicTensorAtomicPair, ISpace space) {
this.waveVectorMethod = waveVectorMethod;
this.space = space;
this.potentialMaster = potentialMaster;
this.box = box;
this.basisDim = basisDim;
this.atomicTensorAtomicPair = atomicTensorAtomicPair;
this.primitive = primitive;
this.nC = nUniyCellsInSupBox;
this.species = species;
}
public void calculateModes() {
int spaceDim = 6;
int eDim = basisDim * spaceDim;
WaveVectorFactorySimple kFactory = new WaveVectorFactorySimple(primitive, space);
kFactory.makeWaveVectors(box);
double[] kCoefficients = kFactory.getCoefficients(); //kCoefficients=0.5 non-deg.; = 1 degenerate twice!
// IVector[] kv = kFactory.getWaveVectors();
// for (int i=0;i<kv.length;i++){
// System.out.println(kv[i]);
// }
// System.exit(0);
Tensor[][] Inertia = new Tensor[basisDim][basisDim];
for(int i=0; i<basisDim; i++) {
for(int j=0; j<basisDim; j++) {
Inertia[i][j] = new TensorND(6);
}
}
IMoleculeList molList = box.getMoleculeList();
Tensor tempTensor = space.makeTensor();
Tensor inertiaTensor = space.makeTensor();
double massH2O = species.getOxygenType().getMass() + 2.0 * species.getHydrogenType().getMass();
AtomPositionCOM comi = new AtomPositionCOM(space);
IVectorMutable drk = space.makeVector();
Tensor identity = new Tensor3D(new double[][] {{1.0,0.0,0.0}, {0.0,1.0,0.0}, {0.0,0.0,1.0}});
for(int i=0; i<basisDim; i++) {
IMolecule moleculei = molList.getMolecule(i);
for(int j=0;j<space.D();j++){ // 4 NOT 3 but that is fine as the mass of M = 0
Inertia[i][i].setComponent(j, j,massH2O);
}
IVectorMutable comPos = (IVectorMutable)comi.position(moleculei);
inertiaTensor.E(0);
for(int j=0; j<moleculei.getChildList().getAtomCount(); j++){
drk.Ev1Mv2(moleculei.getChildList().getAtom(j).getPosition(),comPos);
//System.out.println(drk.dot(drk));
tempTensor.Ev1v2(drk, drk);
tempTensor.TE(-1);
tempTensor.PEa1Tt1(drk.dot(drk), identity);
tempTensor.TE(moleculei.getChildList().getAtom(j).getType().getMass());
inertiaTensor.PE(tempTensor);
}
for(int m=0;m<space.D();m++){
for(int n=0;n<space.D();n++){
Inertia[i][i].setComponent(m+3,n+3,inertiaTensor.component(m, n));
}
}
}
// double[][] arrayM = new double[eDim][eDim];
// outputStream.print("( "+arrayR[n][m]+ " , "+ arrayI[n][m]+" ) ");
String fileM = "M";
try{
PrintWriter outputStreamM = new PrintWriter(fileM);
for(int i=0; i<basisDim; i++) {
for(int alpha=0; alpha<spaceDim; alpha++) {
for(int j=0; j<basisDim; j++) {
for(int beta=0; beta<spaceDim; beta++) {
if(waveVectorMethod == true){
outputStreamM.print("( "+Inertia[i][j].component(alpha, beta)+ " , "+ 0.0 +" ) ");
}else{
outputStreamM.print(Inertia[i][j].component(alpha, beta)+ " ");
}
}
}
outputStreamM.println("");
}
}
outputStreamM.close();
}catch (IOException e) {
throw new RuntimeException(e);
}
summer = new LatticeSumMolecularCrystal(potentialMaster,box,space,basisDim,primitive);
Tensor[][][][] sum = summer.calculateSum(atomicTensorAtomicPair);
double[][] arrayR = new double[eDim][eDim];
double[][] arrayI = new double[eDim][eDim];
for(int k=0; k<kCoefficients.length; k++) {
for(int j=0; j<basisDim; j++) {
for(int jp=0; jp<basisDim; jp++) {
Tensor tensorj_jpR = sum[0][j][jp][k];
Tensor tensorj_jpI = sum[1][j][jp][k];
for(int alpha=0; alpha<spaceDim; alpha++) {
for(int beta=0; beta<spaceDim; beta++) {
double vR = tensorj_jpR.component(alpha, beta);
double vI = tensorj_jpI.component(alpha, beta);
arrayR[spaceDim*j+alpha][spaceDim*jp+beta] = vR; // spaceDim = 6
arrayI[spaceDim*j+alpha][spaceDim*jp+beta] = vI; // spaceDim = 6
}
}
}
}//j
String filek;
if(waveVectorMethod == true){
filek = "D"+nC[0]+nC[1]+nC[2]+k+"_"+kCoefficients[k]+"deg";
}else{
filek = "Dbig"+nC[0]+nC[1]+nC[2];
}
try{
PrintWriter outputStream = new PrintWriter(filek);
for(int n=0;n<eDim;n++){
for(int m=0;m<eDim;m++){
// outputStream.print(String.format("%20.15e%+20.15ei ", arrayR[n][m], arrayI[n][m]));
if(waveVectorMethod == true){
outputStream.print("( "+arrayR[n][m]+ " , "+ arrayI[n][m]+" ) ");
}else{
outputStream.print(arrayR[n][m]+ " ");
}
}
outputStream.println("");
}
outputStream.close();
}catch (IOException e) {
throw new RuntimeException(e);
}
}
}
public void setHarmonicFudge(double newHarmonicFudge) {
// we ignore fudge
}
public void setTemperature(double newTemperature) {
// we ignore temperature
}
public String getFileName() {
return fileName;
}
public void setFileName(String filename) {
this.fileName = filename;
}
@Override
public WaveVectorFactory getWaveVectorFactory() {
return summer.getWaveVectorFactory();
}
@Override
public double[][] getOmegaSquared() {
// TODO Auto-generated method stub
return null;
}
@Override
public double[][][] getEigenvectors() {
// TODO Auto-generated method stub
return null;
}
protected final ISpace space;
private boolean needToCalculateModes;
private String fileName;
protected IBox box;
protected int basisDim;
protected final AtomicTensorAtomicPair atomicTensorAtomicPair;
protected final Primitive primitive;
protected LatticeSumMolecularCrystal summer;
protected IPotentialMaster potentialMaster;
protected final boolean waveVectorMethod;
protected SpeciesWater4P species;
protected int[] nC;
}
| mpl-2.0 |
servinglynk/servinglynk-hmis | client-dedup/src/main/java/com/servinglynk/hmis/warehouse/util/DemoWithXML.java | 6594 | package com.servinglynk.hmis.warehouse.util;
import java.text.DateFormat;
import java.text.Format;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import com.servinglynk.hmis.warehouse.domain.Gender;
import com.servinglynk.hmis.warehouse.domain.Person;
public class DemoWithXML {
private static final String OPENEMPI_HOST = "http://ec2-54-149-78-38.us-west-2.compute.amazonaws.com:8080/openempi-webapp-web-2.2.9/";
public static void main(String args[]) {
RestTemplate restTemplate = new RestTemplate();
String url = OPENEMPI_HOST+"openempi-ws-rest/security-resource/authenticate";
//String requestBody = "{\"username\":\"admin\",\"password\":\"admin\"}";
AuthenticationRequest requestBody = new AuthenticationRequest();
requestBody.setUsername("admin");
requestBody.setPassword("admin");
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<AuthenticationRequest> entity = new HttpEntity<AuthenticationRequest>(requestBody, headers);
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.PUT, entity, String.class);
// check the response, e.g. Location header, Status, and body
response.getHeaders().getLocation();
response.getStatusCode();
String responseBody = response.getBody();
//102243E2A55F9BC337D759EF921BA835
//fa194a0b-2a66-4662-b4fa-3b75d687ae33 568333527 1963-10-26 00:00:00.000000 +00:00:00 Richard Blanco
System.out.println(" SESSION KEY"+responseBody);
headers.setContentType(MediaType.APPLICATION_XML);
headers.set("OPENEMPI_SESSION_KEY", responseBody);
url = OPENEMPI_HOST+"openempi-ws-rest/person-query-resource/findPersonsByAttributes";
//requestBody ="{ \"person\": { \"familyName\": \"Anderson\",\"givenName\": \"John\"}}";
// requestBody = "<person><familyName>Anderson</familyName><givenName>John</givenName><ssn>111111111</ssn></person>";
Person person = new Person();
person.setFamilyName("Blanco");
person.setGivenName("Richard");
person.setSsn("568333527");
person.setDateOfBirth(new Date("1963-10-26"));
// requestBody = "<person><ssn>111111111</ssn></person>";
// Person person = new Person();
// person.setGivenName("John");
// person.setGivenName("Anderson");
HttpEntity<Person> entityHttp = new HttpEntity<Person>(person, headers);
ResponseEntity<Object> responseObject = restTemplate.exchange(url, HttpMethod.POST, entityHttp, Object.class);
LinkedHashMap<Object, Object> persons = (LinkedHashMap<Object, Object>) responseObject.getBody();
List<Person> finalPersons = new ArrayList<Person>();
if( persons.entrySet().size() > 1) {
List<LinkedHashMap<Object, Object>> abcPersons = (ArrayList<LinkedHashMap<Object, Object>>) persons.get("person");
for(LinkedHashMap<Object, Object> linkedPersons : abcPersons) {
// Set<Entry<Object, Object>> entrySet = linkedPersons.entrySet();
// Entry<Object, Object> next = entrySet.iterator().next();
// Object value = next.getValue();
System.out.println("New Person Object------------");
DemoWithXML main = new DemoWithXML();
finalPersons.add(main.hydradePerson(linkedPersons));
}
}else if(persons.entrySet().size() == 1){
LinkedHashMap<Object, Object> abcPersons = (LinkedHashMap<Object, Object>) persons.get("person");
DemoWithXML main = new DemoWithXML();
finalPersons.add(main.hydradePerson(abcPersons));
}
}
private Person hydradePerson(LinkedHashMap<Object, Object> linkedPersons) {
Person person = new Person();
String dob = (String)linkedPersons.get("dateOfBirth");
dob.substring(0, 9);
Format formatter = new SimpleDateFormat("yyyy-MM-dd");
Date date;
try {
date = (Date)((DateFormat) formatter).parse(dob);
person.setDateOfBirth(date);
formatter = new SimpleDateFormat("yyyy-MM-dd");
String s = formatter.format(date);
} catch (ParseException e) {
e.printStackTrace();
}
person.setSsn((String)linkedPersons.get("ssn"));
person.setGivenName((String)linkedPersons.get("givenName"));
person.setFamilyName((String)linkedPersons.get("familyName"));
LinkedHashMap<Object, Object> genderLinkedList = (LinkedHashMap<Object, Object>)linkedPersons.get("gender");
Gender gender = new Gender();
Integer genderCd = Integer.parseInt((String)genderLinkedList.get("genderCd"));
gender.setGenderCd(genderCd);
gender.setGenderCode((String)genderLinkedList.get("genderCode"));
person.setGender(gender);
return person;
}
// }
/*Set<Entry<Object, Object>> entrySet = persons.entrySet();
Entry<Object, Object> next = entrySet.iterator().next();
List<LinkedHashMap<Object, Object>> personsList = (List<LinkedHashMap<Object, Object>>) next.getValue();
// Person finalPerson = personsList.get(0);
LinkedHashMap<Object, Object> finalPersons = (LinkedHashMap<Object, Object>) personsList.get(0);
Person values = (Person) finalPersons.values();
// Person next2 = (Person) values.iterator().next();
System.out.println("Testing:"+values.getGivenName());
// List<LinkedHashMap<Object, Object>> abcPersons = (ArrayList<LinkedHashMap<Object, Object>>) persons.get("person");
//
// LinkedHashMap<Object, Object> finalPersons = (LinkedHashMap<Object, Object>) abcPersons.get(0);
// Person finalPerson =(Person) finalPersons.get("person");
// System.out.println("Testing:"+finalPerson.getGivenName());
System.out.println("Testing:"+responseBody.toString());*/
}
| mpl-2.0 |
Bhamni/openmrs-core | api/src/main/java/org/openmrs/report/ReportDesigner.java | 703 | /**
* The contents of this file are subject to the OpenMRS Public License
* Version 1.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://license.openmrs.org
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations
* under the License.
*
* Copyright (C) OpenMRS, LLC. All Rights Reserved.
*/
package org.openmrs.report;
/**
* @deprecated see reportingcompatibility module
*/
@Deprecated
public interface ReportDesigner {
}
| mpl-2.0 |
diging/giles-eco-giles-web | giles-eco/src/main/java/edu/asu/diging/gilesecosystem/web/core/users/IAdminUserManager.java | 1550 | package edu.asu.diging.gilesecosystem.web.core.users;
import java.util.List;
import org.springframework.security.core.userdetails.UserDetails;
import edu.asu.diging.gilesecosystem.web.core.exceptions.BadPasswordException;
import edu.asu.diging.gilesecosystem.web.core.exceptions.UnauthorizedException;
public interface IAdminUserManager {
/**
* Update password of a admin user. It is assumed that only the admin user
* themselves can update their password. Hence, the old password needs to be provided.
* If it is required to completely reset a password, this should be done
* directly on the server.
* @param username Username of admin user whose password should be changed.
* @param password New Password in plaintext.
* @return true if password was succesfully changed; otherwise false.
* @throws BadPasswordException Thrown if password is empty.
*/
public abstract boolean updatePassword(String username, String oldPassword, String newPassword)
throws BadPasswordException, UnauthorizedException;
/**
* Get all administrators.
* @return
*/
public abstract List<UserDetails> getAdministrators();
/**
* Checks if the provided password is the one stored for the user.
* @param username Username of the administrator to check the password for.
* @param password Password in plain text.
* @return true if password is correct; otherwise false.
*/
public abstract boolean isPasswordValid(String username, String password);
} | mpl-2.0 |
Skelril/Skree | src/main/java/com/skelril/skree/db/schema/tables/Players.java | 3486 | /**
* This class is generated by jOOQ
*/
package com.skelril.skree.db.schema.tables;
import com.skelril.skree.db.schema.Keys;
import com.skelril.skree.db.schema.McDb;
import com.skelril.skree.db.schema.tables.records.PlayersRecord;
import org.jooq.*;
import org.jooq.impl.TableImpl;
import javax.annotation.Generated;
import java.sql.Timestamp;
import java.util.Arrays;
import java.util.List;
/**
* This class is generated by jOOQ.
*/
@Generated(
value = {
"http://www.jooq.org",
"jOOQ version:3.6.0"
},
comments = "This class is generated by jOOQ"
)
@SuppressWarnings({ "all", "unchecked", "rawtypes" })
public class Players extends TableImpl<PlayersRecord> {
private static final long serialVersionUID = 320218677;
/**
* The reference instance of <code>mc_db.players</code>
*/
public static final Players PLAYERS = new Players();
/**
* The class holding records for this type
*/
@Override
public Class<PlayersRecord> getRecordType() {
return PlayersRecord.class;
}
/**
* The column <code>mc_db.players.id</code>.
*/
public final TableField<PlayersRecord, Integer> ID = createField("id", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, "");
/**
* The column <code>mc_db.players.uuid</code>.
*/
public final TableField<PlayersRecord, String> UUID = createField("uuid", org.jooq.impl.SQLDataType.CHAR.length(36).nullable(false), this, "");
/**
* The column <code>mc_db.players.first_login</code>.
*/
public final TableField<PlayersRecord, Timestamp> FIRST_LOGIN = createField("first_login", org.jooq.impl.SQLDataType.TIMESTAMP.nullable(false), this, "");
/**
* The column <code>mc_db.players.last_login</code>.
*/
public final TableField<PlayersRecord, Timestamp> LAST_LOGIN = createField("last_login", org.jooq.impl.SQLDataType.TIMESTAMP.nullable(false), this, "");
/**
* The column <code>mc_db.players.times_played</code>.
*/
public final TableField<PlayersRecord, Integer> TIMES_PLAYED = createField("times_played", org.jooq.impl.SQLDataType.INTEGER.nullable(false).defaulted(true), this, "");
/**
* The column <code>mc_db.players.seconds_played</code>.
*/
public final TableField<PlayersRecord, Integer> SECONDS_PLAYED = createField("seconds_played", org.jooq.impl.SQLDataType.INTEGER.nullable(false).defaulted(true), this, "");
/**
* Create a <code>mc_db.players</code> table reference
*/
public Players() {
this("players", null);
}
/**
* Create an aliased <code>mc_db.players</code> table reference
*/
public Players(String alias) {
this(alias, PLAYERS);
}
private Players(String alias, Table<PlayersRecord> aliased) {
this(alias, aliased, null);
}
private Players(String alias, Table<PlayersRecord> aliased, Field<?>[] parameters) {
super(alias, McDb.MC_DB, aliased, parameters, "");
}
/**
* {@inheritDoc}
*/
@Override
public Identity<PlayersRecord, Integer> getIdentity() {
return Keys.IDENTITY_PLAYERS;
}
/**
* {@inheritDoc}
*/
@Override
public UniqueKey<PlayersRecord> getPrimaryKey() {
return Keys.KEY_PLAYERS_PRIMARY;
}
/**
* {@inheritDoc}
*/
@Override
public List<UniqueKey<PlayersRecord>> getKeys() {
return Arrays.<UniqueKey<PlayersRecord>>asList(Keys.KEY_PLAYERS_PRIMARY, Keys.KEY_PLAYERS_UUID);
}
/**
* {@inheritDoc}
*/
@Override
public Players as(String alias) {
return new Players(alias, this);
}
/**
* Rename this table
*/
public Players rename(String name) {
return new Players(name, null);
}
}
| mpl-2.0 |
yonadev/yona-server | core/src/test/java/nu/yona/server/subscriptions/service/PrivateUserDataMigrationServiceIntegrationTest.java | 6041 | /*******************************************************************************
* Copyright (c) 2016, 2020 Stichting Yona Foundation This Source Code Form is subject to the terms of the Mozilla Public License,
* v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/.
*******************************************************************************/
package nu.yona.server.subscriptions.service;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.core.annotation.Order;
import org.springframework.data.repository.Repository;
import org.springframework.stereotype.Component;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import nu.yona.server.crypto.seckey.CryptoSession;
import nu.yona.server.entities.UserRepositoriesConfiguration;
import nu.yona.server.goals.entities.Goal;
import nu.yona.server.goals.entities.GoalRepository;
import nu.yona.server.messaging.entities.MessageSource;
import nu.yona.server.messaging.entities.MessageSourceRepository;
import nu.yona.server.messaging.service.MessageService;
import nu.yona.server.subscriptions.entities.User;
import nu.yona.server.subscriptions.service.PrivateUserDataMigrationService.MigrationStep;
import nu.yona.server.test.util.BaseSpringIntegrationTest;
import nu.yona.server.test.util.JUnitUtil;
import nu.yona.server.util.HibernateHelperService;
import nu.yona.server.util.LockPool;
@Configuration
@ComponentScan(useDefaultFilters = false, basePackages = { "nu.yona.server.subscriptions.service",
"nu.yona.server.properties" }, includeFilters = {
@ComponentScan.Filter(pattern = "nu.yona.server.subscriptions.service.User.*Service", type = FilterType.REGEX),
@ComponentScan.Filter(pattern = "nu.yona.server.subscriptions.service.PrivateUserDataMigrationService", type = FilterType.REGEX),
@ComponentScan.Filter(pattern = "nu.yona.server.properties.YonaProperties", type = FilterType.REGEX),
@ComponentScan.Filter(pattern = "nu.yona.server.subscriptions.service.MockMigrationStep1", type = FilterType.REGEX),
@ComponentScan.Filter(pattern = "nu.yona.server.subscriptions.service.MockMigrationStep2", type = FilterType.REGEX) }, excludeFilters = {
@ComponentScan.Filter(pattern = "nu.yona.server.subscriptions.service.UserPhotoService", type = FilterType.REGEX) })
class PrivateUserDataMigrationServiceIntegrationTestConfiguration extends UserRepositoriesConfiguration
{
}
@Component
@Order(0)
class MockMigrationStep1 implements MigrationStep
{
@Override
public void upgrade(User userEntity)
{
userEntity.setFirstName(userEntity.getFirstName() + "foo");
}
}
@Component
@Order(1)
class MockMigrationStep2 implements MigrationStep
{
@Override
public void upgrade(User userEntity)
{
userEntity.setFirstName(userEntity.getFirstName() + "bar");
}
}
@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = { PrivateUserDataMigrationServiceIntegrationTestConfiguration.class })
public class PrivateUserDataMigrationServiceIntegrationTest extends BaseSpringIntegrationTest
{
@MockBean
private BuddyService buddyService;
@MockBean
private MessageService messageService;
@MockBean
private GoalRepository mockGoalRepository;
@MockBean
private MessageSourceRepository mockMessageSourceRepository;
@MockBean
private UserAnonymizedService mockUserAnonymizedService;
@MockBean
private LockPool<UUID> mockUserSynchronizer;
@Autowired
private PrivateUserDataMigrationService service;
@MockBean
private HibernateHelperService hibernateHelperService;
@Autowired
private UserService userService;
private final static String PASSWORD = "password";
private User richard;
@BeforeEach
public void setUpPerTest()
{
try (CryptoSession cryptoSession = CryptoSession.start(PASSWORD))
{
richard = JUnitUtil.createRichard();
}
reset(userRepository);
}
@Override
protected Map<Class<?>, Repository<?, ?>> getRepositories()
{
Map<Class<?>, Repository<?, ?>> repositoriesMap = new HashMap<>();
repositoriesMap.put(MessageSource.class, mockMessageSourceRepository);
repositoriesMap.put(Goal.class, mockGoalRepository);
return repositoriesMap;
}
@Test
public void doPreparationsAndCheckCanAccessPrivateData_twoVersionsBehind_migratesToCurrentVersion()
{
richard.setPrivateDataMigrationVersion(0);
try (CryptoSession cryptoSession = CryptoSession.start(PASSWORD))
{
userService.doPreparationsAndCheckCanAccessPrivateData(richard.getId());
ArgumentCaptor<User> userCaptor = ArgumentCaptor.forClass(User.class);
verify(userRepository, times(1)).save(userCaptor.capture());
assertThat(userCaptor.getValue().getFirstName(), equalTo("Richardfoobar"));
assertThat(userCaptor.getValue().getPrivateDataMigrationVersion(), equalTo(service.getCurrentVersion()));
}
}
@Test
public void doPreparationsAndCheckCanAccessPrivateData_upToDate_saveNotCalled()
{
richard.setPrivateDataMigrationVersion(2);
try (CryptoSession cryptoSession = CryptoSession.start(PASSWORD))
{
userService.doPreparationsAndCheckCanAccessPrivateData(richard.getId());
verify(userRepository, never()).save(any(User.class));
}
}
}
| mpl-2.0 |
jembi/openhim-encounter-orchestrator | src/main/java/org/hl7/v3/ActRelationshipTemporallyPertains.java | 779 |
package org.hl7.v3;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for ActRelationshipTemporallyPertains.
*
* <p>The following schema fragment specifies the expected content contained within this class.
* <p>
* <pre>
* <simpleType name="ActRelationshipTemporallyPertains">
* <restriction base="{urn:hl7-org:v3}cs">
* <enumeration value="SAS"/>
* </restriction>
* </simpleType>
* </pre>
*
*/
@XmlType(name = "ActRelationshipTemporallyPertains")
@XmlEnum
public enum ActRelationshipTemporallyPertains {
SAS;
public String value() {
return name();
}
public static ActRelationshipTemporallyPertains fromValue(String v) {
return valueOf(v);
}
}
| mpl-2.0 |
SimpleQueryProtocol/sqp | src/main/java/io/sqp/core/MessageDecoder.java | 2473 | /*
* Copyright 2015 by Rothmeyer Consulting (http://www.rothmeyer.com/)
* Author: Stefan Burnicki <stefan.burnicki@burnicki.net>
*
* This file is part of SQP.
*
* SQP is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License.
*
* SQP is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with SQP. If not, see <http://www.gnu.org/licenses/>.
*/
package io.sqp.core;
import io.sqp.core.exceptions.DecodingException;
import io.sqp.core.messages.MessageType;
import io.sqp.core.messages.SqpMessage;
import java.io.InputStream;
import java.io.Reader;
/**
* Interface for decoding a SQP message from a stream.
* @author Stefan Burnicki
* @see MessageEncoder
* @see SqpMessage
* @see DataFormat
* @see MessageType
*/
public interface MessageDecoder {
/**
* Decodes a message like {@link #decode(DataFormat, InputStream)} but the message type is passed explicitly,
* and the message id must not be part of the input stream.
* @param type The type of the message
* @param format The format of the message
* @param stream The encoded content of the message, without the type id as first byte
* @return The decoded message
* @throws DecodingException
*/
SqpMessage decode(MessageType type, DataFormat format, InputStream stream) throws DecodingException;
/**
* Decodes any {@link SqpMessage} in a given format from an input stream.
* @param format The format of the message
* @param stream The stream with the encoded message. The message id as the first byte, then the content
* @return The decoded message
* @throws DecodingException
* @see MessageType
*/
SqpMessage decode(DataFormat format, InputStream stream) throws DecodingException;
/**
* Decodes a {@link SqpMessage} in text format.
* @param message The encoded message, with the first character being the message id
* @return The decoded message
* @throws DecodingException
* @see MessageType
*/
SqpMessage decode(Reader message) throws DecodingException;
}
| agpl-3.0 |
xionghuiCoder/db4o | src/main/java/com/db4o/foundation/NotImplementedException.java | 1012 | /* This file is part of the db4o object database http://www.db4o.com
Copyright (C) 2004 - 2011 Versant Corporation http://www.versant.com
db4o is free software; you can redistribute it and/or modify it under
the terms of version 3 of the GNU General Public License as published
by the Free Software Foundation.
db4o is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License along
with this program. If not, see http://www.gnu.org/licenses/. */
package com.db4o.foundation;
/**
* @exclude
* @sharpen.ignore
* @sharpen.rename System.NotImplementedException
*/
public class NotImplementedException extends RuntimeException {
public NotImplementedException() {
super();
}
public NotImplementedException(String msg) {
super(msg);
}
}
| agpl-3.0 |
see-r/SeerDataCruncher | src/test/java/com/datacruncher/schema/SchemaEditTest.java | 3001 | /*
* DataCruncher
* Copyright (c) Mario Altimari. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.datacruncher.schema;
import static org.junit.Assert.assertTrue;
import com.datacruncher.jpa.Update;
import com.datacruncher.jpa.dao.DaoSet;
import com.datacruncher.jpa.dao.SchemasDao;
import com.datacruncher.jpa.entity.SchemaEntity;
import java.io.InputStream;
import java.util.Calendar;
import java.util.List;
import java.util.Properties;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
/**
*
* @author KGandhi
* This junit test class updates the schema.
* It will update startdate, enddate and description fields of the schema.
*/
@ContextConfiguration("classpath:test-config.xml")
public class SchemaEditTest extends AbstractJUnit4SpringContextTests implements DaoSet {
private Properties properties;
@Autowired
ApplicationContext ctx;
private SchemasDao schemasDao;
@Before
public void setUp() throws Exception {
schemasDao = (SchemasDao) ctx.getBean("SchemasDao");
properties = new Properties();
InputStream in = this.getClass().getClassLoader().getResourceAsStream("test.properties");
try {
properties.load(in);
} catch (Exception e) {
assertTrue("Failed in loading test.properties file",false);
}
}
@After
public void tearDown() throws Exception {
}
@Test
public void testEditSchema() {
String schemaName = properties.getProperty("schemaname");
List<SchemaEntity> listSchemaEntity = schemasDao.findByName(schemaName);
if(listSchemaEntity == null || listSchemaEntity.size() == 0) {
assertTrue("Schema record not found", false);
return;
}
SchemaEntity schemaEntity = listSchemaEntity.get(0);
Calendar now = Calendar.getInstance();
schemaEntity.setStartDate(now.getTime());
now.add(Calendar.MONTH, 1);
schemaEntity.setEndDate(now.getTime());
schemaEntity.setDescription(properties.getProperty("schemadesc"));
Update update = schemasDao.update(schemaEntity);
assertTrue(update.getMessage(),update.isSuccess());
}
}
| agpl-3.0 |
jankotek/asterope | aladin/cds/allsky/BuilderMocIndex.java | 1116 | // Copyright 2010 - UDS/CNRS
// The Aladin program is distributed under the terms
// of the GNU General Public License version 3.
//
// This file is part of Aladin.
//
// Aladin is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, version 3 of the License.
//
// Aladin is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// The GNU General Public License is available in COPYING file
// along with Aladin.
//
package cds.allsky;
/** Création d'un fichier Moc.fits correspondant à l'index HEALpix
* @author Anaïs Oberto [CDS] & Pierre Fernique [CDS]
*/
public class BuilderMocIndex extends BuilderMoc {
public BuilderMocIndex(Context context) { super(context); }
public void run() throws Exception {
createMoc(context.getHpxFinderPath());
}
public Action getAction() { return Action.MOCINDEX; }
}
| agpl-3.0 |
nmpgaspar/PainlessProActive | src/Core/org/objectweb/proactive/core/event/BodyEvent.java | 2633 | /*
* ################################################################
*
* ProActive Parallel Suite(TM): The Java(TM) library for
* Parallel, Distributed, Multi-Core Computing for
* Enterprise Grids & Clouds
*
* Copyright (C) 1997-2012 INRIA/University of
* Nice-Sophia Antipolis/ActiveEon
* Contact: proactive@ow2.org or contact@activeeon.com
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License
* as published by the Free Software Foundation; version 3 of
* the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*
* If needed, contact us to obtain a release under GPL Version 2 or 3
* or a different license than the AGPL.
*
* Initial developer(s): The ProActive Team
* http://proactive.inria.fr/team_members.htm
* Contributor(s):
*
* ################################################################
* $$PROACTIVE_INITIAL_DEV$$
*/
package org.objectweb.proactive.core.event;
import org.objectweb.proactive.core.body.UniversalBody;
/**
* <p>
* Event sent when a body get created, destroyed or changed.
* </p>
*
* @author The ProActive Team
* @version 1.0, 2001/10/23
* @since ProActive 0.9
*
*/
public class BodyEvent extends ProActiveEvent implements java.io.Serializable {
private static final long serialVersionUID = 54L;
/** constant for the creation of a body */
public static final int BODY_CREATED = 10;
/** constant for the deletion of a body */
public static final int BODY_DESTROYED = 20;
/** constant for the changed of a body */
public static final int BODY_CHANGED = 30;
/**
* Creates a new <code>BodyEvent</code>
* @param body the body created or deleted
* @param messageType the type of the event either BODY_CREATED or BODY_DESTROYED
*/
public BodyEvent(UniversalBody body, int messageType) {
super(body, messageType);
}
/**
* Returns the body associated to this event
* @return the body associated to this event
*/
public UniversalBody getBody() {
return (UniversalBody) getSource();
}
}
| agpl-3.0 |
EaglesoftZJ/actor-platform | actor-sdk/sdk-core/core/core-shared/src/main/java/im/actor/core/api/rpc/RequestMessageSearch.java | 2314 | package im.actor.core.api.rpc;
/*
* Generated by the Actor API Scheme generator. DO NOT EDIT!
*/
import im.actor.runtime.bser.*;
import im.actor.runtime.collections.*;
import static im.actor.runtime.bser.Utils.*;
import im.actor.core.network.parser.*;
import androidx.annotation.Nullable;
import org.jetbrains.annotations.NotNull;
import com.google.j2objc.annotations.ObjectiveCName;
import java.io.IOException;
import java.util.List;
import java.util.ArrayList;
import im.actor.core.api.*;
public class RequestMessageSearch extends Request<ResponseMessageSearchResponse> {
public static final int HEADER = 0xd9;
public static RequestMessageSearch fromBytes(byte[] data) throws IOException {
return Bser.parse(new RequestMessageSearch(), data);
}
private ApiSearchCondition query;
private List<ApiUpdateOptimization> optimizations;
public RequestMessageSearch(@NotNull ApiSearchCondition query, @NotNull List<ApiUpdateOptimization> optimizations) {
this.query = query;
this.optimizations = optimizations;
}
public RequestMessageSearch() {
}
@NotNull
public ApiSearchCondition getQuery() {
return this.query;
}
@NotNull
public List<ApiUpdateOptimization> getOptimizations() {
return this.optimizations;
}
@Override
public void parse(BserValues values) throws IOException {
this.query = ApiSearchCondition.fromBytes(values.getBytes(1));
this.optimizations = new ArrayList<ApiUpdateOptimization>();
for (int b : values.getRepeatedInt(2)) {
optimizations.add(ApiUpdateOptimization.parse(b));
}
}
@Override
public void serialize(BserWriter writer) throws IOException {
if (this.query == null) {
throw new IOException();
}
writer.writeBytes(1, this.query.buildContainer());
for (ApiUpdateOptimization i : this.optimizations) {
writer.writeInt(2, i.getValue());
}
}
@Override
public String toString() {
String res = "rpc MessageSearch{";
res += "query=" + this.query;
res += ", optimizations=" + this.optimizations;
res += "}";
return res;
}
@Override
public int getHeaderKey() {
return HEADER;
}
}
| agpl-3.0 |
MCPhoton/Photon-MC1.8 | src/org/mcphoton/security/PermissionSetting.java | 3243 | /*
* Copyright (C) 2015 ElectronWill
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General
* Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any
* later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*/
package org.mcphoton.security;
import java.util.Objects;
/**
* An permission setting that contains several informations:
* <ol>
* <li>The permission's name</li>
* <li>If it is granted or denied</li>
* <li>Who/What set the permission</li>
*
* @author ElectronWill
*/
public class PermissionSetting {
private final String permission;
private volatile boolean granted;
private final Object source;
/**
* Creates a new PermissionSetting.
*
* @param permission permission's name
* @param granted true if the permission is granted, false if it's denied
* @param source source of this attachment. You should use the <b>this</b> keyword.
*/
public PermissionSetting(String permission, boolean granted, Object source) {
this.permission = permission;
this.granted = granted;
this.source = source;
}
/**
* Create a new PermissionSetting which grants the permission (granted = true).
*
* @param permission permission's name
* @param source source of this attachment. You should use the <b>this</b> keyword.
*/
public PermissionSetting(String permission, Object source) {
this.permission = permission;
this.granted = true;
this.source = source;
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof PermissionSetting)) {
return false;
}
PermissionSetting attachment = (PermissionSetting) obj;
return attachment.permission.equals(permission) && attachment.source.equals(source);
}
@Override
public int hashCode() {
int hash = 3;
hash = 67 * hash + Objects.hashCode(this.permission);
hash = 67 * hash + Objects.hashCode(this.source);
return hash;
}
/**
* Checks if this permssion is explicitly granted.
*/
public boolean isGranted() {
return granted;
}
/**
* Checks if this attachment's permission is equals to the given one.
*/
public boolean permEquals(String s) {
return permission.equals(s);
}
/**
* Gets the permission's name.
*/
public String permission() {
return permission;
}
/**
* Returns {@code permission().split("\\.")}.
*/
public String[] permParts() {
return permission.split("\\.");
}
/**
* Sets if this permission is granted (true) or denied (false).
*
* @param granted true if this permission should be granted, false if it should be denied.
*/
public void setGranted(boolean granted) {
this.granted = granted;
}
/**
* Gets the object who "created" this PermissionSetting.
*/
public Object source() {
return source;
}
}
| agpl-3.0 |
backslash47/jzkit | jzkit_core/src/main/java/org/jzkit/search/util/QueryFormatter/QueryFormatter.java | 705 | /**
* Title: QueryFormatter
* Copyright: Copyright (C) 2001- Knowledge Integration Ltd.
* @author: Ian Ibbotson (ian.ibbotson@k-int.com)
* Company: Knowledge Integration Ltd.
*/
package org.jzkit.search.util.QueryFormatter;
import org.jzkit.search.util.QueryModel.Internal.InternalModelRootNode;
import org.springframework.context.ApplicationContext;
import org.jzkit.search.util.QueryModel.QueryModel;
/**
* @author Ian Ibbotson
* @version $Id: QueryModel.java,v 1.2 2004/11/18 14:25:54 ibbo Exp $
* A QueryFormatter turns a query model into a string.
*/
public interface QueryFormatter {
public String format(InternalModelRootNode query) throws QueryFormatterException;
}
| agpl-3.0 |
FullMetal210/milton2 | milton-server/src/main/java/io/milton/http/http11/DefaultCacheControlHelper.java | 2475 | /*
* Copyright 2012 McEvoy Software Ltd.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package io.milton.http.http11;
import io.milton.http.Auth;
import io.milton.resource.GetableResource;
import io.milton.http.Response;
import java.util.Date;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* @author brad
*/
public class DefaultCacheControlHelper implements CacheControlHelper {
private static final Logger log = LoggerFactory.getLogger( DefaultCacheControlHelper.class );
private boolean usePrivateCache = false;
@Override
public void setCacheControl( final GetableResource resource, final Response response, Auth auth ) {
Long delta = resource.getMaxAgeSeconds( auth );
if( log.isTraceEnabled() ) {
log.trace( "setCacheControl: " + delta + " - " + resource.getClass() );
}
if( delta != null && delta > 0 ) {
if( usePrivateCache && auth != null ) {
response.setCacheControlPrivateMaxAgeHeader( delta );
//response.setCacheControlMaxAgeHeader(delta);
} else {
response.setCacheControlMaxAgeHeader( delta );
}
// Disable, might be interfering with IE.. ?
// Date expiresAt = calcExpiresAt( new Date(), delta.longValue() );
// if( log.isTraceEnabled() ) {
// log.trace( "set expires: " + expiresAt );
// }
// response.setExpiresHeader( expiresAt );
} else {
response.setCacheControlNoCacheHeader();
}
}
public static Date calcExpiresAt( Date modifiedDate, long deltaSeconds ) {
long deltaMs = deltaSeconds * 1000;
long expiresAt = System.currentTimeMillis() + deltaMs;
return new Date( expiresAt );
}
}
| agpl-3.0 |
sergiomt/zesped | src/java/com/zesped/model/Document.java | 991 | package com.zesped.model;
import es.ipsa.atril.doc.user.DataType;
public class Document extends BaseModelObject {
private static final long serialVersionUID = 1L;
private static final Attr[] aAttrs = new Attr[]{
new Attr("amount",DataType.NUMBER,false,false,null),
new Attr("cheque_account",DataType.STRING,false,false,null),
new Attr("cheque_number",DataType.STRING,false,false,null),
new Attr("codeline",DataType.STRING,false,false,null),
new Attr("endorsement",DataType.STRING,false,false,null),
new Attr("incident_cause",DataType.STRING,false,false,null),
new Attr("issue",DataType.STRING,false,false,null),
new Attr("observations",DataType.STRING,false,false,null),
new Attr("status_bo",DataType.STRING,false,false,null),
new Attr("transit_route",DataType.STRING,false,false,null)
};
public Document() {
super("Document");
}
@Override
public Attr[] attributes() {
return aAttrs;
}
}
| agpl-3.0 |
opensourceBIM/BIMserver | PluginBase/generated/org/bimserver/models/ifc4/impl/IfcElectricMotorImpl.java | 3660 | /**
* Copyright (C) 2009-2014 BIMserver.org
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.bimserver.models.ifc4.impl;
/******************************************************************************
* Copyright (C) 2009-2019 BIMserver.org
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see {@literal<http://www.gnu.org/licenses/>}.
*****************************************************************************/
import org.bimserver.models.ifc4.Ifc4Package;
import org.bimserver.models.ifc4.IfcElectricMotor;
import org.bimserver.models.ifc4.IfcElectricMotorTypeEnum;
import org.eclipse.emf.ecore.EClass;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Ifc Electric Motor</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* </p>
* <ul>
* <li>{@link org.bimserver.models.ifc4.impl.IfcElectricMotorImpl#getPredefinedType <em>Predefined Type</em>}</li>
* </ul>
*
* @generated
*/
public class IfcElectricMotorImpl extends IfcEnergyConversionDeviceImpl implements IfcElectricMotor {
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected IfcElectricMotorImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return Ifc4Package.Literals.IFC_ELECTRIC_MOTOR;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public IfcElectricMotorTypeEnum getPredefinedType() {
return (IfcElectricMotorTypeEnum) eGet(Ifc4Package.Literals.IFC_ELECTRIC_MOTOR__PREDEFINED_TYPE, true);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void setPredefinedType(IfcElectricMotorTypeEnum newPredefinedType) {
eSet(Ifc4Package.Literals.IFC_ELECTRIC_MOTOR__PREDEFINED_TYPE, newPredefinedType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void unsetPredefinedType() {
eUnset(Ifc4Package.Literals.IFC_ELECTRIC_MOTOR__PREDEFINED_TYPE);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean isSetPredefinedType() {
return eIsSet(Ifc4Package.Literals.IFC_ELECTRIC_MOTOR__PREDEFINED_TYPE);
}
} //IfcElectricMotorImpl
| agpl-3.0 |
gnosygnu/xowa_android | _400_xowa/src/main/java/gplx/core/ios/Io_buffer_rdr.java | 2471 | package gplx.core.ios; import gplx.*; import gplx.core.*;
import gplx.core.ios.streams.*;/*IoStream*/
public class Io_buffer_rdr implements Rls_able {
private Io_stream_rdr rdr;
Io_buffer_rdr(Io_stream_rdr rdr, Io_url url, int bfr_len) {
this.rdr = rdr; this.url = url;
if (bfr_len <= 0) throw Err_.new_wo_type("bfr_len must be > 0", "bfr_len", bfr_len);
bfr = new byte[bfr_len]; this.bfr_len = bfr_len;
IoItmFil fil = Io_mgr.Instance.QueryFil(url); if (!fil.Exists()) throw Err_.new_wo_type("fil does not exist", "url", url);
fil_len = fil.Size();
fil_pos = 0;
fil_eof = false;
}
public Io_url Url() {return url;} private Io_url url;
public byte[] Bfr() {return bfr;} private byte[] bfr;
public int Bfr_len() {return bfr_len;} private int bfr_len;
public long Fil_len() {return fil_len;} long fil_len;
public long Fil_pos() {return fil_pos;} long fil_pos;
public boolean Fil_eof() {return fil_eof;} private boolean fil_eof;
public boolean Bfr_load_all() {return Bfr_load(0, bfr_len);}
public boolean Bfr_load_from(int bfr_pos) {
if (bfr_pos < 0 || bfr_pos > bfr_len) throw Err_.new_wo_type("invalid bfr_pos", "bfr_pos", bfr_pos, "bfr_len", bfr_len);
for (int i = bfr_pos; i < bfr_len; i++) // shift end of bfr to bgn; EX: bfr[10] and load_from(8); [8] -> [0]; [9] -> [1];
bfr[i - bfr_pos] = bfr[i];
return Bfr_load(bfr_len - bfr_pos, bfr_pos); // fill rest of bfr; EX: [2]... will come from file
}
private boolean Bfr_load(int bgn, int len) {
int read = rdr.Read(bfr, bgn, len);
if (read == gplx.core.ios.streams.Io_stream_rdr_.Read_done) {fil_eof = true; return false;}
fil_pos += read;
bfr_len = bgn + read;
if (read < len) fil_eof = true;
return true;
}
public void Seek(long fil_pos) {
this.fil_pos = fil_pos;
rdr.Skip(fil_pos);
this.Bfr_load_all();
}
public void Rls() {
bfr = null;
bfr_len = -1;
if (rdr != null) rdr.Rls();
}
@gplx.Internal protected void Dump_to_file(int bgn, int len, String url_str, String msg) { // DBG:
String text = String_.new_u8__by_len(bfr, bgn, len);
Io_mgr.Instance.AppendFilStr(Io_url_.new_any_(url_str), msg + text + "\n");
}
public static Io_buffer_rdr new_(Io_stream_rdr rdr, int bfr_len) {
Io_buffer_rdr rv = new Io_buffer_rdr(rdr, rdr.Url(), bfr_len);
rdr.Open();
rv.Bfr_load(0, bfr_len);
return rv;
}
public static final Io_buffer_rdr Null = new Io_buffer_rdr(); Io_buffer_rdr() {}
}
| agpl-3.0 |
shevett/congo | src/main/java/com/stonekeep/congo/coconut/SaveProperties.java | 1710 | package com.stonekeep.congo.coconut;
import java.util.Enumeration;
import java.util.Properties;
import javax.servlet.http.HttpServletRequest;
import org.apache.log4j.Logger;
import org.apache.struts2.interceptor.ServletRequestAware;
import com.opensymphony.xwork2.Action;
import com.stonekeep.congo.config.ConfigurationUpdateFailedException;
import com.stonekeep.congo.config.Configurer;
import com.stonekeep.congo.config.InvalidConfigurationException;
public class SaveProperties implements Action, ServletRequestAware {
private final Configurer configurer;
private Logger logger = Logger.getLogger(SaveProperties.class);
private HttpServletRequest request;
public String savebutton = null;
public String cancelbutton = null;
public SaveProperties(Configurer configurer) {
this.configurer = configurer;
}
@Override
public String execute() throws ConfigurationUpdateFailedException {
try {
if (savebutton != null) {
logger.debug("Updating configuration");
configurer.updateConfiguration(parseProperties(request));
return SUCCESS;
} else {
logger.debug("Cancelled.");
return "exit";
}
} catch (InvalidConfigurationException ice) {
return INPUT;
}
}
private Properties parseProperties(HttpServletRequest request) {
Properties p = new Properties();
Enumeration<?> parameters = request.getParameterNames();
while (parameters.hasMoreElements()) {
String parameterName = parameters.nextElement().toString();
String parameterValue = request.getParameter(parameterName);
p.setProperty(parameterName, parameterValue);
}
return p;
}
@Override
public void setServletRequest(HttpServletRequest request) {
this.request = request;
}
}
| agpl-3.0 |
o2oa/o2oa | o2server/x_program_center/src/main/java/com/x/program/center/jaxrs/appstyle/ActionImageMenuLogoBlur.java | 2169 | package com.x.program.center.jaxrs.appstyle;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.Set;
import java.util.TreeSet;
import java.util.stream.Collectors;
import javax.imageio.ImageIO;
/*
* 114*114
* */
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
import org.imgscalr.Scalr;
import org.imgscalr.Scalr.Method;
import com.x.base.core.project.config.AppStyle.Image;
import com.x.base.core.project.config.Config;
import com.x.base.core.project.exception.ExceptionAccessDenied;
import com.x.base.core.project.http.ActionResult;
import com.x.base.core.project.http.EffectivePerson;
import com.x.base.core.project.jaxrs.WrapBoolean;
class ActionImageMenuLogoBlur extends BaseAction {
ActionResult<Wo> execute(EffectivePerson effectivePerson, byte[] bytes, FormDataContentDisposition disposition)
throws Exception {
try (ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
ActionResult<Wo> result = new ActionResult<>();
if (!effectivePerson.isManager()) {
throw new ExceptionAccessDenied(effectivePerson.getName());
}
BufferedImage image = ImageIO.read(bais);
BufferedImage scalrImage = Scalr.resize(image, Method.QUALITY, 114, 114);
ImageIO.write(scalrImage, "png", baos);
String value = Base64.encodeBase64String(baos.toByteArray());
Image o = Image.index_bottom_menu_logo_blur();
o.setValue(value);
// 由于getImages设置了检查,所以只能对images进行处理
Set<Image> images = Config.appStyle().getImages();
images = images.stream()
.filter(img -> (!StringUtils.equals(img.getName(), Image.name_index_bottom_menu_logo_blur)))
.collect(Collectors.toSet());
images.add(o);
Config.appStyle().setImages(new TreeSet<>(images));
Config.appStyle().save();
Wo wo = new Wo();
wo.setValue(true);
result.setData(wo);
Config.flush();
return result;
}
}
public static class Wo extends WrapBoolean {
}
} | agpl-3.0 |
databazoo/dev-modeler | components/src/main/java/com/databazoo/components/containers/VerticalContainer.java | 1968 |
package com.databazoo.components.containers;
import java.awt.*;
import javax.swing.*;
/**
* Vertical panel. Helps defining placements directly from constructor.
*
* @author bobus
*/
public class VerticalContainer extends JPanel {
/**
* Empty constructor
*/
public VerticalContainer(){
setLayout(new BorderLayout(0,0));
}
/**
* Constructor with components
*
* @param topComponent upper component
* @param centerComponent center component
* @param bottomComponent lower component
*/
public VerticalContainer (Component topComponent, Component centerComponent, Component bottomComponent) {
setLayout(new BorderLayout(0,0));
if(topComponent != null){
add(topComponent, BorderLayout.NORTH);
}
if(centerComponent != null){
add(centerComponent, BorderLayout.CENTER);
}
if(bottomComponent != null){
add(bottomComponent, BorderLayout.SOUTH);
}
}
public static class Builder {
Dimension minSize;
Dimension maxSize;
Component topComponent;
Component centerComponent;
Component bottomComponent;
public Builder min(Dimension size){
minSize = size;
return this;
}
public Builder max(Dimension size){
maxSize = size;
return this;
}
public Builder top(Component component){
topComponent = component;
return this;
}
public Builder center(Component component){
centerComponent = component;
return this;
}
public Builder bottom(Component component){
bottomComponent = component;
return this;
}
public VerticalContainer build(){
VerticalContainer instance = new VerticalContainer();
if(topComponent != null){
instance.add(topComponent, BorderLayout.NORTH);
}
if(centerComponent != null){
instance.add(centerComponent, BorderLayout.CENTER);
}
if(bottomComponent != null){
instance.add(bottomComponent, BorderLayout.SOUTH);
}
instance.setMinimumSize(minSize);
instance.setMaximumSize(maxSize);
return instance;
}
}
}
| agpl-3.0 |
m-sc/yamcs | yamcs-client/src/main/java/org/yamcs/client/timeline/TimelineClient.java | 9010 | package org.yamcs.client.timeline;
import static org.yamcs.client.utils.WellKnownTypes.toTimestamp;
import java.time.Instant;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import org.yamcs.api.MethodHandler;
import org.yamcs.api.Observer;
import org.yamcs.client.Page;
import org.yamcs.client.base.AbstractPage;
import org.yamcs.client.base.ResponseObserver;
import org.yamcs.protobuf.AddBandRequest;
import org.yamcs.protobuf.CreateItemRequest;
import org.yamcs.protobuf.DeleteBandRequest;
import org.yamcs.protobuf.DeleteItemRequest;
import org.yamcs.protobuf.DeleteTimelineGroupRequest;
import org.yamcs.protobuf.GetItemRequest;
import org.yamcs.protobuf.ListBandsRequest;
import org.yamcs.protobuf.ListBandsResponse;
import org.yamcs.protobuf.ListItemsRequest;
import org.yamcs.protobuf.ListItemsResponse;
import org.yamcs.protobuf.ListSourcesRequest;
import org.yamcs.protobuf.ListSourcesResponse;
import org.yamcs.protobuf.ListTimelineTagsRequest;
import org.yamcs.protobuf.ListTimelineTagsResponse;
import org.yamcs.protobuf.TimelineApiClient;
import org.yamcs.protobuf.TimelineBand;
import org.yamcs.protobuf.TimelineItem;
import org.yamcs.protobuf.TimelineSourceCapabilities;
import org.yamcs.protobuf.UpdateItemRequest;
public class TimelineClient {
static public final String RDB_TIMELINE_SOURCE = "rdb";
final String instance;
final TimelineApiClient timelineService;
public TimelineClient(MethodHandler handler, String instance) {
this.instance = instance;
timelineService = new TimelineApiClient(handler);
}
public CompletableFuture<Page<TimelineItem>> getItems(Instant start, Instant stop, String band) {
ListItemsRequest.Builder requestb = ListItemsRequest.newBuilder()
.setInstance(instance);
if (start != null) {
requestb.setStart(toTimestamp(start));
}
if (stop != null) {
requestb.setStop(toTimestamp(stop));
}
if (band != null) {
requestb.setBand(band);
}
return new TimelineItemPage(requestb.build()).future();
}
public CompletableFuture<TimelineItem> addItem(String source, TimelineItem item) {
if (!item.hasType()) {
throw new IllegalArgumentException("type is mandatory");
}
CreateItemRequest.Builder requestb = CreateItemRequest.newBuilder()
.setType(item.getType())
.setInstance(instance)
.setSource(source);
if (item.hasStart()) {
requestb.setStart(item.getStart());
}
if (item.hasRelativeTime()) {
requestb.setRelativeTime(item.getRelativeTime());
}
if (item.hasDuration()) {
requestb.setDuration(item.getDuration());
}
requestb.addAllTags(item.getTagsList());
if (item.hasGroupId()) {
requestb.setGroupId(item.getGroupId());
}
CompletableFuture<TimelineItem> f = new CompletableFuture<>();
timelineService.createItem(null, requestb.build(), new ResponseObserver<>(f));
return f;
}
public CompletableFuture<TimelineItem> addItem(TimelineItem item) {
return addItem(RDB_TIMELINE_SOURCE, item);
}
public CompletableFuture<TimelineItem> getItem(String source, String id) {
CompletableFuture<TimelineItem> f = new CompletableFuture<>();
GetItemRequest.Builder requestb = GetItemRequest.newBuilder()
.setInstance(instance)
.setSource(source)
.setId(id);
timelineService.getItem(null, requestb.build(), new ResponseObserver<>(f));
return f;
}
public CompletableFuture<TimelineItem> deleteItem(String id) {
return deleteItem(RDB_TIMELINE_SOURCE, id);
}
public CompletableFuture<TimelineItem> deleteItem(String source, String id) {
CompletableFuture<TimelineItem> f = new CompletableFuture<>();
DeleteItemRequest.Builder requestb = DeleteItemRequest.newBuilder()
.setInstance(instance)
.setSource(source)
.setId(id);
timelineService.deleteItem(null, requestb.build(), new ResponseObserver<>(f));
return f;
}
public CompletableFuture<TimelineItem> deleteTimelineGroup(String id) {
return deleteTimelineGroup(RDB_TIMELINE_SOURCE, id);
}
public CompletableFuture<TimelineItem> deleteTimelineGroup(String source, String id) {
CompletableFuture<TimelineItem> f = new CompletableFuture<>();
DeleteTimelineGroupRequest.Builder requestb = DeleteTimelineGroupRequest.newBuilder()
.setInstance(instance)
.setSource(source)
.setId(id);
timelineService.deleteTimelineGroup(null, requestb.build(), new ResponseObserver<>(f));
return f;
}
public CompletableFuture<TimelineItem> getItem(String id) {
return getItem(RDB_TIMELINE_SOURCE, id);
}
public CompletableFuture<Map<String, TimelineSourceCapabilities>> getSources() {
ListSourcesRequest.Builder requestb = ListSourcesRequest.newBuilder().setInstance(instance);
CompletableFuture<ListSourcesResponse> f = new CompletableFuture<>();
timelineService.listSources(null, requestb.build(), new ResponseObserver<>(f));
return f.thenApply(r -> r.getSourcesMap());
}
private class TimelineItemPage extends AbstractPage<ListItemsRequest, ListItemsResponse, TimelineItem>
implements Page<TimelineItem> {
public TimelineItemPage(ListItemsRequest request) {
super(request, "items");
}
@Override
protected void fetch(ListItemsRequest request, Observer<ListItemsResponse> observer) {
timelineService.listItems(null, request, observer);
}
}
public CompletableFuture<List<String>> getTags() {
ListTimelineTagsRequest.Builder requestb = ListTimelineTagsRequest.newBuilder().setInstance(instance);
CompletableFuture<ListTimelineTagsResponse> f = new CompletableFuture<>();
timelineService.listTags(null, requestb.build(), new ResponseObserver<>(f));
return f.thenApply(r -> r.getTagsList());
}
public CompletableFuture<TimelineItem> updateItem(TimelineItem item) {
return updateItem(RDB_TIMELINE_SOURCE, item);
}
public CompletableFuture<TimelineItem> updateItem(String source, TimelineItem item) {
if (!item.hasId()) {
throw new IllegalArgumentException("the item needs an id");
}
UpdateItemRequest.Builder requestb = UpdateItemRequest.newBuilder()
.setInstance(instance)
.setSource(source)
.setId(item.getId());
if (item.hasStart()) {
requestb.setStart(item.getStart());
}
if (item.hasRelativeTime()) {
requestb.setRelativeTime(item.getRelativeTime());
}
if (item.hasDuration()) {
requestb.setDuration(item.getDuration());
}
requestb.addAllTags(item.getTagsList());
if (item.hasGroupId()) {
requestb.setGroupId(item.getGroupId());
}
CompletableFuture<TimelineItem> f = new CompletableFuture<>();
timelineService.updateItem(null, requestb.build(), new ResponseObserver<>(f));
return f;
}
public CompletableFuture<List<TimelineBand>> getBands() {
ListBandsRequest.Builder request = ListBandsRequest.newBuilder().setInstance(instance);
CompletableFuture<ListBandsResponse> f = new CompletableFuture<>();
timelineService.listBands(null, request.build(), new ResponseObserver<>(f));
return f.thenApply(r -> r.getBandsList());
}
public CompletableFuture<TimelineBand> deleteBand(String id) {
CompletableFuture<TimelineBand> f = new CompletableFuture<>();
DeleteBandRequest.Builder requestb = DeleteBandRequest.newBuilder()
.setInstance(instance)
.setId(id);
timelineService.deleteBand(null, requestb.build(), new ResponseObserver<>(f));
return f;
}
public CompletableFuture<TimelineBand> addBand(TimelineBand band) {
AddBandRequest.Builder requestb = AddBandRequest.newBuilder()
.setType(band.getType())
.setInstance(instance);
requestb.addAllTags(band.getTagsList());
requestb.putAllProperties(band.getPropertiesMap());
if (band.hasName()) {
requestb.setName(band.getName());
}
if (band.hasDescription()) {
requestb.setDescription(band.getDescription());
}
if (band.hasShared()) {
requestb.setShared(band.getShared());
}
CompletableFuture<TimelineBand> f = new CompletableFuture<>();
timelineService.addBand(null, requestb.build(), new ResponseObserver<>(f));
return f;
}
}
| agpl-3.0 |
ua-eas/ua-kfs-5.3 | work/src/org/kuali/kfs/module/purap/batch/ExtractPdpStep.java | 2507 | /*
* The Kuali Financial System, a comprehensive financial management system for higher education.
*
* Copyright 2005-2014 The Kuali Foundation
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kuali.kfs.module.purap.batch;
import java.util.Date;
import org.kuali.kfs.module.purap.service.PdpExtractService;
import org.kuali.kfs.sys.batch.AbstractStep;
import org.kuali.kfs.sys.util.KfsDateUtils;
import org.kuali.rice.core.api.datetime.DateTimeService;
public class ExtractPdpStep extends AbstractStep {
private static org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(ExtractPdpStep.class);
private PdpExtractService pdpExtractService;
private DateTimeService dateTimeService;
public ExtractPdpStep() {
super();
}
/**
* @see org.kuali.kfs.sys.batch.Step#execute(java.lang.String, java.util.Date)
*/
public boolean execute(String jobName, Date jobRunDate) throws InterruptedException {
LOG.debug("execute() started");
pdpExtractService.extractPayments(KfsDateUtils.convertToSqlDate(jobRunDate));
return true;
}
public boolean execute() throws InterruptedException {
try {
return execute(null, dateTimeService.getCurrentDate());
}
catch (InterruptedException e) {
LOG.error("Exception occured executing step", e);
throw e;
}
catch (RuntimeException e) {
LOG.error("Exception occured executing step", e);
throw e;
}
}
public void setPdpExtractService(PdpExtractService pdpExtractService) {
this.pdpExtractService = pdpExtractService;
}
public void setDateTimeService(DateTimeService dateTimeService) {
this.dateTimeService = dateTimeService;
}
}
| agpl-3.0 |
jletellier/DataHubSystem | client/gwt/src/main/java/fr/gael/dhus/gwt/client/page/TermsPage.java | 1618 | /*
* Data Hub Service (DHuS) - For Space data distribution.
* Copyright (C) 2013,2014,2015 GAEL Systems
*
* This file is part of DHuS software sources.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package fr.gael.dhus.gwt.client.page;
import com.google.gwt.core.client.JavaScriptObject;
public class TermsPage extends AbstractPage
{
public TermsPage()
{
super.name = "Terms";
}
@Override
public native JavaScriptObject getJSInitFunction()
/*-{
return function() {
@fr.gael.dhus.gwt.client.page.TermsPage::init()();
}
}-*/;
@Override
public native JavaScriptObject getJSRefreshFunction()
/*-{
return function() {
@fr.gael.dhus.gwt.client.page.TermsPage::refresh()();
}
}-*/;
private static native void showTerms()
/*-{
$wnd.showTerms();
}-*/;
private static void refresh()
{
}
private static void init()
{
showTerms();
refresh();
}
}
| agpl-3.0 |
iordanis12590/StampalaPasta | app/src/main/java/com/innovationtechnology/iordanis/stampalapasta/ui/pasta/SingleListItem.java | 3817 | package com.innovationtechnology.iordanis.stampalapasta.ui.pasta;
import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.innovationtechnology.iordanis.stampalapasta.R;
import com.parse.GetCallback;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;
/**
* Created by iordanis on 7/3/2015.
*/
public class SingleListItem extends Activity {
TextView nameView;
Spinner materialSpinner;
Spinner amountSpinner;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pastashapes_preview);
getActionBar().setIcon(new ColorDrawable(getResources().getColor(android.R.color.transparent)));
getActionBar().setHomeButtonEnabled(true);
Intent intent = getIntent();
String name = intent.getStringExtra("name");
//get/set name
nameView = (TextView) findViewById(R.id.itemName);
nameView.setText(name);
materialSpinner = ((Spinner) findViewById(R.id.materialSpinner));
ArrayAdapter<CharSequence> materialSpinnerAdapter = ArrayAdapter.createFromResource(getBaseContext(), R.array.material_array, android.R.layout.simple_spinner_dropdown_item);
materialSpinner.setAdapter(materialSpinnerAdapter);
amountSpinner = ((Spinner) findViewById(R.id.amountSpinner));
ArrayAdapter<CharSequence> amountSpinnerAdapter = ArrayAdapter.createFromResource(getBaseContext(), R.array.amount_array, android.R.layout.simple_spinner_dropdown_item);
amountSpinner.setAdapter(amountSpinnerAdapter);
/*
materialSpinner = (Spinner) findViewById(R.id.materialSpinner);
ArrayAdapter<CharSequence> spinnerAdapter = ArrayAdapter.createFromResource(getApplicationContext(), R.array.material_array, android.R.layout.simple_spinner_dropdown_item);
materialSpinner.setAdapter(spinnerAdapter);
//get/set description
TextView descriptionView = (TextView) findViewById(R.id.itemDescription);
descriptionView.setText(description);
//download/set image
ParseQuery<ParseObject> query = ParseQuery.getQuery("Pasta");
query.whereEqualTo("name", name);
query.getFirstInBackground(new GetCallback<ParseObject>() {
@Override
public void done(ParseObject parseObject, ParseException e) {
parseObject.get("image");
ParseImageView itemShape= (ParseImageView) findViewById(R.id.itemImage);
itemShape.setParseFile(parseObject.getParseFile("image"));
}
});
*/
}
public void onClickPrintButton(View view){
ParseQuery<ParseObject> query = ParseQuery.getQuery("Pasta");
String name = getIntent().getStringExtra("name");
query.whereEqualTo("name", name);
query.getFirstInBackground(new GetCallback<ParseObject>() {
@Override
public void done(ParseObject parseObject, ParseException e) {
if (parseObject == null) {
Log.d("pasta", "The getFirst request failed.");
} else {
Log.d("pasta", "Retrieved the object.");
parseObject.increment("counter");
parseObject.saveInBackground();
//checking git
}
Toast.makeText(getApplicationContext(), "Please register a valid 3D printer", Toast.LENGTH_LONG).show();
}
});
}
}
| agpl-3.0 |
DAINTINESS-Group/Hecate | src/gr/uoi/cs/daintiness/hecate/output/tableExports/TableTypeChangeExporter.java | 766 | package gr.uoi.cs.daintiness.hecate.output.tableExports;
import gr.uoi.cs.daintiness.hecate.metrics.tables.Changes;
import gr.uoi.cs.daintiness.hecate.metrics.tables.MetricsOverVersion;
public class TableTypeChangeExporter extends TableMetricsExporter{
public TableTypeChangeExporter(String path) {
super(path, "_perVersion_tables_AttrTypeUpd.csv");
}
@Override
public void writeChanges(MetricsOverVersion metricsOverVersion, int i) {
Changes c = metricsOverVersion.getChanges(i);
writeText(c.getAttrTypeChange() + ";");
}
@Override
public void writeLastColumn() {
writeText("\n");
}
@Override
public void writeEmptyCells() {
writeText("-;");
}
@Override
public void writeHeader(int versions) {
writeVersionsLine(versions);
}
}
| agpl-3.0 |
axelor/axelor-business-suite | axelor-human-resource/src/main/java/com/axelor/apps/hr/db/repo/TimesheetHRRepository.java | 3080 | /*
* Axelor Business Solutions
*
* Copyright (C) 2022 Axelor (<http://axelor.com>).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.axelor.apps.hr.db.repo;
import com.axelor.apps.hr.db.Timesheet;
import com.axelor.apps.hr.db.TimesheetLine;
import com.axelor.apps.hr.service.timesheet.TimesheetLineService;
import com.axelor.apps.hr.service.timesheet.TimesheetService;
import com.axelor.apps.project.db.Project;
import com.axelor.apps.project.db.repo.ProjectRepository;
import com.axelor.inject.Beans;
import com.google.inject.Inject;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;
public class TimesheetHRRepository extends TimesheetRepository {
@Inject private TimesheetService timesheetService;
@Inject private TimesheetLineService timesheetLineService;
@Inject private ProjectRepository projectRepository;
@Override
public Timesheet save(Timesheet timesheet) {
if (timesheet.getTimesheetLineList() != null) {
for (TimesheetLine timesheetLine : timesheet.getTimesheetLineList())
Beans.get(TimesheetLineHRRepository.class).computeFullName(timesheetLine);
}
return super.save(timesheet);
}
@Override
public Map<String, Object> validate(Map<String, Object> json, Map<String, Object> context) {
Map<String, Object> obj = super.validate(json, context);
if (json.get("id") == null) {
Timesheet timesheet = create(json);
if (timesheet.getTimesheetLineList() == null || timesheet.getTimesheetLineList().isEmpty()) {
timesheet.setTimesheetLineList(new ArrayList<TimesheetLine>());
obj.put("timesheetLineList", timesheetService.createDefaultLines(timesheet));
}
}
return obj;
}
@Override
public void remove(Timesheet entity) {
if (entity.getStatusSelect() == TimesheetRepository.STATUS_VALIDATED
&& entity.getTimesheetLineList() != null) {
timesheetService.setProjectTaskTotalRealHrs(entity.getTimesheetLineList(), false);
Map<Project, BigDecimal> projectTimeSpentMap =
timesheetLineService.getProjectTimeSpentMap(entity.getTimesheetLineList());
Iterator<Project> projectIterator = projectTimeSpentMap.keySet().iterator();
while (projectIterator.hasNext()) {
Project project = projectIterator.next();
project.setTimeSpent(project.getTimeSpent().subtract(projectTimeSpentMap.get(project)));
projectRepository.save(project);
}
}
super.remove(entity);
}
}
| agpl-3.0 |
sudduth/Aardin | Core/CoreImpl/src/test/java/org/aardin/npml/tests/unit/SubroutineReferenceTest.java | 1992 | /*******************************************************************************
* Distributed under the terms of the GNU AGPL version 3.
* Copyright (c) 2011 Glenn Sudduth
*******************************************************************************/
package org.aardin.npml.tests.unit;
import static org.easymock.EasyMock.createMock;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.assertFalse;
import org.aardin.core.api.INotification;
import org.aardin.npml.Condition;
import org.aardin.npml.If;
import org.aardin.npml.LogicalTrue;
import org.aardin.npml.Punt;
import org.aardin.npml.Subroutine;
import org.aardin.npml.SubroutineReference;
import org.testng.annotations.Test;
public class SubroutineReferenceTest extends XMLBase {
@Test
public void subref_test_everything() {
// Mock a notification.
INotification notification = createMock(INotification.class);
Subroutine subroutine = new Subroutine();
String subroutineId = String.valueOf(subroutine.getElementId());
subroutine.setName("Test");
assertEquals(subroutine.getName(), "Test");
If iif = new If();
String ifId = String.valueOf(iif.getElementId());
LogicalTrue t = new LogicalTrue();
iif.setCondition(new Condition(t));
Punt p = new Punt(1);
String pId = String.valueOf(p.getElementId());
iif.addChildElement(p);
subroutine.addChildElement(iif);
SubroutineReference ref = new SubroutineReference("Test");
String refId = String.valueOf(ref.getElementId());
ref.setReferencedSubroutine(subroutine);
ref.setNotification(notification);
assertEquals(_serialize.outputString(ref.xml()), "<subroutine_ref ref=\"Test\" />");
assertEquals(ref.getPath(), refId);
assertEquals(p.getPath(), ref.getPath() + "/" + subroutineId + "/" + ifId + "/" + pId);
assertTrue(ref.process());
assertFalse(ref.process());
ref.reset();
assertTrue(ref.process());
assertFalse(ref.process());
}
}
| agpl-3.0 |
boob-sbcm/3838438 | src/main/java/com/rapidminer/operator/performance/SimplePerformanceEvaluator.java | 5244 | /**
* Copyright (C) 2001-2017 by RapidMiner and the contributors
*
* Complete list of developers available at our web site:
*
* http://rapidminer.com
*
* This program is free software: you can redistribute it and/or modify it under the terms of the
* GNU Affero General Public License as published by the Free Software Foundation, either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program.
* If not, see http://www.gnu.org/licenses/.
*/
package com.rapidminer.operator.performance;
import com.rapidminer.example.Attribute;
import com.rapidminer.example.ExampleSet;
import com.rapidminer.operator.OperatorCapability;
import com.rapidminer.operator.OperatorDescription;
import com.rapidminer.operator.OperatorException;
import com.rapidminer.parameter.UndefinedParameterError;
import com.rapidminer.tools.math.ROCBias;
import java.util.LinkedList;
import java.util.List;
/**
* <p>
* In contrast to the other performance evaluation methods, this performance evaluator operator can
* be used for all types of learning tasks. It will automatically determine the learning task type
* and will calculate the most common criteria for this type. For more sophisticated performance
* calculations, you should check the operators {@link RegressionPerformanceEvaluator},
* {@link PolynominalClassificationPerformanceEvaluator}, or
* {@link BinominalClassificationPerformanceEvaluator}. You can even simply write your own
* performance measure and calculate it with the operator {@link UserBasedPerformanceEvaluator}.
* </p>
*
* <p>
* The operator expects a test {@link ExampleSet} as input, whose elements have both true and
* predicted labels, and delivers as output a list of most common performance values for the
* provided learning task type (regression or (binary) classification. If an input performance
* vector was already given, this is used for keeping the performance values.
* </p>
*
* @author Ingo Mierswa
*/
public class SimplePerformanceEvaluator extends AbstractPerformanceEvaluator {
private ExampleSet testSet = null;
public SimplePerformanceEvaluator(OperatorDescription description) {
super(description);
}
/** Does nothing. */
@Override
protected void checkCompatibility(ExampleSet exampleSet) throws OperatorException {}
/** Returns null. */
@Override
protected double[] getClassWeights(Attribute label) throws UndefinedParameterError {
return null;
}
/** Uses this example set in order to create appropriate criteria. */
@Override
protected void init(ExampleSet testSet) {
this.testSet = testSet;
}
/** Returns false. */
@Override
protected boolean showSkipNaNLabelsParameter() {
return false;
}
/** Returns false. */
@Override
protected boolean showComparatorParameter() {
return false;
}
@Override
public List<PerformanceCriterion> getCriteria() {
List<PerformanceCriterion> allCriteria = new LinkedList<PerformanceCriterion>();
if (this.testSet != null) {
Attribute label = this.testSet.getAttributes().getLabel();
if (label != null) {
if (label.isNominal()) {
if (label.getMapping().size() == 2) {
// add most important binominal classification criteria
allCriteria.add(new MultiClassificationPerformance(MultiClassificationPerformance.ACCURACY));
allCriteria.add(new BinaryClassificationPerformance(BinaryClassificationPerformance.PRECISION));
allCriteria.add(new BinaryClassificationPerformance(BinaryClassificationPerformance.RECALL));
allCriteria.add(new AreaUnderCurve(ROCBias.OPTIMISTIC));
allCriteria.add(new AreaUnderCurve(ROCBias.NEUTRAL));
allCriteria.add(new AreaUnderCurve(ROCBias.PESSIMISTIC));
} else {
// add most important polynominal classification criteria
allCriteria.add(new MultiClassificationPerformance(MultiClassificationPerformance.ACCURACY));
allCriteria.add(new MultiClassificationPerformance(MultiClassificationPerformance.KAPPA));
}
} else {
// add most important regression criteria
allCriteria.add(new RootMeanSquaredError());
allCriteria.add(new SquaredError());
}
}
}
this.testSet = null;
return allCriteria;
}
@Override
protected boolean canEvaluate(int valueType) {
return true;
}
@Override
public boolean supportsCapability(OperatorCapability capability) {
switch (capability) {
case NUMERICAL_LABEL:
case BINOMINAL_LABEL:
case POLYNOMINAL_LABEL:
case ONE_CLASS_LABEL:
return true;
case POLYNOMINAL_ATTRIBUTES:
case BINOMINAL_ATTRIBUTES:
case NUMERICAL_ATTRIBUTES:
case WEIGHTED_EXAMPLES:
case MISSING_VALUES:
return true;
case NO_LABEL:
case UPDATABLE:
case FORMULA_PROVIDER:
default:
return false;
}
}
}
| agpl-3.0 |
rapidminer/rapidminer-studio | src/main/java/com/rapidminer/operator/performance/AbstractPerformanceEvaluator.java | 22853 | /**
* Copyright (C) 2001-2020 by RapidMiner and the contributors
*
* Complete list of developers available at our web site:
*
* http://rapidminer.com
*
* This program is free software: you can redistribute it and/or modify it under the terms of the
* GNU Affero General Public License as published by the Free Software Foundation, either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program.
* If not, see http://www.gnu.org/licenses/.
*/
package com.rapidminer.operator.performance;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import com.rapidminer.example.Attribute;
import com.rapidminer.example.Attributes;
import com.rapidminer.example.Example;
import com.rapidminer.example.ExampleSet;
import com.rapidminer.example.Statistics;
import com.rapidminer.operator.Operator;
import com.rapidminer.operator.OperatorCapability;
import com.rapidminer.operator.OperatorDescription;
import com.rapidminer.operator.OperatorException;
import com.rapidminer.operator.ProcessSetupError.Severity;
import com.rapidminer.operator.SimpleProcessSetupError;
import com.rapidminer.operator.UserError;
import com.rapidminer.operator.ValueDouble;
import com.rapidminer.operator.learner.CapabilityProvider;
import com.rapidminer.operator.ports.InputPort;
import com.rapidminer.operator.ports.OutputPort;
import com.rapidminer.operator.ports.metadata.CapabilityPrecondition;
import com.rapidminer.operator.ports.metadata.ExampleSetMetaData;
import com.rapidminer.operator.ports.metadata.MetaData;
import com.rapidminer.operator.ports.metadata.MetaDataInfo;
import com.rapidminer.operator.ports.metadata.MetaDataUnderspecifiedError;
import com.rapidminer.operator.ports.metadata.PassThroughOrGenerateRule;
import com.rapidminer.operator.ports.metadata.PassThroughRule;
import com.rapidminer.operator.ports.metadata.SimpleMetaDataError;
import com.rapidminer.operator.ports.metadata.SimplePrecondition;
import com.rapidminer.operator.ports.quickfix.ParameterSettingQuickFix;
import com.rapidminer.operator.ports.quickfix.QuickFix;
import com.rapidminer.parameter.ParameterType;
import com.rapidminer.parameter.ParameterTypeBoolean;
import com.rapidminer.parameter.ParameterTypeString;
import com.rapidminer.parameter.ParameterTypeStringCategory;
import com.rapidminer.parameter.UndefinedParameterError;
import com.rapidminer.tools.Ontology;
/**
* <p>
* This performance evaluator operator should be used for regression tasks, i.e. in cases where the
* label attribute has a numerical value type. The operator expects a test {@link ExampleSet} as
* input, whose elements have both true and predicted labels, and delivers as output a list of
* performance values according to a list of performance criteria that it calculates. If an input
* performance vector was already given, this is used for keeping the performance values.
* </p>
*
* <p>
* All of the performance criteria can be switched on using boolean parameters. Their values can be
* queried by a {@link com.rapidminer.operator.visualization.ProcessLogOperator} using the same
* names. The main criterion is used for comparisons and need to be specified only for processes
* where performance vectors are compared, e.g. feature selection or other meta optimization process
* setups. If no other main criterion was selected, the first criterion in the resulting performance
* vector will be assumed to be the main criterion.
* </p>
*
* <p>
* The resulting performance vectors are usually compared with a standard performance comparator
* which only compares the fitness values of the main criterion. Other implementations than this
* simple comparator can be specified using the parameter <var>comparator_class</var>. This may for
* instance be useful if you want to compare performance vectors according to the weighted sum of
* the individual criteria. In order to implement your own comparator, simply subclass
* {@link PerformanceComparator}. Please note that for true multi-objective optimization usually
* another selection scheme is used instead of simply replacing the performance comparator.
* </p>
*
* @author Ingo Mierswa
*/
public abstract class AbstractPerformanceEvaluator extends Operator implements CapabilityProvider {
/** The parameter name for "The criterion used for comparing performance vectors." */
public static final String PARAMETER_MAIN_CRITERION = "main_criterion";
/**
* The parameter name for "If set to true, examples with undefined labels are
* skipped."
*/
public static final String PARAMETER_SKIP_UNDEFINED_LABELS = "skip_undefined_labels";
/**
* The parameter name for "Fully qualified classname of the PerformanceComparator
* implementation."
*/
public static final String PARAMETER_COMPARATOR_CLASS = "comparator_class";
/** Indicates if example weights should be used for performance calculations. */
private static final String PARAMETER_USE_EXAMPLE_WEIGHTS = "use_example_weights";
public static final String INPUT_PORT_LABELLED_DATA = "labelled data";
private InputPort exampleSetInput = getInputPorts().createPort(INPUT_PORT_LABELLED_DATA);
private InputPort performanceInput = getInputPorts().createPort("performance");
private OutputPort performanceOutput = getOutputPorts().createPort("performance");
private OutputPort exampleSetOutput = getOutputPorts().createPort("example set");
/**
* The currently used performance vector. This is be used for logging / plotting purposes.
*/
private PerformanceVector currentPerformanceVector = null;
public AbstractPerformanceEvaluator(OperatorDescription description) {
super(description);
// exampleSetInput.addPrecondition(new ExampleSetPrecondition(exampleSetInput,
// Ontology.VALUE_TYPE, Attributes.LABEL_NAME,
// Attributes.PREDICTION_NAME));
exampleSetInput.addPrecondition(new CapabilityPrecondition(this, exampleSetInput));
exampleSetInput.addPrecondition(new SimplePrecondition(exampleSetInput, new ExampleSetMetaData()) {
@Override
public void makeAdditionalChecks(MetaData metaData) {
if (!(metaData instanceof ExampleSetMetaData)) {
exampleSetInput.addError(new MetaDataUnderspecifiedError(exampleSetInput));
return;
}
ExampleSetMetaData emd = (ExampleSetMetaData) metaData;
if (emd.hasSpecial(Attributes.LABEL_NAME) == MetaDataInfo.YES
&& emd.hasSpecial(Attributes.PREDICTION_NAME) == MetaDataInfo.YES) {
int type1 = emd.getSpecial(Attributes.LABEL_NAME).getValueType();
int type2 = emd.getSpecial(Attributes.PREDICTION_NAME).getValueType();
if (type1 != type2) {
exampleSetInput.addError(new SimpleMetaDataError(Severity.ERROR, exampleSetInput,
"label_prediction_mismatch", new Object[] { Ontology.ATTRIBUTE_VALUE_TYPE.mapIndex(type1),
Ontology.ATTRIBUTE_VALUE_TYPE.mapIndex(type2) }));
} else if (!canEvaluate(type1)) {
exampleSetInput.addError(new SimpleMetaDataError(Severity.ERROR, exampleSetInput,
"cannot_evaluate_label_type", new Object[] { Ontology.ATTRIBUTE_VALUE_TYPE.mapIndex(type1) }));
}
}
}
});
performanceInput.addPrecondition(new SimplePrecondition(performanceInput, new MetaData(PerformanceVector.class),
false));
PassThroughOrGenerateRule performanceRule = new PassThroughOrGenerateRule(performanceInput, performanceOutput,
new MetaData(PerformanceVector.class));
getTransformer().addRule(performanceRule);
getTransformer().addRule(new PassThroughRule(exampleSetInput, exampleSetOutput, false));
// add values for logging
List<PerformanceCriterion> criteria = getCriteria();
for (PerformanceCriterion criterion : criteria) {
addPerformanceValue(criterion.getName(), criterion.getDescription());
}
addValue(new ValueDouble("performance", "The last performance (main criterion).") {
@Override
public double getDoubleValue() {
if (currentPerformanceVector != null) {
return currentPerformanceVector.getMainCriterion().getAverage();
} else {
return Double.NaN;
}
}
});
}
/**
* Returns true iff this operator can evaluate labels of the given value type.
*
* @see Ontology.ATTRIBUTE_VALUE_TYPE
*/
protected abstract boolean canEvaluate(int valueType);
/**
* Delivers the list of criteria which is able for this operator. Please note that all criteria
* in the list must be freshly instantiated since no copy is created in different runs of this
* operator. This is important in order to not mess up the results.
*
* This method must not return null but should return an empty list in this case.
*
* ATTENTION! This method is called during the creation of parameters. Do not try to get a
* parameter value inside this method, since this will create an infinite loop!
*/
public abstract List<PerformanceCriterion> getCriteria();
/**
* Delivers class weights for performance criteria which implement the
* {@link ClassWeightedPerformance} interface. Might return null (for example for regression
* task performance evaluators).
*
* @throws UserError
*/
protected abstract double[] getClassWeights(Attribute label) throws UserError;
/** Performs a check if this operator can be used for this type of exampel set at all. */
protected abstract void checkCompatibility(ExampleSet exampleSet) throws OperatorException;
@Override
public boolean shouldAutoConnect(OutputPort port) {
if (port == exampleSetOutput) {
return getParameterAsBoolean("keep_example_set");
} else {
return super.shouldAutoConnect(port);
}
}
/**
* This method will be invoked before the actual calculation is started. The default
* implementation does nothing. Subclasses might want to override this method.
*/
protected void init(ExampleSet exampleSet) {}
/** Subclasses might override this method and return false. */
protected boolean showSkipNaNLabelsParameter() {
return true;
}
/** Subclasses might override this method and return false. */
protected boolean showComparatorParameter() {
return true;
}
/** Subclasses might override this method and return false. */
protected boolean showCriteriaParameter() {
return true;
}
/**
* Helper method if this operator is constructed anonymously. Assigns the exampleSet to the
* input and returns the PerformanceVector from the output.
*/
public PerformanceVector doWork(ExampleSet exampleSet) throws OperatorException {
exampleSetInput.receive(exampleSet);
doWork();
return performanceOutput.getData(PerformanceVector.class);
}
@Override
public void doWork() throws OperatorException {
ExampleSet testSet = exampleSetInput.getData(ExampleSet.class);
checkCompatibility(testSet);
init(testSet);
PerformanceVector inputPerformance = performanceInput.getDataOrNull(PerformanceVector.class);
performanceOutput.deliver(evaluate(testSet, inputPerformance));
exampleSetOutput.deliver(testSet);
}
// --------------------------------------------------------------------------------
/**
* Adds the performance criteria as plottable values, e.g. for the ProcessLog operator.
*/
private void addPerformanceValue(final String name, String description) {
addValue(new ValueDouble(name, description) {
@Override
public double getDoubleValue() {
if (currentPerformanceVector == null) {
return Double.NaN;
}
PerformanceCriterion c = currentPerformanceVector.getCriterion(name);
if (c != null) {
return c.getAverage();
} else {
return Double.NaN;
}
}
});
}
/**
* Creates a new performance vector if the given one is null. Adds all criteria demanded by the
* user. If the criterion was already part of the performance vector before it will be
* overwritten.
*/
private PerformanceVector initialisePerformanceVector(ExampleSet testSet, PerformanceVector performanceCriteria,
List<PerformanceCriterion> givenCriteria) throws OperatorException {
givenCriteria.clear();
if (performanceCriteria == null) {
performanceCriteria = new PerformanceVector();
} else {
for (int i = 0; i < performanceCriteria.getSize(); i++) {
givenCriteria.add(performanceCriteria.getCriterion(i));
}
}
List<PerformanceCriterion> criteria = getCriteria();
for (PerformanceCriterion criterion : criteria) {
if (checkCriterionName(criterion.getName())) {
performanceCriteria.addCriterion(criterion);
}
}
if (performanceCriteria.size() == 0) {
throw new UserError(this, 910);
}
// set suitable main criterion
if (performanceCriteria.size() == 0) {
List<PerformanceCriterion> availableCriteria = getCriteria();
if (availableCriteria.size() > 0) {
PerformanceCriterion criterion = availableCriteria.get(0);
performanceCriteria.addCriterion(criterion);
performanceCriteria.setMainCriterionName(criterion.getName());
logWarning(getName() + ": No performance criterion selected! Using the first available criterion ("
+ criterion.getName() + ").");
} else {
logWarning(getName() + ": not possible to identify available performance criteria.");
throw new UserError(this, 910);
}
} else {
if (showCriteriaParameter()) {
String mcName = getParameterAsString(PARAMETER_MAIN_CRITERION);
if (mcName != null) {
performanceCriteria.setMainCriterionName(mcName);
}
}
}
// comparator
String comparatorClass = null;
if (showComparatorParameter()) {
comparatorClass = getParameterAsString(PARAMETER_COMPARATOR_CLASS);
}
if (comparatorClass == null) {
performanceCriteria.setComparator(new PerformanceVector.DefaultComparator());
} else {
try {
Class<?> pcClass = com.rapidminer.tools.Tools.classForName(comparatorClass);
if (!PerformanceComparator.class.isAssignableFrom(pcClass)) {
throw new UserError(this, 914, new Object[] { pcClass, PerformanceComparator.class });
} else {
performanceCriteria.setComparator((PerformanceComparator) pcClass.newInstance());
}
} catch (Throwable e) {
throw new UserError(this, e, 904, new Object[] { comparatorClass, e });
}
}
return performanceCriteria;
}
/**
* Returns true if the criterion with the given name should be added to the performance vector.
* This is either the case
* <ol>
* <li>if the boolean parameter was selected by the user</li>
* <li>if the given name is equal to the main criterion</li>
* </ol>
*/
private boolean checkCriterionName(String name) throws UndefinedParameterError {
String mainCriterionName = getParameterAsString(PARAMETER_MAIN_CRITERION);
if (name != null && name.trim().length() != 0 && !name.equals(PerformanceVector.MAIN_CRITERION_FIRST)
&& name.equals(mainCriterionName)) {
return true;
} else {
ParameterType type = getParameterType(name);
if (type != null) {
return getParameterAsBoolean(name);
} else {
return true;
}
}
}
/**
* Evaluates the given test set. All {@link PerformanceCriterion} instances in the given
* {@link PerformanceVector} must be subclasses of {@link MeasuredPerformance}.
*/
protected PerformanceVector evaluate(ExampleSet testSet, PerformanceVector inputPerformance) throws OperatorException {
List<PerformanceCriterion> givenCriteria = new LinkedList<PerformanceCriterion>();
this.currentPerformanceVector = initialisePerformanceVector(testSet, inputPerformance, givenCriteria);
boolean skipUndefined = true;
if (showComparatorParameter()) {
skipUndefined = getParameterAsBoolean(PARAMETER_SKIP_UNDEFINED_LABELS);
}
boolean useExampleWeights = getParameterAsBoolean(PARAMETER_USE_EXAMPLE_WEIGHTS);
evaluate(this, testSet, currentPerformanceVector, givenCriteria, skipUndefined, useExampleWeights);
return currentPerformanceVector;
}
/**
* Static version of {@link #evaluate(ExampleSet,PerformanceVector)}. This method was introduced
* to enable testing of the method.
*
* @param evaluator
* Ususally this. May be null for testing. Only needed for exception.
*/
public static void evaluate(AbstractPerformanceEvaluator evaluator, ExampleSet testSet,
PerformanceVector performanceCriteria, List<PerformanceCriterion> givenCriteria, boolean skipUndefinedLabels,
boolean useExampleWeights) throws OperatorException {
if (testSet.getAttributes().getLabel() == null) {
throw new UserError(evaluator, 105, new Object[0]);
}
if (testSet.getAttributes().getPredictedLabel() == null) {
throw new UserError(evaluator, 107, new Object[0]);
}
// sanity check for weight attribute
if (useExampleWeights) {
Attribute weightAttribute = testSet.getAttributes().getWeight();
if (weightAttribute != null) {
if (!weightAttribute.isNumerical()) {
throw new UserError(evaluator, 120, new Object[] { weightAttribute.getName(),
Ontology.VALUE_TYPE_NAMES[weightAttribute.getValueType()],
Ontology.VALUE_TYPE_NAMES[Ontology.NUMERICAL] });
}
testSet.recalculateAttributeStatistics(weightAttribute);
double minimum = testSet.getStatistics(weightAttribute, Statistics.MINIMUM);
if (Double.isNaN(minimum) || minimum < 0.0d) {
throw new UserError(evaluator, 138, new Object[] { weightAttribute.getName(), "positive values",
"negative for some examples" });
}
}
}
// initialize all criteria
for (int pc = 0; pc < performanceCriteria.size(); pc++) {
PerformanceCriterion c = performanceCriteria.getCriterion(pc);
if (!givenCriteria.contains(c)) {
if (!(c instanceof MeasuredPerformance)) {
throw new UserError(evaluator, 903, new Object[0]);
}
// init all criteria
((MeasuredPerformance) c).startCounting(testSet, useExampleWeights);
// init weight handlers
if (c instanceof ClassWeightedPerformance) {
if (evaluator != null) {
Attribute label = testSet.getAttributes().getLabel();
if (label.isNominal()) {
double[] weights = evaluator.getClassWeights(label);
if (weights != null) {
((ClassWeightedPerformance) c).setWeights(weights);
}
}
}
}
}
}
Iterator<Example> exampleIterator = testSet.iterator();
while (exampleIterator.hasNext()) {
Example example = exampleIterator.next();
if (skipUndefinedLabels && (Double.isNaN(example.getLabel()) || Double.isNaN(example.getPredictedLabel()))) {
continue;
}
for (int pc = 0; pc < performanceCriteria.size(); pc++) {
PerformanceCriterion criterion = performanceCriteria.getCriterion(pc);
if (!givenCriteria.contains(criterion)) {
if (criterion instanceof MeasuredPerformance) {
((MeasuredPerformance) criterion).countExample(example);
}
}
}
if (evaluator != null) {
evaluator.checkForStop();
}
}
}
private String[] getAllCriteriaNames() {
List<PerformanceCriterion> criteria = getCriteria();
String[] result = new String[criteria.size()];
int counter = 0;
for (PerformanceCriterion criterion : criteria) {
result[counter++] = criterion.getName();
}
return result;
}
@Override
public List<ParameterType> getParameterTypes() {
List<ParameterType> types = super.getParameterTypes();
if (showCriteriaParameter()) {
String[] criteriaNames = getAllCriteriaNames();
if (criteriaNames.length > 0) {
String[] allCriteriaNames = new String[criteriaNames.length + 1];
allCriteriaNames[0] = PerformanceVector.MAIN_CRITERION_FIRST;
System.arraycopy(criteriaNames, 0, allCriteriaNames, 1, criteriaNames.length);
ParameterType type = new ParameterTypeStringCategory(PARAMETER_MAIN_CRITERION,
"The criterion used for comparing performance vectors.", allCriteriaNames, allCriteriaNames[0]);
type.setExpert(false);
types.add(type);
}
List<PerformanceCriterion> criteria = getCriteria();
boolean isDefault = true;
for (PerformanceCriterion criterion : criteria) {
ParameterType type = new ParameterTypeBoolean(criterion.getName(), criterion.getDescription(), isDefault,
false);
types.add(type);
isDefault = false;
}
}
if (showSkipNaNLabelsParameter()) {
types.add(new ParameterTypeBoolean(PARAMETER_SKIP_UNDEFINED_LABELS,
"If set to true, examples with undefined labels are skipped.", true));
}
if (showComparatorParameter()) {
types.add(new ParameterTypeString(PARAMETER_COMPARATOR_CLASS,
"Fully qualified classname of the PerformanceComparator implementation.", true));
}
types.add(new ParameterTypeBoolean(PARAMETER_USE_EXAMPLE_WEIGHTS,
"Indicated if example weights should be used for performance calculations if possible.", true));
return types;
}
/**
* This will override the checkProperties method of operator in order to add some checks for
* possible quickfixes.
*/
@Override
public int checkProperties() {
boolean criterionChecked = false;
List<PerformanceCriterion> criteria = null;
try {
criteria = getCriteria();
if (criteria != null) {
for (PerformanceCriterion criterion : criteria) {
if (checkCriterionName(criterion.getName())) {
criterionChecked = true;
break;
}
}
}
} catch (UndefinedParameterError err) {
}
if (!criterionChecked && criteria != null) {
// building quick fixes
List<QuickFix> quickFixes = new LinkedList<QuickFix>();
if (criteria.size() > 0) {
quickFixes.add(new ParameterSettingQuickFix(AbstractPerformanceEvaluator.this, getCriteria().get(0)
.getName(), "true"));
addError(new SimpleProcessSetupError(Severity.ERROR, this.getPortOwner(), quickFixes,
"performance_criterion_undefined", criteria.get(0).getName()));
}
if (criteria.size() > 1) {
quickFixes.add(new ParameterSettingQuickFix(AbstractPerformanceEvaluator.this, getCriteria().get(1)
.getName(), "true"));
}
}
return super.checkDeprecations() + super.checkProperties();
}
@Override
public boolean supportsCapability(OperatorCapability capability) {
return true;
}
}
| agpl-3.0 |
o2oa/o2oa | o2server/x_cms_assemble_control/src/main/java/com/x/cms/assemble/control/jaxrs/categoryinfo/ExceptionAppInfoNotExists.java | 352 | package com.x.cms.assemble.control.jaxrs.categoryinfo;
import com.x.base.core.project.exception.LanguagePromptException;
class ExceptionAppInfoNotExists extends LanguagePromptException {
private static final long serialVersionUID = 1859164370743532895L;
ExceptionAppInfoNotExists( String id ) {
super("指定的应用不存在:{}.", id );
}
}
| agpl-3.0 |
Sage-Bionetworks/rstudio | src/gwt/src/org/rstudio/studio/client/workbench/events/SessionInitEvent.java | 993 | /*
* SessionInitEvent.java
*
* Copyright (C) 2009-11 by RStudio, Inc.
*
* This program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
package org.rstudio.studio.client.workbench.events;
import com.google.gwt.event.shared.GwtEvent;
public class SessionInitEvent extends GwtEvent<SessionInitHandler>
{
public static final GwtEvent.Type<SessionInitHandler> TYPE =
new GwtEvent.Type<SessionInitHandler>();
public SessionInitEvent()
{
}
@Override
protected void dispatch(SessionInitHandler handler)
{
handler.onSessionInit(this);
}
@Override
public GwtEvent.Type<SessionInitHandler> getAssociatedType()
{
return TYPE;
}
} | agpl-3.0 |
shenan4321/BIMplatform | generated/cn/dlb/bim/models/ifc4/IfcColumnTypeEnum.java | 7467 | /**
* Copyright (C) 2009-2014 BIMserver.org
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package cn.dlb.bim.models.ifc4;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.eclipse.emf.common.util.Enumerator;
/**
* <!-- begin-user-doc -->
* A representation of the literals of the enumeration '<em><b>Ifc Column Type Enum</b></em>',
* and utility methods for working with them.
* <!-- end-user-doc -->
* @see cn.dlb.bim.models.ifc4.Ifc4Package#getIfcColumnTypeEnum()
* @model
* @generated
*/
public enum IfcColumnTypeEnum implements Enumerator {
/**
* The '<em><b>NULL</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #NULL_VALUE
* @generated
* @ordered
*/
NULL(0, "NULL", "NULL"),
/**
* The '<em><b>NOTDEFINED</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #NOTDEFINED_VALUE
* @generated
* @ordered
*/
NOTDEFINED(1, "NOTDEFINED", "NOTDEFINED"),
/**
* The '<em><b>COLUMN</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #COLUMN_VALUE
* @generated
* @ordered
*/
COLUMN(2, "COLUMN", "COLUMN"),
/**
* The '<em><b>USERDEFINED</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #USERDEFINED_VALUE
* @generated
* @ordered
*/
USERDEFINED(3, "USERDEFINED", "USERDEFINED"),
/**
* The '<em><b>PILASTER</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #PILASTER_VALUE
* @generated
* @ordered
*/
PILASTER(4, "PILASTER", "PILASTER");
/**
* The '<em><b>NULL</b></em>' literal value.
* <!-- begin-user-doc -->
* <p>
* If the meaning of '<em><b>NULL</b></em>' literal object isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @see #NULL
* @model
* @generated
* @ordered
*/
public static final int NULL_VALUE = 0;
/**
* The '<em><b>NOTDEFINED</b></em>' literal value.
* <!-- begin-user-doc -->
* <p>
* If the meaning of '<em><b>NOTDEFINED</b></em>' literal object isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @see #NOTDEFINED
* @model
* @generated
* @ordered
*/
public static final int NOTDEFINED_VALUE = 1;
/**
* The '<em><b>COLUMN</b></em>' literal value.
* <!-- begin-user-doc -->
* <p>
* If the meaning of '<em><b>COLUMN</b></em>' literal object isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @see #COLUMN
* @model
* @generated
* @ordered
*/
public static final int COLUMN_VALUE = 2;
/**
* The '<em><b>USERDEFINED</b></em>' literal value.
* <!-- begin-user-doc -->
* <p>
* If the meaning of '<em><b>USERDEFINED</b></em>' literal object isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @see #USERDEFINED
* @model
* @generated
* @ordered
*/
public static final int USERDEFINED_VALUE = 3;
/**
* The '<em><b>PILASTER</b></em>' literal value.
* <!-- begin-user-doc -->
* <p>
* If the meaning of '<em><b>PILASTER</b></em>' literal object isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @see #PILASTER
* @model
* @generated
* @ordered
*/
public static final int PILASTER_VALUE = 4;
/**
* An array of all the '<em><b>Ifc Column Type Enum</b></em>' enumerators.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private static final IfcColumnTypeEnum[] VALUES_ARRAY = new IfcColumnTypeEnum[] { NULL, NOTDEFINED, COLUMN, USERDEFINED, PILASTER, };
/**
* A public read-only list of all the '<em><b>Ifc Column Type Enum</b></em>' enumerators.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public static final List<IfcColumnTypeEnum> VALUES = Collections.unmodifiableList(Arrays.asList(VALUES_ARRAY));
/**
* Returns the '<em><b>Ifc Column Type Enum</b></em>' literal with the specified literal value.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param literal the literal.
* @return the matching enumerator or <code>null</code>.
* @generated
*/
public static IfcColumnTypeEnum get(String literal) {
for (int i = 0; i < VALUES_ARRAY.length; ++i) {
IfcColumnTypeEnum result = VALUES_ARRAY[i];
if (result.toString().equals(literal)) {
return result;
}
}
return null;
}
/**
* Returns the '<em><b>Ifc Column Type Enum</b></em>' literal with the specified name.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param name the name.
* @return the matching enumerator or <code>null</code>.
* @generated
*/
public static IfcColumnTypeEnum getByName(String name) {
for (int i = 0; i < VALUES_ARRAY.length; ++i) {
IfcColumnTypeEnum result = VALUES_ARRAY[i];
if (result.getName().equals(name)) {
return result;
}
}
return null;
}
/**
* Returns the '<em><b>Ifc Column Type Enum</b></em>' literal with the specified integer value.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the integer value.
* @return the matching enumerator or <code>null</code>.
* @generated
*/
public static IfcColumnTypeEnum get(int value) {
switch (value) {
case NULL_VALUE:
return NULL;
case NOTDEFINED_VALUE:
return NOTDEFINED;
case COLUMN_VALUE:
return COLUMN;
case USERDEFINED_VALUE:
return USERDEFINED;
case PILASTER_VALUE:
return PILASTER;
}
return null;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private final int value;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private final String name;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private final String literal;
/**
* Only this class can construct instances.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private IfcColumnTypeEnum(int value, String name, String literal) {
this.value = value;
this.name = name;
this.literal = literal;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public int getValue() {
return value;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getName() {
return name;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getLiteral() {
return literal;
}
/**
* Returns the literal value of the enumerator, which is its string representation.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String toString() {
return literal;
}
} //IfcColumnTypeEnum
| agpl-3.0 |
moskiteau/KalturaGeneratedAPIClientsJava | src/com/kaltura/client/types/KalturaSiteCondition.java | 2106 | // ===================================================================================================
// _ __ _ _
// | |/ /__ _| | |_ _ _ _ _ __ _
// | ' </ _` | | _| || | '_/ _` |
// |_|\_\__,_|_|\__|\_,_|_| \__,_|
//
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
//
// Copyright (C) 2006-2015 Kaltura Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
// @ignore
// ===================================================================================================
package com.kaltura.client.types;
import org.w3c.dom.Element;
import com.kaltura.client.KalturaParams;
import com.kaltura.client.KalturaApiException;
/**
* This class was generated using generate.php
* against an XML schema provided by Kaltura.
* @date Mon, 10 Aug 15 02:02:11 -0400
*
* MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN.
*/
@SuppressWarnings("serial")
public class KalturaSiteCondition extends KalturaMatchCondition {
public KalturaSiteCondition() {
}
public KalturaSiteCondition(Element node) throws KalturaApiException {
super(node);
}
public KalturaParams toParams() {
KalturaParams kparams = super.toParams();
kparams.add("objectType", "KalturaSiteCondition");
return kparams;
}
}
| agpl-3.0 |
ridalarry/ProtocolSupport | src/protocolsupport/protocol/PacketDataSerializer.java | 9425 | package protocolsupport.protocol;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutput;
import java.io.DataOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.UUID;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import org.bukkit.Bukkit;
import org.bukkit.craftbukkit.v1_8_R3.inventory.CraftItemStack;
import org.spigotmc.LimitStream;
import org.spigotmc.SneakyThrow;
import com.mojang.authlib.GameProfile;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufInputStream;
import io.netty.buffer.ByteBufOutputStream;
import io.netty.handler.codec.EncoderException;
import net.minecraft.server.v1_8_R3.BlockPosition;
import net.minecraft.server.v1_8_R3.GameProfileSerializer;
import net.minecraft.server.v1_8_R3.IChatBaseComponent.ChatSerializer;
import net.minecraft.server.v1_8_R3.Item;
import net.minecraft.server.v1_8_R3.ItemStack;
import net.minecraft.server.v1_8_R3.Items;
import net.minecraft.server.v1_8_R3.NBTCompressedStreamTools;
import net.minecraft.server.v1_8_R3.NBTReadLimiter;
import net.minecraft.server.v1_8_R3.NBTTagCompound;
import net.minecraft.server.v1_8_R3.NBTTagList;
import net.minecraft.server.v1_8_R3.NBTTagString;
import protocolsupport.api.ProtocolVersion;
import protocolsupport.api.events.ItemStackWriteEvent;
import protocolsupport.protocol.transformer.utils.LegacyUtils;
import protocolsupport.protocol.typeremapper.id.IdRemapper;
import protocolsupport.protocol.typeskipper.id.IdSkipper;
import protocolsupport.protocol.typeskipper.id.SkippingTable;
import protocolsupport.utils.netty.Allocator;
import protocolsupport.utils.netty.ChannelUtils;
public class PacketDataSerializer extends net.minecraft.server.v1_8_R3.PacketDataSerializer {
private ProtocolVersion version;
public PacketDataSerializer(ByteBuf buf, ProtocolVersion version) {
this(buf);
this.version = version;
}
public ProtocolVersion getVersion() {
return version;
}
protected PacketDataSerializer(ByteBuf buf) {
super(buf);
}
protected void setVersion(ProtocolVersion version) {
this.version = version;
}
@Override
public void a(ItemStack itemstack) {
itemstack = transformItemStack(itemstack);
if ((itemstack == null) || (itemstack.getItem() == null)) {
writeShort(-1);
} else {
int itemId = Item.getId(itemstack.getItem());
writeShort(IdRemapper.ITEM.getTable(getVersion()).getRemap(itemId));
writeByte(itemstack.count);
writeShort(itemstack.getData());
a(itemstack.getTag());
}
}
@Override
public void a(NBTTagCompound nbttagcompound) {
if (getVersion().isBefore(ProtocolVersion.MINECRAFT_1_8)) {
if (nbttagcompound == null) {
writeShort(-1);
} else {
byte[] abyte = write(nbttagcompound);
writeShort(abyte.length);
writeBytes(abyte);
}
} else {
if (nbttagcompound == null) {
writeByte(0);
} else {
ByteBufOutputStream out = new ByteBufOutputStream(Allocator.allocateBuffer());
try {
NBTCompressedStreamTools.a(nbttagcompound, (DataOutput) new DataOutputStream(out));
writeBytes(out.buffer());
} catch (Throwable ioexception) {
throw new EncoderException(ioexception);
} finally {
out.buffer().release();
}
}
}
}
private ItemStack transformItemStack(ItemStack original) {
if (original == null) {
return null;
}
ItemStack itemstack = original.cloneItemStack();
Item item = itemstack.getItem();
NBTTagCompound nbttagcompound = itemstack.getTag();
if (nbttagcompound != null) {
if (getVersion().isBefore(ProtocolVersion.MINECRAFT_1_8) && item == Items.WRITTEN_BOOK) {
if (nbttagcompound.hasKeyOfType("pages", 9)) {
NBTTagList pages = nbttagcompound.getList("pages", 8);
NBTTagList newpages = new NBTTagList();
for (int i = 0; i < pages.size(); i++) {
newpages.add(new NBTTagString(LegacyUtils.toText(ChatSerializer.a(pages.getString(i)))));
}
nbttagcompound.set("pages", newpages);
}
}
if (getVersion().isBeforeOrEq(ProtocolVersion.MINECRAFT_1_7_5) && item == Items.SKULL) {
transformSkull(nbttagcompound);
}
if (nbttagcompound.hasKeyOfType("ench", 9)) {
SkippingTable enchSkip = IdSkipper.ENCHANT.getTable(getVersion());
NBTTagList enchList = nbttagcompound.getList("ench", 10);
NBTTagList newList = new NBTTagList();
for (int i = 0; i < enchList.size(); i++) {
NBTTagCompound enchData = enchList.get(i);
if (!enchSkip.shouldSkip(enchData.getInt("id") & 0xFFFF)) {
newList.add(enchData);
}
}
if (newList.size() > 0) {
nbttagcompound.set("ench", newList);
} else {
nbttagcompound.remove("ench");
}
}
}
if (ItemStackWriteEvent.getHandlerList().getRegisteredListeners().length > 0) {
ItemStackWriteEvent event = new InternalItemStackWriteEvent(getVersion(), original, itemstack);
Bukkit.getPluginManager().callEvent(event);
}
return itemstack;
}
public static void transformSkull(NBTTagCompound nbttagcompound) {
transformSkull(nbttagcompound, "SkullOwner", "SkullOwner");
transformSkull(nbttagcompound, "Owner", "ExtraType");
}
private static void transformSkull(NBTTagCompound tag, String tagname, String newtagname) {
if (tag.hasKeyOfType(tagname, 10)) {
GameProfile gameprofile = GameProfileSerializer.deserialize(tag.getCompound(tagname));
if (gameprofile.getName() != null) {
tag.set(newtagname, new NBTTagString(gameprofile.getName()));
} else {
tag.remove(tagname);
}
}
}
@Override
public NBTTagCompound h() throws IOException {
if (getVersion().isBefore(ProtocolVersion.MINECRAFT_1_8)) {
final short length = readShort();
if (length < 0) {
return null;
}
final byte[] data = new byte[length];
readBytes(data);
return read(data, new NBTReadLimiter(2097152L));
} else {
int index = readerIndex();
if (readByte() == 0) {
return null;
}
readerIndex(index);
return NBTCompressedStreamTools.a(new DataInputStream(new ByteBufInputStream(this)), new NBTReadLimiter(2097152L));
}
}
@Override
public String c(int limit) {
if (getVersion().isBeforeOrEq(ProtocolVersion.MINECRAFT_1_6_4)) {
return new String(ChannelUtils.toArray(readBytes(readUnsignedShort() * 2)), StandardCharsets.UTF_16BE);
} else {
return super.c(limit);
}
}
@Override
public PacketDataSerializer a(String string) {
if (getVersion().isBeforeOrEq(ProtocolVersion.MINECRAFT_1_6_4)) {
writeShort(string.length());
writeBytes(string.getBytes(StandardCharsets.UTF_16BE));
} else {
super.a(string);
}
return this;
}
@Override
public byte[] a() {
if (getVersion().isBeforeOrEq(ProtocolVersion.MINECRAFT_1_7_10)) {
byte[] array = new byte[readShort()];
readBytes(array);
return array;
} else {
return super.a();
}
}
@Override
public void a(byte[] array) {
if (getVersion().isBeforeOrEq(ProtocolVersion.MINECRAFT_1_7_10)) {
if (array.length > 32767) {
throw new IllegalArgumentException("Too big array length of "+array.length);
}
writeShort(array.length);
writeBytes(array);
} else {
super.a(array);
}
}
public int readVarInt() {
return e();
}
public void writeVarInt(int varInt) {
b(varInt);
}
public String readString(int limit) {
return c(limit);
}
public void writeString(String string) {
a(string);
}
public ItemStack readItemStack() throws IOException {
return i();
}
public void writeItemStack(ItemStack itemstack) {
a(itemstack);
}
public byte[] readArray() {
return a();
}
public void writeArray(byte[] array) {
a(array);
}
public BlockPosition readPosition() {
return c();
}
public void writePosition(BlockPosition position) {
a(position);
}
public UUID readUUID() {
return g();
}
public void writeUUID(UUID uuid) {
a(uuid);
}
public NBTTagCompound readTag() throws IOException {
return h();
}
public void writeTag(NBTTagCompound tag) {
a(tag);
}
private static NBTTagCompound read(final byte[] data, final NBTReadLimiter nbtreadlimiter) {
try {
try (DataInputStream datainputstream = new DataInputStream(new BufferedInputStream(new LimitStream(new GZIPInputStream(new ByteArrayInputStream(data)), nbtreadlimiter)))) {
return NBTCompressedStreamTools.a(datainputstream, nbtreadlimiter);
}
} catch (IOException ex) {
SneakyThrow.sneaky(ex);
return null;
}
}
private static byte[] write(final NBTTagCompound nbttagcompound) {
try {
ByteArrayOutputStream bytearrayoutputstream = new ByteArrayOutputStream();
try (DataOutputStream dataoutputstream = new DataOutputStream(new GZIPOutputStream(bytearrayoutputstream))) {
NBTCompressedStreamTools.a(nbttagcompound, (DataOutput) dataoutputstream);
}
return bytearrayoutputstream.toByteArray();
} catch (IOException ex) {
SneakyThrow.sneaky(ex);
return null;
}
}
public static class InternalItemStackWriteEvent extends ItemStackWriteEvent {
private final CraftItemStack wrapped;
public InternalItemStackWriteEvent(ProtocolVersion version, ItemStack original, ItemStack itemstack) {
super(version, CraftItemStack.asCraftMirror(original));
this.wrapped = CraftItemStack.asCraftMirror(itemstack);
}
@Override
public org.bukkit.inventory.ItemStack getResult() {
return wrapped;
}
}
}
| agpl-3.0 |
SilverDav/Silverpeas-Core | core-web/src/integration-test/java/org/silverpeas/core/webapi/workflow/ReplacementResourceGettingIT.java | 14372 | /*
* Copyright (C) 2000 - 2021 Silverpeas
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* As a special exception to the terms and conditions of version 3.0 of
* the GPL, you may redistribute this Program in connection with Free/Libre
* Open Source Software ("FLOSS") applications as described in Silverpeas's
* FLOSS exception. You should have received a copy of the text describing
* the FLOSS exception, and it is also available here:
* "https://www.silverpeas.org/legal/floss_exception.html"
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.silverpeas.core.webapi.workflow;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.Archive;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.silverpeas.core.admin.user.model.User;
import org.silverpeas.core.web.test.WarBuilder4WebCore;
import org.silverpeas.core.webapi.util.UserEntity;
import org.silverpeas.core.workflow.api.user.Replacement;
import org.silverpeas.web.ResourceGettingTest;
import javax.ws.rs.core.Response;
import java.time.LocalDate;
import java.util.stream.Stream;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
/**
* Integration tests on the web service handling the replacements of users in a workflow.
* @author mmoquillon
*/
@RunWith(Arquillian.class)
public class ReplacementResourceGettingIT extends ResourceGettingTest {
private static final String TABLE_CREATION_SCRIPT =
"/org/silverpeas/core/webapi/workflow/replacement/create-table.sql";
private static final String DATA_SET_SCRIPT =
"/org/silverpeas/core/webapi/workflow/replacement/create-dataset.sql";
private static final String SUPERVISOR_ID = "0";
private static final int STATUS_OK = Response.Status.OK.getStatusCode();
private String authToken;
private User user;
private ReplacementEntity resource;
@Deployment
public static Archive<?> createTestArchive() {
return WarBuilder4WebCore.onWarForTestClass(ReplacementResourceGettingIT.class)
.addRESTWebServiceEnvironment()
.addStringTemplateFeatures()
.addClasses(UserEntity.class)
.addMavenDependenciesWithPersistence(
"org.silverpeas.core.services:silverpeas-core-workflow",
"org.silverpeas.core.services:silverpeas-core-personalorganizer")
.testFocusedOn(w -> w.addPackages(true, "org.silverpeas.core.webapi.workflow")
.addAsResource("org/silverpeas/workflow/multilang"))
.build();
}
@Before
public void prepareTests() {
user = User.getById("1");
authToken = getTokenKeyOf(user);
final String replacementId = "92b0fa2f-3287-4f99-a9b7-16424f82d607";
Replacement replacement = Replacement.get(replacementId)
.orElseThrow(() -> new AssertionError("No replacement with id " + replacementId));
resource = new ReplacementEntity(replacement);
}
@Override
protected String getTableCreationScript() {
return TABLE_CREATION_SCRIPT;
}
@Override
protected String getDataSetScript() {
return DATA_SET_SCRIPT;
}
@Test
public void getAllReplacementsByAnAuthorizedUser() {
final String aWorkflowId = getExistingComponentInstances()[0];
Response response = getAt(uriWithSubstitute(replacementsUri(aWorkflowId), "2"), Response.class);
assertThat(response.getStatus(), is(STATUS_OK));
ReplacementEntity[] replacements = response.readEntity(ReplacementEntity[].class);
assertThat(replacements.length, is(1));
assertThat(replacements[0].getURI().isAbsolute(), is(true));
assertThat(replacements[0].getIncumbent().getId(), is("1"));
assertThat(replacements[0].getSubstitute().getId(), is("2"));
assertThat(replacements[0].getWorkflowInstanceId(), is(aWorkflowId));
}
@Test
public void getAllReplacementsOfAnAuthorizedUser() {
final String aWorkflowId = getExistingComponentInstances()[0];
Response response = getAt(uriWithIncumbent(replacementsUri(aWorkflowId), "1"), Response.class);
assertThat(response.getStatus(), is(STATUS_OK));
ReplacementEntity[] replacements = response.readEntity(ReplacementEntity[].class);
assertThat(replacements.length, is(1));
assertThat(replacements[0].getURI().isAbsolute(), is(true));
assertThat(replacements[0].getIncumbent().getId(), is("1"));
assertThat(replacements[0].getSubstitute().getId(), is("2"));
assertThat(replacements[0].getWorkflowInstanceId(), is(aWorkflowId));
}
@Test
public void getAllReplacementsWithConcernedUsers() {
final String aWorkflowId = getExistingComponentInstances()[0];
Response response =
getAt(uriWithSubstitute(uriWithIncumbent(replacementsUri(aWorkflowId), "1"), "2"),
Response.class);
assertThat(response.getStatus(), is(STATUS_OK));
ReplacementEntity[] replacements = response.readEntity(ReplacementEntity[].class);
assertThat(replacements.length, is(1));
assertThat(replacements[0].getURI().isAbsolute(), is(true));
assertThat(replacements[0].getIncumbent().getId(), is("1"));
assertThat(replacements[0].getSubstitute().getId(), is("2"));
assertThat(replacements[0].getWorkflowInstanceId(), is(aWorkflowId));
}
@Test
public void aNonConcernedUserAsksForAllReplacementsByASubstitute() {
user = User.getById("3");
authToken = getTokenKeyOf(user);
final String aWorkflowId = getExistingComponentInstances()[0];
Response response = getAt(uriWithSubstitute(replacementsUri(aWorkflowId), "2"), Response.class);
assertThat(response.getStatus(), is(STATUS_OK));
ReplacementEntity[] replacements = response.readEntity(ReplacementEntity[].class);
assertThat(replacements.length, is(0));
}
@Test
public void aNonConcernedUserAsksForAllReplacementsOfAnIncumbent() {
user = User.getById("3");
authToken = getTokenKeyOf(user);
final String aWorkflowId = getExistingComponentInstances()[0];
Response response = getAt(uriWithIncumbent(replacementsUri(aWorkflowId), "1"), Response.class);
assertThat(response.getStatus(), is(STATUS_OK));
ReplacementEntity[] replacements = response.readEntity(ReplacementEntity[].class);
assertThat(replacements.length, is(0));
}
@Test
public void aSupervisorAsksForAllReplacementsByASubstitute() {
user = User.getById(SUPERVISOR_ID);
authToken = getTokenKeyOf(user);
final String aWorkflowId = getExistingComponentInstances()[0];
Response response = getAt(uriWithSubstitute(replacementsUri(aWorkflowId), "2"), Response.class);
assertThat(response.getStatus(), is(STATUS_OK));
ReplacementEntity[] replacements = response.readEntity(ReplacementEntity[].class);
assertThat(replacements.length, is(1));
assertThat(replacements[0].getURI().isAbsolute(), is(true));
assertThat(replacements[0].getIncumbent().getId(), is("1"));
assertThat(replacements[0].getSubstitute().getId(), is("2"));
assertThat(replacements[0].getWorkflowInstanceId(), is(aWorkflowId));
}
@Test
public void aSupervisorAsksForAllReplacementsOfAnIncumbent() {
user = User.getById(SUPERVISOR_ID);
authToken = getTokenKeyOf(user);
final String aWorkflowId = getExistingComponentInstances()[0];
Response response = getAt(uriWithIncumbent(replacementsUri(aWorkflowId), "1"), Response.class);
assertThat(response.getStatus(), is(STATUS_OK));
ReplacementEntity[] replacements = response.readEntity(ReplacementEntity[].class);
assertThat(replacements.length, is(1));
assertThat(replacements[0].getURI().isAbsolute(), is(true));
assertThat(replacements[0].getIncumbent().getId(), is("1"));
assertThat(replacements[0].getSubstitute().getId(), is("2"));
assertThat(replacements[0].getWorkflowInstanceId(), is(aWorkflowId));
}
@Test
public void aSupervisorAsksForAllReplacementsInAWorkflow() {
user = User.getById(SUPERVISOR_ID);
authToken = getTokenKeyOf(user);
final String aWorkflowId = getExistingComponentInstances()[1];
Response response = getAt(replacementsUri(aWorkflowId), Response.class);
assertThat(response.getStatus(), is(STATUS_OK));
ReplacementEntity[] replacements = response.readEntity(ReplacementEntity[].class);
assertThat(replacements.length, is(4));
assertThat(Stream.of(replacements).allMatch(r -> r.getWorkflowInstanceId().equals(aWorkflowId)),
is(true));
}
@Test
public void aNonSupervisorAsksForAllReplacementsInAWorkflow() {
final String aWorkflowId = getExistingComponentInstances()[1];
final int Forbidden = Response.Status.FORBIDDEN.getStatusCode();
Response response = getAt(replacementsUri(aWorkflowId), Response.class);
assertThat(response.getStatus(), is(Forbidden));
}
@Test
public void aSupervisorAsksForAGivenReplacement() {
user = User.getById(SUPERVISOR_ID);
authToken = getTokenKeyOf(user);
final String aWorkflowId = getExistingComponentInstances()[1];
final String replacementId = "64c8e712-e48a-4c63-b768-a5385f30a1ae";
Response response =
getAt(uriOfReplacement(replacementsUri(aWorkflowId), replacementId), Response.class);
assertThat(response.getStatus(), is(STATUS_OK));
ReplacementEntity replacement = response.readEntity(ReplacementEntity.class);
assertThat(replacement.getURI()
.toString()
.endsWith(uriOfReplacement(replacementsUri(aWorkflowId), replacementId)), is(true));
assertThat(replacement.getIncumbent().getId(), is("1"));
assertThat(replacement.getSubstitute().getId(), is("3"));
assertThat(replacement.getWorkflowInstanceId(), is(aWorkflowId));
assertThat(replacement.getStartDate(), is(LocalDate.parse("2018-04-09")));
assertThat(replacement.getEndDate(), is(LocalDate.parse("2018-04-13")));
}
@Test
public void anIncumbentAsksForOneOfHisReplacement() {
user = User.getById("1");
authToken = getTokenKeyOf(user);
final String aWorkflowId = getExistingComponentInstances()[1];
final String replacementId = "64c8e712-e48a-4c63-b768-a5385f30a1ae";
Response response =
getAt(uriOfReplacement(replacementsUri(aWorkflowId), replacementId), Response.class);
assertThat(response.getStatus(), is(STATUS_OK));
ReplacementEntity replacement = response.readEntity(ReplacementEntity.class);
assertThat(replacement.getURI()
.toString()
.endsWith(uriOfReplacement(replacementsUri(aWorkflowId), replacementId)), is(true));
assertThat(replacement.getIncumbent().getId(), is("1"));
assertThat(replacement.getSubstitute().getId(), is("3"));
assertThat(replacement.getWorkflowInstanceId(), is(aWorkflowId));
assertThat(replacement.getStartDate(), is(LocalDate.parse("2018-04-09")));
assertThat(replacement.getEndDate(), is(LocalDate.parse("2018-04-13")));
}
@Test
public void aSubstituteAsksForOneOfHisReplacement() {
user = User.getById("3");
authToken = getTokenKeyOf(user);
final String aWorkflowId = getExistingComponentInstances()[1];
final String replacementId = "64c8e712-e48a-4c63-b768-a5385f30a1ae";
Response response =
getAt(uriOfReplacement(replacementsUri(aWorkflowId), replacementId), Response.class);
assertThat(response.getStatus(), is(STATUS_OK));
ReplacementEntity replacement = response.readEntity(ReplacementEntity.class);
assertThat(replacement.getURI()
.toString()
.endsWith(uriOfReplacement(replacementsUri(aWorkflowId), replacementId)), is(true));
assertThat(replacement.getIncumbent().getId(), is("1"));
assertThat(replacement.getSubstitute().getId(), is("3"));
assertThat(replacement.getWorkflowInstanceId(), is(aWorkflowId));
assertThat(replacement.getStartDate(), is(LocalDate.parse("2018-04-09")));
assertThat(replacement.getEndDate(), is(LocalDate.parse("2018-04-13")));
}
@Test
public void aNonSupervisorAsksForAReplacementForWhichHeIsNotConcerned() {
user = User.getById("2");
authToken = getTokenKeyOf(user);
final String aWorkflowId = getExistingComponentInstances()[1];
final int Forbidden = Response.Status.FORBIDDEN.getStatusCode();
final String replacementId = "64c8e712-e48a-4c63-b768-a5385f30a1ae";
Response response =
getAt(uriOfReplacement(replacementsUri(aWorkflowId), replacementId), Response.class);
assertThat(response.getStatus(), is(Forbidden));
}
@Override
public String[] getExistingComponentInstances() {
return new String[]{"workflow24", "workflow42"};
}
@Override
public String aResourceURI() {
return uriWithIncumbent(replacementsUri(getExistingComponentInstances()[0]), "1");
}
@Override
public String anUnexistingResourceURI() {
return uriWithIncumbent(replacementsUri("workflow32"), "1");
}
@Override
public ReplacementEntity aResource() {
return resource;
}
@Override
public String getAPITokenValue() {
return authToken;
}
@Override
public Class<?> getWebEntityClass() {
return ReplacementEntity.class;
}
private String uriWithIncumbent(final String replacementsUri, final String incumbentId) {
final String sep = replacementsUri.contains("?") ? "&" : "?";
return replacementsUri + sep + "incumbent=" + incumbentId;
}
private String uriWithSubstitute(final String replacementsUri, final String substituteId) {
final String sep = replacementsUri.contains("?") ? "&" : "?";
return replacementsUri + sep + "substitute=" + substituteId;
}
private String replacementsUri(final String workflowId) {
return "workflow/" + workflowId + "/replacements";
}
private String uriOfReplacement(final String replacementsUri, final String replacementId) {
return replacementsUri + "/" + replacementId;
}
}
| agpl-3.0 |
jjgao/oncokb | core/src/main/java/org/mskcc/cbio/oncokb/model/GeneNumber.java | 2772 | package org.mskcc.cbio.oncokb.model;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
@ApiModel(description = "")
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-08T23:17:19.384Z")
public class GeneNumber {
private Gene gene = null;
private Integer alteration = null;
private Integer tumorType = null;
private String highestLevel = null;
/**
**/
@ApiModelProperty(value = "")
@JsonProperty("gene")
public Gene getGene() {
return gene;
}
public void setGene(Gene gene) {
this.gene = gene;
}
/**
**/
@ApiModelProperty(value = "")
@JsonProperty("alteration")
public Integer getAlteration() {
return alteration;
}
public void setAlteration(Integer alteration) {
this.alteration = alteration;
}
/**
**/
@ApiModelProperty(value = "")
@JsonProperty("tumorType")
public Integer getTumorType() {
return tumorType;
}
public void setTumorType(Integer tumorType) {
this.tumorType = tumorType;
}
/**
**/
@ApiModelProperty(value = "")
@JsonProperty("highestLevel")
public String getHighestLevel() {
return highestLevel;
}
public void setHighestLevel(String highestLevel) {
this.highestLevel = highestLevel;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
GeneNumber that = (GeneNumber) o;
if (gene != null ? !gene.equals(that.gene) : that.gene != null) return false;
if (alteration != null ? !alteration.equals(that.alteration) : that.alteration != null) return false;
if (tumorType != null ? !tumorType.equals(that.tumorType) : that.tumorType != null) return false;
if (highestLevel != null ? !highestLevel.equals(that.highestLevel) : that.highestLevel != null) return false;
return true;
}
@Override
public int hashCode() {
int result = gene != null ? gene.hashCode() : 0;
result = 31 * result + (alteration != null ? alteration.hashCode() : 0);
result = 31 * result + (tumorType != null ? tumorType.hashCode() : 0);
result = 31 * result + (highestLevel != null ? highestLevel.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "GeneNumber{" +
"gene=" + gene +
", alteration=" + alteration +
", tumorType=" + tumorType +
", highestLevel='" + highestLevel + '\'' +
'}';
}
}
| agpl-3.0 |
dzhw/metadatamanagement | src/main/java/eu/dzhw/fdz/metadatamanagement/common/domain/validation/ValidShadowIdValidator.java | 1210 | package eu.dzhw.fdz.metadatamanagement.common.domain.validation;
import eu.dzhw.fdz.metadatamanagement.common.domain.AbstractShadowableRdcDomainObject;
import org.springframework.util.StringUtils;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
/**
* Default validator implementation for {@link ValidShadowId} validation.
*/
public class ValidShadowIdValidator
implements ConstraintValidator<ValidShadowId, AbstractShadowableRdcDomainObject> {
@Override
public boolean isValid(AbstractShadowableRdcDomainObject abstractShadowableRdcDomainObject,
ConstraintValidatorContext constraintValidatorContext) {
if (!abstractShadowableRdcDomainObject.isShadow()) {
return true;
}
String masterId = abstractShadowableRdcDomainObject.getMasterId();
String id = abstractShadowableRdcDomainObject.getId();
if (!StringUtils.hasText(masterId) || !StringUtils.hasText(id)) {
return false;
}
if (!id.startsWith(masterId)) {
return false;
}
String idSuffix = id.substring(masterId.length());
return idSuffix.isEmpty() || idSuffix.matches("^-[0-9]+\\.[0-9]+\\.[0-9]+$");
}
}
| agpl-3.0 |
objective-solutions/taskboard | kpi-parent/kpi-cycle-time/src/test/java/objective/taskboard/followup/kpi/cycletime/CycleTimeDataProviderTest.java | 18809 | package objective.taskboard.followup.kpi.cycletime;
import static objective.taskboard.followup.kpi.properties.KpiCycleTimePropertiesMocker.withSubtaskCycleTimeProperties;
import static org.assertj.core.api.Assertions.assertThat;
import java.time.ZoneId;
import java.util.List;
import java.util.Optional;
import org.junit.Test;
import objective.taskboard.configuration.DashboardConfigurationService;
import objective.taskboard.domain.IssueColorService;
import objective.taskboard.followup.kpi.KpiLevel;
import objective.taskboard.followup.kpi.properties.KpiCycleTimeProperties;
import objective.taskboard.followup.kpi.services.DSLKpi;
import objective.taskboard.followup.kpi.services.DSLSimpleBehaviorWithAsserter;
import objective.taskboard.followup.kpi.services.KpiDataService;
import objective.taskboard.followup.kpi.services.KpiEnvironment;
import objective.taskboard.jira.ProjectService;
import objective.taskboard.timeline.DashboardTimelineProvider;
import objective.taskboard.utils.Clock;
public class CycleTimeDataProviderTest {
@Test
public void getDataSet_happyDay() {
dsl()
.environment()
.givenSubtask("I-1")
.type("Development")
.project("PROJ")
.withTransitions()
.status("Open").date("2019-01-01")
.status("To Do").date("2019-01-02")
.status("Doing").date("2019-01-03")
.status("To Review").date("2019-01-04")
.status("Reviewing").date("2019-01-05")
.status("Done").date("2019-01-06")
.status("Cancelled").noDate()
.eoT()
.eoI()
.givenSubtask("I-2")
.type("Development")
.project("PROJ")
.withTransitions()
.status("Open").date("2019-01-03")
.status("To Do").date("2019-01-04")
.status("Doing").date("2019-01-05")
.status("To Review").date("2019-01-06")
.status("Reviewing").date("2019-01-07")
.status("Done").date("2019-01-08")
.status("Cancelled").noDate()
.eoT()
.eoI()
.withKpiProperties(
withSubtaskCycleTimeProperties("To Do","Doing","To Review","Reviewing")
)
.when()
.appliesBehavior(generateDataSet("PROJ",KpiLevel.SUBTASKS))
.then()
.dataSetHasTotalSize(2)
.givenIssue("I-1")
.hasTotalCycleTime(5l)
.startsAt("2019-01-02")
.endsAt("2019-01-06")
.hasSubCycles()
.subCycle("To Do").hasCycleTimeInDays(1l).eoS()
.subCycle("Doing").hasCycleTimeInDays(1l).eoS()
.subCycle("To Review").hasCycleTimeInDays(1l).eoS()
.subCycle("Reviewing").hasCycleTimeInDays(1l).eoS()
.eoSC()
.eoCK()
.givenIssue("I-2")
.hasTotalCycleTime(5l)
.startsAt("2019-01-04")
.endsAt("2019-01-08")
.hasSubCycles()
.subCycle("To Do").hasCycleTimeInDays(1l).eoS()
.subCycle("Doing").hasCycleTimeInDays(1l).eoS()
.subCycle("To Review").hasCycleTimeInDays(1l).eoS()
.subCycle("Reviewing").hasCycleTimeInDays(1l).eoS()
.eoSC()
.eoCK();
}
@Test
public void givenHasDashboardConfiguration_whenGetDataSet_thenFiltersUsingDashboardTimeline() {
dsl()
.environment()
.todayIs("2019-01-10")
.services()
.dashboardConfiguration()
.forProject("PROJ").timelineDaysToDisplay(3)
.endOfDashboardConfiguration()
.eoS()
.givenSubtask("I-1")
.type("Development")
.project("PROJ")
.withTransitions()
.status("Open").date("2019-01-01")
.status("To Do").date("2019-01-02")
.status("Doing").date("2019-01-03")
.status("To Review").date("2019-01-04")
.status("Reviewing").date("2019-01-05")
.status("Done").date("2019-01-06")
.status("Cancelled").noDate()
.eoT()
.eoI()
.givenSubtask("I-2")
.type("Development")
.project("PROJ")
.withTransitions()
.status("Open").date("2019-01-03")
.status("To Do").date("2019-01-04")
.status("Doing").date("2019-01-05")
.status("To Review").date("2019-01-06")
.status("Reviewing").date("2019-01-07")
.status("Done").date("2019-01-08")
.status("Cancelled").noDate()
.eoT()
.eoI()
.withKpiProperties(
withSubtaskCycleTimeProperties("To Do","Doing","To Review","Reviewing")
)
.when()
.appliesBehavior(generateDataSet("PROJ",KpiLevel.SUBTASKS))
.then()
.dataSetHasTotalSize(1)
.givenIssue("I-2")
.hasTotalCycleTime(5l)
.startsAt("2019-01-04")
.endsAt("2019-01-08")
.hasSubCycles()
.subCycle("To Do").hasCycleTimeInDays(1l).eoS()
.subCycle("Doing").hasCycleTimeInDays(1l).eoS()
.subCycle("To Review").hasCycleTimeInDays(1l).eoS()
.subCycle("Reviewing").hasCycleTimeInDays(1l).eoS()
.eoSC()
.eoCK();
}
@Test
public void givenMissingDashboardConfiguration_whenGetDataSet_thenSelectAll() {
dsl()
.environment()
.todayIs("2019-01-10")
.services()
.dashboardConfiguration()
.forProject("PROJ").emptyConfiguration()
.endOfDashboardConfiguration()
.eoS()
.givenSubtask("I-1")
.type("Development")
.project("PROJ")
.withTransitions()
.status("Open").date("2019-01-01")
.status("To Do").date("2019-01-02")
.status("Doing").date("2019-01-03")
.status("To Review").date("2019-01-04")
.status("Reviewing").date("2019-01-05")
.status("Done").date("2019-01-06")
.status("Cancelled").noDate()
.eoT()
.eoI()
.givenSubtask("I-2")
.type("Development")
.project("PROJ")
.withTransitions()
.status("Open").date("2019-01-03")
.status("To Do").date("2019-01-04")
.status("Doing").date("2019-01-05")
.status("To Review").date("2019-01-06")
.status("Reviewing").date("2019-01-07")
.status("Done").date("2019-01-08")
.status("Cancelled").noDate()
.eoT()
.eoI()
.withKpiProperties(
withSubtaskCycleTimeProperties("To Do","Doing","To Review","Reviewing")
)
.when()
.appliesBehavior(generateDataSet("PROJ",KpiLevel.SUBTASKS))
.then()
.dataSetHasTotalSize(2)
.givenIssue("I-1")
.hasTotalCycleTime(5l)
.startsAt("2019-01-02")
.endsAt("2019-01-06")
.hasSubCycles()
.subCycle("To Do").hasCycleTimeInDays(1l).eoS()
.subCycle("Doing").hasCycleTimeInDays(1l).eoS()
.subCycle("To Review").hasCycleTimeInDays(1l).eoS()
.subCycle("Reviewing").hasCycleTimeInDays(1l).eoS()
.eoSC()
.eoCK()
.givenIssue("I-2")
.hasTotalCycleTime(5l)
.startsAt("2019-01-04")
.endsAt("2019-01-08")
.hasSubCycles()
.subCycle("To Do").hasCycleTimeInDays(1l).eoS()
.subCycle("Doing").hasCycleTimeInDays(1l).eoS()
.subCycle("To Review").hasCycleTimeInDays(1l).eoS()
.subCycle("Reviewing").hasCycleTimeInDays(1l).eoS()
.eoSC()
.eoCK();
}
@Test
public void getDataSet_whenNoIssues_thenEmptyDataSet() {
dsl()
.environment()
.withKpiProperties(
withSubtaskCycleTimeProperties("To Do","Doing","To Review","Reviewing")
)
.when()
.appliesBehavior(generateDataSet("PROJ",KpiLevel.SUBTASKS))
.then()
.emptyDataSet();
}
@Test
public void getDataSet_whenNoIssuesForLevel_thenEmptyDataSet(){
dsl()
.environment()
.givenDemand("I-1")
.type("Demand")
.project("PROJ")
.withTransitions()
.status("Open").date("2019-01-01")
.status("To Do").noDate()
.status("Doing").noDate()
.status("To Review").noDate()
.status("Reviewing").noDate()
.status("Done").noDate()
.status("Cancelled").noDate()
.eoT()
.eoI()
.withKpiProperties(
withSubtaskCycleTimeProperties("To Do","Doing","To Review","Reviewing")
)
.when()
.appliesBehavior(generateDataSet("PROJ",KpiLevel.SUBTASKS))
.then()
.emptyDataSet();
}
@Test
public void getDataSet_whenIssuesJumpAllCycleStatus_thenEmptyDataSet(){
dsl()
.environment()
.givenDemand("I-1")
.type("Demand")
.project("PROJ")
.withTransitions()
.status("Open").date("2019-01-01")
.status("To Do").noDate()
.status("Doing").noDate()
.status("To Review").noDate()
.status("Reviewing").noDate()
.status("Done").noDate()
.status("Cancelled").date("2019-01-10")
.eoT()
.eoI()
.withKpiProperties(
withSubtaskCycleTimeProperties("To Do","Doing","To Review","Reviewing")
)
.when()
.appliesBehavior(generateDataSet("PROJ",KpiLevel.SUBTASKS))
.then()
.emptyDataSet();
}
@Test
public void getDataSet_whenAllIssuesAreInProgress_thenEmptyDataSet(){
dsl()
.environment()
.givenSubtask("I-1")
.type("Development")
.project("PROJ")
.withTransitions()
.status("Open").date("2019-01-01")
.status("To Do").date("2019-01-02")
.status("Doing").date("2019-01-03")
.status("To Review").date("2019-01-04")
.status("Reviewing").date("2019-01-05")
.status("Done").noDate()
.status("Cancelled").noDate()
.eoT()
.eoI()
.givenSubtask("I-2")
.type("Development")
.project("PROJ")
.withTransitions()
.status("Open").date("2019-01-03")
.status("To Do").date("2019-01-04")
.status("Doing").date("2019-01-05")
.status("To Review").date("2019-01-06")
.status("Reviewing").date("2019-01-07")
.status("Done").noDate()
.status("Cancelled").noDate()
.eoT()
.eoI()
.withKpiProperties(
withSubtaskCycleTimeProperties("To Do","Doing","To Review","Reviewing")
)
.when()
.appliesBehavior(generateDataSet("PROJ",KpiLevel.SUBTASKS))
.then()
.emptyDataSet();
}
@Test
public void getDataSet_whenCyclePropertiesUnconfigured_thenEmptyDataSet(){
dsl()
.environment()
.givenSubtask("I-1")
.type("Development")
.project("PROJ")
.withTransitions()
.status("Open").date("2019-01-01")
.status("To Do").date("2019-01-02")
.status("Doing").date("2019-01-03")
.status("To Review").date("2019-01-04")
.status("Reviewing").date("2019-01-05")
.status("Done").noDate()
.status("Cancelled").noDate()
.eoT()
.eoI()
.givenSubtask("I-2")
.type("Development")
.project("PROJ")
.withTransitions()
.status("Open").date("2019-01-03")
.status("To Do").date("2019-01-04")
.status("Doing").date("2019-01-05")
.status("To Review").date("2019-01-06")
.status("Reviewing").date("2019-01-07")
.status("Done").noDate()
.status("Cancelled").noDate()
.eoT()
.eoI()
.withKpiProperties(
withSubtaskCycleTimeProperties()
)
.when()
.appliesBehavior(generateDataSet("PROJ",KpiLevel.SUBTASKS))
.then()
.emptyDataSet();
}
@Test
public void getDataSet_whenCyclePropertiesMisconfigured_thenEmptyDataSet(){
dsl()
.environment()
.givenSubtask("I-1")
.type("Development")
.project("PROJ")
.withTransitions()
.status("Open").date("2019-01-01")
.status("To Do").date("2019-01-02")
.status("Doing").date("2019-01-03")
.status("To Review").date("2019-01-04")
.status("Reviewing").date("2019-01-05")
.status("Done").noDate()
.status("Cancelled").noDate()
.eoT()
.eoI()
.givenSubtask("I-2")
.type("Development")
.project("PROJ")
.withTransitions()
.status("Open").date("2019-01-03")
.status("To Do").date("2019-01-04")
.status("Doing").date("2019-01-05")
.status("To Review").date("2019-01-06")
.status("Reviewing").date("2019-01-07")
.status("Done").noDate()
.status("Cancelled").noDate()
.eoT()
.eoI()
.withKpiProperties(
withSubtaskCycleTimeProperties("Foo")
)
.when()
.appliesBehavior(generateDataSet("PROJ",KpiLevel.SUBTASKS))
.then()
.emptyDataSet();
}
private DSLKpi dsl() {
DSLKpi dsl = new DSLKpi();
dsl.environment()
.services()
.projects()
.withKey("PROJ")
.eoP()
.eoPs()
.eoS()
.types()
.addDemand("Demand")
.addFeatures("Feature")
.addSubtasks("Development")
.eoT()
.statuses()
.withProgressingStatuses("Doing","Reviewing","Planning")
.withNotProgressingStatuses("Open","To Do","To Plan","To Review","Cancelled","Done")
.eoS();
return dsl;
}
private GenerateCycleData generateDataSet(String projectKey, KpiLevel level) {
return new GenerateCycleData(projectKey,level);
}
private class GenerateCycleData implements DSLSimpleBehaviorWithAsserter<CycleTimeKpiDataAsserter>{
private String projectKey;
private KpiLevel level;
private CycleTimeKpiDataAsserter asserter;
public GenerateCycleData(String projectKey, KpiLevel level) {
this.projectKey = projectKey;
this.level = level;
}
@Override
public void behave(KpiEnvironment environment) {
KpiDataService kpiService = environment.services().kpiDataService().getImplementation();
KpiCycleTimeProperties properties = environment.getKPIProperties(KpiCycleTimeProperties.class);
IssueColorService colorService = environment.services().issueColor().getService();
ZoneId timezone = environment.getTimezone();
DashboardConfigurationService dashboardConfigurationService = environment.services().dashboardConfiguration().getService();
ProjectService projectService = environment.services().projects().getService();
Clock clock = environment.getClock();
DashboardTimelineProvider timelineProvider = new DashboardTimelineProvider(dashboardConfigurationService, projectService, clock);
CycleTimeDataProvider subject = new CycleTimeDataProvider(kpiService, properties, colorService, timelineProvider);
List<CycleTimeKpi> dataSet = subject.getDataSet(projectKey, level, timezone);
asserter = new CycleTimeKpiDataAsserter(dataSet);
}
@Override
public CycleTimeKpiDataAsserter then() {
return asserter;
}
}
private class CycleTimeKpiDataAsserter {
private List<CycleTimeKpi> dataSet;
public CycleTimeKpiDataAsserter(List<CycleTimeKpi> dataSet) {
this.dataSet = dataSet;
}
public void emptyDataSet() {
assertThat(dataSet).hasSize(0);
}
public CycleTimeKpiAsserter<CycleTimeKpiDataAsserter> givenIssue(String pkey) {
Optional<CycleTimeKpi> opKpi = dataSet.stream().filter(c -> c.getIssueKey().equals(pkey)).findFirst();
assertThat(opKpi).as("Cycle Kpi for issue %s not found.",pkey).isPresent();
return new CycleTimeKpiAsserter<CycleTimeKpiDataAsserter>(opKpi.get(), this);
}
public CycleTimeKpiDataAsserter dataSetHasTotalSize(int size) {
assertThat(dataSet).hasSize(size);
return this;
}
}
}
| agpl-3.0 |
Igorek2312/LibreLingvo | src/main/java/org/libre/lingvo/dto/TranslationsDto.java | 1423 | package org.libre.lingvo.dto;
import org.libre.lingvo.reference.PartOfSpeech;
import java.util.List;
/**
* Created by igorek2312 on 30.10.16.
*/
public class TranslationsDto {
private List<TranslationListItemDto> translations;
private Long filteredRecords;
private Long totalRecords;
private List<LangCodesPairDto> langCodesPairs;
private List<PartOfSpeech> partsOfSpeech;
public List<TranslationListItemDto> getTranslations() {
return translations;
}
public void setTranslations(List<TranslationListItemDto> translations) {
this.translations = translations;
}
public Long getFilteredRecords() {
return filteredRecords;
}
public void setFilteredRecords(Long filteredRecords) {
this.filteredRecords = filteredRecords;
}
public Long getTotalRecords() {
return totalRecords;
}
public void setTotalRecords(Long totalRecords) {
this.totalRecords = totalRecords;
}
public List<LangCodesPairDto> getLangCodesPairs() {
return langCodesPairs;
}
public void setLangCodesPairs(List<LangCodesPairDto> langCodesPairs) {
this.langCodesPairs = langCodesPairs;
}
public List<PartOfSpeech> getPartsOfSpeech() {
return partsOfSpeech;
}
public void setPartsOfSpeech(List<PartOfSpeech> partsOfSpeech) {
this.partsOfSpeech = partsOfSpeech;
}
}
| agpl-3.0 |
RestComm/jss7 | map/map-impl/src/main/java/org/restcomm/protocols/ss7/map/service/mobility/subscriberInformation/LocationInformationEPSImpl.java | 20790 | /*
* TeleStax, Open Source Cloud Communications Copyright 2012.
* and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.restcomm.protocols.ss7.map.service.mobility.subscriberInformation;
import java.io.IOException;
import javolution.xml.XMLFormat;
import javolution.xml.stream.XMLStreamException;
import org.mobicents.protocols.asn.AsnException;
import org.mobicents.protocols.asn.AsnInputStream;
import org.mobicents.protocols.asn.AsnOutputStream;
import org.mobicents.protocols.asn.Tag;
import org.restcomm.protocols.ss7.map.api.MAPException;
import org.restcomm.protocols.ss7.map.api.MAPParsingComponentException;
import org.restcomm.protocols.ss7.map.api.MAPParsingComponentExceptionReason;
import org.restcomm.protocols.ss7.map.api.primitives.DiameterIdentity;
import org.restcomm.protocols.ss7.map.api.primitives.MAPExtensionContainer;
import org.restcomm.protocols.ss7.map.api.service.mobility.subscriberInformation.EUtranCgi;
import org.restcomm.protocols.ss7.map.api.service.mobility.subscriberInformation.GeodeticInformation;
import org.restcomm.protocols.ss7.map.api.service.mobility.subscriberInformation.GeographicalInformation;
import org.restcomm.protocols.ss7.map.api.service.mobility.subscriberInformation.LocationInformationEPS;
import org.restcomm.protocols.ss7.map.api.service.mobility.subscriberInformation.TAId;
import org.restcomm.protocols.ss7.map.primitives.DiameterIdentityImpl;
import org.restcomm.protocols.ss7.map.primitives.MAPExtensionContainerImpl;
import org.restcomm.protocols.ss7.map.primitives.SequenceBase;
/**
* @author amit bhayani
* @author sergey vetyutnev
*
*/
public class LocationInformationEPSImpl extends SequenceBase implements LocationInformationEPS {
public static final int _ID_eUtranCellGlobalIdentity = 0;
public static final int _ID_trackingAreaIdentity = 1;
public static final int _ID_extensionContainer = 2;
public static final int _ID_geographicalInformation = 3;
public static final int _ID_geodeticInformation = 4;
public static final int _ID_currentLocationRetrieved = 5;
public static final int _ID_ageOfLocationInformation = 6;
public static final int _ID_mme_Name = 7;
private static final String E_UTRAN_CELL_GLOBAL_IDENTITY = "eUtranCellGlobalIdentity";
private static final String TRACKING_AREA_IDENTITY = "trackingAreaIdentity";
private static final String EXTENSION_CONTAINER = "extensionContainer";
private static final String GEOGRAPHICAL_INFORMATION = "geographicalInformation";
private static final String GEODETIC_INFORMATION = "geodeticInformation";
private static final String CURRENT_LOCATION_RETRIEVED = "currentLocationRetrieved";
private static final String AGE_OF_LOCATION_INFORMATION = "ageOfLocationInformation";
private static final String MME_NAME = "mmeName";
private EUtranCgi eUtranCellGlobalIdentity = null;
private TAId trackingAreaIdentity = null;
private MAPExtensionContainer extensionContainer = null;
private GeographicalInformation geographicalInformation = null;
private GeodeticInformation geodeticInformation = null;
private boolean currentLocationRetrieved = false;
private Integer ageOfLocationInformation = null;
private DiameterIdentity mmeName = null;
/**
*
*/
public LocationInformationEPSImpl() {
super("LocationInformationEPS");
}
/**
* @param eUtranCellGlobalIdentity
* @param trackingAreaIdentity
* @param extensionContainer
* @param geographicalInformation
* @param geodeticInformation
* @param currentLocationRetrieved
* @param ageOfLocationInformation
* @param mmeName
*/
public LocationInformationEPSImpl(EUtranCgi eUtranCellGlobalIdentity, TAId trackingAreaIdentity,
MAPExtensionContainer extensionContainer, GeographicalInformation geographicalInformation,
GeodeticInformation geodeticInformation, boolean currentLocationRetrieved, Integer ageOfLocationInformation,
DiameterIdentity mmeName) {
super("LocationInformationEPS");
this.eUtranCellGlobalIdentity = eUtranCellGlobalIdentity;
this.trackingAreaIdentity = trackingAreaIdentity;
this.extensionContainer = extensionContainer;
this.geographicalInformation = geographicalInformation;
this.geodeticInformation = geodeticInformation;
this.currentLocationRetrieved = currentLocationRetrieved;
this.ageOfLocationInformation = ageOfLocationInformation;
this.mmeName = mmeName;
}
/*
* (non-Javadoc)
*
* @see org.restcomm.protocols.ss7.map.api.service.subscriberInformation.
* LocationInformationEPS#getEUtranCellGlobalIdentity()
*/
public EUtranCgi getEUtranCellGlobalIdentity() {
return this.eUtranCellGlobalIdentity;
}
/*
* (non-Javadoc)
*
* @see org.restcomm.protocols.ss7.map.api.service.subscriberInformation. LocationInformationEPS#getTrackingAreaIdentity()
*/
public TAId getTrackingAreaIdentity() {
return this.trackingAreaIdentity;
}
/*
* (non-Javadoc)
*
* @see org.restcomm.protocols.ss7.map.api.service.subscriberInformation. LocationInformationEPS#getExtensionContainer()
*/
public MAPExtensionContainer getExtensionContainer() {
return this.extensionContainer;
}
/*
* (non-Javadoc)
*
* @see org.restcomm.protocols.ss7.map.api.service.subscriberInformation.
* LocationInformationEPS#getGeographicalInformation()
*/
public GeographicalInformation getGeographicalInformation() {
return this.geographicalInformation;
}
/*
* (non-Javadoc)
*
* @see org.restcomm.protocols.ss7.map.api.service.subscriberInformation. LocationInformationEPS#getGeodeticInformation()
*/
public GeodeticInformation getGeodeticInformation() {
return this.geodeticInformation;
}
/*
* (non-Javadoc)
*
* @see org.restcomm.protocols.ss7.map.api.service.subscriberInformation.
* LocationInformationEPS#getCurrentLocationRetrieved()
*/
public boolean getCurrentLocationRetrieved() {
return this.currentLocationRetrieved;
}
/*
* (non-Javadoc)
*
* @see org.restcomm.protocols.ss7.map.api.service.subscriberInformation.
* LocationInformationEPS#getAgeOfLocationInformation()
*/
public Integer getAgeOfLocationInformation() {
return this.ageOfLocationInformation;
}
/*
* (non-Javadoc)
*
* @see org.restcomm.protocols.ss7.map.api.service.subscriberInformation. LocationInformationEPS#getMmeName()
*/
public DiameterIdentity getMmeName() {
return this.mmeName;
}
protected void _decode(AsnInputStream ansIS, int length) throws MAPParsingComponentException, IOException, AsnException {
this.eUtranCellGlobalIdentity = null;
this.trackingAreaIdentity = null;
this.extensionContainer = null;
this.geographicalInformation = null;
this.geodeticInformation = null;
this.currentLocationRetrieved = false;
this.ageOfLocationInformation = null;
AsnInputStream ais = ansIS.readSequenceStreamData(length);
while (true) {
if (ais.available() == 0)
break;
int tag = ais.readTag();
if (ais.getTagClass() == Tag.CLASS_CONTEXT_SPECIFIC) {
switch (tag) {
case _ID_eUtranCellGlobalIdentity:
if (!ais.isTagPrimitive())
throw new MAPParsingComponentException("Error while decoding " + _PrimitiveName
+ " eUtranCellGlobalIdentity: Parameter is not primitive",
MAPParsingComponentExceptionReason.MistypedParameter);
this.eUtranCellGlobalIdentity = new EUtranCgiImpl();
((EUtranCgiImpl) this.eUtranCellGlobalIdentity).decodeAll(ais);
break;
case _ID_trackingAreaIdentity:
if (!ais.isTagPrimitive())
throw new MAPParsingComponentException("Error while decoding " + _PrimitiveName
+ " trackingAreaIdentity: Parameter is not primitive",
MAPParsingComponentExceptionReason.MistypedParameter);
this.trackingAreaIdentity = new TAIdImpl();
((TAIdImpl) this.trackingAreaIdentity).decodeAll(ais);
break;
case _ID_extensionContainer:
if (ais.isTagPrimitive())
throw new MAPParsingComponentException("Error while decoding " + _PrimitiveName
+ " extensionContainer: Parameter is primitive",
MAPParsingComponentExceptionReason.MistypedParameter);
this.extensionContainer = new MAPExtensionContainerImpl();
((MAPExtensionContainerImpl) this.extensionContainer).decodeAll(ais);
break;
case _ID_geographicalInformation:
if (!ais.isTagPrimitive())
throw new MAPParsingComponentException("Error while decoding " + _PrimitiveName
+ " geographicalInformation: Parameter is not primitive",
MAPParsingComponentExceptionReason.MistypedParameter);
this.geographicalInformation = new GeographicalInformationImpl();
((GeographicalInformationImpl) this.geographicalInformation).decodeAll(ais);
break;
case _ID_geodeticInformation:
if (!ais.isTagPrimitive())
throw new MAPParsingComponentException("Error while decoding " + _PrimitiveName
+ " geodeticInformation: Parameter is not primitive",
MAPParsingComponentExceptionReason.MistypedParameter);
this.geodeticInformation = new GeodeticInformationImpl();
((GeodeticInformationImpl) this.geodeticInformation).decodeAll(ais);
break;
case _ID_currentLocationRetrieved:
if (!ais.isTagPrimitive()) {
throw new MAPParsingComponentException(
"Error while decoding LocationInformation: Parameter [currentLocationRetrieved [8] NULL ] not primitive",
MAPParsingComponentExceptionReason.MistypedParameter);
}
ais.readNull();
this.currentLocationRetrieved = true;
break;
case _ID_ageOfLocationInformation:
if (!ais.isTagPrimitive())
throw new MAPParsingComponentException("Error while decoding " + _PrimitiveName
+ " ageOfLocationInformation: Parameter is not primitive",
MAPParsingComponentExceptionReason.MistypedParameter);
this.ageOfLocationInformation = (int) ais.readInteger();
break;
case _ID_mme_Name:
if (!ais.isTagPrimitive())
throw new MAPParsingComponentException("Error while decoding " + _PrimitiveName
+ " mmeName: Parameter is not primitive",
MAPParsingComponentExceptionReason.MistypedParameter);
this.mmeName = new DiameterIdentityImpl();
((DiameterIdentityImpl) this.mmeName).decodeAll(ais);
break;
default:
ais.advanceElement();
break;
}
} else {
ais.advanceElement();
}
}
}
/*
* (non-Javadoc)
*
* @see org.restcomm.protocols.ss7.map.primitives.MAPAsnPrimitive#encodeData (org.mobicents.protocols.asn.AsnOutputStream)
*/
public void encodeData(AsnOutputStream asnOs) throws MAPException {
try {
if (this.eUtranCellGlobalIdentity != null)
((EUtranCgiImpl) this.eUtranCellGlobalIdentity).encodeAll(asnOs, Tag.CLASS_CONTEXT_SPECIFIC,
_ID_eUtranCellGlobalIdentity);
if (this.trackingAreaIdentity != null) {
((TAIdImpl) this.trackingAreaIdentity).encodeAll(asnOs, Tag.CLASS_CONTEXT_SPECIFIC, _ID_trackingAreaIdentity);
}
if (this.extensionContainer != null)
((MAPExtensionContainerImpl) this.extensionContainer).encodeAll(asnOs, Tag.CLASS_CONTEXT_SPECIFIC,
_ID_extensionContainer);
if (this.geographicalInformation != null)
((GeographicalInformationImpl) this.geographicalInformation).encodeAll(asnOs, Tag.CLASS_CONTEXT_SPECIFIC,
_ID_geographicalInformation);
if (this.geodeticInformation != null)
((GeodeticInformationImpl) this.geodeticInformation).encodeAll(asnOs, Tag.CLASS_CONTEXT_SPECIFIC,
_ID_geodeticInformation);
if (this.currentLocationRetrieved) {
try {
asnOs.writeNull(Tag.CLASS_CONTEXT_SPECIFIC, _ID_currentLocationRetrieved);
} catch (IOException e) {
throw new MAPException(
"Error while encoding LocationInformation the optional parameter currentLocationRetrieved encoding failed ",
e);
} catch (AsnException e) {
throw new MAPException(
"Error while encoding LocationInformation the optional parameter currentLocationRetrieved encoding failed ",
e);
}
}
if (ageOfLocationInformation != null)
asnOs.writeInteger(Tag.CLASS_CONTEXT_SPECIFIC, _ID_ageOfLocationInformation, (int) ageOfLocationInformation);
if (this.mmeName != null) {
((DiameterIdentityImpl) this.mmeName).encodeAll(asnOs, Tag.CLASS_CONTEXT_SPECIFIC, _ID_mme_Name);
}
} catch (IOException e) {
throw new MAPException("IOException when encoding " + _PrimitiveName + ": " + e.getMessage(), e);
} catch (AsnException e) {
throw new MAPException("AsnException when encoding " + _PrimitiveName + ": " + e.getMessage(), e);
}
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(_PrimitiveName);
sb.append(" [");
if (this.eUtranCellGlobalIdentity != null) {
sb.append("eUtranCellGlobalIdentity=");
sb.append(this.eUtranCellGlobalIdentity);
}
if (this.trackingAreaIdentity != null) {
sb.append(", trackingAreaIdentity=");
sb.append(this.trackingAreaIdentity);
}
if (this.extensionContainer != null) {
sb.append(", extensionContainer=");
sb.append(this.extensionContainer);
}
if (this.geographicalInformation != null) {
sb.append(", geographicalInformation=");
sb.append(this.geographicalInformation);
}
if (this.geodeticInformation != null) {
sb.append(", geodeticInformation=");
sb.append(this.geodeticInformation);
}
if (currentLocationRetrieved) {
sb.append(", currentLocationRetrieved");
}
if (this.ageOfLocationInformation != null) {
sb.append(", ageOfLocationInformation=");
sb.append(this.ageOfLocationInformation);
}
if (this.mmeName != null) {
sb.append(", mmeName=");
sb.append(this.mmeName);
}
sb.append("]");
return sb.toString();
}
/**
* XML Serialization/Deserialization
*/
protected static final XMLFormat<LocationInformationEPSImpl> LOCATION_INFORMATION_EPS_XML = new XMLFormat<LocationInformationEPSImpl>(
LocationInformationEPSImpl.class) {
@Override
public void read(javolution.xml.XMLFormat.InputElement xml, LocationInformationEPSImpl locationInformationEPS)
throws XMLStreamException {
locationInformationEPS.eUtranCellGlobalIdentity = xml.get(E_UTRAN_CELL_GLOBAL_IDENTITY, EUtranCgiImpl.class);
locationInformationEPS.trackingAreaIdentity = xml.get(TRACKING_AREA_IDENTITY, TAIdImpl.class);
locationInformationEPS.extensionContainer = xml.get(EXTENSION_CONTAINER, MAPExtensionContainerImpl.class);
locationInformationEPS.geographicalInformation = xml.get(GEOGRAPHICAL_INFORMATION,
GeographicalInformationImpl.class);
locationInformationEPS.geodeticInformation = xml.get(GEODETIC_INFORMATION, GeodeticInformationImpl.class);
Boolean bval = xml.get(CURRENT_LOCATION_RETRIEVED, Boolean.class);
if (bval != null)
locationInformationEPS.currentLocationRetrieved = bval;
locationInformationEPS.ageOfLocationInformation = xml.get(AGE_OF_LOCATION_INFORMATION, Integer.class);
locationInformationEPS.mmeName = xml.get(MME_NAME, DiameterIdentityImpl.class);
}
@Override
public void write(LocationInformationEPSImpl locationInformationEPS, javolution.xml.XMLFormat.OutputElement xml)
throws XMLStreamException {
if (locationInformationEPS.eUtranCellGlobalIdentity != null) {
xml.add((EUtranCgiImpl) locationInformationEPS.eUtranCellGlobalIdentity, E_UTRAN_CELL_GLOBAL_IDENTITY,
EUtranCgiImpl.class);
}
if (locationInformationEPS.trackingAreaIdentity != null) {
xml.add((TAIdImpl) locationInformationEPS.trackingAreaIdentity, TRACKING_AREA_IDENTITY, TAIdImpl.class);
}
if (locationInformationEPS.extensionContainer != null) {
xml.add((MAPExtensionContainerImpl) locationInformationEPS.extensionContainer, EXTENSION_CONTAINER,
MAPExtensionContainerImpl.class);
}
if (locationInformationEPS.geographicalInformation != null) {
xml.add((GeographicalInformationImpl) locationInformationEPS.geographicalInformation, GEOGRAPHICAL_INFORMATION,
GeographicalInformationImpl.class);
}
if (locationInformationEPS.geodeticInformation != null) {
xml.add((GeodeticInformationImpl) locationInformationEPS.geodeticInformation, GEODETIC_INFORMATION,
GeodeticInformationImpl.class);
}
if (locationInformationEPS.currentLocationRetrieved) {
xml.add((Boolean) locationInformationEPS.currentLocationRetrieved, CURRENT_LOCATION_RETRIEVED, Boolean.class);
}
if (locationInformationEPS.ageOfLocationInformation != null) {
xml.add((Integer) locationInformationEPS.ageOfLocationInformation, AGE_OF_LOCATION_INFORMATION, Integer.class);
}
if (locationInformationEPS.mmeName != null) {
xml.add((DiameterIdentityImpl) locationInformationEPS.mmeName, MME_NAME, DiameterIdentityImpl.class);
}
}
};
}
| agpl-3.0 |
BrightSpots/rcv | src/main/java/network/brightspots/rcv/ClearBallotCvrReader.java | 6881 | /*
* Universal RCV Tabulator
* Copyright (c) 2017-2020 Bright Spots Developers.
*
* This program is free software: you can redistribute it and/or modify it under the terms of the
* GNU Affero General Public License as published by the Free Software Foundation, either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See
* the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this
* program. If not, see <http://www.gnu.org/licenses/>.
*/
package network.brightspots.rcv;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javafx.util.Pair;
import network.brightspots.rcv.CastVoteRecord.CvrParseException;
import network.brightspots.rcv.TabulatorSession.UnrecognizedCandidatesException;
class ClearBallotCvrReader {
private final String cvrPath;
private final ContestConfig contestConfig;
private final String undeclaredWriteInLabel;
ClearBallotCvrReader(String cvrPath, ContestConfig contestConfig, String undeclaredWriteInLabel) {
this.cvrPath = cvrPath;
this.contestConfig = contestConfig;
this.undeclaredWriteInLabel = undeclaredWriteInLabel;
}
// parse Cvr json into CastVoteRecord objects and append them to the input castVoteRecords list
// see Clear Ballot 2.1 RCV Format Specification for details
void readCastVoteRecords(List<CastVoteRecord> castVoteRecords, String contestId)
throws CvrParseException, UnrecognizedCandidatesException {
BufferedReader csvReader;
// map for tracking unrecognized candidates during parsing
Map<String, Integer> unrecognizedCandidateCounts = new HashMap<>();
try {
csvReader = new BufferedReader(new FileReader(this.cvrPath));
// each "choice column" in the input Csv corresponds to a unique ranking: candidate+rank pair
// we parse these rankings from the header row into a map for lookup during CVR parsing
String firstRow = csvReader.readLine();
if (firstRow == null) {
Logger.severe("No header row found in cast vote record file: %s", this.cvrPath);
throw new CvrParseException();
}
String[] headerData = firstRow.split(",");
if (headerData.length < CvrColumnField.ChoicesBegin.ordinal()) {
Logger.severe("No choice columns found in cast vote record file: %s", this.cvrPath);
throw new CvrParseException();
}
Map<Integer, Pair<Integer, String>> columnIndexToRanking = new HashMap<>();
for (int columnIndex = CvrColumnField.ChoicesBegin.ordinal();
columnIndex < headerData.length;
columnIndex++) {
String choiceColumnHeader = headerData[columnIndex];
String[] choiceFields = choiceColumnHeader.split(":");
// validate field count
if (choiceFields.length != RcvChoiceHeaderField.FIELD_COUNT.ordinal()) {
Logger.severe(
"Wrong number of choice header fields in cast vote record file: %s", this.cvrPath);
throw new CvrParseException();
}
// filter by contest
String contestName = choiceFields[RcvChoiceHeaderField.CONTEST_NAME.ordinal()];
if (!contestName.equals(contestId)) {
continue;
}
// validate and store the ranking associated with this choice column
String choiceName = choiceFields[RcvChoiceHeaderField.CHOICE_NAME.ordinal()];
if (choiceName.equals(undeclaredWriteInLabel)) {
choiceName = Tabulator.UNDECLARED_WRITE_IN_OUTPUT_LABEL;
} else if (!contestConfig.getCandidateCodeList().contains(choiceName)) {
unrecognizedCandidateCounts.merge(choiceName, 1, Integer::sum);
}
Integer rank = Integer.parseInt(choiceFields[RcvChoiceHeaderField.RANK.ordinal()]);
if (rank > this.contestConfig.getMaxRankingsAllowed()) {
Logger.severe(
"Rank: %d exceeds max rankings allowed in config: %d",
rank, this.contestConfig.getMaxRankingsAllowed());
throw new CvrParseException();
}
columnIndexToRanking.put(columnIndex, new Pair<>(rank, choiceName));
}
// read all remaining rows and create CastVoteRecords for each one
while (true) {
String row = csvReader.readLine();
if (row == null) {
break;
}
// parse rankings
String[] cvrData = row.split(",");
ArrayList<Pair<Integer, String>> rankings = new ArrayList<>();
for (int columnIndex : columnIndexToRanking.keySet()) {
if (Integer.parseInt(cvrData[columnIndex]) == 1) {
// user marked this column
Pair<Integer, String> ranking = columnIndexToRanking.get(columnIndex);
rankings.add(ranking);
}
}
// create the cast vote record
CastVoteRecord castVoteRecord =
new CastVoteRecord(
contestId,
cvrData[CvrColumnField.ScanComputerName.ordinal()],
null,
cvrData[CvrColumnField.BallotID.ordinal()],
cvrData[CvrColumnField.PrecinctID.ordinal()],
null,
cvrData[CvrColumnField.BallotStyleID.ordinal()],
rankings);
castVoteRecords.add(castVoteRecord);
// provide some user feedback on the Cvr count
if (castVoteRecords.size() % 50000 == 0) {
Logger.info("Parsed %d cast vote records.", castVoteRecords.size());
}
}
csvReader.close();
} catch (FileNotFoundException exception) {
Logger.severe("Cast vote record file not found!\n%s", exception);
} catch (IOException exception) {
Logger.severe("Error reading file!\n%s", exception);
}
if (unrecognizedCandidateCounts.size() > 0) {
throw new UnrecognizedCandidatesException(unrecognizedCandidateCounts);
}
}
// These values correspond to the data in Clear Vote Cvr Csv columns
@SuppressWarnings({"unused", "RedundantSuppression"})
public enum CvrColumnField {
RowNumber,
BoxID,
BoxPosition,
BallotID,
PrecinctID,
BallotStyleID,
PrecinctStyleName,
ScanComputerName,
Status,
Remade,
ChoicesBegin
}
// These values correspond to the data in Clear Vote Rcv choice column header fields
@SuppressWarnings({"unused", "RedundantSuppression"})
public enum RcvChoiceHeaderField {
HEADER,
CONTEST_NAME,
RANK,
VOTE_RULE,
CHOICE_NAME,
PARTY_NAME,
FIELD_COUNT
}
}
| agpl-3.0 |
pgdurand/Bioinformatics-Core-API | src/bzh/plealog/bioinfo/api/data/searchresult/SRHspSequence.java | 2640 | /* Copyright (C) 2006-2016 Patrick G. Durand
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/agpl-3.0.txt
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*/
package bzh.plealog.bioinfo.api.data.searchresult;
import java.io.Serializable;
import bzh.plealog.bioinfo.api.data.feature.FeatureTable;
import bzh.plealog.bioinfo.api.data.sequence.DSequence;
/**
* This interface defines a sequence constituing a Blast HSP.
*
* @author Patrick G. Durand
*/
public interface SRHspSequence extends Serializable{
public static final int TYPE_ALIGNED_SEQ = 1;
public static final int TYPE_MIDLINE = 2;
// *** IMPORTANT NOTICE ***
//when modifying this API, also modify
//filter.implem.datamodel.BGDataModel#initialize()
/**
* Returns the sequence type.
*
* @return one of the TYPE_XXX values defined in this interface.
*/
public int getType();
public void setType(int val);
/**
* Returns the starting position. Sequence coordinate.
*/
public int getFrom();
public void setFrom(int val);
/**
* Returns the ending position. Sequence coordinate.
*/
public int getTo();
public void setTo(int val);
/**
* Returns the number of gaps.
*/
public int getGaps();
public void setGaps(int val);
/**
* Returns the frame.
*/
public int getFrame();
public void setFrame(int val);
/**
* Returns the full size of the sequence.
*/
public int getSeqFullSize();
public void setSeqFullSize(int val);
/**
* Returns the sequence as a String.
*/
public String getSequence();
public void setSequence(String seq);
/**
* Returns the sequence as a DSequence.
*/
public DSequence getSequence(SRHsp hsp);
public void setFeatures(FeatureTable ft);
/**
* Returns the FeatureTable associated to the hit sequence. Can be null if this
* sequence is not the hit sequence and/or no features are available.
*/
public FeatureTable getFeatures();
/**
* Forces the implementation of a clone method.
*/
public SRHspSequence clone(boolean shallow);
}
| agpl-3.0 |
herbert-venancio/taskboard | kpi-parent/kpi-testutils/src/test/java/objective/taskboard/followup/kpi/IssueKpiTest.java | 43095 | package objective.taskboard.followup.kpi;
import org.junit.Test;
import objective.taskboard.followup.kpi.services.DSLKpi;
public class IssueKpiTest {
@Test
public void checkStatusOnDay_happyDay() {
dsl()
.environment()
.givenSubtask("I-1")
.type("Subtask")
.project("PROJ")
.withTransitions()
.status("To Do").date("2020-01-01")
.status("Doing").date("2020-01-02")
.status("Done").date("2020-01-03")
.eoT()
.eoI()
.then()
.assertThat()
.issueKpi("I-1")
.atDate("2020-01-01")
.isOnStatus("To Do")
.isNotOnStatus("Doing")
.isNotOnStatus("Done").eoDc()
.atDate("2020-01-02")
.isNotOnStatus("To Do")
.isOnStatus("Doing")
.isNotOnStatus("Done").eoDc()
.atDate("2020-01-03")
.isNotOnStatus("To Do")
.isNotOnStatus("Doing")
.isOnStatus("Done").eoDc()
.atDate("2020-01-01")
.isNotOnStatus("Review").eoDc()
.atDate("2020-01-04")
.isNotOnStatus("Doing").eoDc();
}
@Test
public void checkStatusOnDay_emptyTransitions() {
dsl()
.environment()
.givenSubtask("I-1")
.type("Subtask")
.project("PROJ")
.withTransitions()
.status("To Do").date("2020-01-01")
.status("Doing").noDate()
.status("Done").date("2020-01-03")
.eoT()
.eoI()
.then()
.assertThat()
.issueKpi("I-1")
.atDate("2020-01-01")
.isOnStatus("To Do")
.isNotOnStatus("Doing")
.isNotOnStatus("Done").eoDc()
.atDate("2020-01-02")
.isOnStatus("To Do")
.isNotOnStatus("Doing")
.isNotOnStatus("Done").eoDc()
.atDate("2020-01-03")
.isNotOnStatus("To Do")
.isNotOnStatus("Doing")
.isOnStatus("Done").eoDc()
.atDate("2020-01-04")
.isNotOnStatus("To Do")
.isNotOnStatus("Doing")
.isOnStatus("Done").eoDc();
}
@Test
public void checkStatusOnDay_openIssue() {
dsl()
.environment()
.givenSubtask("I-1")
.type("Subtask")
.project("PROJ")
.withTransitions()
.status("To Do").date("2020-01-01")
.eoT()
.eoI()
.then()
.assertThat()
.issueKpi("I-1")
.atDate("2020-01-01")
.isOnStatus("To Do")
.isNotOnStatus("Doing").eoDc()
.atDate("2020-01-02")
.isOnStatus("To Do")
.isNotOnStatus("Doing").eoDc();
}
@Test
public void checkStatusOnDay_futureIssue() {
dsl()
.environment()
.givenSubtask("I-1")
.type("Subtask")
.project("PROJ")
.withTransitions()
.status("To Do").date("2020-01-02")
.status("Doing").date("2020-01-03")
.status("Done").date("2020-01-04")
.eoT()
.eoI()
.then()
.assertThat()
.issueKpi("I-1")
.atDate("2020-01-01")
.isNotOnStatus("To Do")
.isNotOnStatus("Doing")
.isNotOnStatus("Done").eoDc()
.atDate("2020-01-02")
.isOnStatus("To Do")
.isNotOnStatus("Doing")
.isNotOnStatus("Done").eoDc();
}
@Test
public void hasTransitedToStatus_happyDay() {
dsl()
.environment()
.givenSubtask("I-1")
.project("PROJ")
.type("Subtask")
.withTransitions()
.status("To Do").date("2020-01-01")
.status("Doing").date("2020-01-02")
.status("Done").date("2020-01-03")
.eoT()
.eoI()
.then()
.assertThat()
.issueKpi("I-1")
.atDate("2020-01-01")
.hasNotTransitedToAnyStatus("Done").eoDc()
.atDate("2020-01-02")
.hasNotTransitedToAnyStatus("Done").eoDc()
.atDate("2020-01-03")
.hasTransitedToAnyStatus("Done").eoDc();
}
@Test
public void hasTransitedToStatus_nonExistentStatus() {
dsl()
.environment()
.givenSubtask("I-1")
.type("Subtask")
.project("PROJ")
.withTransitions()
.status("To Do").date("2020-01-01")
.status("Doing").date("2020-01-02")
.status("Done").date("2020-01-03")
.eoT()
.eoI()
.then()
.assertThat()
.issueKpi("I-1")
.atDate("2020-01-01")
.hasNotTransitedToAnyStatus("Integrating","Cancelled").eoDc()
.atDate("2020-01-02")
.hasNotTransitedToAnyStatus("Integrating","Cancelled").eoDc()
.atDate("2020-01-03")
.hasNotTransitedToAnyStatus("Integrating","Cancelled").eoDc();
}
@Test
public void hasTransitedToStatus_onlyOneStatusTransited() {
dsl()
.environment()
.givenSubtask("I-1")
.project("PROJ")
.type("Subtask")
.withTransitions()
.status("To Do").date("2020-01-01")
.status("Doing").noDate()
.status("Done").date("2020-01-03")
.eoT()
.eoI()
.then()
.assertThat()
.issueKpi("I-1")
.atDate("2020-01-01")
.hasNotTransitedToAnyStatus("Doing","Done").eoDc()
.atDate("2020-01-02")
.hasNotTransitedToAnyStatus("Doing","Done").eoDc()
.atDate("2020-01-03")
.hasTransitedToAnyStatus("Doing","Done").eoDc();
}
@Test
public void hasTransitedToStatus_onlyNotTransited() {
dsl()
.environment()
.givenSubtask("I-1")
.type("Subtask")
.project("PROJ")
.withTransitions()
.status("To Do").date("2020-01-01")
.status("Doing").noDate()
.status("Done").date("2020-01-03")
.eoT()
.eoI()
.then()
.assertThat()
.issueKpi("I-1")
.atDate("2020-01-01")
.hasNotTransitedToAnyStatus("Doing").eoDc()
.atDate("2020-01-02")
.hasNotTransitedToAnyStatus("Doing").eoDc()
.atDate("2020-01-03")
.hasNotTransitedToAnyStatus("Doing").eoDc();
}
@Test
public void hasTransitedToStatus_earliestTransition() {
dsl()
.environment()
.givenSubtask("I-1")
.type("Subtask")
.project("PROJ")
.withTransitions()
.status("To Do").date("2020-01-01")
.status("Doing").date("2020-01-02")
.status("Done").date("2020-01-03")
.eoT()
.eoI()
.then()
.assertThat()
.issueKpi("I-1")
.atDate("2020-01-01")
.hasNotTransitedToAnyStatus("Doing","Done").eoDc()
.atDate("2020-01-02")
.hasTransitedToAnyStatus("Doing","Done").eoDc()
.atDate("2020-01-03")
.hasNotTransitedToAnyStatus("Doing","Done").eoDc();
}
@Test
public void getWorklogFromChildren() {
dsl()
.environment()
.givenFeature("PROJ-01")
.type("Feature")
.project("PROJ")
.withTransitions()
.status("To Do").date("2020-01-01")
.status("Doing").date("2020-01-02")
.status("Done").date("2020-01-03")
.eoT()
.subtask("PROJ-02")
.type("Subtask")
.withTransitions()
.status("To Do").date("2020-01-01")
.status("Doing").date("2020-01-02")
.status("Done").date("2020-01-03")
.eoT()
.worklogs()
.at("2020-01-01").timeSpentInSeconds(300)
.eoW()
.endOfSubtask()
.eoI()
.then()
.assertThat()
.issueKpi("PROJ-01")
.givenSubtaskType("Subtask")
.hasTotalWorklogs(1).withTotalValue(300).eoSc()
.withChild("PROJ-02")
.atStatus("Doing").hasTotalEffort(300l);
}
@Test
public void wrongConfiguration_dontGetWorklogFromChildren() {
dsl()
.environment()
.givenFeature("PROJ-01")
.type("Feature")
.project("PROJ")
.withTransitions()
.status("To Do").date("2020-01-01")
.status("Doing").date("2020-01-02")
.status("Done").date("2020-01-03")
.eoT()
.subtask("PROJ-02")
.emptyType()
.withTransitions()
.status("To Do").date("2020-01-01")
.status("Doing").date("2020-01-02")
.status("Done").date("2020-01-03")
.eoT()
.worklogs()
.at("2020-01-01").timeSpentInSeconds(300)
.eoW()
.endOfSubtask()
.eoI()
.then()
.assertThat()
.issueKpi("PROJ-01")
.givenSubtaskType("Subtask")
.doesNotHaveWorklogs().eoSc()
.withChild("PROJ-02")
.atStatus("Doing").hasTotalEffort(300l);
}
@Test
public void getWorklogFromChildrenStatus_happyDay() {
dsl().
environment()
.givenFeature("PROJ-01")
.type("Feature")
.project("PROJ")
.withTransitions()
.status("To Do").date("2020-01-01")
.status("Doing").date("2020-01-02")
.status("Done").date("2020-01-03")
.eoT()
.subtask("PROJ-02")
.type("Subtask")
.withTransitions()
.status("To Do").date("2020-01-01")
.status("Doing").date("2020-01-02")
.status("Done").date("2020-01-03")
.eoT()
.worklogs()
.at("2020-01-01").timeSpentInSeconds(300)
.eoW()
.endOfSubtask()
.eoI()
.then()
.assertThat()
.issueKpi("PROJ-01")
.givenSubtaskStatus("To Do")
.doesNotHaveWorklogs().eoSc()
.givenSubtaskStatus("Doing")
.hasTotalWorklogs(1)
.withTotalValue(300).eoSc()
.withChild("PROJ-02")
.atStatus("Doing")
.hasTotalEffort(300l);
}
@Test
public void wrongConfiguration_dontGetWorklogFromChildrenStatus() {
dsl().
environment()
.givenFeature("PROJ-01")
.type("Feature")
.project("PROJ")
.withTransitions()
.status("To Do").date("2020-01-01")
.status("Doing").date("2020-01-02")
.status("Done").date("2020-01-03")
.eoT()
.subtask("PROJ-02")
.type("Subtask")
.withTransitions()
.status("To Do").date("2020-01-01")
.status("Doing").date("2020-01-02")
.status("Done").date("2020-01-03")
.eoT()
.worklogs()
.at("2020-01-01").timeSpentInSeconds(300)
.eoW()
.endOfSubtask()
.eoI()
.then()
.assertThat()
.issueKpi("PROJ-01")
.givenSubtaskStatus("To Do")
.doesNotHaveWorklogs().eoSc()
.givenSubtaskStatus("Inexistent")
.doesNotHaveWorklogs().eoSc();
}
@Test
public void getRangeByProgressingStatuses_happyDay() {
dsl().
environment()
.todayIs("2020-01-06")
.givenFeature("PROJ-01")
.type("Feature")
.project("PROJ")
.withTransitions()
.status("To Do").date("2020-01-01")
.status("Doing").date("2020-01-02")
.status("To Review").date("2020-01-03")
.status("Reviewing").date("2020-01-04")
.status("Done").date("2020-01-05")
.eoT()
.eoI()
.then()
.assertThat()
.issueKpi("PROJ-01")
.rangeBasedOnProgressingStatuses()
.startsOn("2020-01-02").endsOn("2020-01-05");
}
@Test
public void getRangeByProgressingStatuses_onlyOneProgressingWithDate() {
dsl().
environment()
.todayIs("2020-01-06")
.givenFeature("PROJ-01")
.type("Feature")
.project("PROJ")
.withTransitions()
.status("To Do").date("2020-01-01")
.status("Doing").date("2020-01-02")
.status("To Review").noDate()
.status("Reviewing").noDate()
.status("Done").date("2020-01-06")
.eoT()
.eoI()
.then()
.assertThat()
.issueKpi("PROJ-01")
.rangeBasedOnProgressingStatuses()
.startsOn("2020-01-02").endsOn("2020-01-06");
}
@Test
public void getRangeByProgressingStatuses_doingIssue() {
dsl().
environment()
.todayIs("2020-01-03")
.givenFeature("PROJ-01")
.type("Feature")
.project("PROJ")
.withTransitions()
.status("To Do").date("2020-01-01")
.status("Doing").date("2020-01-02")
.status("To Review").noDate()
.status("Reviewing").noDate()
.status("Done").noDate()
.eoT()
.eoI()
.then()
.assertThat()
.issueKpi("PROJ-01")
.rangeBasedOnProgressingStatuses()
.startsOn("2020-01-02").endsOn("2020-01-03");
}
@Test
public void getRangeByProgressingStatuses_straightToReview_workingOnDoing() {
dsl().
environment()
.todayIs("2020-01-10")
.givenSubtask("PROJ-01")
.type("Subtask")
.project("PROJ")
.withTransitions()
.status("To Do").date("2020-01-01")
.status("Doing").noDate()
.status("To Review").noDate()
.status("Reviewing").date("2020-01-06")
.status("Done").date("2020-01-08")
.eoT()
.worklogs()
.at("2020-01-01").timeSpentInSeconds(300)
.eoW()
.eoI()
.then()
.assertThat()
.issueKpi("PROJ-01")
.rangeBasedOnProgressingStatuses()
.startsOn("2020-01-01").endsOn("2020-01-08")
.atStatus("Doing").hasTotalEffort(300l);
}
@Test
public void getRangeByProgressingStatuses_openIssue_workingOnReview() {
dsl().
environment()
.todayIs("2020-01-10")
.givenSubtask("PROJ-01")
.type("Subtask")
.project("PROJ")
.withTransitions()
.status("To Do").date("2020-01-01")
.status("Doing").noDate()
.status("To Review").noDate()
.status("Reviewing").date("2020-01-06")
.status("Done").noDate()
.eoT()
.worklogs()
.at("2020-01-06").timeSpentInSeconds(300)
.eoW()
.eoI()
.then()
.assertThat()
.issueKpi("PROJ-01")
.rangeBasedOnProgressingStatuses()
.startsOn("2020-01-06").endsOn("2020-01-10")
.atStatus("Doing").doesNotHaveEffort()
.atStatus("Reviewing").hasTotalEffort(300l);
}
@Test
public void getRangeByProgressingStatuses_straightToDone_workingOnDoing() {
dsl().
environment()
.todayIs("2020-01-10")
.givenSubtask("PROJ-01")
.type("Subtask")
.project("PROJ")
.withTransitions()
.status("To Do").date("2020-01-01")
.status("Doing").noDate()
.status("To Review").noDate()
.status("Reviewing").noDate()
.status("Done").date("2020-01-06")
.eoT()
.worklogs()
.at("2020-01-03").timeSpentInSeconds(300)
.eoW()
.eoI()
.then()
.assertThat()
.issueKpi("PROJ-01")
.rangeBasedOnProgressingStatuses()
.startsOn("2020-01-03").endsOn("2020-01-06")
.atStatus("Doing").hasTotalEffort(300l);
}
@Test
public void getRangeByProgressingStatuses_straightToDone_workingOnReview() {
dsl().
environment()
.todayIs("2020-01-10")
.givenSubtask("PROJ-01")
.type("Subtask")
.project("PROJ")
.withTransitions()
.status("To Do").date("2020-01-01")
.status("Doing").noDate()
.status("To Review").noDate()
.status("Reviewing").noDate()
.status("Done").date("2020-01-06")
.eoT()
.worklogs()
.at("2020-01-06").timeSpentInSeconds(300)
.eoW()
.eoI()
.then()
.assertThat()
.issueKpi("PROJ-01")
.rangeBasedOnProgressingStatuses()
.startsOn("2020-01-06").endsOn("2020-01-06")
.atStatus("Reviewing").hasTotalEffort(300l);
}
@Test
public void getRangeByProgressingStatuses_datesOnlyOnNoProgressingStatuses_worklogDistributed() {
dsl().
environment()
.todayIs("2020-01-10")
.givenSubtask("PROJ-01")
.type("Subtask")
.project("PROJ")
.withTransitions()
.status("To Do").date("2020-01-01")
.status("Doing").noDate()
.status("To Review").date("2020-01-03")
.status("Reviewing").noDate()
.status("Done").date("2020-01-06")
.eoT()
.worklogs()
.at("2020-01-02").timeSpentInSeconds(100)
.at("2020-01-03").timeSpentInSeconds(200)
.at("2020-01-04").timeSpentInSeconds(300)
.at("2020-01-05").timeSpentInSeconds(400)
.eoW()
.eoI()
.then()
.assertThat()
.issueKpi("PROJ-01")
.rangeBasedOnProgressingStatuses()
.startsOn("2020-01-02").endsOn("2020-01-06")
.atStatus("Doing").hasTotalEffort(300l).eoSa()
.atStatus("Reviewing").hasTotalEffort(700l);
}
@Test
public void getRangeByProgressingStatuses_openIssue() {
dsl().
environment()
.todayIs("2020-01-10")
.givenFeature("PROJ-01")
.type("Feature")
.project("PROJ")
.withTransitions()
.status("To Do").date("2020-01-01")
.status("Doing").noDate()
.status("To Review").noDate()
.status("Reviewing").noDate()
.status("Done").noDate()
.eoT()
.eoI()
.then()
.assertThat()
.issueKpi("PROJ-01")
.rangeBasedOnProgressingStatuses().isNotPresent();
}
@Test
public void getRangeByProgressingStatuses_closedIssue_WithoutWorking() {
dsl().
environment()
.todayIs("2020-01-10")
.givenFeature("PROJ-01")
.type("Feature")
.project("PROJ")
.withTransitions()
.status("To Do").date("2020-01-01")
.status("Doing").noDate()
.status("To Review").noDate()
.status("Reviewing").noDate()
.status("Done").date("2020-01-01")
.eoT()
.eoI()
.then()
.assertThat()
.issueKpi("PROJ-01")
.rangeBasedOnProgressingStatuses().isNotPresent();
}
@Test
public void getRangeByProgressingStatuses_straightToDone_worklogOnReviewAfterDone() {
dsl().
environment()
.todayIs("2020-01-10")
.givenSubtask("PROJ-01")
.type("Subtask")
.project("PROJ")
.withTransitions()
.status("To Do").date("2020-01-01")
.status("Doing").noDate()
.status("To Review").noDate()
.status("Reviewing").noDate()
.status("Done").date("2020-01-06")
.eoT()
.worklogs()
.at("2020-01-07").timeSpentInSeconds(100)
.eoW()
.eoI()
.then()
.assertThat()
.issueKpi("PROJ-01")
.rangeBasedOnProgressingStatuses()
.startsOn("2020-01-07").endsOn("2020-01-07")
.atStatus("Doing").doesNotHaveEffort()
.atStatus("Reviewing").hasTotalEffort(100l);
}
@Test
public void getRangeByProgressingStatuses_issueClosedNormally_withWorklogOnReviewAfterDone() {
dsl().
environment()
.todayIs("2020-01-10")
.givenSubtask("PROJ-01")
.type("Subtask")
.project("PROJ")
.withTransitions()
.status("To Do").date("2020-01-01")
.status("Doing").date("2020-01-02")
.status("To Review").date("2020-01-03")
.status("Reviewing").date("2020-01-04")
.status("Done").date("2020-01-06")
.eoT()
.worklogs()
.at("2020-01-07").timeSpentInSeconds(100)
.eoW()
.eoI()
.then()
.assertThat()
.issueKpi("PROJ-01")
.rangeBasedOnProgressingStatuses()
.startsOn("2020-01-02").endsOn("2020-01-07")
.atStatus("Doing").doesNotHaveEffort()
.atStatus("Reviewing").hasTotalEffort(100l);
}
@Test
public void getAllWorklog_untilDate() {
dsl().
environment()
.todayIs("2020-01-10")
.givenSubtask("PROJ-01")
.type("Subtask")
.project("PROJ")
.withTransitions()
.status("To Do").date("2020-01-01")
.status("Doing").date("2020-01-02")
.status("To Review").date("2020-01-04")
.status("Reviewing").date("2020-01-04")
.status("Done").date("2020-01-05")
.eoT()
.worklogs()
.at("2020-01-02").timeSpentInSeconds(200)
.at("2020-01-03").timeSpentInSeconds(300)
.at("2020-01-04").timeSpentInSeconds(700)
.eoW()
.eoI()
.then()
.assertThat()
.issueKpi("PROJ-01")
.atStatus("Doing")
.hasTotalEffort(500L)
.untilDate("2020-01-02").hasEffort(200L)
.untilDate("2020-01-03").hasEffort(500L)
.untilDate("2020-01-04").hasEffort(500L)
.untilDate("2020-01-05").hasEffort(500L)
.eoSa()
.atStatus("Reviewing")
.hasTotalEffort(700L)
.untilDate("2020-01-02").hasEffort(0L)
.untilDate("2020-01-03").hasEffort(0L)
.untilDate("2020-01-04").hasEffort(700L)
.untilDate("2020-01-05").hasEffort(700L)
.eoSa()
.atDate("2020-01-02").hasEffort(200L).eoDc()
.atDate("2020-01-03").hasEffort(500L).eoDc()
.atDate("2020-01-04").hasEffort(1200L).eoDc()
.atDate("2020-01-05").hasEffort(1200L);
}
@Test
public void getEffortSumFromStatusesUntilDate_happyPath() {
dsl()
.environment()
.todayIs("2020-01-10")
.givenSubtask("I-1")
.type("Subtask")
.project("PROJ")
.withTransitions()
.status("To Do").date("2020-01-01")
.status("Doing").date("2020-01-02")
.status("To Review").date("2020-01-04")
.status("Reviewing").date("2020-01-04")
.status("Done").date("2020-01-05")
.eoT()
.worklogs()
.at("2020-01-02").timeSpentInSeconds(200)
.at("2020-01-03").timeSpentInSeconds(300)
.at("2020-01-04").timeSpentInSeconds(700)
.eoW()
.eoI()
.then()
.assertThat()
.issueKpi("I-1")
.atDate("2020-01-10").forStatuses("Doing", "Reviewing").hasEffortSumInSeconds(1200L);
}
@Test
public void getEffortSumFromStatusesUntilDate_whenUsingOnlyOneStatus_thenHappyPath() {
dsl()
.environment()
.todayIs("2020-01-10")
.givenSubtask("I-1")
.type("Subtask")
.project("PROJ")
.withTransitions()
.status("To Do").date("2020-01-01")
.status("Doing").date("2020-01-02")
.status("To Review").date("2020-01-04")
.status("Reviewing").date("2020-01-04")
.status("Done").date("2020-01-05")
.eoT()
.worklogs()
.at("2020-01-02").timeSpentInSeconds(200)
.at("2020-01-03").timeSpentInSeconds(300)
.at("2020-01-04").timeSpentInSeconds(700)
.eoW()
.eoI()
.then()
.assertThat()
.issueKpi("I-1")
.atDate("2020-01-10").forStatuses("Doing").hasEffortSumInSeconds(500L);
}
@Test
public void getEffortSumFromStatusesUntilDate_whenNoStatuses_thenSumIsZero() {
dsl()
.environment()
.todayIs("2020-01-10")
.givenFeature("I-1")
.type("Feature")
.project("PROJ")
.withTransitions()
.status("To Do").date("2020-01-01")
.status("Doing").date("2020-01-02")
.status("To Review").date("2020-01-04")
.status("Reviewing").date("2020-01-04")
.status("Done").date("2020-01-05")
.eoT()
.worklogs()
.at("2020-01-02").timeSpentInSeconds(200)
.at("2020-01-03").timeSpentInSeconds(300)
.at("2020-01-04").timeSpentInSeconds(700)
.eoW()
.eoI()
.then()
.assertThat()
.issueKpi("I-1")
.atDate("2020-01-10").forStatuses().hasEffortSumInSeconds(0L);
}
@Test
public void getEffortSumFromStatusesUntilDate_whenInvalidStatuses_thenSumIsZero() {
dsl()
.environment()
.todayIs("2020-01-10")
.givenSubtask("I-1")
.type("Subtask")
.project("PROJ")
.withTransitions()
.status("To Do").date("2020-01-01")
.status("Doing").date("2020-01-02")
.status("To Review").date("2020-01-04")
.status("Reviewing").date("2020-01-04")
.status("Done").date("2020-01-05")
.eoT()
.worklogs()
.at("2020-01-02").timeSpentInSeconds(200)
.at("2020-01-03").timeSpentInSeconds(300)
.at("2020-01-04").timeSpentInSeconds(700)
.eoW()
.eoI()
.then()
.assertThat()
.issueKpi("I-1")
.atDate("2020-01-10").forStatuses("Foo", "Bar").hasEffortSumInSeconds(0L);
}
@Test
public void hasCompletedCycle_happyDay() {
dsl()
.environment()
.givenSubtask("PROJ-01")
.type("Subtask")
.project("PROJ")
.withTransitions()
.status("Open").date("2020-01-01")
.status("To Do").date("2020-01-02")
.status("Doing").date("2020-01-03")
.status("To Review").date("2020-01-04")
.status("Reviewing").date("2020-01-05")
.status("Done").date("2020-01-06")
.eoT()
.eoI()
.then()
.assertThat()
.issueKpi("PROJ-01")
.hasCompletedCycle("Doing","To Review","Review");
}
@Test
public void hasNotCompletedCycle() {
dsl()
.environment()
.givenSubtask("PROJ-01")
.type("Subtask")
.project("PROJ")
.withTransitions()
.status("Open").date("2020-01-01")
.status("To Do").date("2020-01-02")
.status("Doing").date("2020-01-03")
.status("To Review").noDate()
.status("Reviewing").noDate()
.status("Done").noDate()
.eoT()
.eoI()
.then()
.assertThat()
.issueKpi("PROJ-01")
.hasNotCompletedCycle("Doing","To Review","Review");
}
@Test
public void issueNotEnteringCycle_hasNotCompletedCycle() {
dsl()
.environment()
.givenSubtask("PROJ-01")
.type("Subtask")
.project("PROJ")
.withTransitions()
.status("Open").date("2020-01-01")
.status("To Do").date("2020-01-02")
.status("Doing").noDate()
.status("To Review").noDate()
.status("Reviewing").noDate()
.status("Done").noDate()
.eoT()
.eoI()
.then()
.assertThat()
.issueKpi("PROJ-01")
.hasNotCompletedCycle("Doing","To Review","Review");
}
@Test
public void getIssueTypeName_whenTypeExists_thenHappyPath() {
dsl()
.environment()
.givenSubtask("PROJ-01")
.type("Subtask")
.project("PROJ")
.withTransitions()
.status("Open").date("2020-01-01")
.status("To Do").noDate()
.status("Doing").noDate()
.status("To Review").noDate()
.status("Reviewing").noDate()
.status("Done").noDate()
.eoT()
.eoI()
.then()
.assertThat()
.issueKpi("PROJ-01")
.hasType("Subtask");
}
@Test
public void getIssueTypeName_whenTypeNotConfigured_thenReturnUnmappedType() {
dsl()
.environment()
.givenSubtask("PROJ-01")
.emptyType()
.project("PROJ")
.withTransitions()
.status("Open").date("2020-01-01")
.status("To Do").noDate()
.status("Doing").noDate()
.status("To Review").noDate()
.status("Reviewing").noDate()
.status("Done").noDate()
.eoT()
.eoI()
.then()
.assertThat()
.issueKpi("PROJ-01")
.hasType("Unmapped");
}
@Test
public void getEffortSumFromChildrenWithSubtaskTypeId_happyPath() {
dsl()
.environment()
.givenDemand("PROJ-01")
.type("Demand")
.project("PROJ")
.withTransitions()
.status("Open").date("2020-01-01")
.status("To Do").date("2020-01-02")
.status("Doing").date("2020-01-03")
.status("To Review").date("2020-01-04")
.status("Reviewing").date("2020-01-05")
.status("Done").date("2020-01-06")
.eoT()
.subtask("PROJ-02")
.type("Subtask")
.withTransitions()
.status("Open").date("2020-01-01")
.status("To Do").date("2020-01-02")
.status("Doing").date("2020-01-03")
.status("To Review").date("2020-01-04")
.status("Reviewing").date("2020-01-05")
.status("Done").date("2020-01-06")
.eoT()
.worklogs()
.at("2020-01-03").timeSpentInHours(2.0)
.at("2020-01-05").timeSpentInHours(3.0)
.eoW()
.endOfSubtask()
.subtask("PROJ-03")
.type("Subtask")
.withTransitions()
.status("Open").date("2020-01-01")
.status("To Do").date("2020-01-02")
.status("Doing").date("2020-01-03")
.status("To Review").date("2020-01-04")
.status("Reviewing").date("2020-01-05")
.status("Done").date("2020-01-06")
.eoT()
.worklogs()
.at("2020-01-03").timeSpentInHours(3.0)
.at("2020-01-05").timeSpentInHours(5.0)
.eoW()
.endOfSubtask()
.subtask("PROJ-04")
.type("Another Subtask")
.withTransitions()
.status("Open").date("2020-01-01")
.status("To Do").date("2020-01-02")
.status("Doing").date("2020-01-03")
.status("To Review").date("2020-01-04")
.status("Reviewing").date("2020-01-05")
.status("Done").date("2020-01-06")
.eoT()
.worklogs()
.at("2020-01-03").timeSpentInHours(5.0)
.at("2020-01-05").timeSpentInHours(7.0)
.eoW()
.endOfSubtask()
.eoI()
.then()
.assertThat()
.issueKpi("PROJ-01")
.hasType("Demand")
.hasEffortSumFromChildrenWithSubtaskTypeName(13.0, "Subtask");
}
@Test
public void getEffortSumFromChildrenWithSubtaskTypeId_whenInvalidType_thenSumIsZero() {
dsl()
.environment()
.givenDemand("PROJ-01")
.type("Demand")
.project("PROJ")
.withTransitions()
.status("Open").date("2020-01-01")
.status("To Do").date("2020-01-02")
.status("Doing").date("2020-01-03")
.status("To Review").date("2020-01-04")
.status("Reviewing").date("2020-01-05")
.status("Done").date("2020-01-06")
.eoT()
.subtask("PROJ-02")
.type("Subtask")
.withTransitions()
.status("Open").date("2020-01-01")
.status("To Do").date("2020-01-02")
.status("Doing").date("2020-01-03")
.status("To Review").date("2020-01-04")
.status("Reviewing").date("2020-01-05")
.status("Done").date("2020-01-06")
.eoT()
.worklogs()
.at("2020-01-03").timeSpentInHours(2.0)
.at("2020-01-05").timeSpentInHours(3.0)
.eoW()
.eoI()
.then()
.assertThat()
.issueKpi("PROJ-01")
.hasType("Demand")
.hasEffortSumFromChildrenWithSubtaskTypeName(0.0, "Foo");
}
@Test
public void getLastTransitedStatus_happyDay() {
dsl()
.environment()
.givenSubtask("PROJ-01")
.emptyType()
.project("PROJ")
.withTransitions()
.status("Open").date("2020-01-01")
.status("To Do").date("2020-01-02")
.status("Doing").date("2020-01-03")
.status("To Review").date("2020-01-06")
.status("Reviewing").date("2020-01-07")
.status("Done").date("2020-01-08")
.eoT()
.eoI()
.then()
.assertThat()
.issueKpi("PROJ-01").hasLastTransitedStatus("Done");
}
@Test
public void getLastTransitedStatus_skippingStatus() {
dsl()
.environment()
.givenSubtask("PROJ-01")
.emptyType()
.project("PROJ")
.withTransitions()
.status("Open").date("2020-01-01")
.status("To Do").noDate()
.status("Doing").date("2020-01-02")
.status("To Review").noDate()
.status("Reviewing").noDate()
.status("Done").date("2020-01-08")
.eoT()
.eoI()
.then()
.assertThat()
.issueKpi("PROJ-01").hasLastTransitedStatus("Done");
}
@Test
public void getLastTransitedStatus_issueInProgress() {
dsl()
.environment()
.givenSubtask("PROJ-01")
.emptyType()
.project("PROJ")
.withTransitions()
.status("Open").date("2020-01-01")
.status("To Do").noDate()
.status("Doing").date("2020-01-02")
.status("To Review").noDate()
.status("Reviewing").noDate()
.status("Done").noDate()
.eoT()
.eoI()
.then()
.assertThat()
.issueKpi("PROJ-01").hasLastTransitedStatus("Doing");
}
@Test
public void getLastTransitedStatus_issueIOpen() {
dsl()
.environment()
.givenSubtask("PROJ-01")
.emptyType()
.project("PROJ")
.withTransitions()
.status("Open").date("2020-01-01")
.status("To Do").noDate()
.status("Doing").noDate()
.status("To Review").noDate()
.status("Reviewing").noDate()
.status("Done").noDate()
.eoT()
.eoI()
.then()
.assertThat()
.issueKpi("PROJ-01").hasLastTransitedStatus("Open");
}
@Test
public void getLastTransitedStatus_idisregardingWorklogs() {
dsl()
.environment()
.givenSubtask("PROJ-01")
.emptyType()
.project("PROJ")
.withTransitions()
.status("Open").date("2020-01-01")
.status("To Do").noDate()
.status("Doing").date("2020-01-06")
.status("To Review").noDate()
.status("Reviewing").noDate()
.status("Done").date("2020-01-08")
.eoT()
.worklogs()
.at("2020-01-07").timeSpentInHours(1.0)
.eoW()
.eoI()
.then()
.assertThat()
.issueKpi("PROJ-01").hasLastTransitedStatus("Done");
}
private DSLKpi dsl() {
DSLKpi dsl = new DSLKpi();
dsl.environment()
.statuses()
.withProgressingStatuses("Doing", "Reviewing")
.withNotProgressingStatuses("Open", "To Do", "To Review", "Done")
.eoS()
.types()
.addDemand("Demand")
.addFeatures("Feature")
.addSubtasks("Subtask", "Another Subtask")
.eoT();
return dsl;
}
}
| agpl-3.0 |
Xenoage/Zong | desktop/src/com/xenoage/zong/commands/desktop/app/WebsiteOpen.java | 808 | package com.xenoage.zong.commands.desktop.app;
import static com.xenoage.utils.log.Log.log;
import static com.xenoage.utils.log.Report.warning;
import java.awt.Desktop;
import java.net.URI;
import lombok.AllArgsConstructor;
import com.xenoage.utils.document.command.TransparentCommand;
/**
* Opens the given website in the default browser.
*
* @author Andreas Wenger
*/
@AllArgsConstructor
public class WebsiteOpen
extends TransparentCommand {
private String uri;
/**
* Execute or redo the command.
*/
@Override public void execute() {
try {
if (false == uri.contains("://"))
uri = "http://" + uri;
Desktop.getDesktop().browse(new URI(uri));
} catch (Exception ex) {
INSTANCE.log(Companion.warning("Could not open URI: " + uri + " (" + ex.getMessage() + ")"));
}
}
}
| agpl-3.0 |
Xianguang-Zhou/light-pp | src/main/java/org/zxg/chat/lightpp/ui/FaceTable.java | 1234 | /*
* Copyright (C) 2014-2018 Xianguang Zhou <xianguang.zhou@outlook.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.zxg.chat.lightpp.ui;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Table;
/**
* @author <a href="mailto:xianguang.zhou@outlook.com">Xianguang Zhou</a>
*/
public class FaceTable extends Table {
public FaceTable(Composite parent, int style, int itemHeight) {
super(parent, style);
addListener(SWT.MeasureItem, event -> {
event.height = itemHeight;
});
}
@Override
protected void checkSubclass() {
}
}
| agpl-3.0 |
BrunoEberhard/open-ech | src/main/model/ch/ech/ech0058/NamedMetaData.java | 454 | package ch.ech.ech0058;
import org.minimalj.model.annotation.Size;
import org.minimalj.model.annotation.NotEmpty;
import javax.annotation.Generated;
import org.minimalj.model.Keys;
@Generated(value="org.minimalj.metamodel.generator.ClassGenerator")
public class NamedMetaData {
public static final NamedMetaData $ = Keys.of(NamedMetaData.class);
@NotEmpty
@Size(20)
public String metaDataName;
@NotEmpty
@Size(50)
public String metaDataValue;
} | agpl-3.0 |
centralperf/centralperf | src/main/java/org/centralperf/controller/BootstrapController.java | 2007 | /*
* Copyright (C) 2014 The Central Perf authors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.centralperf.controller;
import javax.annotation.Resource;
import org.centralperf.service.BootstrapService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
/**
* The Bootstrap controller is used when CP is launched for the first time, to propose to initialize with samples
*
* @since 1.0
*
*/
@Controller
public class BootstrapController {
@Resource
BootstrapService bootstrapService;
/**
* Initial bootstrap page
* @return
*/
@GetMapping(value = "/bootstrap")
public String showBootstrapPage() {
return "bootstrap";
}
/**
* Import samples or not
* @param importSamples True if the user has choosen to import the samples
* @return Path to the home page mapping
*/
@GetMapping(value = "/bootstrap/initialize")
public String initialize(@RequestParam(value="importSamples") Boolean importSamples) {
// Import CP samples if specified
if(importSamples){
bootstrapService.importSamples();
}
// Update configuration, set as initialized
bootstrapService.setInitialized();
// Display Welcome Page
return "redirect:/home";
}
}
| agpl-3.0 |
tagland/anarchia | src/us/anarchia/gwt/client/ui/ImageDesigner.java | 1199 | package us.anarchia.gwt.client.ui;
import com.google.gwt.user.client.ui.Label;
import us.anarchia.obj.Copyright;
import us.anarchia.obj.Date;
import us.anarchia.obj.Image;
public class ImageDesigner extends Designer<Image> {
public ImageDesigner(final Image image) {
super(image);
this.image = image;
Label designerLabel = new Label();
designerLabel.setText("Copyright");
panel.add(designerLabel);
imageUrl = new LabelEdit("Image URL"){
public void onStringValueChanged(String newValue){
image.setImgURL(newValue);
}
};
panel.add(imageUrl);
imageCaption = new LabelEdit("Image Caption"){
public void onStringValueChanged(String newValue){
image.setCaption(newValue);
}
};
panel.add(imageCaption);
}
public void onModelChanged(){
imageCaption.setText(image.getCaption());
imageUrl.setText(image.getImgURL());
}
LabelEdit imageCaption;
LabelEdit imageUrl;
private Image image;
} | agpl-3.0 |
jperals/PGBNet-to-OpenBravo-POS | OpenBravoCSV2SQLImport.java | 5249 | import au.com.bytecode.opencsv.CSVReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.Properties;
import java.util.UUID;
public class OpenBravoCSV2SQLImport
{
private static final String configFileName = "config.properties";
private static final String csvFileName = "plu1.csv";
private static Statement stmt = null;
private static int rs;
private static int productCount = 0;
private static int productsAdded = 0;
private static int productsSkipped = 0;
private static ArrayList<String[]> productsWithoutCode = new ArrayList<String[]>();
public static void main(String[] args) throws ClassNotFoundException, IOException, SQLException {
connectAndStart();
}
public static void connectAndStart() throws ClassNotFoundException, IOException, SQLException {
try {
Properties properties = new Properties();
properties.load(new FileInputStream(configFileName));
Class.forName(properties.getProperty("driverclass"));
String connectionURL = properties.getProperty("database");
Connection connection = DriverManager.getConnection(connectionURL,properties);
System.out.println("Connected to the database");
stmt = connection.createStatement();
readAndImportCSV();
connection.close();
System.out.println("Done.");
System.out.println("Products added: " + productsAdded);
System.out.println("Products skipped: " + productsSkipped);
System.out.println("Total: " + productCount);
System.out.println(productsWithoutCode.size() + " products had an invalid barcode, and an incremental number was used instead.");
} catch (IOException ex) {
ex.printStackTrace();
}
finally {
if (stmt != null) {
try {
stmt.close();
}
catch (SQLException sqlEx) {
System.out.println("SQLException: " + sqlEx.getMessage());
}
stmt = null;
}
}
}
private static void readAndImportCSV() throws IOException, SQLException {
CSVReader reader = new CSVReader(new FileReader(csvFileName));
String[] line;
try {
while ((line = reader.readNext()) != null) {
insertProduct(line);
}
int nProductsWithoutCode = productsWithoutCode.size();
System.out.println("Finished inserting products with valid barcode. Now inserting " + nProductsWithoutCode + " products with invalid barcode.");
for (int i=0; i < nProductsWithoutCode; i++) {
String[] productProperties = productsWithoutCode.get(i);
productProperties[26] = String.format("%013d", i);
insertProduct(productProperties);
}
}
catch (IOException e) {
e.printStackTrace();
}
}
private static void insertProduct(String[] productProperties) throws SQLException {
String barcode = productProperties[26];
if(barcode.equals("0000000000000") || barcode.equals("")) {
productsWithoutCode.add(productProperties);
}
else {
String productId = UUID.randomUUID().toString();
String productName = productProperties[25].replace("'", "''");
int priceBuy = (Integer.parseInt(productProperties[27])/100);
int priceSell = (Integer.parseInt(productProperties[30])/100);
String SQLQuery = "INSERT INTO PRODUCTS (ID, REFERENCE, CODE, NAME, PRICEBUY, PRICESELL, CATEGORY, TAXCAT) VALUES ('" + productId + "', '" + productProperties[24] + "', '" + barcode + "', '" + productName + "', " + priceBuy + ", " + priceSell + ", '000', '001')";
try {
rs = stmt.executeUpdate(SQLQuery);
if (rs > 0) {
productsAdded++;
System.out.println("Product " + productCount + " added: \"" + productProperties[25] + "\"");
}
else {
productsSkipped++;
System.out.println("WARNING: Product not added: " + productProperties[25]);
}
rs = stmt.executeUpdate("INSERT INTO PRODUCTS_CAT (PRODUCT) VALUES ('" + productId + "')");
if (rs > 0) {
System.out.println("Product added to catalog.");
}
else {
System.out.println("Product not added to catalog.");
}
}
catch (SQLException ex) {
System.out.println("SQLException: " + ex.getMessage());
System.out.println("SQLState: " + ex.getSQLState());
System.out.println("VendorError: " + ex.getErrorCode());
System.out.println("Query: " + SQLQuery);
productsSkipped++;
}
finally {
productCount++;
}
}
}
}
| agpl-3.0 |
RestComm/jss7 | tcap-ansi/tcap-ansi-impl/src/main/java/org/restcomm/protocols/ss7/tcapAnsi/TCAPProviderImpl.java | 73784 | /*
* TeleStax, Open Source Cloud Communications
* Copyright 2012, Telestax Inc and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.restcomm.protocols.ss7.tcapAnsi;
import io.netty.util.concurrent.DefaultThreadFactory;
import java.io.IOException;
import java.io.Serializable;
import java.util.List;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import javolution.util.FastMap;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.mobicents.protocols.asn.AsnInputStream;
import org.mobicents.protocols.asn.AsnOutputStream;
import org.mobicents.protocols.asn.Tag;
import org.restcomm.protocols.ss7.sccp.NetworkIdState;
import org.restcomm.protocols.ss7.sccp.RemoteSccpStatus;
import org.restcomm.protocols.ss7.sccp.SccpConnection;
import org.restcomm.protocols.ss7.sccp.SccpListener;
import org.restcomm.protocols.ss7.sccp.SccpProvider;
import org.restcomm.protocols.ss7.sccp.SignallingPointStatus;
import org.restcomm.protocols.ss7.sccp.message.MessageFactory;
import org.restcomm.protocols.ss7.sccp.message.SccpDataMessage;
import org.restcomm.protocols.ss7.sccp.message.SccpNoticeMessage;
import org.restcomm.protocols.ss7.sccp.parameter.Credit;
import org.restcomm.protocols.ss7.sccp.parameter.ErrorCause;
import org.restcomm.protocols.ss7.sccp.parameter.Importance;
import org.restcomm.protocols.ss7.sccp.parameter.ParameterFactory;
import org.restcomm.protocols.ss7.sccp.parameter.ProtocolClass;
import org.restcomm.protocols.ss7.sccp.parameter.RefusalCause;
import org.restcomm.protocols.ss7.sccp.parameter.ReleaseCause;
import org.restcomm.protocols.ss7.sccp.parameter.ResetCause;
import org.restcomm.protocols.ss7.sccp.parameter.SccpAddress;
import org.restcomm.protocols.ss7.tcapAnsi.api.ComponentPrimitiveFactory;
import org.restcomm.protocols.ss7.tcapAnsi.api.DialogPrimitiveFactory;
import org.restcomm.protocols.ss7.tcapAnsi.api.MessageType;
import org.restcomm.protocols.ss7.tcapAnsi.api.TCAPException;
import org.restcomm.protocols.ss7.tcapAnsi.api.TCAPProvider;
import org.restcomm.protocols.ss7.tcapAnsi.api.TCListener;
import org.restcomm.protocols.ss7.tcapAnsi.api.asn.ParseException;
import org.restcomm.protocols.ss7.tcapAnsi.api.asn.ProtocolVersion;
import org.restcomm.protocols.ss7.tcapAnsi.api.asn.comp.Component;
import org.restcomm.protocols.ss7.tcapAnsi.api.asn.comp.PAbortCause;
import org.restcomm.protocols.ss7.tcapAnsi.api.asn.comp.Reject;
import org.restcomm.protocols.ss7.tcapAnsi.api.asn.comp.RejectProblem;
import org.restcomm.protocols.ss7.tcapAnsi.api.asn.comp.TCAbortMessage;
import org.restcomm.protocols.ss7.tcapAnsi.api.asn.comp.TCConversationMessage;
import org.restcomm.protocols.ss7.tcapAnsi.api.asn.comp.TCQueryMessage;
import org.restcomm.protocols.ss7.tcapAnsi.api.asn.comp.TCResponseMessage;
import org.restcomm.protocols.ss7.tcapAnsi.api.asn.comp.TCUniMessage;
import org.restcomm.protocols.ss7.tcapAnsi.api.tc.dialog.Dialog;
import org.restcomm.protocols.ss7.tcapAnsi.api.tc.dialog.TRPseudoState;
import org.restcomm.protocols.ss7.tcapAnsi.api.tc.dialog.events.DraftParsedMessage;
import org.restcomm.protocols.ss7.tcapAnsi.asn.InvokeImpl;
import org.restcomm.protocols.ss7.tcapAnsi.asn.TCAbortMessageImpl;
import org.restcomm.protocols.ss7.tcapAnsi.asn.TCNoticeIndicationImpl;
import org.restcomm.protocols.ss7.tcapAnsi.asn.TCResponseMessageImpl;
import org.restcomm.protocols.ss7.tcapAnsi.asn.TCUnidentifiedMessage;
import org.restcomm.protocols.ss7.tcapAnsi.asn.TcapFactory;
import org.restcomm.protocols.ss7.tcapAnsi.asn.TransactionID;
import org.restcomm.protocols.ss7.tcapAnsi.asn.Utils;
import org.restcomm.protocols.ss7.tcapAnsi.tc.component.ComponentPrimitiveFactoryImpl;
import org.restcomm.protocols.ss7.tcapAnsi.tc.dialog.events.DialogPrimitiveFactoryImpl;
import org.restcomm.protocols.ss7.tcapAnsi.tc.dialog.events.DraftParsedMessageImpl;
import org.restcomm.protocols.ss7.tcapAnsi.tc.dialog.events.TCConversationIndicationImpl;
import org.restcomm.protocols.ss7.tcapAnsi.tc.dialog.events.TCPAbortIndicationImpl;
import org.restcomm.protocols.ss7.tcapAnsi.tc.dialog.events.TCQueryIndicationImpl;
import org.restcomm.protocols.ss7.tcapAnsi.tc.dialog.events.TCResponseIndicationImpl;
import org.restcomm.protocols.ss7.tcapAnsi.tc.dialog.events.TCUniIndicationImpl;
import org.restcomm.protocols.ss7.tcapAnsi.tc.dialog.events.TCUserAbortIndicationImpl;
import org.restcomm.ss7.congestion.ExecutorCongestionMonitor;
import org.restcomm.ss7.congestion.MemoryCongestionMonitorImpl;
/**
* @author amit bhayani
* @author baranowb
* @author sergey vetyutnev
*
*/
public class TCAPProviderImpl implements TCAPProvider, SccpListener {
private static final Logger logger = Logger.getLogger(TCAPProviderImpl.class); // listenres
private transient List<TCListener> tcListeners = new CopyOnWriteArrayList<TCListener>();
protected transient ScheduledExecutorService _EXECUTOR;
// boundry for Uni directional dialogs :), tx id is always encoded
// on 4 octets, so this is its max value
// private static final long _4_OCTETS_LONG_FILL = 4294967295l;
private transient ComponentPrimitiveFactory componentPrimitiveFactory;
private transient DialogPrimitiveFactory dialogPrimitiveFactory;
private transient SccpProvider sccpProvider;
private transient MessageFactory messageFactory;
private transient ParameterFactory parameterFactory;
private transient TCAPStackImpl stack; // originating TX id ~=Dialog, its direct
// mapping, but not described
// explicitly...
// private transient FastMap<Long, DialogImpl> dialogs = new FastMap<Long, DialogImpl>();
private transient ConcurrentHashMap<Long, DialogImpl> dialogs = new ConcurrentHashMap<Long, DialogImpl>();
// protected transient FastMap<PrevewDialogDataKey, PreviewDialogData> dialogPreviewList = new FastMap<PrevewDialogDataKey, PreviewDialogData>();
protected transient ConcurrentHashMap<PreviewDialogDataKey, PreviewDialogData> dialogPreviewList = new ConcurrentHashMap<PreviewDialogDataKey, PreviewDialogData>();
private transient FastMap<Integer, NetworkIdState> networkIdStateList = new FastMap<Integer, NetworkIdState>().shared();
private NetworkIdStateListUpdater currentNetworkIdStateListUpdater;
private AtomicInteger seqControl = new AtomicInteger(1);
private int ssn;
private long curDialogId = 0;
// private AtomicLong currentDialogId = new AtomicLong(1);
private int cumulativeCongestionLevel = 0;
private int executorCongestionLevel = 0;
private int executorCountWithCongestionLevel_1 = 0;
private int executorCountWithCongestionLevel_2 = 0;
private int executorCountWithCongestionLevel_3 = 0;
private MemoryCongestionMonitorImpl memoryCongestionMonitor;
private transient FastMap<String, Integer> lstUserPartCongestionLevel = new FastMap<String, Integer>();
private int userPartCongestionLevel_1 = 0;
private int userPartCongestionLevel_2 = 0;
private int userPartCongestionLevel_3 = 0;
protected TCAPProviderImpl(SccpProvider sccpProvider, TCAPStackImpl stack, int ssn) {
super();
this.sccpProvider = sccpProvider;
this.ssn = ssn;
messageFactory = sccpProvider.getMessageFactory();
parameterFactory = sccpProvider.getParameterFactory();
this.stack = stack;
this.componentPrimitiveFactory = new ComponentPrimitiveFactoryImpl(this);
this.dialogPrimitiveFactory = new DialogPrimitiveFactoryImpl(this.componentPrimitiveFactory);
}
public boolean getPreviewMode() {
return this.stack.getPreviewMode();
}
/*
* (non-Javadoc)
*
* @see org.restcomm.protocols.ss7.tcap.api.TCAPStack#addTCListener(org.mobicents .protocols.ss7.tcap.api.TCListener)
*/
public void addTCListener(TCListener lst) {
if (this.tcListeners.contains(lst)) {
} else {
this.tcListeners.add(lst);
}
}
/*
* (non-Javadoc)
*
* @see org.restcomm.protocols.ss7.tcap.api.TCAPStack#removeTCListener(org.mobicents .protocols.ss7.tcap.api.TCListener)
*/
public void removeTCListener(TCListener lst) {
this.tcListeners.remove(lst);
}
private boolean checkAvailableTxId(Long id) {
if (!this.dialogs.containsKey(id))
return true;
else
return false;
}
// some help methods... crude but will work for first impl.
private synchronized Long getAvailableTxId() throws TCAPException {
if (this.dialogs.size() >= this.stack.getMaxDialogs())
throw new TCAPException("Current dialog count exceeds its maximum value");
while (true) {
// Long id;
// if (!currentDialogId.compareAndSet(this.stack.getDialogIdRangeEnd(), this.stack.getDialogIdRangeStart() + 1)) {
// id = currentDialogId.getAndIncrement();
// } else {
// id = this.stack.getDialogIdRangeStart();
// }
// if (checkAvailableTxId(id))
// return id;
if (this.curDialogId < this.stack.getDialogIdRangeStart())
this.curDialogId = this.stack.getDialogIdRangeStart() - 1;
if (++this.curDialogId > this.stack.getDialogIdRangeEnd())
this.curDialogId = this.stack.getDialogIdRangeStart();
Long id = this.curDialogId;
if (checkAvailableTxId(id))
return id;
}
}
protected void resetDialogIdValueAfterRangeChange() {
if (this.curDialogId < this.stack.getDialogIdRangeStart())
this.curDialogId = this.stack.getDialogIdRangeStart();
if (this.curDialogId >= this.stack.getDialogIdRangeEnd())
this.curDialogId = this.stack.getDialogIdRangeEnd() - 1;
// if (this.currentDialogId.longValue() < this.stack.getDialogIdRangeStart())
// this.currentDialogId.set(this.stack.getDialogIdRangeStart());
// if (this.currentDialogId.longValue() >= this.stack.getDialogIdRangeEnd())
// this.currentDialogId.set(this.stack.getDialogIdRangeEnd() - 1);
}
// get next Seq Control value available
protected int getNextSeqControl() {
int res = seqControl.getAndIncrement();
// if (!seqControl.compareAndSet(256, 1)) {
// return seqControl.getAndIncrement();
// } else {
// return 0;
// }
// seqControl++;
// if (seqControl > 255) {
// seqControl = 0;
//
// }
// return seqControl;
if (this.stack.getSlsRangeType() == SlsRangeType.Odd) {
if (res % 2 == 0)
res++;
} else if (this.stack.getSlsRangeType() == SlsRangeType.Even) {
if (res %2 != 0)
res++;
}
res = res & 0xFF;
return res;
}
/*
* (non-Javadoc)
*
* @seeorg.restcomm.protocols.ss7.tcap.api.TCAPProvider# getComopnentPrimitiveFactory()
*/
public ComponentPrimitiveFactory getComponentPrimitiveFactory() {
return this.componentPrimitiveFactory;
}
/*
* (non-Javadoc)
*
* @see org.restcomm.protocols.ss7.tcap.api.TCAPProvider#getDialogPrimitiveFactory ()
*/
public DialogPrimitiveFactory getDialogPrimitiveFactory() {
return this.dialogPrimitiveFactory;
}
/*
* (non-Javadoc)
*
* @see org.restcomm.protocols.ss7.tcap.api.TCAPProvider#getNewDialog(org.mobicents
* .protocols.ss7.sccp.parameter.SccpAddress, org.restcomm.protocols.ss7.sccp.parameter.SccpAddress)
*/
public Dialog getNewDialog(SccpAddress localAddress, SccpAddress remoteAddress) throws TCAPException {
DialogImpl res = getNewDialog(localAddress, remoteAddress, getNextSeqControl(), null);
if (this.stack.getStatisticsEnabled()) {
this.stack.getCounterProviderImpl().updateAllLocalEstablishedDialogsCount();
this.stack.getCounterProviderImpl().updateAllEstablishedDialogsCount();
}
this.setSsnToDialog(res, localAddress.getSubsystemNumber());
return res;
}
/*
* (non-Javadoc)
*
* @see org.restcomm.protocols.ss7.tcap.api.TCAPProvider#getNewDialog(org.mobicents
* .protocols.ss7.sccp.parameter.SccpAddress, org.restcomm.protocols.ss7.sccp.parameter.SccpAddress, Long id)
*/
public Dialog getNewDialog(SccpAddress localAddress, SccpAddress remoteAddress, Long id) throws TCAPException {
DialogImpl res = getNewDialog(localAddress, remoteAddress, getNextSeqControl(), id);
if (this.stack.getStatisticsEnabled()) {
this.stack.getCounterProviderImpl().updateAllLocalEstablishedDialogsCount();
this.stack.getCounterProviderImpl().updateAllEstablishedDialogsCount();
}
this.setSsnToDialog(res, localAddress.getSubsystemNumber());
return res;
}
/*
* (non-Javadoc)
*
* @see org.restcomm.protocols.ss7.tcap.api.TCAPProvider#getNewUnstructuredDialog
* (org.restcomm.protocols.ss7.sccp.parameter.SccpAddress, org.restcomm.protocols.ss7.sccp.parameter.SccpAddress)
*/
public Dialog getNewUnstructuredDialog(SccpAddress localAddress, SccpAddress remoteAddress) throws TCAPException {
DialogImpl res = _getDialog(localAddress, remoteAddress, false, getNextSeqControl(), null);
this.setSsnToDialog(res, localAddress.getSubsystemNumber());
return res;
}
private DialogImpl getNewDialog(SccpAddress localAddress, SccpAddress remoteAddress, int seqControl, Long id) throws TCAPException {
return _getDialog(localAddress, remoteAddress, true, seqControl, id);
}
private DialogImpl _getDialog(SccpAddress localAddress, SccpAddress remoteAddress, boolean structured, int seqControl, Long id)
throws TCAPException {
if (this.stack.getPreviewMode()) {
throw new TCAPException("Can not create a Dialog in a PreviewMode");
}
if (localAddress == null) {
throw new NullPointerException("LocalAddress must not be null");
}
// synchronized (this.dialogs) {
if (id == null) {
id = this.getAvailableTxId();
} else {
if (!checkAvailableTxId(id)) {
throw new TCAPException("Suggested local TransactionId is already present in system: " + id);
}
}
if (structured) {
DialogImpl di = new DialogImpl(localAddress, remoteAddress, id, structured, this._EXECUTOR, this, seqControl,
this.stack.getPreviewMode());
this.dialogs.put(id, di);
if (this.stack.getStatisticsEnabled()) {
this.stack.getCounterProviderImpl().updateMinDialogsCount(this.dialogs.size());
this.stack.getCounterProviderImpl().updateMaxDialogsCount(this.dialogs.size());
}
return di;
} else {
DialogImpl di = new DialogImpl(localAddress, remoteAddress, id, structured, this._EXECUTOR, this, seqControl,
this.stack.getPreviewMode());
return di;
}
// }
}
private void setSsnToDialog(DialogImpl di, int ssn) {
if (ssn != this.ssn) {
if (ssn <= 0 || !this.stack.isExtraSsnPresent(ssn))
ssn = this.ssn;
}
di.setLocalSsn(ssn);
}
@Override
public int getCurrentDialogsCount() {
return this.dialogs.size();
}
public void send(byte[] data, boolean returnMessageOnError, SccpAddress destinationAddress, SccpAddress originatingAddress,
int seqControl, int networkId, int localSsn) throws IOException {
if (this.stack.getPreviewMode())
return;
SccpDataMessage msg = messageFactory.createDataMessageClass1(destinationAddress, originatingAddress, data, seqControl,
localSsn, returnMessageOnError, null, null);
msg.setNetworkId(networkId);
sccpProvider.updateSPCongestion(ssn, getCumulativeCongestionLevel());
sccpProvider.send(msg);
}
public int getMaxUserDataLength(SccpAddress calledPartyAddress, SccpAddress callingPartyAddress, int networkId) {
return this.sccpProvider.getMaxUserDataLength(calledPartyAddress, callingPartyAddress, networkId);
}
public void deliver(DialogImpl dialogImpl, TCQueryIndicationImpl msg) {
if (this.stack.getStatisticsEnabled()) {
this.stack.getCounterProviderImpl().updateTcQueryReceivedCount(dialogImpl);
}
try {
for (TCListener lst : this.tcListeners) {
lst.onTCQuery(msg);
}
} catch (Exception e) {
if (logger.isEnabledFor(Level.ERROR)) {
logger.error("Received exception while delivering data to transport layer.", e);
}
}
}
public void deliver(DialogImpl dialogImpl, TCConversationIndicationImpl tcContinueIndication) {
if (this.stack.getStatisticsEnabled()) {
this.stack.getCounterProviderImpl().updateTcConversationReceivedCount(dialogImpl);
}
try {
for (TCListener lst : this.tcListeners) {
lst.onTCConversation(tcContinueIndication);
}
} catch (Exception e) {
if (logger.isEnabledFor(Level.ERROR)) {
logger.error("Received exception while delivering data to transport layer.", e);
}
}
}
public void deliver(DialogImpl dialogImpl, TCResponseIndicationImpl tcEndIndication) {
if (this.stack.getStatisticsEnabled()) {
this.stack.getCounterProviderImpl().updateTcResponseReceivedCount(dialogImpl);
}
try {
for (TCListener lst : this.tcListeners) {
lst.onTCResponse(tcEndIndication);
}
} catch (Exception e) {
if (logger.isEnabledFor(Level.ERROR)) {
logger.error("Received exception while delivering data to transport layer.", e);
}
}
}
public void deliver(DialogImpl dialogImpl, TCPAbortIndicationImpl tcAbortIndication) {
if (this.stack.getStatisticsEnabled()) {
this.stack.getCounterProviderImpl().updateTcPAbortReceivedCount(dialogImpl, tcAbortIndication.getPAbortCause());
}
try {
for (TCListener lst : this.tcListeners) {
lst.onTCPAbort(tcAbortIndication);
}
} catch (Exception e) {
if (logger.isEnabledFor(Level.ERROR)) {
logger.error("Received exception while delivering data to transport layer.", e);
}
}
}
public void deliver(DialogImpl dialogImpl, TCUserAbortIndicationImpl tcAbortIndication) {
if (this.stack.getStatisticsEnabled()) {
this.stack.getCounterProviderImpl().updateTcUserAbortReceivedCount(dialogImpl);
}
try {
for (TCListener lst : this.tcListeners) {
lst.onTCUserAbort(tcAbortIndication);
}
} catch (Exception e) {
if (logger.isEnabledFor(Level.ERROR)) {
logger.error("Received exception while delivering data to transport layer.", e);
}
}
}
public void deliver(DialogImpl dialogImpl, TCUniIndicationImpl tcUniIndication) {
if (this.stack.getStatisticsEnabled()) {
this.stack.getCounterProviderImpl().updateTcUniReceivedCount(dialogImpl);
}
try {
for (TCListener lst : this.tcListeners) {
lst.onTCUni(tcUniIndication);
}
} catch (Exception e) {
if (logger.isEnabledFor(Level.ERROR)) {
logger.error("Received exception while delivering data to transport layer.", e);
}
}
}
public void deliver(DialogImpl dialogImpl, TCNoticeIndicationImpl tcNoticeIndication) {
try {
for (TCListener lst : this.tcListeners) {
lst.onTCNotice(tcNoticeIndication);
}
} catch (Exception e) {
if (logger.isEnabledFor(Level.ERROR)) {
logger.error("Received exception while delivering data to transport layer.", e);
}
}
}
public void release(DialogImpl d) {
Long did = d.getLocalDialogId();
if (!d.getPreviewMode()) {
// synchronized (this.dialogs) {
this.dialogs.remove(did);
if (this.stack.getStatisticsEnabled()) {
this.stack.getCounterProviderImpl().updateMinDialogsCount(this.dialogs.size());
this.stack.getCounterProviderImpl().updateMaxDialogsCount(this.dialogs.size());
}
// }
this.doRelease(d);
}
}
private void doRelease(DialogImpl d) {
if (d.isStructured() && this.stack.getStatisticsEnabled()) {
this.stack.getCounterProviderImpl().updateDialogReleaseCount(d);
}
try {
for (TCListener lst : this.tcListeners) {
lst.onDialogReleased(d);
}
} catch (Exception e) {
if (logger.isEnabledFor(Level.ERROR)) {
logger.error("Received exception while delivering dialog release.", e);
}
}
}
/**
* @param d
*/
public void timeout(DialogImpl d) {
if (this.stack.getStatisticsEnabled()) {
this.stack.getCounterProviderImpl().updateDialogTimeoutCount(d);
}
try {
for (TCListener lst : this.tcListeners) {
lst.onDialogTimeout(d);
}
} catch (Exception e) {
if (logger.isEnabledFor(Level.ERROR)) {
logger.error("Received exception while delivering dialog release.", e);
}
}
}
public TCAPStackImpl getStack() {
return this.stack;
}
// ///////////////////////////////////////////
// Some methods invoked by operation FSM //
// //////////////////////////////////////////
public Future createOperationTimer(Runnable operationTimerTask, long invokeTimeout) {
return this._EXECUTOR.schedule(operationTimerTask, invokeTimeout, TimeUnit.MILLISECONDS);
}
public void operationTimedOut(InvokeImpl tcInvokeRequestImpl) {
try {
for (TCListener lst : this.tcListeners) {
lst.onInvokeTimeout(tcInvokeRequestImpl);
}
} catch (Exception e) {
if (logger.isEnabledFor(Level.ERROR)) {
logger.error("Received exception while delivering Begin.", e);
}
}
}
void start() {
logger.info("Starting TCAP Provider");
this._EXECUTOR = Executors.newScheduledThreadPool(4, new DefaultThreadFactory("Tcap-Thread"));
this.sccpProvider.registerSccpListener(ssn, this);
logger.info("Registered SCCP listener with ssn " + ssn);
List<Integer> extraSsns = this.stack.getExtraSsns();
if (extraSsns != null) {
for (Integer I1 : extraSsns) {
if (I1 != null) {
int extraSsn = I1;
this.sccpProvider.registerSccpListener(extraSsn, this);
logger.info("Registered SCCP listener with extra ssn " + extraSsn);
}
}
}
// congestion caring
updateNetworkIdStateList();
this._EXECUTOR.scheduleWithFixedDelay(new CongestionExecutor(), 1000, 1000, TimeUnit.MILLISECONDS);
memoryCongestionMonitor = new MemoryCongestionMonitorImpl();
lstUserPartCongestionLevel.clear();
}
void stop() {
stopNetworkIdStateList();
this._EXECUTOR.shutdown();
this.sccpProvider.deregisterSccpListener(ssn);
List<Integer> extraSsns = this.stack.getExtraSsns();
if (extraSsns != null) {
for (Integer I1 : extraSsns) {
if (I1 != null) {
int extraSsn = I1;
this.sccpProvider.deregisterSccpListener(extraSsn);
}
}
}
this.dialogs.clear();
this.dialogPreviewList.clear();
}
protected void sendProviderAbort(PAbortCause pAbortCause, byte[] remoteTransactionId, SccpAddress remoteAddress,
SccpAddress localAddress, int seqControl, int networkId) {
if (this.stack.getPreviewMode())
return;
TCAbortMessageImpl msg = (TCAbortMessageImpl) TcapFactory.createTCAbortMessage();
msg.setDestinationTransactionId(remoteTransactionId);
msg.setPAbortCause(pAbortCause);
AsnOutputStream aos = new AsnOutputStream();
try {
msg.encode(aos);
if (this.stack.getStatisticsEnabled()) {
this.stack.getCounterProviderImpl().updateTcPAbortSentCount(remoteTransactionId, pAbortCause);
}
this.send(aos.toByteArray(), false, remoteAddress, localAddress, seqControl, networkId, localAddress.getSubsystemNumber());
} catch (Exception e) {
if (logger.isEnabledFor(Level.ERROR)) {
logger.error("Failed to send message: ", e);
}
}
}
protected void sendRejectAsProviderAbort(PAbortCause pAbortCause, byte[] remoteTransactionId, SccpAddress remoteAddress,
SccpAddress localAddress, int seqControl, int networkId) {
if (this.stack.getPreviewMode())
return;
RejectProblem rp = RejectProblem.getFromPAbortCause(pAbortCause);
if (rp == null)
rp = RejectProblem.transactionBadlyStructuredTransPortion;
TCResponseMessageImpl msg = (TCResponseMessageImpl) TcapFactory.createTCResponseMessage();
msg.setDestinationTransactionId(remoteTransactionId);
Component[] cc = new Component[1];
Reject r = TcapFactory.createComponentReject();
r.setProblem(rp);
cc[0] = r;
msg.setComponent(cc);
AsnOutputStream aos = new AsnOutputStream();
try {
msg.encode(aos);
if (this.stack.getStatisticsEnabled()) {
this.stack.getCounterProviderImpl().updateTcPAbortSentCount(remoteTransactionId, pAbortCause);
}
this.send(aos.toByteArray(), false, remoteAddress, localAddress, seqControl, networkId, localAddress.getSubsystemNumber());
} catch (Exception e) {
if (logger.isEnabledFor(Level.ERROR)) {
logger.error("Failed to send message: ", e);
}
}
}
public void onMessage(SccpDataMessage message) {
try {
byte[] data = message.getData();
SccpAddress localAddress = message.getCalledPartyAddress();
SccpAddress remoteAddress = message.getCallingPartyAddress();
// asnData - it should pass
AsnInputStream ais = new AsnInputStream(data);
// this should have TC message tag :)
int tag = ais.readTag();
if (ais.getTagClass() != Tag.CLASS_PRIVATE) {
unrecognizedPackageType(message, localAddress, remoteAddress, ais, tag, message.getNetworkId());
return;
}
switch (tag) {
case TCConversationMessage._TAG_CONVERSATION_WITH_PERM:
case TCConversationMessage._TAG_CONVERSATION_WITHOUT_PERM:
TCConversationMessage tcm = null;
try {
tcm = TcapFactory.createTCConversationMessage(ais);
} catch (ParseException e) {
logger.error("ParseException when parsing TCConversationMessage: " + e.toString(), e);
// parsing OriginatingTransactionId
ais = new AsnInputStream(data);
tag = ais.readTag();
TCUnidentifiedMessage tcUnidentified = new TCUnidentifiedMessage();
tcUnidentified.decode(ais);
if (tcUnidentified.getOriginatingTransactionId() != null) {
boolean isDP = false;
if (tcUnidentified.isDialogPortionExists()) {
isDP = true;
} else {
Dialog ddi = null;
if (tcUnidentified.getDestinationTransactionId() != null) {
long dialogId = Utils.decodeTransactionId(tcUnidentified.getDestinationTransactionId(), this.stack.getSwapTcapIdBytes());
ddi = this.dialogs.get(dialogId);
}
if (ddi != null && ddi.getProtocolVersion() != null)
isDP = true;
}
if (isDP) {
if (e.getPAbortCauseType() != null) {
this.sendProviderAbort(e.getPAbortCauseType(),
tcUnidentified.getOriginatingTransactionId(), remoteAddress, localAddress,
message.getSls(), message.getNetworkId());
} else {
this.sendProviderAbort(PAbortCause.BadlyStructuredDialoguePortion,
tcUnidentified.getOriginatingTransactionId(), remoteAddress, localAddress,
message.getSls(), message.getNetworkId());
}
} else {
if (e.getPAbortCauseType() != null) {
this.sendRejectAsProviderAbort(e.getPAbortCauseType(),
tcUnidentified.getOriginatingTransactionId(), remoteAddress, localAddress,
message.getSls(), message.getNetworkId());
} else {
this.sendRejectAsProviderAbort(PAbortCause.BadlyStructuredTransactionPortion,
tcUnidentified.getOriginatingTransactionId(), remoteAddress, localAddress,
message.getSls(), message.getNetworkId());
}
}
}
return;
}
if (this.stack.isCongControl_blockingIncomingTcapMessages() && cumulativeCongestionLevel >= 3) {
// rejecting of new incoming TCAP dialogs
this.sendProviderAbort(PAbortCause.ResourceUnavailable, tcm.getOriginatingTransactionId(),
remoteAddress, localAddress, message.getSls(), message.getNetworkId());
return;
}
long dialogId = Utils.decodeTransactionId(tcm.getDestinationTransactionId(), this.stack.getSwapTcapIdBytes());
DialogImpl di;
if (this.stack.getPreviewMode()) {
PreviewDialogDataKey ky1 = new PreviewDialogDataKey(message.getIncomingDpc(), (message
.getCalledPartyAddress().getGlobalTitle() != null ? message.getCalledPartyAddress()
.getGlobalTitle().getDigits() : null), message.getCalledPartyAddress().getSubsystemNumber(),
dialogId);
long dId = Utils.decodeTransactionId(tcm.getOriginatingTransactionId(), this.stack.getSwapTcapIdBytes());
PreviewDialogDataKey ky2 = new PreviewDialogDataKey(message.getIncomingOpc(), (message
.getCallingPartyAddress().getGlobalTitle() != null ? message.getCallingPartyAddress()
.getGlobalTitle().getDigits() : null), message.getCallingPartyAddress().getSubsystemNumber(),
dId);
di = (DialogImpl) this.getPreviewDialog(ky1, ky2, localAddress, remoteAddress, 0);
setSsnToDialog(di, message.getCalledPartyAddress().getSubsystemNumber());
} else {
di = this.dialogs.get(dialogId);
}
if (di == null) {
logger.warn("TC-Conversation: No dialog/transaction for id: " + dialogId);
if (tcm.getDialogPortion() != null) {
this.sendProviderAbort(PAbortCause.UnassignedRespondingTransactionID,
tcm.getOriginatingTransactionId(), remoteAddress, localAddress, message.getSls(),
message.getNetworkId());
} else {
this.sendRejectAsProviderAbort(PAbortCause.UnassignedRespondingTransactionID,
tcm.getOriginatingTransactionId(), remoteAddress, localAddress, message.getSls(),
message.getNetworkId());
}
} else {
di.processConversation(tcm, localAddress, remoteAddress,
tag == TCConversationMessage._TAG_CONVERSATION_WITH_PERM);
}
break;
case TCQueryMessage._TAG_QUERY_WITH_PERM:
case TCQueryMessage._TAG_QUERY_WITHOUT_PERM:
TCQueryMessage tcb = null;
try {
tcb = TcapFactory.createTCQueryMessage(ais);
} catch (ParseException e) {
logger.error("ParseException when parsing TCQueryMessage: " + e.toString(), e);
// parsing OriginatingTransactionId
ais = new AsnInputStream(data);
tag = ais.readTag();
TCUnidentifiedMessage tcUnidentified = new TCUnidentifiedMessage();
tcUnidentified.decode(ais);
if (tcUnidentified.getOriginatingTransactionId() != null) {
if (tcUnidentified.isDialogPortionExists()) {
if (e.getPAbortCauseType() != null) {
this.sendProviderAbort(e.getPAbortCauseType(),
tcUnidentified.getOriginatingTransactionId(), remoteAddress, localAddress,
message.getSls(), message.getNetworkId());
} else {
this.sendProviderAbort(PAbortCause.BadlyStructuredDialoguePortion,
tcUnidentified.getOriginatingTransactionId(), remoteAddress, localAddress,
message.getSls(), message.getNetworkId());
}
} else {
if (e.getPAbortCauseType() != null) {
this.sendRejectAsProviderAbort(e.getPAbortCauseType(),
tcUnidentified.getOriginatingTransactionId(), remoteAddress, localAddress,
message.getSls(), message.getNetworkId());
} else {
this.sendRejectAsProviderAbort(PAbortCause.BadlyStructuredTransactionPortion,
tcUnidentified.getOriginatingTransactionId(), remoteAddress, localAddress,
message.getSls(), message.getNetworkId());
}
}
}
return;
}
if (this.stack.isCongControl_blockingIncomingTcapMessages() && cumulativeCongestionLevel >= 2) {
// rejecting of new incoming TCAP dialogs
this.sendProviderAbort(PAbortCause.ResourceUnavailable, tcb.getOriginatingTransactionId(),
remoteAddress, localAddress, message.getSls(), message.getNetworkId());
return;
}
di = null;
try {
if (this.stack.getPreviewMode()) {
long dId = Utils.decodeTransactionId(tcb.getOriginatingTransactionId(), this.stack.getSwapTcapIdBytes());
PreviewDialogDataKey ky = new PreviewDialogDataKey(message.getIncomingOpc(), (message
.getCallingPartyAddress().getGlobalTitle() != null ? message.getCallingPartyAddress()
.getGlobalTitle().getDigits() : null), message.getCallingPartyAddress()
.getSubsystemNumber(), dId);
di = (DialogImpl) this.createPreviewDialog(ky, localAddress, remoteAddress, 0);
setSsnToDialog(di, message.getCalledPartyAddress().getSubsystemNumber());
} else {
di = (DialogImpl) this.getNewDialog(localAddress, remoteAddress, message.getSls(), null);
setSsnToDialog(di, message.getCalledPartyAddress().getSubsystemNumber());
}
} catch (TCAPException e) {
if (tcb.getDialogPortion() != null) {
this.sendProviderAbort(PAbortCause.ResourceUnavailable, tcb.getOriginatingTransactionId(),
remoteAddress, localAddress, message.getSls(), message.getNetworkId());
} else {
this.sendRejectAsProviderAbort(PAbortCause.ResourceUnavailable, tcb.getOriginatingTransactionId(),
remoteAddress, localAddress, message.getSls(), message.getNetworkId());
}
logger.error("Can not add a new dialog when receiving TCBeginMessage: " + e.getMessage(), e);
return;
}
if (tcb.getDialogPortion() != null) {
if (tcb.getDialogPortion().getProtocolVersion() != null) {
di.setProtocolVersion(tcb.getDialogPortion().getProtocolVersion());
} else {
ProtocolVersion pv = TcapFactory.createProtocolVersionEmpty();
di.setProtocolVersion(pv);
}
}
if (this.stack.getStatisticsEnabled()) {
this.stack.getCounterProviderImpl().updateAllRemoteEstablishedDialogsCount();
this.stack.getCounterProviderImpl().updateAllEstablishedDialogsCount();
}
di.setNetworkId(message.getNetworkId());
di.processQuery(tcb, localAddress, remoteAddress, tag == TCQueryMessage._TAG_QUERY_WITH_PERM);
if (this.stack.getPreviewMode()) {
di.getPrevewDialogData().setLastACN(di.getApplicationContextName());
di.getPrevewDialogData().setOperationsSentB(di.operationsSent);
di.getPrevewDialogData().setOperationsSentA(di.operationsSentA);
}
break;
case TCResponseMessage._TAG_RESPONSE:
TCResponseMessage teb = null;
try {
teb = TcapFactory.createTCResponseMessage(ais);
} catch (ParseException e) {
logger.error("ParseException when parsing TCResponseMessage: " + e.toString(), e);
return;
}
if (this.stack.isCongControl_blockingIncomingTcapMessages() && cumulativeCongestionLevel >= 3) {
// rejecting of new incoming TCAP dialogs
return;
}
dialogId = Utils.decodeTransactionId(teb.getDestinationTransactionId(), this.stack.getSwapTcapIdBytes());
if (this.stack.getPreviewMode()) {
PreviewDialogDataKey ky = new PreviewDialogDataKey(message.getIncomingDpc(), (message
.getCalledPartyAddress().getGlobalTitle() != null ? message.getCalledPartyAddress()
.getGlobalTitle().getDigits() : null), message.getCalledPartyAddress().getSubsystemNumber(),
dialogId);
di = (DialogImpl) this.getPreviewDialog(ky, null, localAddress, remoteAddress, 0);
setSsnToDialog(di, message.getCalledPartyAddress().getSubsystemNumber());
} else {
di = this.dialogs.get(dialogId);
}
if (di == null) {
logger.warn("TC-Response: No dialog/transaction for id: " + dialogId);
} else {
di.processResponse(teb, localAddress, remoteAddress);
if (this.stack.getPreviewMode()) {
this.removePreviewDialog(di);
}
}
break;
case TCAbortMessage._TAG_ABORT:
TCAbortMessage tub = null;
try {
tub = TcapFactory.createTCAbortMessage(ais);
} catch (ParseException e) {
logger.error("ParseException when parsing TCAbortMessage: " + e.toString(), e);
return;
}
if (this.stack.isCongControl_blockingIncomingTcapMessages() && cumulativeCongestionLevel >= 3) {
// rejecting of new incoming TCAP dialogs
return;
}
dialogId = Utils.decodeTransactionId(tub.getDestinationTransactionId(), this.stack.getSwapTcapIdBytes());
if (this.stack.getPreviewMode()) {
long dId = Utils.decodeTransactionId(tub.getDestinationTransactionId(), this.stack.getSwapTcapIdBytes());
PreviewDialogDataKey ky = new PreviewDialogDataKey(message.getIncomingDpc(), (message
.getCalledPartyAddress().getGlobalTitle() != null ? message.getCalledPartyAddress()
.getGlobalTitle().getDigits() : null), message.getCalledPartyAddress().getSubsystemNumber(),
dId);
di = (DialogImpl) this.getPreviewDialog(ky, null, localAddress, remoteAddress, 0);
setSsnToDialog(di, message.getCalledPartyAddress().getSubsystemNumber());
} else {
di = this.dialogs.get(dialogId);
}
if (di == null) {
logger.warn("TC-ABORT: No dialog/transaction for id: " + dialogId);
} else {
di.processAbort(tub, localAddress, remoteAddress);
if (this.stack.getPreviewMode()) {
this.removePreviewDialog(di);
}
}
break;
case TCUniMessage._TAG_UNI:
TCUniMessage tcuni;
try {
tcuni = TcapFactory.createTCUniMessage(ais);
} catch (ParseException e) {
logger.error("ParseException when parsing TCUniMessage: " + e.toString(), e);
return;
}
if (this.stack.isCongControl_blockingIncomingTcapMessages() && cumulativeCongestionLevel >= 3) {
// rejecting of new incoming TCAP dialogs
return;
}
DialogImpl uniDialog = (DialogImpl) this.getNewUnstructuredDialog(localAddress, remoteAddress);
setSsnToDialog(uniDialog, message.getCalledPartyAddress().getSubsystemNumber());
uniDialog.processUni(tcuni, localAddress, remoteAddress);
break;
default:
unrecognizedPackageType(message, localAddress, remoteAddress, ais, tag, message.getNetworkId());
break;
}
} catch (Exception e) {
e.printStackTrace();
logger.error(String.format("Error while decoding Rx SccpMessage=%s", message), e);
}
}
private void unrecognizedPackageType(SccpDataMessage message, SccpAddress localAddress, SccpAddress remoteAddress, AsnInputStream ais, int tag,
int networkId) {
if (this.stack.getPreviewMode()) {
return;
}
logger.error(String.format("Rx unidentified messageType=%s. SccpMessage=%s", tag, message));
TCUnidentifiedMessage tcUnidentified = new TCUnidentifiedMessage();
try {
tcUnidentified.decode(ais);
} catch (ParseException e) {
// we do nothing
}
if (tcUnidentified.getOriginatingTransactionId() != null) {
byte[] otid = tcUnidentified.getOriginatingTransactionId();
if (tcUnidentified.getDestinationTransactionId() != null) {
Long dtid = Utils.decodeTransactionId(tcUnidentified.getDestinationTransactionId(), this.stack.getSwapTcapIdBytes());
this.sendProviderAbort(PAbortCause.UnrecognizedPackageType, otid, remoteAddress, localAddress, message.getSls(), networkId);
} else {
this.sendProviderAbort(PAbortCause.UnrecognizedPackageType, otid, remoteAddress, localAddress, message.getSls(), networkId);
}
} else {
this.sendProviderAbort(PAbortCause.UnrecognizedPackageType, new byte[4], remoteAddress, localAddress, message.getSls(), networkId);
}
}
public void onNotice(SccpNoticeMessage msg) {
if (this.stack.getPreviewMode()) {
return;
}
DialogImpl dialog = null;
try {
byte[] data = msg.getData();
AsnInputStream ais = new AsnInputStream(data);
// this should have TC message tag :)
int tag = ais.readTag();
TCUnidentifiedMessage tcUnidentified = new TCUnidentifiedMessage();
tcUnidentified.decode(ais);
if (tcUnidentified.getOriginatingTransactionId() != null) {
long otid = Utils.decodeTransactionId(tcUnidentified.getOriginatingTransactionId(), this.stack.getSwapTcapIdBytes());
dialog = this.dialogs.get(otid);
}
} catch (Exception e) {
e.printStackTrace();
logger.error(String.format("Error while decoding Rx SccpNoticeMessage=%s", msg), e);
}
TCNoticeIndicationImpl ind = new TCNoticeIndicationImpl();
ind.setRemoteAddress(msg.getCallingPartyAddress());
ind.setLocalAddress(msg.getCalledPartyAddress());
ind.setDialog(dialog);
ind.setReportCause(msg.getReturnCause().getValue());
if (dialog != null) {
try {
dialog.dialogLock.lock();
this.deliver(dialog, ind);
if (dialog.getState() != TRPseudoState.Active) {
dialog.release();
}
} finally {
dialog.dialogLock.unlock();
}
} else {
this.deliver(dialog, ind);
}
}
protected Dialog createPreviewDialog(PreviewDialogDataKey ky, SccpAddress localAddress, SccpAddress remoteAddress,
int seqControl) throws TCAPException {
if (this.dialogPreviewList.size() >= this.stack.getMaxDialogs())
throw new TCAPException("Current dialog count exceeds its maximum value");
Long dialogId = this.getAvailableTxIdPreview();
PreviewDialogData pdd = new PreviewDialogData(this, dialogId);
pdd.setPrevewDialogDataKey1(ky);
PreviewDialogData pddx = this.dialogPreviewList.putIfAbsent(ky, pdd);
if (pddx != null) {
this.removePreviewDialog(pddx);
throw new TCAPException("Dialog with trId=" + ky.origTxId + " is already exists - we ignore it and drops curent dialog");
}
DialogImpl di = new DialogImpl(localAddress, remoteAddress, seqControl, this._EXECUTOR, this, pdd, false);
pdd.startIdleTimer();
return di;
// synchronized (this.dialogPreviewList) {
// if (this.dialogPreviewList.size() >= this.stack.getMaxDialogs())
// throw new TCAPException("Current dialog count exceeds its maximum value");
//
// // checking if a Dialog is current already exists
// PreviewDialogData pddx = this.dialogPreviewList.get(ky);
// if (pddx != null) {
// this.removePreviewDialog(pddx);
// throw new TCAPException("Dialog with trId=" + ky.origTxId + " is already exists - we ignore it and drops curent dialog");
// }
//
// Long dialogId = this.getAvailableTxIdPreview();
// PreviewDialogData pdd = new PreviewDialogData(this, dialogId);
// this.dialogPreviewList.put(ky, pdd);
// DialogImpl di = new DialogImpl(localAddress, remoteAddress, seqControl, this._EXECUTOR, this, pdd, false);
// pdd.setPrevewDialogDataKey1(ky);
//
// pdd.startIdleTimer();
//
// return di;
// }
}
protected synchronized Long getAvailableTxIdPreview() throws TCAPException {
while (true) {
// Long id;
// if (!currentDialogId.compareAndSet(this.stack.getDialogIdRangeEnd(), this.stack.getDialogIdRangeStart() + 1)) {
// id = currentDialogId.getAndIncrement();
// } else {
// id = this.stack.getDialogIdRangeStart();
// }
// return id;
if (this.curDialogId < this.stack.getDialogIdRangeStart())
this.curDialogId = this.stack.getDialogIdRangeStart() - 1;
if (++this.curDialogId > this.stack.getDialogIdRangeEnd())
this.curDialogId = this.stack.getDialogIdRangeStart();
Long id = this.curDialogId;
return id;
}
}
protected Dialog getPreviewDialog(PreviewDialogDataKey ky1, PreviewDialogDataKey ky2, SccpAddress localAddress,
SccpAddress remoteAddress, int seqControl) {
// synchronized (this.dialogPreviewList) {
PreviewDialogData pdd = this.dialogPreviewList.get(ky1);
DialogImpl di = null;
boolean sideB = false;
if (pdd != null) {
sideB = pdd.getPrevewDialogDataKey1().equals(ky1);
di = new DialogImpl(localAddress, remoteAddress, seqControl, this._EXECUTOR, this, pdd, sideB);
} else {
if (ky2 != null)
pdd = this.dialogPreviewList.get(ky2);
if (pdd != null) {
sideB = pdd.getPrevewDialogDataKey1().equals(ky1);
di = new DialogImpl(localAddress, remoteAddress, seqControl, this._EXECUTOR, this, pdd, sideB);
} else {
return null;
}
}
pdd.restartIdleTimer();
if (pdd.getPrevewDialogDataKey2() == null && ky2 != null) {
if (pdd.getPrevewDialogDataKey1().equals(ky1))
pdd.setPrevewDialogDataKey2(ky2);
else
pdd.setPrevewDialogDataKey2(ky1);
this.dialogPreviewList.put(pdd.getPrevewDialogDataKey2(), pdd);
}
return di;
// }
}
protected void removePreviewDialog(DialogImpl di) {
// synchronized (this.dialogPreviewList) {
PreviewDialogData pdd = this.dialogPreviewList.get(di.prevewDialogData.getPrevewDialogDataKey1());
if (pdd == null && di.prevewDialogData.getPrevewDialogDataKey2() != null) {
pdd = this.dialogPreviewList.get(di.prevewDialogData.getPrevewDialogDataKey2());
}
if (pdd != null)
removePreviewDialog(pdd);
// }
this.doRelease(di);
}
protected void removePreviewDialog(PreviewDialogData pdd) {
// synchronized (this.dialogPreviewList) {
this.dialogPreviewList.remove(pdd.getPrevewDialogDataKey1());
if (pdd.getPrevewDialogDataKey2() != null) {
this.dialogPreviewList.remove(pdd.getPrevewDialogDataKey2());
}
// }
pdd.stopIdleTimer();
// TODO ??? : create Dialog and invoke "this.doRelease(di);"
}
@Override
public void onCoordResponse(int ssn, int multiplicityIndicator) {
// TODO Auto-generated method stub
}
@Override
public DraftParsedMessage parseMessageDraft(byte[] data) {
try {
DraftParsedMessageImpl res = new DraftParsedMessageImpl();
AsnInputStream ais = new AsnInputStream(data);
int tag = ais.readTag();
if (ais.getTagClass() != Tag.CLASS_PRIVATE) {
res.setParsingErrorReason("Message tag class must be CLASS_PRIVATE");
return res;
}
switch (tag) {
case TCConversationMessage._TAG_CONVERSATION_WITH_PERM:
case TCConversationMessage._TAG_CONVERSATION_WITHOUT_PERM:
AsnInputStream localAis = ais.readSequenceStream();
// transaction portion
TransactionID tid = TcapFactory.readTransactionID(localAis);
if (tid.getFirstElem() == null || tid.getSecondElem() == null) {
res.setParsingErrorReason("TCTCConversationMessage decoding error: a message does not contain both both origination and resination transactionId");
return res;
}
byte[] originatingTransactionId = tid.getFirstElem();
res.setOriginationDialogId(Utils.decodeTransactionId(originatingTransactionId, this.stack.getSwapTcapIdBytes()));
byte[] destinationTransactionId = tid.getSecondElem();
res.setDestinationDialogId(Utils.decodeTransactionId(destinationTransactionId, this.stack.getSwapTcapIdBytes()));
if (tag == TCConversationMessage._TAG_CONVERSATION_WITH_PERM)
res.setMessageType(MessageType.ConversationWithPerm);
else
res.setMessageType(MessageType.ConversationWithoutPerm);
break;
case TCQueryMessage._TAG_QUERY_WITH_PERM:
case TCQueryMessage._TAG_QUERY_WITHOUT_PERM:
localAis = ais.readSequenceStream();
// transaction portion
tid = TcapFactory.readTransactionID(localAis);
if (tid.getFirstElem() == null || tid.getSecondElem() != null) {
res.setParsingErrorReason("TCQueryMessage decoding error: transactionId must contain only one transactionId");
return res;
}
originatingTransactionId = tid.getFirstElem();
res.setOriginationDialogId(Utils.decodeTransactionId(originatingTransactionId, this.stack.getSwapTcapIdBytes()));
if (tag == TCQueryMessage._TAG_QUERY_WITH_PERM)
res.setMessageType(MessageType.QueryWithPerm);
else
res.setMessageType(MessageType.QueryWithoutPerm);
break;
case TCResponseMessage._TAG_RESPONSE:
localAis = ais.readSequenceStream();
// transaction portion
tid = TcapFactory.readTransactionID(localAis);
if (tid.getFirstElem() == null || tid.getSecondElem() != null) {
res.setParsingErrorReason("TCResponseMessage decoding error: transactionId must contain only one transactionId");
return res;
}
destinationTransactionId = tid.getFirstElem();
res.setDestinationDialogId(Utils.decodeTransactionId(destinationTransactionId, this.stack.getSwapTcapIdBytes()));
res.setMessageType(MessageType.Response);
break;
case TCAbortMessage._TAG_ABORT:
localAis = ais.readSequenceStream();
// transaction portion
tid = TcapFactory.readTransactionID(localAis);
if (tid.getFirstElem() == null || tid.getSecondElem() != null) {
res.setParsingErrorReason("TCAbortMessage decoding error: transactionId must contain only one transactionId");
return res;
}
destinationTransactionId = tid.getFirstElem();
res.setDestinationDialogId(Utils.decodeTransactionId(destinationTransactionId, this.stack.getSwapTcapIdBytes()));
res.setMessageType(MessageType.Abort);
break;
case TCUniMessage._TAG_UNI:
res.setMessageType(MessageType.Unidirectional);
break;
default:
res.setParsingErrorReason("Unrecognized message tag");
break;
}
return res;
}
catch (Exception e) {
DraftParsedMessageImpl res = new DraftParsedMessageImpl();
res.setParsingErrorReason("Exception when message parsing: " + e.getMessage());
return res;
}
}
@Override
public void onState(int dpc, int ssn, boolean inService, int multiplicityIndicator) {
// TODO Auto-generated method stub
}
@Override
public void onPcState(int dpc, SignallingPointStatus status, Integer restrictedImportanceLevel,
RemoteSccpStatus remoteSccpStatus) {
// TODO Auto-generated method stub
}
@Override
public void onNetworkIdState(int networkId, NetworkIdState networkIdState) {
Integer ni = networkId;
NetworkIdState prev = networkIdStateList.get(ni);
if (!networkIdState.equals(prev)) {
logger.warn("Outgoing congestion control: TCAP-ANSI: onNetworkIdState: networkId=" + networkId + ", networkIdState="
+ networkIdState);
}
networkIdStateList.put(ni, networkIdState);
}
@Override
public void onConnectIndication(SccpConnection conn, SccpAddress calledAddress, SccpAddress callingAddress, ProtocolClass clazz, Credit credit, byte[] data, Importance importance) throws Exception {
// TODO Auto-generated method stub
}
@Override
public void onConnectConfirm(SccpConnection conn, byte[] data) {
// TODO Auto-generated method stub
}
@Override
public void onDisconnectIndication(SccpConnection conn, ReleaseCause reason, byte[] data) {
// TODO Auto-generated method stub
}
@Override
public void onDisconnectIndication(SccpConnection conn, RefusalCause reason, byte[] data) {
// TODO Auto-generated method stub
}
@Override
public void onDisconnectIndication(SccpConnection conn, ErrorCause errorCause) {
// TODO Auto-generated method stub
}
@Override
public void onResetIndication(SccpConnection conn, ResetCause reason) {
// TODO Auto-generated method stub
}
@Override
public void onResetConfirm(SccpConnection conn) {
// TODO Auto-generated method stub
}
@Override
public void onData(SccpConnection conn, byte[] data) {
// TODO Auto-generated method stub
}
@Override
public void onDisconnectConfirm(SccpConnection conn) {
// TODO Auto-generated method stub
}
@Override
public FastMap<Integer, NetworkIdState> getNetworkIdStateList() {
return networkIdStateList;
}
@Override
public NetworkIdState getNetworkIdState(int networkId) {
return networkIdStateList.get(networkId);
}
private void stopNetworkIdStateList() {
NetworkIdStateListUpdater curUpd = currentNetworkIdStateListUpdater;
if (curUpd != null)
curUpd.cancel();
}
private void updateNetworkIdStateList() {
stopNetworkIdStateList();
currentNetworkIdStateListUpdater = new NetworkIdStateListUpdater();
this._EXECUTOR.schedule(currentNetworkIdStateListUpdater, 1000, TimeUnit.MILLISECONDS);
networkIdStateList = this.sccpProvider.getNetworkIdStateList();
int cntNotAvailable = 0;
int cntCongLevel1 = 0;
int cntCongLevel2 = 0;
int cntCongLevel3 = 0;
if (networkIdStateList != null) {
for (NetworkIdState state : networkIdStateList.values()) {
if (!state.isAvailavle())
cntNotAvailable++;
if (state.getCongLevel() >= 1) {
cntCongLevel1++;
}
if (state.getCongLevel() >= 2) {
cntCongLevel1++;
cntCongLevel2++;
}
if (state.getCongLevel() >= 3) {
cntCongLevel1++;
cntCongLevel2++;
cntCongLevel3++;
}
}
}
this.stack.getCounterProviderImpl().updateMaxNetworkIdAreasNotAvailable(cntNotAvailable);
this.stack.getCounterProviderImpl().updateMaxNetworkIdAreasCongLevel_1(cntCongLevel1);
this.stack.getCounterProviderImpl().updateMaxNetworkIdAreasCongLevel_2(cntCongLevel2);
this.stack.getCounterProviderImpl().updateMaxNetworkIdAreasCongLevel_3(cntCongLevel3);
}
public int getNetworkIdAreasNotAvailableCount() {
int cntNotAvailable = 0;
for (NetworkIdState state : networkIdStateList.values()) {
if (!state.isAvailavle())
cntNotAvailable++;
}
return cntNotAvailable;
}
public int getNetworkIdAreasCongLevel_1_Count() {
int cntCongLevel1 = 0;
for (NetworkIdState state : networkIdStateList.values()) {
if (state.getCongLevel() >= 1) {
cntCongLevel1++;
}
}
return cntCongLevel1;
}
public int getNetworkIdAreasCongLevel_2_Count() {
int cntCongLevel2 = 0;
for (NetworkIdState state : networkIdStateList.values()) {
if (state.getCongLevel() >= 2) {
cntCongLevel2++;
}
}
return cntCongLevel2;
}
public int getNetworkIdAreasCongLevel_3_Count() {
int cntCongLevel3 = 0;
for (NetworkIdState state : networkIdStateList.values()) {
if (state.getCongLevel() >= 3) {
cntCongLevel3++;
}
}
return cntCongLevel3;
}
private class NetworkIdStateListUpdater implements Runnable, Serializable {
private boolean isCancelled;
public void cancel() {
isCancelled = true;
}
@Override
public void run() {
if (isCancelled || !stack.isStarted())
return;
updateNetworkIdStateList();
}
}
private class CongestionExecutor implements Runnable {
@Override
public void run() {
// MTP3 Executor monitors
ExecutorCongestionMonitor[] lst = sccpProvider.getExecutorCongestionMonitorList();
int maxExecutorCongestionLevel = 0;
int countExecutorCountWithCongestionLevel_1 = 0;
int countExecutorCountWithCongestionLevel_2 = 0;
int countExecutorCountWithCongestionLevel_3 = 0;
for (ExecutorCongestionMonitor ecm : lst) {
int level = ecm.getAlarmLevel();
if (maxExecutorCongestionLevel < level)
maxExecutorCongestionLevel = level;
if (level >= 1) {
countExecutorCountWithCongestionLevel_1++;
}
if (level >= 2) {
countExecutorCountWithCongestionLevel_1++;
countExecutorCountWithCongestionLevel_2++;
}
if (level >= 3) {
countExecutorCountWithCongestionLevel_1++;
countExecutorCountWithCongestionLevel_2++;
countExecutorCountWithCongestionLevel_3++;
}
try {
ecm.setDelayThreshold_1(stack.getCongControl_ExecutorDelayThreshold_1());
ecm.setDelayThreshold_2(stack.getCongControl_ExecutorDelayThreshold_2());
ecm.setDelayThreshold_3(stack.getCongControl_ExecutorDelayThreshold_3());
ecm.setBackToNormalDelayThreshold_1(stack.getCongControl_ExecutorBackToNormalDelayThreshold_1());
ecm.setBackToNormalDelayThreshold_2(stack.getCongControl_ExecutorBackToNormalDelayThreshold_2());
ecm.setBackToNormalDelayThreshold_3(stack.getCongControl_ExecutorBackToNormalDelayThreshold_3());
} catch (Exception e) {
// this must not be
}
}
executorCongestionLevel = maxExecutorCongestionLevel;
executorCountWithCongestionLevel_1 = countExecutorCountWithCongestionLevel_1;
executorCountWithCongestionLevel_2 = countExecutorCountWithCongestionLevel_2;
executorCountWithCongestionLevel_3 = countExecutorCountWithCongestionLevel_3;
stack.getCounterProviderImpl().updateMaxExecutorsCongLevel_1(executorCountWithCongestionLevel_1);
stack.getCounterProviderImpl().updateMaxExecutorsCongLevel_2(executorCountWithCongestionLevel_2);
stack.getCounterProviderImpl().updateMaxExecutorsCongLevel_3(executorCountWithCongestionLevel_3);
// MemoryMonitor
memoryCongestionMonitor.setMemoryThreshold1(stack.getCongControl_MemoryThreshold_1());
memoryCongestionMonitor.setMemoryThreshold2(stack.getCongControl_MemoryThreshold_2());
memoryCongestionMonitor.setMemoryThreshold3(stack.getCongControl_MemoryThreshold_3());
memoryCongestionMonitor.setBackToNormalMemoryThreshold1(stack.getCongControl_BackToNormalMemoryThreshold_1());
memoryCongestionMonitor.setBackToNormalMemoryThreshold2(stack.getCongControl_BackToNormalMemoryThreshold_2());
memoryCongestionMonitor.setBackToNormalMemoryThreshold3(stack.getCongControl_BackToNormalMemoryThreshold_3());
memoryCongestionMonitor.monitor();
stack.getCounterProviderImpl().updateMaxMemoryCongLevel(memoryCongestionMonitor.getAlarmLevel());
// cumulativeCongestionLevel
int newCumulativeCongestionLevel = getCumulativeCongestionLevel();
if (cumulativeCongestionLevel != newCumulativeCongestionLevel) {
logger.warn("Outgoing congestion control: Changing of internal congestion level: " + cumulativeCongestionLevel
+ "->" + newCumulativeCongestionLevel + "\n" + getCumulativeCongestionLevelString());
cumulativeCongestionLevel = newCumulativeCongestionLevel;
}
}
}
@Override
public synchronized void setUserPartCongestionLevel(String congObject, int level) {
if (congObject != null) {
if (level > 0) {
lstUserPartCongestionLevel.put(congObject, level);
} else {
lstUserPartCongestionLevel.remove(congObject);
}
int cntUserPartCongestionLevel_1 = 0;
int cntUserPartCongestionLevel_2 = 0;
int cntUserPartCongestionLevel_3 = 0;
for (Integer lev : lstUserPartCongestionLevel.values()) {
if (lev >= 1) {
cntUserPartCongestionLevel_1++;
}
if (lev >= 2) {
cntUserPartCongestionLevel_1++;
cntUserPartCongestionLevel_2++;
}
if (lev >= 3) {
cntUserPartCongestionLevel_1++;
cntUserPartCongestionLevel_2++;
cntUserPartCongestionLevel_3++;
}
}
userPartCongestionLevel_1 = cntUserPartCongestionLevel_1;
userPartCongestionLevel_2 = cntUserPartCongestionLevel_2;
userPartCongestionLevel_3 = cntUserPartCongestionLevel_3;
stack.getCounterProviderImpl().updateMaxUserPartsCongLevel_1(userPartCongestionLevel_1);
stack.getCounterProviderImpl().updateMaxUserPartsCongLevel_2(userPartCongestionLevel_2);
stack.getCounterProviderImpl().updateMaxUserPartsCongLevel_3(userPartCongestionLevel_3);
}
}
@Override
public int getMemoryCongestionLevel() {
return memoryCongestionMonitor.getAlarmLevel();
}
@Override
public int getExecutorCongestionLevel() {
return executorCongestionLevel;
}
public int getExecutorCountWithCongestionLevel_1() {
return executorCountWithCongestionLevel_1;
}
public int getExecutorCountWithCongestionLevel_2() {
return executorCountWithCongestionLevel_2;
}
public int getExecutorCountWithCongestionLevel_3() {
return executorCountWithCongestionLevel_3;
}
public int getUserPartCongestionLevel_1() {
return userPartCongestionLevel_1;
}
public int getUserPartCongestionLevel_2() {
return userPartCongestionLevel_2;
}
public int getUserPartCongestionLevel_3() {
return userPartCongestionLevel_3;
}
@Override
public int getCumulativeCongestionLevel() {
int level = 0;
for (Integer lev : lstUserPartCongestionLevel.values()) {
if (level < lev) {
level = lev;
}
}
int lev2 = getMemoryCongestionLevel();
if (level < lev2) {
level = lev2;
}
lev2 = getExecutorCongestionLevel();
if (level < lev2) {
level = lev2;
}
return level;
}
protected String getCumulativeCongestionLevelString() {
StringBuilder sb = new StringBuilder();
sb.append("CongestionLevel=[");
int i1 = 0;
int lev2 = getMemoryCongestionLevel();
if (lev2 > 0) {
sb.append("MemoryCongestionLevel=");
sb.append(lev2);
}
lev2 = getExecutorCongestionLevel();
if (lev2 > 0) {
if (i1 == 0)
i1 = 1;
else
sb.append(", ");
sb.append("ExecutorCongestionLevel=");
sb.append(lev2);
}
for (Entry<String, Integer> entry : lstUserPartCongestionLevel.entrySet()) {
lev2 = entry.getValue();
if (lev2 > 0) {
if (i1 == 0)
i1 = 1;
else
sb.append(", ");
sb.append("UserPartCongestion=");
sb.append(entry.getKey());
sb.append("-");
sb.append(lev2);
}
}
if (this.stack.isCongControl_blockingIncomingTcapMessages()) {
lev2 = getCumulativeCongestionLevel();
if (lev2 == 3) {
sb.append(", all incoming TCAP messages will be rejected");
}
if (lev2 == 2) {
sb.append(", new incoming TCAP dialogs will be rejected");
}
}
sb.append("]");
return sb.toString();
}
}
| agpl-3.0 |
GrowthcraftCE/Growthcraft-1.11 | src/main/java/growthcraft/bamboo/GrowthcraftBamboo.java | 1530 | package growthcraft.bamboo;
import growthcraft.bamboo.init.GrowthcraftBambooBlocks;
import growthcraft.bamboo.init.GrowthcraftBambooItems;
import growthcraft.bamboo.init.GrowthcraftBambooRecipes;
import growthcraft.bamboo.proxy.CommonProxy;
import net.minecraftforge.common.config.Configuration;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.SidedProxy;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPostInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
@Mod(modid = Reference.MODID, name = Reference.NAME, version = Reference.VERSION)
public class GrowthcraftBamboo {
public static Configuration configuration;
@Mod.Instance(Reference.MODID)
public static GrowthcraftBamboo instance;
@SidedProxy(serverSide = Reference.SERVER_PROXY_CLASS, clientSide = Reference.CLIENT_PROXY_CLASS)
public static CommonProxy proxy;
@Mod.EventHandler
public static void preInit(FMLPreInitializationEvent event) {
GrowthcraftBambooBlocks.init();
GrowthcraftBambooBlocks.register();
GrowthcraftBambooItems.init();
GrowthcraftBambooItems.register();
proxy.preInit();
}
@Mod.EventHandler
public static void init(FMLInitializationEvent event) {
GrowthcraftBambooRecipes.registerRecipes();
proxy.init();
}
@Mod.EventHandler
public static void postInit(FMLPostInitializationEvent event) {
}
}
| agpl-3.0 |
shaoliancheng/videoplayer-android-tv | playkit/src/main/java/com/kaltura/playkit/PlayerDecorator.java | 1784 | /*
* ============================================================================
* Copyright (C) 2017 Kaltura Inc.
*
* Licensed under the AGPLv3 license, unless a different license for a
* particular library is specified in the applicable library path.
*
* You may obtain a copy of the License at
* https://www.gnu.org/licenses/agpl-3.0.html
* ============================================================================
*/
package com.kaltura.playkit;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import com.kaltura.playkit.player.PlayerView;
public abstract class PlayerDecorator extends PlayerDecoratorBase {
@Override
public final void destroy() {
super.destroy();
}
@Override
final public PlayerView getView() {
return super.getView();
}
@Override
final public void skip() {
super.skip();
}
@Override
final public void addEventListener(@NonNull PKEvent.Listener listener, Enum... events) {
super.addEventListener(listener, events);
}
@Override
final public void addStateChangeListener(@NonNull PKEvent.Listener listener) {
super.addStateChangeListener(listener);
}
final Player getPlayer() {
return super.getPlayer();
}
@Override
final public void onApplicationResumed() {
super.onApplicationResumed();
}
@Override
final public void onApplicationPaused() {
super.onApplicationPaused();
}
@Override
final public void updatePluginConfig(@NonNull String pluginName, @Nullable Object pluginConfig) {
super.updatePluginConfig(pluginName, pluginConfig);
}
final void setPlayer(Player player) {
super.setPlayer(player);
}
}
| agpl-3.0 |
splicemachine/spliceengine | splice_machine/src/test/java/com/splicemachine/derby/impl/sql/execute/tester/Column.java | 887 | /*
* Copyright (c) 2012 - 2020 Splice Machine, Inc.
*
* This file is part of Splice Machine.
* Splice Machine is free software: you can redistribute it and/or modify it under the terms of the
* GNU Affero General Public License as published by the Free Software Foundation, either
* version 3, or (at your option) any later version.
* Splice Machine is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
* You should have received a copy of the GNU Affero General Public License along with Splice Machine.
* If not, see <http://www.gnu.org/licenses/>.
*/
package com.splicemachine.derby.impl.sql.execute.tester;
/**
* @author Scott Fines
* Created on: 8/2/13
*/
public enum Column {
}
| agpl-3.0 |
davidwong/TestDataCaptureJ | src/au/com/dw/testdatacapturej/log/constructor/ParameterizedConstructorGenerator.java | 1777 | /*******************************************************************************
* Copyright () 2009, 2011 David Wong
*
* This file is part of TestDataCaptureJ.
*
* TestDataCaptureJ is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* TestDataCaptureJ is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Afferro General Public License for more details.
*
* You should have received a copy of the GNU Afferro General Public License
* along with TestDataCaptureJ. If not, see <http://www.gnu.org/licenses/>.
*******************************************************************************/
package au.com.dw.testdatacapturej.log.constructor;
import au.com.dw.testdatacapturej.log.FormatConstants;
import au.com.dw.testdatacapturej.log.LogBuilder;
import au.com.dw.testdatacapturej.meta.ObjectInfo;
/**
* Generate a constructor line with parameters.
*
* @author David Wong
*
*/
public class ParameterizedConstructorGenerator extends BaseConstructorGenerator {
@Override
public void generateConstructor(LogBuilder builder, ObjectInfo info) {
builder.append(FormatConstants.newLine);
// get the constructor line
getLineBuilder().createParameterizedConstructorLine(builder, info);
// pass the newly created class field name to child objects
for (ObjectInfo fieldInfo : info.getFieldList())
{
fieldInfo.setContainingClassFieldName(info.getFullFieldName());
}
builder.append(FormatConstants.newLine);
}
}
| agpl-3.0 |
semantic-web-software/dynagent | lib/javamail-1.4/demo/webapp/src/classes/demo/MailUserBean.java | 5578 | /*
* @(#)MailUserBean.java 1.7 03/10/30
*
* Copyright 2001-2003 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES,
* INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A
* PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND
* ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES OR LIABILITIES
* SUFFERED BY LICENSEE AS A RESULT OF OR RELATING TO USE, MODIFICATION
* OR DISTRIBUTION OF THE SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL
* SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR
* FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE
* DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY,
* ARISING OUT OF THE USE OF OR INABILITY TO USE SOFTWARE, EVEN IF SUN HAS
* BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that Software is not designed, licensed or intended
* for use in the design, construction, operation or maintenance of any
* nuclear facility.
*
*/
package demo;
import java.util.*;
import javax.mail.*;
import javax.naming.*;
/**
* This JavaBean is used to store mail user information.
*/
public class MailUserBean {
private Folder folder;
private String hostname;
private String username;
private String password;
private Session session;
private Store store;
private URLName url;
private String protocol = "imap";
private String mbox = "INBOX";
public MailUserBean(){}
/**
* Returns the javax.mail.Folder object.
*/
public Folder getFolder() {
return folder;
}
/**
* Returns the number of messages in the folder.
*/
public int getMessageCount() throws MessagingException {
return folder.getMessageCount();
}
/**
* hostname getter method.
*/
public String getHostname() {
return hostname;
}
/**
* hostname setter method.
*/
public void setHostname(String hostname) {
this.hostname = hostname;
}
/**
* username getter method.
*/
public String getUsername() {
return username;
}
/**
* username setter method.
*/
public void setUsername(String username) {
this.username = username;
}
/**
* password getter method.
*/
public String getPassword() {
return password;
}
/**
* password setter method.
*/
public void setPassword(String password) {
this.password = password;
}
/**
* session getter method.
*/
public Session getSession() {
return session;
}
/**
* session setter method.
*/
public void setSession(Session session) {
this.session = session;
}
/**
* store getter method.
*/
public Store getStore() {
return store;
}
/**
* store setter method.
*/
public void setStore(Store store) {
this.store = store;
}
/**
* url getter method.
*/
public URLName getUrl() {
return url;
}
/**
* Method for checking if the user is logged in.
*/
public boolean isLoggedIn() {
return store.isConnected();
}
/**
* Method used to login to the mail host.
*/
public void login() throws Exception {
url = new URLName(protocol, getHostname(), -1, mbox,
getUsername(), getPassword());
/*
* First, try to get the session from JNDI,
* as would be done under J2EE.
*/
try {
InitialContext ic = new InitialContext();
Context ctx = (Context)ic.lookup("java:comp/env");
session = (Session)ctx.lookup("MySession");
} catch (Exception ex) {
// ignore it
}
// if JNDI fails, try the old way that should work everywhere
if (session == null) {
Properties props = null;
try {
props = System.getProperties();
} catch (SecurityException sex) {
props = new Properties();
}
session = Session.getInstance(props, null);
}
store = session.getStore(url);
store.connect();
folder = store.getFolder(url);
folder.open(Folder.READ_WRITE);
}
/**
* Method used to login to the mail host.
*/
public void login(String hostname, String username, String password)
throws Exception {
this.hostname = hostname;
this.username = username;
this.password = password;
login();
}
/**
* Method used to logout from the mail host.
*/
public void logout() throws MessagingException {
folder.close(false);
store.close();
store = null;
session = null;
}
}
| agpl-3.0 |
dmontag/neo4j-enterprise | ha/src/main/java/org/neo4j/kernel/ha/SlavePriority.java | 940 | /**
* Copyright (c) 2002-2012 "Neo Technology,"
* Network Engine for Objects in Lund AB [http://neotechnology.com]
*
* This file is part of Neo4j.
*
* Neo4j is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.neo4j.kernel.ha;
public interface SlavePriority
{
Iterable<Slave> prioritize( Iterable<Slave> slaves );
}
| agpl-3.0 |
Asqatasun/Asqatasun | rules/rules-rgaa4.0/src/main/java/org/asqatasun/rules/rgaa40/Rgaa40Rule010102.java | 1898 | /**
* Asqatasun - Automated webpage assessment
* Copyright (C) 2008-2020 Asqatasun.org
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Contact us by mail: asqatasun AT asqatasun DOT org
*/
package org.asqatasun.rules.rgaa40;
import org.asqatasun.rules.elementselector.AreaElementSelector;
import org.asqatasun.rules.elementselector.ImageElementSelector;
import static org.asqatasun.rules.keystore.AttributeStore.*;
import static org.asqatasun.rules.keystore.EvidenceStore.COMPUTED_LINK_TITLE;
/**
* Implementation of rule 1.1.2 (referential RGAA 4.0)
*
* For more details about implementation, refer to <a href="https://gitlab.com/asqatasun/Asqatasun/-/blob/master/documentation/en/90_Rules/rgaa4.0/01.Images/Rule-1-1-2.md">rule 1.1.2 design page</a>.
* @see <a href="https://www.numerique.gouv.fr/publications/rgaa-accessibilite/methode/criteres/#test-1-1-2">1.1.2 rule specification</a>
*/
public class Rgaa40Rule010102 extends AbstractInformativeImagePresenceAlternativePageRuleImplementation {
public Rgaa40Rule010102() {
super(
new ImageElementSelector(new AreaElementSelector(), true, true),
true,
ALT_ATTR,
ARIA_LABEL_ATTR,
COMPUTED_LINK_TITLE,
HREF_ATTR);
}
}
| agpl-3.0 |
boob-sbcm/3838438 | src/main/java/com/rapidminer/gui/tools/XMLEditor.java | 1686 | /**
* Copyright (C) 2001-2017 by RapidMiner and the contributors
*
* Complete list of developers available at our web site:
*
* http://rapidminer.com
*
* This program is free software: you can redistribute it and/or modify it under the terms of the
* GNU Affero General Public License as published by the Free Software Foundation, either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program.
* If not, see http://www.gnu.org/licenses/.
*/
package com.rapidminer.gui.tools;
import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea;
import com.rapidminer.gui.tools.syntax.JEditTextArea;
import com.rapidminer.gui.tools.syntax.TextAreaDefaults;
import com.rapidminer.gui.tools.syntax.XMLTokenMarker;
/**
* A generic XML editor.
*
* @deprecated Use {@link RSyntaxTextArea} with XML highlighting instead
* @author Ingo Mierswa
*/
@Deprecated
public class XMLEditor extends JEditTextArea {
private static final long serialVersionUID = 5515907668417632521L;
public XMLEditor() {
super(getDefaults());
setTokenMarker(new XMLTokenMarker());
}
private static TextAreaDefaults getDefaults() {
TextAreaDefaults defaultSettings = TextAreaDefaults.getDefaults();
defaultSettings.styles = SwingTools.getSyntaxStyles();
return defaultSettings;
}
}
| agpl-3.0 |
BrunoEberhard/open-ech | src/main/model/ch/ech/ech0211/v1/EventRequest.java | 651 | package ch.ech.ech0211.v1;
import java.util.List;
import org.minimalj.model.annotation.NotEmpty;
import javax.annotation.Generated;
import org.minimalj.model.Keys;
@Generated(value="org.minimalj.metamodel.generator.ClassGenerator")
public class EventRequest {
public static final EventRequest $ = Keys.of(EventRequest.class);
public Object id;
@NotEmpty
public EventType eventType;
@NotEmpty
public PlanningPermissionApplicationIdentification planningPermissionApplicationIdentification;
public ch.ech.ech0147.t2.Directive directive;
public List<ch.ech.ech0147.t0.Document> document;
public List<String> remark;
public byte[] extension;
} | agpl-3.0 |
hogi/kunagi | src/main/java/scrum/client/tasks/ClaimTaskDropAction.java | 1447 | package scrum.client.tasks;
import ilarkesto.core.scope.Scope;
import ilarkesto.gwt.client.undo.AUndoOperation;
import scrum.client.admin.User;
import scrum.client.dnd.BlockListDropAction;
import scrum.client.project.Requirement;
import scrum.client.sprint.Task;
import scrum.client.workspace.VisibleDataChangedEvent;
public class ClaimTaskDropAction implements BlockListDropAction<Task> {
private Requirement requirement;
public ClaimTaskDropAction(Requirement requirement) {
this.requirement = requirement;
}
public boolean onDrop(Task task) {
Requirement requirement = task.getRequirement();
User owner = task.getOwner();
task.setRequirement(this.requirement);
task.claim();
new VisibleDataChangedEvent().fireInCurrentScope();
Scope.get().getComponent(scrum.client.undo.Undo.class).getManager().add(new Undo(owner, task, requirement));
return true;
}
class Undo extends AUndoOperation {
private User owner;
private Task task;
private Requirement requirement;
public Undo(User owner, Task task, Requirement requirement) {
this.owner = owner;
this.task = task;
this.requirement = requirement;
}
@Override
public String getLabel() {
return "Undo Claim/Change Story for " + task.getReference() + " " + task.getLabel();
}
@Override
protected void onUndo() {
task.setRequirement(requirement);
task.setOwner(owner);
new VisibleDataChangedEvent().fireInCurrentScope();
}
}
}
| agpl-3.0 |
aborg0/rapidminer-studio | src/main/java/com/rapidminer/operator/learner/subgroups/utility/Squared.java | 2015 | /**
* Copyright (C) 2001-2019 by RapidMiner and the contributors
*
* Complete list of developers available at our web site:
*
* http://rapidminer.com
*
* This program is free software: you can redistribute it and/or modify it under the terms of the
* GNU Affero General Public License as published by the Free Software Foundation, either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program.
* If not, see http://www.gnu.org/licenses/.
*/
package com.rapidminer.operator.learner.subgroups.utility;
import com.rapidminer.operator.learner.subgroups.hypothesis.Hypothesis;
import com.rapidminer.operator.learner.subgroups.hypothesis.Rule;
/**
* Calculates the squared error of a rule.
*
* @author Tobias Malbrecht
*/
public class Squared extends UtilityFunction {
/**
*
*/
private static final long serialVersionUID = 1L;
public Squared(double totalWeight, double totalPredictionWeight) {
super(totalWeight, totalPredictionWeight);
}
@Override
public double utility(Rule rule) {
double g = rule.getCoveredWeight() / totalWeight;
double p = rule.getPredictionWeight() / rule.getCoveredWeight();
double p0 = priors[rule.predictsPositive() ? POSITIVE_CLASS : NEGATIVE_CLASS];
return g * g * (p - p0);
}
@Override
public double optimisticEstimate(Hypothesis hypothesis) {
double g = hypothesis.getCoveredWeight() / totalWeight;
return g * g * Math.max(priors[POSITIVE_CLASS], priors[NEGATIVE_CLASS]);
}
@Override
public String getName() {
return "Squared";
}
@Override
public String getAbbreviation() {
return "Squ";
}
}
| agpl-3.0 |
shred/cilla | cilla-service/src/main/java/org/shredzone/cilla/service/HeaderService.java | 3874 | /*
* cilla - Blog Management System
*
* Copyright (C) 2012 Richard "Shred" Körber
* http://cilla.shredzone.org
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.shredzone.cilla.service;
import java.util.List;
import javax.activation.DataSource;
import org.shredzone.cilla.core.datasource.ResourceDataSource;
import org.shredzone.cilla.core.model.Header;
import org.shredzone.cilla.ws.exception.CillaServiceException;
/**
* A service that takes care for header images.
*
* @author Richard "Shred" Körber
*/
public interface HeaderService {
/**
* Creates a new, empty header.
*
* @return {@link Header} that was created
*/
Header createNew();
/**
* Adds a new {@link Header} object to the database.
*
* @param header
* {@link Header} to be added
* @param headerImg
* The uploaded file to be used as header image
* @param fullImg
* The uploaded file to be used as a full view of the image in the header's
* description page
*/
void create(Header header, DataSource headerImg, DataSource fullImg) throws CillaServiceException;
/**
* Updates a {@link Header}. Must be invoked after a header was changed.
*
* @param header
* {@link Header} that was changed
*/
void update(Header header) throws CillaServiceException;
/**
* Updates the images of an existing {@link Header}.
*
* @param header
* {@link Header} to change the images of
* @param headerImg
* The uploaded file to be used as header image, or {@code null} to keep
* the existing image
* @param fullImg
* The uploaded file to be used as a full view of the image in the header's
* description page, or {@code null} to keep the existing image
*/
void updateImage(Header header, DataSource headerImg, DataSource fullImg)
throws CillaServiceException;
/**
* Gets the header image.
*
* @param header
* {@link Header} to get the image of
* @return {@link ResourceDataSource} of the image
*/
ResourceDataSource getHeaderImage(Header header) throws CillaServiceException;
/**
* Gets a scaled instance of the full sized header image.
*
* @param header
* {@link Header} to get the image of
* @return {@link ResourceDataSource} of the image
*/
ResourceDataSource getFullImage(Header header) throws CillaServiceException;
/**
* Removes a header, deleting its resources.
*
* @param header
* {@link Header} to be removed
*/
void remove(Header header) throws CillaServiceException;
/**
* Checks if the header is visible to the currently logged in user.
*
* @param header
* {@link Header} to check
* @return {@code true} if the header is visible
*/
boolean isVisible(Header header);
/**
* Returns a collection of all {@link Header} that are visible to the currently logged
* in user.
*
* @return List of {@link Header}
*/
List<Header> getVisibleHeaders();
}
| agpl-3.0 |
quikkian-ua-devops/will-financials | kfs-kns/src/main/java/org/kuali/kfs/krad/bo/AdHocRouteRecipient.java | 3399 | /*
* The Kuali Financial System, a comprehensive financial management system for higher education.
*
* Copyright 2005-2017 Kuali, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kuali.kfs.krad.bo;
import org.apache.commons.lang.StringUtils;
import org.kuali.rice.kew.api.KewApiConstants;
import org.kuali.rice.kew.api.util.CodeTranslator;
import javax.persistence.Column;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import javax.persistence.Transient;
import java.util.Map;
/**
* TODO we should not be referencing kew constants from this class and wedding ourselves to that workflow application Ad Hoc Route
* Recipient Business Object
*/
@MappedSuperclass
public class AdHocRouteRecipient extends PersistableBusinessObjectBase {
private static final long serialVersionUID = -6499610180752232494L;
private static Map actionRequestCds;
public static final Integer PERSON_TYPE = new Integer(0);
public static final Integer WORKGROUP_TYPE = new Integer(1);
@Id
@Column(name = "RECIP_TYP_CD")
protected Integer type;
@Id
@Column(name = "ACTN_RQST_CD")
protected String actionRequested;
@Id
@Column(name = "ACTN_RQST_RECIP_ID")
protected String id; // can be networkId or group id
@Transient
protected String name;
@Column(name = "DOC_HDR_ID")
protected String documentNumber;
public AdHocRouteRecipient() {
// set some defaults that can be overridden
this.actionRequested = KewApiConstants.ACTION_REQUEST_APPROVE_REQ;
this.versionNumber = new Long(1);
}
public String getActionRequested() {
return actionRequested;
}
public void setActionRequested(String actionRequested) {
this.actionRequested = actionRequested;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getType() {
return type;
}
public void setType(Integer type) {
this.type = type;
}
public void setdocumentNumber(String documentNumber) {
this.documentNumber = documentNumber;
}
public String getdocumentNumber() {
return documentNumber;
}
public String getActionRequestedValue() {
String actionRequestedValue = null;
if (StringUtils.isNotBlank(getActionRequested())) {
actionRequestCds.clear();
actionRequestCds.putAll(CodeTranslator.arLabels);
actionRequestedValue = (String) actionRequestCds.get(getActionRequested());
}
return actionRequestedValue;
}
}
| agpl-3.0 |
opensourceBIM/BIMserver | PluginBase/generated/org/bimserver/models/ifc4/IfcSensorType.java | 2921 | /**
* Copyright (C) 2009-2014 BIMserver.org
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.bimserver.models.ifc4;
/******************************************************************************
* Copyright (C) 2009-2019 BIMserver.org
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see {@literal<http://www.gnu.org/licenses/>}.
*****************************************************************************/
public interface IfcSensorType extends IfcDistributionControlElementType {
/**
* Returns the value of the '<em><b>Predefined Type</b></em>' attribute.
* The literals are from the enumeration {@link org.bimserver.models.ifc4.IfcSensorTypeEnum}.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Predefined Type</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Predefined Type</em>' attribute.
* @see org.bimserver.models.ifc4.IfcSensorTypeEnum
* @see #setPredefinedType(IfcSensorTypeEnum)
* @see org.bimserver.models.ifc4.Ifc4Package#getIfcSensorType_PredefinedType()
* @model
* @generated
*/
IfcSensorTypeEnum getPredefinedType();
/**
* Sets the value of the '{@link org.bimserver.models.ifc4.IfcSensorType#getPredefinedType <em>Predefined Type</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Predefined Type</em>' attribute.
* @see org.bimserver.models.ifc4.IfcSensorTypeEnum
* @see #getPredefinedType()
* @generated
*/
void setPredefinedType(IfcSensorTypeEnum value);
} // IfcSensorType
| agpl-3.0 |
CecileBONIN/Silverpeas-Components | resources-manager/resources-manager-jar/src/main/java/org/silverpeas/resourcemanager/repository/ResourceRepository.java | 3540 | /*
* Copyright (C) 2000 - 2013 Silverpeas
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* As a special exception to the terms and conditions of version 3.0 of
* the GPL, you may redistribute this Program in connection with Free/Libre
* Open Source Software ("FLOSS") applications as described in Silverpeas's
* FLOSS exception. You should have recieved a copy of the text describing
* the FLOSS exception, and it is also available here:
* "http://www.silverpeas.org/docs/core/legal/floss_exception.html"
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.silverpeas.resourcemanager.repository;
import java.util.List;
import org.silverpeas.resourcemanager.model.Resource;
import org.silverpeas.resourcemanager.model.ResourceValidator;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
public interface ResourceRepository extends JpaRepository<Resource, Long> {
@Query("from Resource resource WHERE resource.category.id = :categoryId")
public List<Resource> findAllResourcesByCategory(@Param("categoryId") Long categoryId);
@Query("from Resource resource WHERE resource.instanceId = :instanceId AND resource.bookable = 1 AND resource.category.bookable = 1")
public List<Resource> findAllBookableResources(@Param("instanceId") String instanceId);
@Query("SELECT DISTINCT reservedResource.resource FROM ReservedResource reservedResource WHERE reservedResource.reservedResourcePk.reservationId = :reservationId")
public List<Resource> findAllResourcesForReservation(
@Param("reservationId") Long reservationId);
@Query("SELECT DISTINCT reservedResource.resource FROM ReservedResource reservedResource " +
"WHERE reservedResource.reservation.id != :reservationIdToSkip AND reservedResource.status != 'R'" +
"AND reservedResource.resource.id IN :aimedResourceIds " +
"AND reservedResource.reservation.beginDate < :endPeriod " +
"AND reservedResource.reservation.endDate > :startPeriod ")
public List<Resource> findAllReservedResources(
@Param("reservationIdToSkip") Long reservationIdToSkip,
@Param("aimedResourceIds") List<Long> aimedResourceIds,
@Param("startPeriod") String startPeriod, @Param("endPeriod") String endPeriod);
@Query("SELECT DISTINCT resourceValidator FROM ResourceValidator resourceValidator " +
"WHERE resourceValidator.resourceValidatorPk.managerId = :currentUserId AND resourceValidator.resourceValidatorPk.resourceId = :reservationId")
public ResourceValidator getResourceValidator(
@Param("reservationId") Long currentResourceId, @Param("currentUserId") Long currentUserId);
@Modifying
@Query("DELETE Resource resource WHERE resource.category.id = :categoryId")
public void deleteResourcesFromCategory(@Param("categoryId") Long categoryId);
} | agpl-3.0 |
RestComm/jss7 | tcap/tcap-impl/src/test/java/org/restcomm/protocols/ss7/tcap/asn/DialogResponseAPDUTest.java | 5530 | /*
* JBoss, Home of Professional Open Source
* Copyright 2011, Red Hat, Inc. and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.restcomm.protocols.ss7.tcap.asn;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertNull;
import static org.testng.Assert.assertTrue;
import java.util.Arrays;
import org.mobicents.protocols.asn.AsnInputStream;
import org.mobicents.protocols.asn.AsnOutputStream;
import org.restcomm.protocols.ss7.tcap.asn.DialogResponseAPDU;
import org.restcomm.protocols.ss7.tcap.asn.DialogServiceProviderType;
import org.restcomm.protocols.ss7.tcap.asn.DialogServiceUserType;
import org.restcomm.protocols.ss7.tcap.asn.Result;
import org.restcomm.protocols.ss7.tcap.asn.ResultSourceDiagnostic;
import org.restcomm.protocols.ss7.tcap.asn.ResultType;
import org.restcomm.protocols.ss7.tcap.asn.TcapFactory;
import org.restcomm.protocols.ss7.tcap.asn.UserInformation;
import org.testng.annotations.Test;
/**
*
* @author sergey vetyutnev
*
*/
@Test(groups = { "asn" })
public class DialogResponseAPDUTest {
private byte[] getData() {
return new byte[] { 97, 44, (byte) 128, 2, 7, (byte) 128, (byte) 161, 9, 6, 7, 4, 0, 0, 1, 0, 21, 2, (byte) 162, 3, 2,
1, 0, (byte) 163, 5, (byte) 161, 3, 2, 1, 0, (byte) 190, 15, 40, 13, 6, 7, 4, 0, 0, 1, 1, 1, 1, (byte) 160, 2,
(byte) 161, 0 };
}
private byte[] getData2() {
return new byte[] { 97, 27, (byte) 128, 2, 7, (byte) 128, (byte) 161, 9, 6, 7, 4, 0, 0, 1, 0, 25, 2, (byte) 162, 3, 2,
1, 1, (byte) 163, 5, (byte) 161, 3, 2, 1, 2 };
}
private byte[] getData3() {
return new byte[] { 97, 27, (byte) 128, 2, 7, (byte) 128, (byte) 161, 9, 6, 7, 4, 0, 0, 1, 0, 25, 2, (byte) 162, 3, 2,
1, 1, (byte) 163, 5, (byte) 162, 3, 2, 1, 2 };
}
@Test(groups = { "functional.encode", "functional.decode" })
public void testResponseAPDU() throws Exception {
byte[] b = getData();
AsnInputStream asnIs = new AsnInputStream(b);
int tag = asnIs.readTag();
assertEquals(1, tag);
DialogResponseAPDU d = TcapFactory.createDialogAPDUResponse();
d.decode(asnIs);
assertTrue(Arrays.equals(new long[] { 0, 4, 0, 0, 1, 0, 21, 2 }, d.getApplicationContextName().getOid()));
Result r = d.getResult();
assertEquals(ResultType.Accepted, r.getResultType());
ResultSourceDiagnostic diag = d.getResultSourceDiagnostic();
assertNotNull(diag.getDialogServiceUserType());
assertEquals(DialogServiceUserType.Null, diag.getDialogServiceUserType());
UserInformation ui = d.getUserInformation();
assertNotNull(ui);
assertNotNull(ui.getEncodeType());
ui.getEncodeType();
assertTrue(Arrays.equals(new byte[] { -95, 0 }, ui.getEncodeType()));
AsnOutputStream aos = new AsnOutputStream();
d.encode(aos);
assertTrue(Arrays.equals(b, aos.toByteArray()));
b = getData2();
asnIs = new AsnInputStream(b);
tag = asnIs.readTag();
assertEquals(1, tag);
d = TcapFactory.createDialogAPDUResponse();
d.decode(asnIs);
assertTrue(Arrays.equals(new long[] { 0, 4, 0, 0, 1, 0, 25, 2 }, d.getApplicationContextName().getOid()));
r = d.getResult();
assertEquals(ResultType.RejectedPermanent, r.getResultType());
diag = d.getResultSourceDiagnostic();
assertNotNull(diag.getDialogServiceUserType());
assertEquals(DialogServiceUserType.AcnNotSupported, diag.getDialogServiceUserType());
ui = d.getUserInformation();
assertNull(ui);
aos = new AsnOutputStream();
d.encode(aos);
assertTrue(Arrays.equals(b, aos.toByteArray()));
b = getData3();
asnIs = new AsnInputStream(b);
tag = asnIs.readTag();
assertEquals(1, tag);
d = TcapFactory.createDialogAPDUResponse();
d.decode(asnIs);
assertTrue(Arrays.equals(new long[] { 0, 4, 0, 0, 1, 0, 25, 2 }, d.getApplicationContextName().getOid()));
r = d.getResult();
assertEquals(ResultType.RejectedPermanent, r.getResultType());
diag = d.getResultSourceDiagnostic();
assertNotNull(diag.getDialogServiceProviderType());
assertEquals(DialogServiceProviderType.NoCommonDialogPortion, diag.getDialogServiceProviderType());
ui = d.getUserInformation();
assertNull(ui);
aos = new AsnOutputStream();
d.encode(aos);
assertTrue(Arrays.equals(b, aos.toByteArray()));
}
}
| agpl-3.0 |
automenta/java_dann | src/syncleus/dann/learn/probability/proposition/NotProposition.java | 1002 | package syncleus.dann.learn.probability.proposition;
import java.util.Map;
import syncleus.dann.learn.probability.RandomVariable;
public class NotProposition extends AbstractProposition implements
UnarySentenceProposition {
private Proposition proposition;
//
private String toString = null;
public NotProposition(Proposition prop) {
if (null == prop) {
throw new IllegalArgumentException(
"Proposition to be negated must be specified.");
}
// Track nested scope
addScope(prop.getScope());
addUnboundScope(prop.getUnboundScope());
proposition = prop;
}
@Override
public boolean holds(Map<RandomVariable, Object> possibleWorld) {
return !proposition.holds(possibleWorld);
}
@Override
public String toString() {
if (null == toString) {
StringBuilder sb = new StringBuilder();
sb.append("(NOT ");
sb.append(proposition.toString());
sb.append(")");
toString = sb.toString();
}
return toString;
}
}
| agpl-3.0 |
0x7678/openss7 | src/java/javax/media/mscontrol/JoinEvent.java | 3833 | /*
@(#) $RCSfile: JoinEvent.java,v $ $Name: $($Revision: 1.1.2.1 $) $Date: 2009-06-21 11:35:20 $ <p>
Copyright © 2008-2009 Monavacon Limited <a href="http://www.monavacon.com/"><http://www.monavacon.com/></a>. <br>
Copyright © 2001-2008 OpenSS7 Corporation <a href="http://www.openss7.com/"><http://www.openss7.com/></a>. <br>
Copyright © 1997-2001 Brian F. G. Bidulock <a href="mailto:bidulock@openss7.org"><bidulock@openss7.org></a>. <p>
All Rights Reserved. <p>
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License as published by the Free
Software Foundation, version 3 of the license. <p>
This program is distributed in the hope that it will be useful, but <b>WITHOUT
ANY WARRANTY</b>; without even the implied warranty of <b>MERCHANTABILITY</b>
or <b>FITNESS FOR A PARTICULAR PURPOSE</b>. See the GNU Affero General Public
License for more details. <p>
You should have received a copy of the GNU Affero General Public License along
with this program. If not, see
<a href="http://www.gnu.org/licenses/"><http://www.gnu.org/licenses/></a>,
or write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA
02139, USA. <p>
<em>U.S. GOVERNMENT RESTRICTED RIGHTS</em>. If you are licensing this
Software on behalf of the U.S. Government ("Government"), the following
provisions apply to you. If the Software is supplied by the Department of
Defense ("DoD"), it is classified as "Commercial Computer Software" under
paragraph 252.227-7014 of the DoD Supplement to the Federal Acquisition
Regulations ("DFARS") (or any successor regulations) and the Government is
acquiring only the license rights granted herein (the license rights
customarily provided to non-Government users). If the Software is supplied to
any unit or agency of the Government other than DoD, it is classified as
"Restricted Computer Software" and the Government's rights in the Software are
defined in paragraph 52.227-19 of the Federal Acquisition Regulations ("FAR")
(or any successor regulations) or, in the cases of NASA, in paragraph
18.52.227-86 of the NASA Supplement to the FAR (or any successor regulations). <p>
Commercial licensing and support of this software is available from OpenSS7
Corporation at a fee. See
<a href="http://www.openss7.com/">http://www.openss7.com/</a> <p>
Last Modified $Date: 2009-06-21 11:35:20 $ by $Author: brian $
*/
package javax.media.mscontrol;
/** This event is delivered to the application upon completion of a join
* operation, that was started with
* Joinable.joinInitiate(javax.media.mscontrol.Joinable.Direction,
* Joinable, java.io.Serializable).
* @version 1.2.2
* @author Monavacon Limited
*/
public interface JoinEvent extends StatusEvent {
/** This Symbol is returned by getEventID() to signal the completion
* of a join operation. */
static final Symbol ev_Joined;
/** This Symbol is returned by getEventID() to signal the completion
* of an unjoin operation. */
static final Symbol ev_Unjoined;
/** Return a reference on the "other" Joinable, that was the second
* argument of
* Joinable.joinInitiate(javax.media.mscontrol.Joinable.Direction,
* Joinable, java.io.Serializable). */
Joinable getOtherJoinable();
/** Return a reference to the object on which joinInitiate was
* called. */
Joinable getThisJoinable();
/** Return a reference on the third argument of
* Joinable.joinInitiate(javax.media.mscontrol.Joinable.Direction,
* Joinable, java.io.Serializable). */
java.io.Serializable getContext();
}
// vim: sw=4 et tw=72 com=srO\:/**,mb\:*,ex\:*/,srO\:/*,mb\:*,ex\:*/,b\:TRANS,\://,b\:#,\:%,\:XCOMM,n\:>,fb\:-
| agpl-3.0 |
Xapagy/Xapagy | src/main/java/org/xapagy/ui/queryhandlers/qh_CONCEPT.java | 6674 | /*
This file is part of the Xapagy Cognitive Architecture
Copyright (C) 2008-2017 Ladislau Boloni
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.xapagy.ui.queryhandlers;
import java.util.AbstractMap.SimpleEntry;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.xapagy.agents.Agent;
import org.xapagy.concepts.AbstractConceptDB;
import org.xapagy.concepts.Concept;
import org.xapagy.concepts.ConceptOverlay;
import org.xapagy.concepts.Hardwired;
import org.xapagy.httpserver.RESTQuery;
import org.xapagy.httpserver.Session;
import org.xapagy.instances.Instance;
import org.xapagy.ui.formatters.PwFormatter;
import org.xapagy.ui.prettyhtml.IQueryAttributes;
import org.xapagy.ui.prettyhtml.IQueryHandler;
import org.xapagy.ui.prettyhtml.PwQueryLinks;
import org.xapagy.util.SimpleEntryComparator;
public class qh_CONCEPT implements IQueryHandler, IQueryAttributes {
@Override
public void generate(PwFormatter fmt, Agent agent, RESTQuery query, Session session) {
String identifier = query.getAttribute(Q_ID);
Concept concept = null;
for (Concept concept2 : agent.getConceptDB().getAllConcepts()) {
if (concept2.getIdentifier().equals(identifier)) {
concept = concept2;
break;
}
}
int countHideable = 1;
if (concept == null) {
fmt.addPre("could not find the concept with the identifier "
+ identifier);
return;
}
AbstractConceptDB<Concept> cdb = agent.getConceptDB();
//
// Identifier block
//
String redheader =
"Concept " + concept.getName() + " (" + concept.getIdentifier()
+ ")";
// check if it is a negation
if (concept.getName().startsWith(Hardwired.CONCEPT_PREFIX_NEGATION)) {
redheader += " negation";
}
//
fmt.addH2(redheader, "class=identifier");
fmt.addLabelParagraph("Documentation");
fmt.explanatoryNote(concept.getDocumentation());
fmt.is("area", cdb.getArea(concept));
//
// Adding the overlaps, decreasing order
//
Map<Concept, Double> overlaps = cdb.getOverlaps(concept);
if (overlaps.isEmpty()) {
fmt.addH3("Overlaps: None.");
} else {
fmt.addH3("Overlaps:");
// sort them in decreasing order
List<SimpleEntry<Concept, Double>> listOverlap = new ArrayList<>();
for (Concept c : overlaps.keySet()) {
listOverlap.add(new SimpleEntry<>(c, overlaps.get(c)));
}
Collections.sort(listOverlap, new SimpleEntryComparator<Concept>());
Collections.reverse(listOverlap);
for (SimpleEntry<Concept, Double> entry : listOverlap) {
//fmt.openP();
Concept conceptOverlap = entry.getKey();
double valueOverlap = entry.getValue();
PwFormatter fmt2 = new PwFormatter();
fmt2.progressBar(valueOverlap, 1.0);
PwQueryLinks.linkToConcept(fmt2, agent, query, conceptOverlap);
fmt.is(fmt2.toString() + " overlaps", valueOverlap);
//fmt.closeP();
}
}
//
// Adding the implications, decreasing order
//
Map<Concept, Double> impacts = cdb.getImpacts(concept);
if (impacts == null) {
fmt.addH3("Implications: None.");
} else {
fmt.addH3("Implications: ");
// sort them in decreasing order
List<SimpleEntry<Concept, Double>> listImpacts = new ArrayList<>();
for (Concept c : impacts.keySet()) {
listImpacts.add(new SimpleEntry<>(c, impacts.get(c)));
}
Collections.sort(listImpacts, new SimpleEntryComparator<Concept>());
Collections.reverse(listImpacts);
for (SimpleEntry<Concept, Double> entry : listImpacts) {
//fmt.openP();
Concept conceptImpact = entry.getKey();
double valueImpact = entry.getValue();
PwFormatter fmt2 = new PwFormatter();
fmt2.progressBar(valueImpact, 1.0);
PwQueryLinks.linkToConcept(fmt2, agent, query, conceptImpact);
fmt.is(fmt2.toString(), valueImpact);
//fmt.progressBar(valueImpact, 1.0);
//PwQueryLinks.linkToConcept(fmt, agent, query, conceptImpact);
//fmt.add(" impact = " + Formatter.fmt(valueImpact));
//fmt.closeP();
}
}
//
// Adding the list of instances which have the concept
//
PwFormatter fmt2 = new PwFormatter("");
qh_CONCEPT.pwReferringInstances(fmt2, concept, agent, query);
fmt.addExtensibleH2("id" + countHideable++, "Referring instances",
fmt2.toString(), true);
}
/**
* Generates links to instances which overlap with this concept
*
* @return
*/
public static String pwReferringInstances(PwFormatter fmt, Concept concept,
Agent agent, RESTQuery query) {
fmt.explanatoryNote("The instances which have an attribute which overlaps with this concept.");
ConceptOverlay co = new ConceptOverlay(agent);
co.addFullEnergy(concept);
Set<Instance> instances =
agent.getAutobiographicalMemory()
.getInstancesOverlappingWithCo(co);
for (Instance instance : instances) {
fmt.openP();
PwQueryLinks.linkToInstance(fmt, agent, query, instance);
fmt.closeP();
}
return fmt.toString();
}
}
| agpl-3.0 |
JennifferBautista/JAVA-PROGRAMAS | Devolver_Mes/src/Mes/main.java | 232 | package Mes;
import javax.swing.JOptionPane;
public class main {
public static void main(String[] args) {
// TODO Auto-generated method stub
int resp=0;
vec_mes vec = new vec_mes(0);
vec.devolver_Nombre(resp);
}
}
| agpl-3.0 |
uckelman/tite-ocs | src/com/btinternet/george973/TiteBuild.java | 5541 | /*
*
* Copyright (c) 2008 by George Hayward
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License (LGPL) as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, copies are available
* at http://www.opensource.org.
*/
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.btinternet.george973;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Shape;
import java.awt.event.InputEvent;
import java.util.Iterator;
import javax.swing.KeyStroke;
import javax.swing.JMenu;
import java.util.HashMap;
import java.util.Map;
import VASSAL.counters.BasicPiece;
import VASSAL.counters.Decorator;
import VASSAL.counters.EditablePiece;
import VASSAL.counters.KeyCommand;
import VASSAL.counters.GamePiece;
import VASSAL.counters.Properties;
import VASSAL.counters.Restricted;
import VASSAL.counters.Stack;
import VASSAL.counters.PieceEditor;
import VASSAL.build.module.documentation.HelpFile;
import VASSAL.tools.SequenceEncoder;
import VASSAL.command.Command;
import VASSAL.build.GameModule;
import javax.swing.JPanel;
import javax.swing.BoxLayout;
import VASSAL.configure.BooleanConfigurer;
import VASSAL.configure.IntConfigurer;
import VASSAL.configure.StringConfigurer;
import VASSAL.configure.StringArrayConfigurer;
/**
*
* @author george
*/
public class TiteBuild extends TiteTrait implements EditablePiece {
public static final String ID = "titeA;";
private int ersatzState;
private static GamePiece[] ersatzViews;
private static KeyStroke myStroke
= KeyStroke.getKeyStroke('B', InputEvent.CTRL_DOWN_MASK);
public TiteBuild() {
this (ID, null );
}
public TiteBuild( String type, GamePiece p ) {
if ( ersatzViews == null ) {
ersatzViews = new GamePiece[]{
GameModule.getGameModule().createPiece(BasicPiece.ID + ";;con1.png;;"),
GameModule.getGameModule().createPiece(BasicPiece.ID + ";;con2.png;;"),
GameModule.getGameModule().createPiece(BasicPiece.ID + ";;con3.png;;"),
GameModule.getGameModule().createPiece(BasicPiece.ID + ";;con4.png;;"),
GameModule.getGameModule().createPiece(BasicPiece.ID + ";;con5.png;;"),
GameModule.getGameModule().createPiece(BasicPiece.ID + ";;con6.png;;")
};
}
setInner(p);
mySetType(type);
}
public String getDescription() {
return "TITE Contruct IP";
}
public HelpFile getHelpFile() {
return HelpFile.getReferenceManualPage("TiteTrait.htm");
}
public void mySetType(String type) {
}
public String myGetType() {
return ID;
}
public void mySetState( String type) {
SequenceEncoder.Decoder st = new SequenceEncoder.Decoder (type, ';' );
ersatzState = st.nextInt(0);
}
public String myGetState() {
SequenceEncoder se = new SequenceEncoder(';');
se.append(ersatzState);
return se.getValue();
}
public Command myKeyEvent(KeyStroke stroke) {
if ( stroke == myStroke) {
Command c = Tite.getTite().getStrokeCommand( myStroke, getId(), null);
ersatzState++;
if ( ersatzState > 6 ) {
ersatzState = 0;
setDoing( false );
} else {
setDoing( true );
}
setMoved( true );
return c;
}
return null;
}
public KeyCommand[] myGetKeyCommands() {
if ( !isDoing() || ersatzState != 0 )
return new KeyCommand[] { new KeyCommand ( "Spend MP Constructing IP", myStroke, this )
};
return new KeyCommand[0];
}
public String getName() {
return piece.getName();
}
public Shape getShape() {
return piece.getShape();
}
public Rectangle boundingBox() {
return piece.boundingBox();
}
public void draw(Graphics g, int x, int y, Component obs, double zoom) {
piece.draw(g, x, y, obs, zoom);
}
public String getMyTiteStatus() {
if ( ersatzState == 0 ) return null;
return ersatzState + " MPs ersatz";
}
public String getMyTiteRestrictedStatus() {
return null;
}
public int getMyNumberOfMarkers() {
return ersatzState == 0 ? 0 : 1;
}
public int getMyRestrictedNumberOfMarkers() {
return 0;
}
public int myDrawMarkers(Graphics g, int x, int y, Component obs, double zoom, int width) {
if ( ersatzState == 0 ) return x;
ersatzViews[ersatzState - 1].draw(g, x, y, obs, zoom);
return x + width;
}
public int myRestrictedDrawMarkers(Graphics g, int x, int y, Component obs, double zoom, int width) {
return x;
}
public PieceEditor getEditor() {
return new Ed(this);
}
public static class Ed implements PieceEditor {
private JPanel panel;
public Ed(TiteBuild p) {
panel = new JPanel();
panel.setLayout( new BoxLayout(panel, BoxLayout.Y_AXIS));
}
public Component getControls() {
return panel;
}
public String getType() {
return ID;
}
public String getState() {
return "";
}
}
}
| lgpl-2.1 |
OPENDAP/olfs | retired/src/opendap/webstart/WebStartServlet.java | 18678 | /*
* /////////////////////////////////////////////////////////////////////////////
* // This file is part of the "Hyrax Data Server" project.
* //
* //
* // Copyright (c) 2013 OPeNDAP, Inc.
* // Author: Nathan David Potter <ndp@opendap.org>
* //
* // This library is free software; you can redistribute it and/or
* // modify it under the terms of the GNU Lesser General Public
* // License as published by the Free Software Foundation; either
* // version 2.1 of the License, or (at your option) any later version.
* //
* // This library is distributed in the hope that it will be useful,
* // but WITHOUT ANY WARRANTY; without even the implied warranty of
* // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* // Lesser General Public License for more details.
* //
* // You should have received a copy of the GNU Lesser General Public
* // License along with this library; if not, write to the Free Software
* // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
* //
* // You can contact OPeNDAP, Inc. at PO Box 112, Saunderstown, RI. 02874-0112.
* /////////////////////////////////////////////////////////////////////////////
*/
package opendap.webstart;
import net.sf.saxon.s9api.SaxonApiException;
import net.sf.saxon.s9api.XdmNode;
import opendap.bes.BESError;
import opendap.bes.BadConfigurationException;
import opendap.bes.dap2Responders.BesApi;
import opendap.coreServlet.*;
import opendap.dap.Request;
import opendap.http.error.BadRequest;
import opendap.http.error.NotFound;
import opendap.http.error.NotImplemented;
import opendap.http.mediaTypes.TextHtml;
import opendap.io.HyraxStringEncoding;
import opendap.logging.LogUtil;
import opendap.ppt.PPTException;
import opendap.xml.Transformer;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.transform.JDOMSource;
import org.slf4j.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.transform.stream.StreamSource;
import java.io.*;
import java.net.URL;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Vector;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Created by IntelliJ IDEA.
* User: ndp
* Date: Jul 23, 2010
* Time: 1:41:09 PM
* To change this template use File | Settings | File Templates.
*/
public class WebStartServlet extends HttpServlet {
private Logger _log;
private boolean disabled = false;
private String resourcesDirectory;
private Document configDoc;
private BesApi _besApi;
private ConcurrentHashMap<String, JwsHandler> jwsHandlers = null;
//private Document configDoc;
private AtomicInteger reqNumber;
public void init() throws ServletException {
super.init();
_log = org.slf4j.LoggerFactory.getLogger(getClass());
reqNumber = new AtomicInteger(0);
String dir = ServletUtil.getConfigPath(this) + "WebStart";
File f = new File(dir);
_log.info("Checking for resources Directory: " + dir);
if (f.exists() && f.isDirectory()) {
resourcesDirectory = dir;
_log.info("Found resources Directory: " + dir);
} else {
_log.warn("Could not locate resources Directory: " + dir);
dir = this.getServletContext().getRealPath("WebStart");
f = new File(dir);
_log.info("Checking for resources Directory: " + dir);
if (f.exists() && f.isDirectory()) {
resourcesDirectory = dir;
_log.info("Found resources Directory: " + dir);
} else {
disabled = true;
_log.error("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
_log.error("Could not locate resources Directory: " + dir);
_log.error("Java WebStart Disabled!");
_log.error("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
}
}
if (!disabled) {
_log.info("resourcesDirectory: " + resourcesDirectory);
configDoc = loadConfig();
// Build Handler Objects
jwsHandlers = buildJwsHandlers(resourcesDirectory, configDoc.getRootElement());
_besApi = new BesApi();
}
}
/**
* Loads the configuration file specified in the servlet parameter
* OLFSConfigFileName.
*
* @throws ServletException When the file is missing, unreadable, or fails
* to parse (as an XML document).
*/
private Document loadConfig() throws ServletException {
Document doc;
String filename = getInitParameter("WebStartConfigFileName");
if (filename == null) {
String msg = "Servlet configuration must include a file name for " +
"the WebStart configuration!\n";
System.err.println(msg);
throw new ServletException(msg);
}
filename = Scrub.fileName(ServletUtil.getConfigPath(this) + filename);
_log.debug("Loading Configuration File: " + filename);
try {
File confFile = new File(filename);
FileInputStream fis = new FileInputStream(confFile);
try {
// Parse the XML doc into a Document object.
SAXBuilder sb = new SAXBuilder();
doc = sb.build(fis);
}
finally {
fis.close();
}
} catch (FileNotFoundException e) {
String msg = "WebStart configuration file \"" + filename + "\" cannot be found.";
_log.error(msg);
throw new ServletException(msg, e);
} catch (IOException e) {
String msg = "WebStart configuration file \"" + filename + "\" is not readable.";
_log.error(msg);
throw new ServletException(msg, e);
} catch (JDOMException e) {
String msg = "WebStart configuration file \"" + filename + "\" cannot be parsed.";
_log.error(msg);
throw new ServletException(msg, e);
}
_log.debug("WebStart Configuration loaded and parsed.");
return doc;
}
/**
* Navigates the config document to instantiate an ordered list of
* JwsHandler Handlers. Then all of the handlers are initialized by
* calling their init() methods and passing into them the XML Element
* that defined them from the config document.
*
* @return A VEector of JwsHandlers that have been intialized and are ready to use.
* @throws ServletException When things go poorly
*/
private ConcurrentHashMap<String, JwsHandler> buildJwsHandlers(String resourcesDir, Element webStartConfig) throws ServletException {
String msg;
ConcurrentHashMap<String, JwsHandler> jwsHandlers = new ConcurrentHashMap<String, JwsHandler>();
_log.debug("Building JwsHandlers");
for (Object o : webStartConfig.getChildren("JwsHandler")) {
Element handlerElement = (Element) o;
String className = handlerElement.getAttributeValue("className");
if(className!=null) {
JwsHandler dh;
try {
_log.debug("Building Handler: " + className);
Class classDefinition = Class.forName(className);
dh = (JwsHandler) classDefinition.newInstance();
} catch (ClassNotFoundException e) {
msg = "Cannot find class: " + className;
_log.error(msg);
throw new ServletException(msg, e);
} catch (InstantiationException e) {
msg = "Cannot instantiate class: " + className;
_log.error(msg);
throw new ServletException(msg, e);
} catch (IllegalAccessException e) {
msg = "Cannot access class: " + className;
_log.error(msg);
throw new ServletException(msg, e);
} catch (ClassCastException e) {
msg = "Cannot cast class: " + className + " to opendap.coreServlet.IsoDispatchHandler";
_log.error(msg);
throw new ServletException(msg, e);
}
_log.debug("Initializing Handler: " + className);
dh.init(handlerElement, resourcesDir);
jwsHandlers.put(dh.getServiceId(), dh);
}
else {
_log.error("buildJwsHandlers() - FAILED to locate the required 'className' attribute in JwsHandler element. SKIPPING.");
}
}
_log.debug("JwsHandlers have been built.");
return jwsHandlers;
}
public long getLastModified(HttpServletRequest req) {
long lmt;
if (disabled)
return -1;
String name = Scrub.fileName(getName(req));
File f = new File(name);
if (f.exists())
lmt = f.lastModified();
else
lmt = -1;
//log.debug("getLastModified() - Tomcat requested lastModified for: " + name + " Returning: " + new Date(lmt));
return lmt;
}
private String getName(HttpServletRequest req) {
String name = req.getPathInfo();
if (name == null)
name = "/";
name = resourcesDirectory + name;
return name;
}
private HashMap<String, String> parseQuery(String query){
HashMap<String, String> params = new HashMap<String, String>();
if(query==null){
_log.error("Incorrect parameters sent to '{}' query:{}", getClass().getName(), Scrub.simpleQueryString(query));
return params;
}
String args[] = query.split("&");
if (args == null) {
_log.error("Incorrect parameters sent to '{}' query:{}", getClass().getName(), Scrub.simpleQueryString(query));
return params;
}
String[] pairs;
for (String arg : args) {
pairs = arg.split("=");
if (pairs != null) {
if (pairs.length == 2) {
params.put(pairs[0], pairs[1]);
} else {
_log.error("Parse failed for argument: " + Scrub.simpleQueryString(arg));
}
}
}
return params;
}
public void doGet(HttpServletRequest req, HttpServletResponse resp) {
RequestCache.openThreadCache();
LogUtil.logServerAccessStart(req, "WebStartServletAccess", "HTTP-GET", Integer.toString(reqNumber.incrementAndGet()));
_log.debug(ServletUtil.showRequest(req, reqNumber.get()));
//log.debug(opendap.coreServlet.AwsUtil.probeRequest(this, req));
Request dapRequest = new Request(this,req);
String query = req.getQueryString();
HashMap<String, String> params;
int request_status = HttpServletResponse.SC_OK;
try {
if (disabled) {
String msg = "Java WebStart is currently DISABLED!";
_log.error("doGet() - {}", msg);
throw new NotImplemented(msg);
}
params = parseQuery(query);
String dapService = Scrub.fileName(params.get("dapService"));
String besDatasetId = Scrub.fileName(params.get("datasetID"));
if(dapService==null || besDatasetId==null){
String msg = "Incorrect parameters sent to '" + getClass().getName() + "' query: '"+ Scrub.simpleQueryString(query) +"'";
_log.error("doGet() - {}", msg);
throw new BadRequest(msg);
}
URL serviceURL = new URL(new Request(null,req).getServiceUrl());
String protocol = serviceURL.getProtocol();
String host = serviceURL.getHost();
int port = serviceURL.getPort();
String serverURL = protocol+"://" + host + ":" + (port==-1 ? "" : port);
Document ddx = getDDX(serverURL, dapService, besDatasetId);
if(ddx == null){
String msg = "Failed to locate dataset: " + besDatasetId;
_log.error("doGet() - {} ",msg);
throw new NotFound(msg);
}
String applicationID = req.getPathInfo();
// Condition applicationID.
if (applicationID != null)
{
while (applicationID.startsWith("/")) { // Strip leading slashes
applicationID = applicationID.substring(1, applicationID.length());
}
if (applicationID.equals(""))
applicationID = null;
}
if(applicationID == null){
String msg = "The WebStart service request is missing the required applicationID.";
_log.error("doGet() - {}",msg);
throw new BadRequest(msg);
}
if (applicationID.equals("viewers")) {
resp.setContentType("text/html");
sendDatasetPage(dapRequest.getWebStartServiceLocalID(),dapRequest.getDocsServiceLocalID(), dapService, besDatasetId, ddx, resp.getOutputStream());
} else {
String dataAccessURL = serverURL+dapService+besDatasetId;
// Attempt to locate the application...
JwsHandler jwsHandler = jwsHandlers.get(applicationID);
if (jwsHandler != null) {
// get the jnlp content
String jnlpContent = jwsHandler.getJnlpForDataset(dataAccessURL);
//set the mime type for the return document
String mType = MimeTypes.getMimeType("jnlp");
if (mType != null)
resp.setContentType(mType);
// Get the sink
PrintWriter pw = resp.getWriter();
// Send the jnlp to the client.
pw.print(jnlpContent);
} else {
String msg = "Unable to locate a Java WebStart handler to respond to: "+Scrub.simpleString(applicationID)+"?"+Scrub.simpleQueryString(query);
_log.error("doGet() - {}", msg);
throw new NotFound(msg);
}
}
}
catch (Throwable t){
try {
request_status = OPeNDAPException.anyExceptionHandler(t, this, resp);
}
catch (Throwable t2) {
try {
_log.error("\n########################################################\n" +
"Request proccessing failed.\n" +
"Normal Exception handling failed.\n" +
"This is the last error log attempt for this request.\n" +
"########################################################\n", t2);
}
catch (Throwable t3) {
// It's boned now.. Leave it be.
}
}
}
finally {
LogUtil.logServerAccessEnd(request_status, "WebStartServletAccess");
RequestCache.closeThreadCache();
}
}
private void sendDatasetPage(String webStartService, String docsService, String dapService, String datasetID, Document ddx, OutputStream os) throws IOException, PPTException, BadConfigurationException, SaxonApiException, JDOMException
{
String xsltDoc = ServletUtil.getSystemPath(this, "/xsl/webStartDataset.xsl");
Transformer transformer = new Transformer(xsltDoc);
transformer.setParameter("datasetID",datasetID);
transformer.setParameter("dapService",dapService);
transformer.setParameter("docsService",docsService);
transformer.setParameter("webStartService", webStartService);
String handlers = getHandlersParam(ddx);
_log.debug("Handlers: " + handlers);
if(handlers!=null){
ByteArrayInputStream reader = new ByteArrayInputStream(handlers.getBytes(HyraxStringEncoding.getCharset()));
XdmNode valueNode = transformer.build(new StreamSource(reader));
transformer.setParameter("webStartApplications",valueNode);
}
JDOMSource ddxSource = new JDOMSource(ddx);
transformer.transform(ddxSource, os);
}
private Vector<JwsHandler> getApplicationsforDataset(Document ddx){
Enumeration<JwsHandler> e = jwsHandlers.elements();
JwsHandler jwsHandler;
Vector<JwsHandler> canHandleDataset = new Vector<JwsHandler>();
while(e.hasMoreElements()){
jwsHandler = e.nextElement();
if(jwsHandler.datasetCanBeViewed(ddx)){
canHandleDataset.add(jwsHandler);
}
}
return canHandleDataset;
}
private String getHandlersParam(Document ddx) {
String nodeString = null;
Vector<JwsHandler> jwsHandlers = getApplicationsforDataset(ddx);
for(JwsHandler jwsh : jwsHandlers){
if(nodeString==null)
nodeString = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><WebStartApplications>";
nodeString += "<wsApp id=\"" +jwsh.getServiceId()+"\" applicationName=\""+jwsh.getName()+"\" />";
}
if(nodeString!=null){
nodeString += "</WebStartApplications>";
}
return nodeString;
}
public Document getDDX(String serverURL, String dapService, String datasetID) throws IOException, PPTException, BadConfigurationException, BESError, SaxonApiException, JDOMException {
String constraintExpression = "";
String xdap_accept = "3.2";
String xmlBase = serverURL+dapService+datasetID;
Document ddx = new Document();
// Stash the Media type in case there's an error. That way the error handler will know how to encode the error.
RequestCache.put(OPeNDAPException.ERROR_RESPONSE_MEDIA_TYPE_KEY, new TextHtml());
_besApi.getDDXDocument(
datasetID,
constraintExpression,
xdap_accept,
xmlBase,
ddx);
return ddx;
}
}
| lgpl-2.1 |
phoenixctms/ctsms | core/src/main/java/org/phoenixctms/ctsms/excel/InventoryBookingsExcelSettingCodes.java | 1437 | package org.phoenixctms.ctsms.excel;
public interface InventoryBookingsExcelSettingCodes {
public static final String TEMPLATE_FILE_NAME = "template_file_name";
public static final String AUTOSIZE = "autosize";
public static final String WRITEHEAD = "writehead";
public static final String PAGE_BREAK_AT_ROW = "page_break_at_row";
public static final String SCALE_FACTOR = "scale_factor";
public static final String ROW_FORMAT = "row_format";
public static final String HEAD_FORMAT = "head_format";
public static final String ROW_COLORS = "row_colors";
public static final String VO_GRAPH_RECURSION_DEPTH = "vo_graph_recursion_depth";
public static final String SPREADSHEET_NAME = "spreadsheet_name";
public static final String SHOW_TAGS = "show_tags";
public static final String SHOW_ADDRESSES = "show_addresses";
public static final String SHOW_CONTACT_DETAILS = "show_contact_details";
public static final String SHOW_CV_ADDRESS_BLOCK = "show_cv_address_block";
public static final String AGGREGATE_ADDRESSES = "aggregate_addresses";
public static final String AGGREGATE_CONTACT_DETAILS = "aggregate_contact_details";
public static final String GRAPH_MAX_STAFF_INSTANCES = "graph_max_staff_instances";
public static final String APPEND_HEADER_FOOTER = "append_header_footer";
public static final String PAINTER_CLASS = "painter_class";
public static final String PAINTER_SOURCE_FILES = "painter_source_files";
}
| lgpl-2.1 |
spotbugs/spotbugs | spotbugs/src/main/java/edu/umd/cs/findbugs/CategoryFilteringBugReporter.java | 1840 | /*
* FindBugs - Find Bugs in Java programs
* Copyright (C) 2003-2006, University of Maryland
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package edu.umd.cs.findbugs;
import java.util.Set;
import javax.annotation.Nonnull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Filter reported warnings by category.
*/
public class CategoryFilteringBugReporter extends DelegatingBugReporter {
private static final Logger LOG = LoggerFactory.getLogger(CategoryFilteringBugReporter.class);
private final Set<String> categorySet;
public CategoryFilteringBugReporter(BugReporter realBugReporter, Set<String> categorySet) {
super(realBugReporter);
this.categorySet = categorySet;
}
@Override
public void reportBug(@Nonnull BugInstance bugInstance) {
BugPattern bugPattern = bugInstance.getBugPattern();
String category = bugPattern.getCategory();
if (categorySet.contains(category)) {
getDelegate().reportBug(bugInstance);
} else {
LOG.debug("CategoryFilteringBugReporter: filtered due to category {}", category);
}
}
}
| lgpl-2.1 |
JiriOndrusek/wildfly-core | server/src/main/java/org/jboss/as/server/operations/ServerShutdownHandler.java | 9813 | /*
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.server.operations;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SHUTDOWN;
import java.util.EnumSet;
import org.jboss.as.controller.ControlledProcessState;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.controller.OperationStepHandler;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.SimpleAttributeDefinition;
import org.jboss.as.controller.SimpleAttributeDefinitionBuilder;
import org.jboss.as.controller.SimpleOperationDefinition;
import org.jboss.as.controller.SimpleOperationDefinitionBuilder;
import org.jboss.as.controller.access.Action;
import org.jboss.as.controller.access.AuthorizationResult;
import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
import org.jboss.as.controller.logging.ControllerLogger;
import org.jboss.as.process.ExitCodes;
import org.jboss.as.server.SystemExiter;
import org.jboss.as.server.controller.descriptions.ServerDescriptions;
import org.jboss.as.server.logging.ServerLogger;
import org.jboss.as.server.suspend.OperationListener;
import org.jboss.as.server.suspend.SuspendController;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.ModelType;
import org.jboss.msc.service.ServiceController;
import org.jboss.msc.service.ServiceRegistry;
import java.util.concurrent.atomic.AtomicBoolean;
import org.jboss.as.controller.client.helpers.MeasurementUnit;
/**
* Handler that shuts down the standalone server.
*
* @author Jason T. Greene
*/
public class ServerShutdownHandler implements OperationStepHandler {
protected static final SimpleAttributeDefinition RESTART = new SimpleAttributeDefinitionBuilder(ModelDescriptionConstants.RESTART, ModelType.BOOLEAN)
.setDefaultValue(new ModelNode(false))
.setRequired(false)
.build();
protected static final SimpleAttributeDefinition TIMEOUT = new SimpleAttributeDefinitionBuilder(ModelDescriptionConstants.TIMEOUT, ModelType.INT)
.setDefaultValue(new ModelNode(0))
.setRequired(false)
.setMeasurementUnit(MeasurementUnit.SECONDS)
.build();
public static final SimpleOperationDefinition DEFINITION = new SimpleOperationDefinitionBuilder(ModelDescriptionConstants.SHUTDOWN, ServerDescriptions.getResourceDescriptionResolver())
.setParameters(RESTART, TIMEOUT)
.setRuntimeOnly()
.build();
private final ControlledProcessState processState;
public ServerShutdownHandler(ControlledProcessState processState) {
this.processState = processState;
}
/**
* {@inheritDoc}
*/
@Override
public void execute(OperationContext context, ModelNode operation) throws OperationFailedException {
final boolean restart = RESTART.resolveModelAttribute(context, operation).asBoolean();
final int timeout = TIMEOUT.resolveModelAttribute(context, operation).asInt(); //in seconds, need to convert to ms
// Acquire the controller lock to prevent new write ops and wait until current ones are done
context.acquireControllerLock();
context.addStep(new OperationStepHandler() {
@Override
public void execute(OperationContext context, ModelNode operation) throws OperationFailedException {
// WFLY-2741 -- DO NOT call context.getServiceRegistry(true) as that will trigger blocking for
// service container stability and one use case for this op is to recover from a
// messed up service container from a previous op. Instead just ask for authorization.
// Note that we already have the exclusive lock, so we are just skipping waiting for stability.
// If another op that is a step in a composite step with this op needs to modify the container
// it will have to wait for container stability, so skipping this only matters for the case
// where this step is the only runtime change.
// context.getServiceRegistry(true);
AuthorizationResult authorizationResult = context.authorize(operation, EnumSet.of(Action.ActionEffect.WRITE_RUNTIME));
if (authorizationResult.getDecision() == AuthorizationResult.Decision.DENY) {
throw ControllerLogger.ACCESS_LOGGER.unauthorized(operation.get(OP).asString(),
PathAddress.pathAddress(operation.get(OP_ADDR)), authorizationResult.getExplanation());
}
context.completeStep(new OperationContext.ResultHandler() {
@Override
public void handleResult(OperationContext.ResultAction resultAction, OperationContext context, ModelNode operation) {
if(resultAction == OperationContext.ResultAction.KEEP) {
//even if the timeout is zero we still pause the server
//to stop new requests being accepted as it is shutting down
final ShutdownAction shutdown = new ShutdownAction(getOperationName(operation), restart);
final ServiceRegistry registry = context.getServiceRegistry(false);
final ServiceController<SuspendController> suspendControllerServiceController = (ServiceController<SuspendController>) registry.getRequiredService(SuspendController.SERVICE_NAME);
final SuspendController suspendController = suspendControllerServiceController.getValue();
OperationListener listener = new OperationListener() {
@Override
public void suspendStarted() {
}
@Override
public void complete() {
suspendController.removeListener(this);
shutdown.shutdown();
}
@Override
public void cancelled() {
suspendController.removeListener(this);
shutdown.cancel();
}
@Override
public void timeout() {
suspendController.removeListener(this);
shutdown.shutdown();
}
};
suspendController.addListener(listener);
suspendController.suspend(timeout > 0 ? timeout * 1000 : timeout);
if(timeout == 0) {
shutdown.shutdown();
}
}
}
});
}
}, OperationContext.Stage.RUNTIME);
}
private static String getOperationName(ModelNode op) {
return op.hasDefined(OP) ? op.get(OP).asString() : SHUTDOWN;
}
private final class ShutdownAction extends AtomicBoolean {
private final String op;
private final boolean restart;
private ShutdownAction(String op, boolean restart) {
this.op = op;
this.restart = restart;
}
void cancel() {
compareAndSet(false, true);
}
void shutdown() {
if(compareAndSet(false, true)) {
processState.setStopping();
final Thread thread = new Thread(new Runnable() {
public void run() {
int exitCode = restart ? ExitCodes.RESTART_PROCESS_FROM_STARTUP_SCRIPT : ExitCodes.NORMAL;
SystemExiter.logAndExit(new SystemExiter.ExitLogger() {
@Override
public void logExit() {
ServerLogger.ROOT_LOGGER.shuttingDownInResponseToManagementRequest(op);
}
}, exitCode);
}
});
// The intention is that this shutdown is graceful, and so the client gets a reply.
// At the time of writing we did not yet have graceful shutdown.
thread.setName("Management Triggered Shutdown");
thread.start();
}
}
}
}
| lgpl-2.1 |
paolopavan/biojava | biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/MultipleAlignmentDisplay.java | 8731 | /*
* BioJava development code
*
* This code may be freely distributed and modified under the
* terms of the GNU Lesser General Public Licence. This should
* be distributed with the code. If you do not have a copy,
* see:
*
* http://www.gnu.org/copyleft/lesser.html
*
* Copyright for this code is held jointly by the individual
* authors. These should be listed in @author doc comments.
*
* For more information on the BioJava project and its aims,
* or to join the biojava-l mailing list, visit the home page
* at:
*
* http://www.biojava.org/
*
*/
package org.biojava.nbio.structure.align.gui;
import java.awt.Dimension;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.swing.Box;
import javax.swing.JFrame;
import javax.swing.JMenuBar;
import javax.swing.JScrollPane;
import javax.vecmath.Matrix4d;
import org.biojava.nbio.structure.Atom;
import org.biojava.nbio.structure.Calc;
import org.biojava.nbio.structure.Chain;
import org.biojava.nbio.structure.Group;
import org.biojava.nbio.structure.Structure;
import org.biojava.nbio.structure.StructureException;
import org.biojava.nbio.structure.StructureImpl;
import org.biojava.nbio.structure.StructureTools;
import org.biojava.nbio.structure.align.gui.aligpanel.MultipleAligPanel;
import org.biojava.nbio.structure.align.gui.aligpanel.MultipleStatusDisplay;
import org.biojava.nbio.structure.align.gui.jmol.AbstractAlignmentJmol;
import org.biojava.nbio.structure.align.gui.jmol.JmolTools;
import org.biojava.nbio.structure.align.gui.jmol.MultipleAlignmentJmol;
import org.biojava.nbio.structure.align.multiple.Block;
import org.biojava.nbio.structure.align.multiple.MultipleAlignment;
import org.biojava.nbio.structure.align.multiple.util.MultipleSuperimposer;
import org.biojava.nbio.structure.align.multiple.util.ReferenceSuperimposer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Utility Class that provides helper methods for the visualization of
* {@link MultipleAlignment}s.
* <p>
* Currently supported: Alignment Panel Display, select aligned
* residues in Jmol by their PDB name, show a text Frame for any sequence
* alignment format, basic Jmol display from a MultipleAlignment, generate
* an artificial PDB structure with a new model for every aligned structure.
*
* @author Aleix Lafita
* @since 4.2.0
*
*/
public class MultipleAlignmentDisplay {
private static final Logger logger =
LoggerFactory.getLogger(MultipleAlignmentDisplay.class);
/**
* Utility method used in the {@link MultipleAlignmentJmol} Frame,
* when the aligned residues of a structure in the alignment have
* to be selected for formatting them (coloring and style).
*
* @param structNum the structure index (row) of the alignment
* @param multAln the MultipleAlignment that contains the equivalent
* positions
* @param ca the atom array of the structure specified
* (corresponding to the structure index)
* @return List of pdb Strings corresponding to the aligned positions
* of the structure.
*/
public static final List<String> getPDBresnum(int structNum,
MultipleAlignment multAln, Atom[] ca){
List<String> lst = new ArrayList<String>();
for(Block block : multAln.getBlocks() ) {
for (int i=0; i<block.length(); i++){
Integer pos = block.getAlignRes().get(structNum).get(i);
if (pos==null) continue; //gap
else if (pos < ca.length) {
String pdbInfo = JmolTools.getPdbInfo(ca[pos]);
lst.add(pdbInfo);
}
}
}
return lst;
}
/**
* Creates a new Frame with the MultipleAlignment Sequence Panel.
* The panel can communicate with the Jmol 3D visualization by
* selecting the aligned residues of every structure.
*
* @param multAln
* @param jmol
* @param colors
* @throws StructureException
*/
public static void showMultipleAligmentPanel(MultipleAlignment multAln,
AbstractAlignmentJmol jmol) throws StructureException {
MultipleAligPanel me = new MultipleAligPanel(multAln, jmol);
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setTitle(jmol.getTitle());
me.setPreferredSize(new Dimension(
me.getCoordManager().getPreferredWidth() ,
me.getCoordManager().getPreferredHeight()));
JMenuBar menu = MenuCreator.getAlignmentPanelMenu(
frame,me,null, multAln);
frame.setJMenuBar(menu);
JScrollPane scroll = new JScrollPane(me);
scroll.setAutoscrolls(true);
MultipleStatusDisplay status = new MultipleStatusDisplay(me);
me.addAlignmentPositionListener(status);
Box vBox = Box.createVerticalBox();
vBox.add(scroll);
vBox.add(status);
frame.getContentPane().add(vBox);
frame.pack();
frame.setVisible(true);
frame.addWindowListener(me);
frame.addWindowListener(status);
}
/**
* Creates a new Frame with the String output representation of the
* {@link MultipleAlignment}.
*
* @param multAln
* @param result String output
*/
public static void showAlignmentImage(MultipleAlignment multAln,
String result) {
JFrame frame = new JFrame();
String title = multAln.getEnsemble().getAlgorithmName() +
" V."+multAln.getEnsemble().getVersion();
frame.setTitle(title);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
AlignmentTextPanel txtPanel = new AlignmentTextPanel();
txtPanel.setText(result);
JMenuBar menu = MenuCreator.getAlignmentTextMenu(
frame,txtPanel,null,multAln);
frame.setJMenuBar(menu);
JScrollPane js = new JScrollPane();
js.getViewport().add(txtPanel);
js.getViewport().setBorder(null);
frame.getContentPane().add(js);
frame.pack();
frame.setVisible(true);
}
/**
* Display a MultipleAlignment with a JmolPanel.
* New structures are downloaded if they were
* not cached in the alignment and they are entirely
* transformed here with the superposition information
* in the Multiple Alignment.
*
* @param multAln
* @return MultipleAlignmentJmol instance
* @throws StructureException
*/
public static MultipleAlignmentJmol display(MultipleAlignment multAln)
throws StructureException {
int size = multAln.size();
List<Atom[]> atomArrays = multAln.getAtomArrays();
for (int i=0; i<size; i++){
if (atomArrays.get(i).length < 1)
throw new StructureException(
"Length of atoms arrays is too short! Size: "
+ atomArrays.get(i).length);
}
List<Atom[]> rotatedAtoms = new ArrayList<Atom[]>();
//TODO implement independent BlockSet superposition of the structure
List<Matrix4d> transf = multAln.getBlockSet(0).getTransformations();
if(transf == null) {
logger.error("Alignment Transformations are not calculated. "
+ "Superimposing to first structure as reference.");
multAln = multAln.clone();
MultipleSuperimposer imposer = new ReferenceSuperimposer();
imposer.superimpose(multAln);
transf = multAln.getBlockSet(0).getTransformations();
assert(transf != null);
}
//Rotate the atom coordinates of all the structures
for (int i=0; i<size; i++){
//TODO handle BlockSet-level transformations
//make sure this method has the same behavior as the other display.
//-SB 2015-06
//Assume all atoms are from the same structure
Structure displayS = atomArrays.get(i)[0].getGroup().
getChain().getParent().clone();
//Get all the atoms and include ligands and hetatoms
Atom[] rotCA = StructureTools.getRepresentativeAtomArray(displayS);
List<Group> hetatms = StructureTools.getUnalignedGroups(rotCA);
for (Group g:hetatms){
rotCA = Arrays.copyOf(rotCA, rotCA.length + 1);
rotCA[rotCA.length - 1] = g.getAtom(0);
}
//Transform the structure to ensure a full rotation in the display
Calc.transform(displayS, transf.get(i));
rotatedAtoms.add(rotCA);
}
MultipleAlignmentJmol jmol =
new MultipleAlignmentJmol(multAln, rotatedAtoms);
jmol.setTitle(jmol.getStructure().getPDBHeader().getTitle());
return jmol;
}
/**
* Get an artifical Structure containing a different model for every
* input structure, so that the alignment result can be viewed in Jmol.
* The Atoms have to be rotated beforehand.
*
* @param atomArrays an array of Atoms for every aligned structure
* @return a structure object containing a set of models,
* one for each input array of Atoms.
* @throws StructureException
*/
public static final Structure getAlignedStructure(List<Atom[]> atomArrays)
throws StructureException {
Structure s = new StructureImpl();
for (int i=0; i<atomArrays.size(); i++){
List<Chain> model = DisplayAFP.getAlignedModel(atomArrays.get(i));
s.addModel(model);
}
return s;
}
}
| lgpl-2.1 |
phiresky/tuxguitar | TuxGuitar-ui-toolkit-qt5/src/org/herac/tuxguitar/ui/qt/widget/QTAbstractContainer.java | 1539 | package org.herac.tuxguitar.ui.qt.widget;
import java.util.ArrayList;
import java.util.List;
import org.herac.tuxguitar.ui.widget.UIControl;
import org.qtjambi.qt.widgets.QWidget;
public abstract class QTAbstractContainer<T extends QWidget> extends QTWidget<T> implements QTContainer {
private List<QTWidget<? extends QWidget>> children;
public QTAbstractContainer(T control, QTContainer parent, boolean immediatelyShow) {
super(control, parent, immediatelyShow);
this.children = new ArrayList<QTWidget<? extends QWidget>>();
}
public QTAbstractContainer(T control, QTContainer parent) {
this(control, parent, true);
}
public List<UIControl> getChildren() {
List<QTWidget<? extends QWidget>> children = new ArrayList<QTWidget<? extends QWidget>>(this.children);
for(QTWidget<? extends QWidget> child : children) {
if( child.isDisposed()) {
this.removeChild(child);
}
}
return new ArrayList<UIControl>(this.children);
}
public void addChild(QTWidget<? extends QWidget> uiControl) {
if(!this.children.contains(uiControl)) {
this.children.add(uiControl);
}
}
public void removeChild(QTWidget<? extends QWidget> uiControl) {
if( this.children.contains(uiControl)) {
this.children.remove(uiControl);
}
}
public void dispose() {
List<QTWidget<? extends QWidget>> children = new ArrayList<QTWidget<? extends QWidget>>(this.children);
for(QTWidget<? extends QWidget> child : children) {
if(!child.isDisposed()) {
child.dispose();
}
}
super.dispose();
}
}
| lgpl-2.1 |
DanielCoutoVale/openccg | src/opennlp/ccg/parse/tagger/util/ResultSink.java | 7052 | ///////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2009 Dennis N. Mehay
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//////////////////////////////////////////////////////////////////////////////
package opennlp.ccg.parse.tagger.util;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import opennlp.ccg.lexicon.Association;
import opennlp.ccg.util.Pair;
/**
* Inspired (loosely, based on my recollection) by Jason Baldridge's similar
* class for tracking classifier performance. Here we simply track the
* <code>Word</code>-by-<code>Word</code> tagging performance of a CCG
* supertagger by passing in a multitagging and a gold-standard answer and
* tabulating the results. The results are reported by a custom
* <code>report</code> method, which returns a <code>String</code>
* representation of the results.
*
* @author Dennis N. Mehay
* @version $Revision: 1.1 $, $Date: 2010/09/21 04:12:42 $
*/
public class ResultSink {
public static enum ResultSinkType {
SUPERTAG, POSTAG
};
private int totalTags = 0, totalWords = 0, totalRight = 0;
// for keeping pos-specific stats.
private Map<String, Integer> posToRight = new HashMap<String, Integer>(),
posTot = new HashMap<String, Integer>();
// for tracking the total number of sentences, number totally tagged
// correctly, etc.
private int sentNum = 0, sentsCorrect = 0;
private boolean allCorrect = true;
// what type of tag are we tracking the results over?
private ResultSinkType whatType;
// for general pos-specific stats (e.g., N... -> <stats>, not NNP -> <stats>
// and NNPS -> <stats>, etc.)
private Map<String, Integer> genPOSToRight = new HashMap<String, Integer>(),
genPOSTot = new HashMap<String, Integer>();
/**
* Nullary constructor. Defaults to supertag result sink. (TODO: add log
* file logging for more detailed error reporting.)
*/
public ResultSink() {
this(ResultSinkType.SUPERTAG);
}
public ResultSink(ResultSinkType whatType) {
this.whatType = whatType;
}
/**
* Add and store a sentence of tagged words (
* <code>List<List<Pair<Double,String>>></code>) wrt a gold-standard tagged
* word.
*/
public void addSent(List<List<Pair<Double, String>>> sent, List<Association> goldTagging) {
sentNum++;
allCorrect = true;
Iterator<Association> gold = goldTagging.iterator();
for (List<Pair<Double, String>> tgging : sent) {
addResult(tgging, gold.next());
}
if (allCorrect) {
sentsCorrect++;
}
}
/**
* Add a single-word tagging result alongside its gold-standard tagging.
* Compare and log whether the gold-standard tag is in the beta-best (also
* log pos-specific error stats).
*/
public void addResult(List<Pair<Double, String>> tagging, Association goldTagging) {
String goldTag = (whatType == ResultSinkType.SUPERTAG) ? goldTagging.getSupertag()
: goldTagging.getFunctions();
totalTags += tagging.size();
totalWords++;
// mww: check for missing gold POS (grrr)
if (goldTagging.getFunctions() == null) {
System.err.println("Warning: found null gold POS, skipping word: " + goldTagging);
this.allCorrect = false;
return;
}
String thisPOS = goldTagging.getFunctions(), thisGenPOS = goldTagging.getFunctions()
.substring(0, 1);
Integer posT = this.posTot.get(thisPOS), gPOST = this.genPOSTot.get(thisGenPOS);
if (posT == null) {
this.posTot.put(thisPOS, new Integer(1));
} else {
this.posTot.put(thisPOS, new Integer(posT.intValue() + 1));
}
if (gPOST == null) {
this.genPOSTot.put(thisGenPOS, new Integer(1));
} else {
this.genPOSTot.put(thisGenPOS, new Integer(gPOST.intValue() + 1));
}
// assume this tagging is incorrect, until proven otherwise.
boolean gotIt = false;
for (Pair<Double, String> tag : tagging) {
if (tag.b.equals(goldTag)) {
gotIt = true;
totalRight++;
// add one both to the pos right and total for that pos type.
Integer posLkup = this.posToRight.get(thisPOS), genPOSLkup = this.genPOSToRight
.get(thisGenPOS);
if (posLkup == null) {
this.posToRight.put(thisPOS, new Integer(1));
} else {
this.posToRight.put(thisPOS, new Integer(posLkup.intValue() + 1));
}
if (genPOSLkup == null) {
this.genPOSToRight.put(thisGenPOS, new Integer(1));
} else {
this.genPOSToRight.put(thisGenPOS, new Integer(genPOSLkup.intValue() + 1));
}
break;
}
}
// mistagged this one word, so tagging the whole sentence correctly --
// allCorrect==true -- is not possible.
if (!gotIt) {
this.allCorrect = false;
}
}
public String report() {
// make sure 0 counts are inserted for POS types that were never got
// right.
for (String post : this.posTot.keySet()) {
if (this.posToRight.get(post) == null) {
this.posToRight.put(post, new Integer(0));
}
}
for (String post : this.genPOSTot.keySet()) {
if (this.genPOSToRight.get(post) == null) {
this.genPOSToRight.put(post, new Integer(0));
}
}
String rep = "";
rep += "\n\nAccuracy by POS type:\n\n";
for (String post : this.posTot.keySet()) {
rep += post
+ ": "
+ ((this.posToRight.get(post).intValue() + 0.0) / (this.posTot.get(post)))
+ " <==> "
+ this.posToRight.get(post).intValue()
+ "/"
+ (this.posTot.get(post))
+ " = "
+ (100 * ((this.posTot.get(post) - this.posToRight.get(post) + 0.0) / (totalWords - totalRight)))
+ " (% of total errors) \n";
}
rep += "\nAccuracy by general (truncated) POS type:\n\n";
for (String post : this.genPOSTot.keySet()) {
rep += post
+ ": "
+ (this.genPOSToRight.get(post).intValue() + 0.0)
/ (this.genPOSTot.get(post))
+ " <==> "
+ this.genPOSToRight.get(post).intValue()
+ "/"
+ (this.genPOSTot.get(post))
+ " = "
+ (100 * ((this.genPOSTot.get(post) - this.genPOSToRight.get(post) + 0.0) / (totalWords - totalRight)))
+ " (% of total errors) \n";
}
rep += "\nTotal words: " + totalWords + "\nTotal sents: " + this.sentNum
+ "\nAggregate total tags: " + totalTags + "\nAve. tags/word: "
+ ((totalTags + 0.0) / (totalWords + 0.0)) + "\nWord accuracy: "
+ ((totalRight + 0.0) / totalWords) + "\n" + "\nSent accuracy: "
+ ((this.sentsCorrect + 0.0) / (this.sentNum)) + "\n\n";
return rep;
}
} | lgpl-2.1 |
cchantep/acolyte | jdbc-driver/src/main/java/acolyte/jdbc/QueryResult.java | 2672 | package acolyte.jdbc;
import java.sql.SQLWarning;
/**
* Query result.
*
* @author Cedric Chantepie
*/
public interface QueryResult extends Result<QueryResult> {
/**
* Returns underlying row list.
* @return the list of rows in this result
*/
public RowList<?> getRowList();
// --- Shared ---
/**
* Nil query result
*/
public static final QueryResult Nil = new Default(RowList.Nil);
// --- Inner classes ---
/**
* Default implementation.
*/
final class Default implements QueryResult {
final RowList<?> rowList;
final SQLWarning warning;
/**
* Rows constructor.
*
* @param list the list of rows for this result
*/
protected Default(final RowList<?> list) {
this(list, null);
} // end of <init>
/**
* Bulk constructor
*
* @param list the list of rows for this result
* @param warning the SQL warning
*/
private Default(final RowList<?> list, final SQLWarning warning) {
this.rowList = list;
this.warning = warning;
} // end of <init>
// ---
/**
* {@inheritDoc}
*/
public RowList<?> getRowList() {
return this.rowList;
} // end of getRowList
/**
* {@inheritDoc}
*/
public QueryResult withWarning(final SQLWarning warning) {
return new Default(this.rowList, warning);
} // end of withWarning
/**
* {@inheritDoc}
*/
public QueryResult withWarning(final String reason) {
return withWarning(new SQLWarning(reason));
} // end of withWarning
/**
* {@inheritDoc}
*/
public SQLWarning getWarning() {
return this.warning;
} // end of getWarning
/**
* {@inheritDoc}
*/
public boolean equals(final Object o) {
if (o == null || !(o instanceof QueryResult.Default)) {
return false;
} // end of if
final QueryResult.Default other = (QueryResult.Default) o;
return ((this.rowList == null && other.rowList == null) ||
(this.rowList != null &&
this.rowList.equals(other.rowList)));
} // end of equals
/**
* {@inheritDoc}
*/
public int hashCode() {
return (this.rowList == null) ? -1 : this.rowList.hashCode();
} // end of hashCode
} // end of class Default
} // end of interface QueryResult
| lgpl-2.1 |
metteo/jts | jts-jvm/src/test/java/com/vividsolutions/jts/io/gml2/WritingTestCase.java | 2993 | /*
* The JTS Topology Suite is a collection of Java classes that
* implement the fundamental operations required to validate a given
* geo-spatial data set to a known topological specification.
*
* Copyright (C) 2001 Vivid Solutions
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* For more information, contact:
*
* Vivid Solutions
* Suite #1A
* 2328 Government Street
* Victoria BC V8T 5G5
* Canada
*
* (250)385-6040
* www.vividsolutions.com
*/
package com.vividsolutions.jts.io.gml2;
import java.io.*;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.SAXException;
import com.vividsolutions.jts.geom.*;
import junit.framework.TestCase;
/**
* Test Case framework for GML unit tests.
*
* @author David Zwiers, Vivid Solutions.
* @author Martin Davis
*/
public abstract class WritingTestCase extends TestCase
{
/**
* @param arg
*/
public WritingTestCase(String arg){
super(arg);
}
protected StringWriter sw = null;
protected Writer getWriter(){
sw = new StringWriter();
sw.write("<?xml version='1.0' encoding='UTF-8'?>\n");
return sw;
}
protected Reader getReader() throws IOException{
sw.flush();
sw.close();
String s = sw.toString();
// System.out.println(s);
return new StringReader(s);
}
protected static PrecisionModel precisionModel = new PrecisionModel(1000);
protected static GeometryFactory geometryFactory = new GeometryFactory(precisionModel);
protected void checkRoundTrip(Geometry g)
throws SAXException, IOException, ParserConfigurationException
{
GMLWriter out = new GMLWriter();
out.setPrefix(null);
out.setNamespace(true);
out.setSrsName("foo");
// this markup is not currently work with GMLReader
// out.setCustomElements(new String[] { "<test>1</test>" } );
out.write(g, getWriter());
System.out.println(sw.toString());
GMLReader in = new GMLReader();
Geometry g2 = in.read(getReader(), geometryFactory);
// System.out.println((pt==null?"NULL":pt.toString()));
// System.out.println((pt2==null?"NULL":pt2.toString()));
assertTrue("The input Geometry is not the same as the output Geometry", g
.equalsExact(g2));
}
}
| lgpl-2.1 |
MenoData/Time4J | base/src/test/java/net/time4j/tz/threeten/JdkZoneProviderTest.java | 7150 | package net.time4j.tz.threeten;
import net.time4j.Moment;
import net.time4j.PlainDate;
import net.time4j.PlainTime;
import net.time4j.tz.OffsetSign;
import net.time4j.tz.Timezone;
import net.time4j.tz.TransitionHistory;
import net.time4j.tz.ZonalOffset;
import net.time4j.tz.ZonalTransition;
import net.time4j.tz.ZoneModelProvider;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import java.io.IOException;
import static net.time4j.ClockUnit.MINUTES;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.fail;
@RunWith(JUnit4.class)
public class JdkZoneProviderTest {
private static ZoneModelProvider zp = null;
@BeforeClass
public static void init() {
zp = new JdkZoneProviderSPI();
System.out.println("Test of Threeten-ZoneProvider: version=" + zp.getVersion());
}
@Test
public void getFallback() {
assertThat(zp.getFallback(), is(""));
}
@Test
public void getLocation() {
assertThat(zp.getLocation(), is("{java.home}/lib/tzdb.dat"));
}
@Test
public void getName() {
assertThat(zp.getName(), is("TZDB"));
}
@Test
public void getAliases() {
assertThat(
zp.getAliases().isEmpty(),
is(true));
}
@Test
public void normalize() {
assertThat(
Timezone.normalize("Asia/Calcutta").canonical().equals("Asia/Kolkata"),
is(false)); // no support for normalization in JSR-310
}
/*
@Test
public void normalized() {
assertThat(
ZoneId.of("Atlantic/Jan_Mayen").normalized().getId(),
is("Europe/Oslo")); // normalization does not work (is just relevant for resolving fixed offsets)
}
*/
@Test
public void compareAliasWithOriginal() {
TransitionHistory histJanMayen = zp.load("Atlantic/Jan_Mayen");
TransitionHistory histOslo = zp.load("Europe/Oslo");
assertThat(histJanMayen, is(histOslo)); // same rules as expected for an alias
}
@Test
public void loadSystemV() {
TransitionHistory h = zp.load("SystemV/EST5");
assertThat(h.isEmpty(), is(true));
assertThat(
h.getInitialOffset(),
is(ZonalOffset.ofHours(OffsetSign.BEHIND_UTC, 5)));
}
@Test
public void loadAllData() {
for (String tzid : zp.getAvailableIDs()) {
try {
TransitionHistory history = zp.load(tzid);
assertThat(history, notNullValue());
} catch (RuntimeException ex) {
fail("Problem with loading history of: " + tzid);
}
}
}
@Test
public void dumpCasablanca() throws IOException {
System.out.println("Africa/Casablanca ----------------------");
zp.load("Africa/Casablanca").dump(System.out);
}
@Test
public void dumpDhaka() throws IOException {
System.out.println("Asia/Dhaka -----------------------------");
zp.load("Asia/Dhaka").dump(System.out);
}
@Test
public void dumpBerlin() throws IOException {
System.out.println("Europe/Berlin --------------------------");
zp.load("Europe/Berlin").dump(System.out);
}
@Test
public void midsummer() {
PlainDate date = PlainDate.of(1945, 5, 24);
PlainTime time = PlainTime.of(2);
Moment m = date.at(time).at(ZonalOffset.ofTotalSeconds(7200));
ZonalTransition conflict =
zp.load("Europe/Berlin").getConflictTransition(date, time);
assertThat(
conflict.getPosixTime(),
is(m.getPosixTime()));
assertThat(
conflict.getPreviousOffset(),
is(2 * 3600));
assertThat(
conflict.getTotalOffset(),
is(3 * 3600));
assertThat(
conflict.getExtraOffset(),
is(2 * 3600));
}
@Test
public void dhakaInDSTa() {
TransitionHistory history = zp.load("Asia/Dhaka");
PlainDate date = PlainDate.of(2009, 6, 19);
PlainTime time = PlainTime.of(23, 0);
Moment m = date.at(time).at(ZonalOffset.ofTotalSeconds(6 * 3600));
ZonalTransition conflict = // at first position in gap
history.getConflictTransition(date, time);
assertThat(
conflict.getPosixTime(),
is(m.getPosixTime()));
assertThat(
conflict.getPreviousOffset(),
is(6 * 3600));
assertThat(
conflict.getTotalOffset(),
is(7 * 3600));
assertThat(
conflict.getExtraOffset(),
is(3600));
}
@Test
public void dhakaInDSTb() {
TransitionHistory history = zp.load("Asia/Dhaka");
PlainDate date = PlainDate.of(2009, 6, 19);
PlainTime time = PlainTime.of(23, 0);
Moment m = date.at(time).at(ZonalOffset.ofTotalSeconds(6 * 3600));
ZonalTransition conflict = // at late position in gap
history.getConflictTransition(date, time.plus(59, MINUTES));
assertThat(
conflict.getPosixTime(),
is(m.getPosixTime()));
assertThat(
conflict.getPreviousOffset(),
is(6 * 3600));
assertThat(
conflict.getTotalOffset(),
is(7 * 3600));
assertThat(
conflict.getExtraOffset(),
is(3600));
}
@Test
public void dhakaAtEndOf2009a() {
TransitionHistory history = zp.load("Asia/Dhaka");
PlainDate date = PlainDate.of(2009, 12, 31);
PlainTime time = PlainTime.midnightAtEndOfDay();
Moment m = date.at(time).at(ZonalOffset.ofTotalSeconds(7 * 3600));
ZonalTransition conflict = // at first ambivalent time
history.getConflictTransition(date, PlainTime.of(23, 0));
assertThat(
conflict.getPosixTime(),
is(m.getPosixTime()));
assertThat(
conflict.getPreviousOffset(),
is(7 * 3600));
assertThat(
conflict.getTotalOffset(),
is(6 * 3600));
assertThat(
conflict.getExtraOffset(),
is(0));
}
@Test
public void dhakaAtEndOf2009b() {
TransitionHistory history = zp.load("Asia/Dhaka");
PlainDate date = PlainDate.of(2009, 12, 31);
PlainTime time = PlainTime.midnightAtEndOfDay();
Moment m = date.at(time).at(ZonalOffset.ofTotalSeconds(7 * 3600));
ZonalTransition conflict = // any ambivalent time
history.getConflictTransition(date, PlainTime.of(23, 30));
assertThat(
conflict.getPosixTime(),
is(m.getPosixTime()));
assertThat(
conflict.getPreviousOffset(),
is(7 * 3600));
assertThat(
conflict.getTotalOffset(),
is(6 * 3600));
assertThat(
conflict.getExtraOffset(),
is(0));
}
} | lgpl-2.1 |
GhostMonk3408/MidgarCrusade | src/main/java/fr/toss/FF7itemsg/itemg165.java | 159 | package fr.toss.FF7itemsg;
public class itemg165 extends FF7itemsgbase {
public itemg165(int id) {
super(id);
setUnlocalizedName("itemg165");
}
}
| lgpl-2.1 |
SinishaDjukic/Meshwork | Code/Host/JMeshwork/org.meshwork.app.host.l3.router/src/main/java/org/meshwork/app/host/l3/router/console/perf/TestSendRoutedStats.java | 1483 | package org.meshwork.app.host.l3.router.console.perf;
import org.meshwork.core.host.l3.Constants;
import java.util.ArrayList;
/**
* Created by Sinisha Djukic on 14-2-25.
*/
public class TestSendRoutedStats extends TestStats {
public static final String NAME_SEND_ROUTED = "TestSendRouted";
public static final int UID_SEND_ROUTED = Constants.DELIVERY_ROUTED;
public TestSendRoutedStats(TestSendRoutedConfiguration config) {
this.config = config;
testUID = UID_SEND_ROUTED;
}
@Override
public String getTestName() {
return NAME_SEND_ROUTED;
}
@Override
public String getTestDescription() {
return "Sends Routed messages to one or more nodes";
}
@Override
public String getTestDetails() {
int routecount = ((TestSendRoutedConfiguration)config).routelist.size();
StringBuffer sb = new StringBuffer("Route count: ").append(routecount);
if ( routecount > 0 ) {
for ( int i = 0; i < routecount; i ++ ) {
sb.append("\r\n\tRoute ").append(i).append(": ");
ArrayList<Byte> route = (ArrayList<Byte>) ((TestSendRoutedConfiguration)config).routelist.get(i);
sb.append(route);
// int size = route.size() - 1;
// sb.append(route.get(i));
// if ( i < size - 1 )
// sb.append(", ");
}
}
return sb.toString();
}
}
| lgpl-2.1 |