repo_name
stringlengths
7
104
file_path
stringlengths
13
198
context
stringlengths
67
7.15k
import_statement
stringlengths
16
4.43k
code
stringlengths
40
6.98k
prompt
stringlengths
227
8.27k
next_line
stringlengths
8
795
goerlitz/rdffederator
src/de/uni_koblenz/west/splendid/SPLENDID.java
// Path: src/de/uni_koblenz/west/splendid/test/config/ConfigurationException.java // public class ConfigurationException extends Exception { // // private static final long serialVersionUID = -944853354860850390L; // // public ConfigurationException(String message) { // super(message); // } // // }
import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.openrdf.model.Graph; import org.openrdf.model.impl.GraphImpl; import org.openrdf.query.BooleanQuery; import org.openrdf.query.GraphQuery; import org.openrdf.query.MalformedQueryException; import org.openrdf.query.Query; import org.openrdf.query.QueryEvaluationException; import org.openrdf.query.QueryLanguage; import org.openrdf.query.TupleQuery; import org.openrdf.query.TupleQueryResultHandlerException; import org.openrdf.query.resultio.sparqljson.SPARQLResultsJSONWriter; import org.openrdf.repository.Repository; import org.openrdf.repository.RepositoryConnection; import org.openrdf.repository.RepositoryException; import org.openrdf.repository.config.RepositoryConfig; import org.openrdf.repository.config.RepositoryConfigException; import org.openrdf.repository.config.RepositoryFactory; import org.openrdf.repository.config.RepositoryImplConfig; import org.openrdf.repository.config.RepositoryRegistry; import org.openrdf.rio.RDFFormat; import org.openrdf.rio.RDFHandlerException; import org.openrdf.rio.RDFParseException; import org.openrdf.rio.RDFParser; import org.openrdf.rio.Rio; import org.openrdf.rio.UnsupportedRDFormatException; import org.openrdf.rio.helpers.StatementCollector; import org.openrdf.rio.n3.N3Writer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import de.uni_koblenz.west.splendid.test.config.ConfigurationException;
/* * This file is part of SPLENDID. * * SPLENDID 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 3 of the License, or * (at your option) any later version. * * SPLENDID 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 SPLENDID. If not, see <http://www.gnu.org/licenses/>. * * SPLENDID uses libraries from the OpenRDF Sesame Project licensed * under the Aduna BSD-style license. */ package de.uni_koblenz.west.splendid; /** * Command Line Interface for the SPLENDID federation. * * @author [email protected] */ public class SPLENDID { private static final Logger LOGGER = LoggerFactory.getLogger(SPLENDID.class); private Repository repo; public static void main(String[] args) { if (args.length < 2) { System.out.println("USAGE: java SPLENDID <config> <query>"); System.exit(1); } String configFile = args[0]; List<String> queryFiles = Arrays.asList(Arrays.copyOfRange(args, 1, args.length)); try { SPLENDID splendid = new SPLENDID(configFile); splendid.execSparqlQueries(queryFiles);
// Path: src/de/uni_koblenz/west/splendid/test/config/ConfigurationException.java // public class ConfigurationException extends Exception { // // private static final long serialVersionUID = -944853354860850390L; // // public ConfigurationException(String message) { // super(message); // } // // } // Path: src/de/uni_koblenz/west/splendid/SPLENDID.java import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.openrdf.model.Graph; import org.openrdf.model.impl.GraphImpl; import org.openrdf.query.BooleanQuery; import org.openrdf.query.GraphQuery; import org.openrdf.query.MalformedQueryException; import org.openrdf.query.Query; import org.openrdf.query.QueryEvaluationException; import org.openrdf.query.QueryLanguage; import org.openrdf.query.TupleQuery; import org.openrdf.query.TupleQueryResultHandlerException; import org.openrdf.query.resultio.sparqljson.SPARQLResultsJSONWriter; import org.openrdf.repository.Repository; import org.openrdf.repository.RepositoryConnection; import org.openrdf.repository.RepositoryException; import org.openrdf.repository.config.RepositoryConfig; import org.openrdf.repository.config.RepositoryConfigException; import org.openrdf.repository.config.RepositoryFactory; import org.openrdf.repository.config.RepositoryImplConfig; import org.openrdf.repository.config.RepositoryRegistry; import org.openrdf.rio.RDFFormat; import org.openrdf.rio.RDFHandlerException; import org.openrdf.rio.RDFParseException; import org.openrdf.rio.RDFParser; import org.openrdf.rio.Rio; import org.openrdf.rio.UnsupportedRDFormatException; import org.openrdf.rio.helpers.StatementCollector; import org.openrdf.rio.n3.N3Writer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import de.uni_koblenz.west.splendid.test.config.ConfigurationException; /* * This file is part of SPLENDID. * * SPLENDID 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 3 of the License, or * (at your option) any later version. * * SPLENDID 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 SPLENDID. If not, see <http://www.gnu.org/licenses/>. * * SPLENDID uses libraries from the OpenRDF Sesame Project licensed * under the Aduna BSD-style license. */ package de.uni_koblenz.west.splendid; /** * Command Line Interface for the SPLENDID federation. * * @author [email protected] */ public class SPLENDID { private static final Logger LOGGER = LoggerFactory.getLogger(SPLENDID.class); private Repository repo; public static void main(String[] args) { if (args.length < 2) { System.out.println("USAGE: java SPLENDID <config> <query>"); System.exit(1); } String configFile = args[0]; List<String> queryFiles = Arrays.asList(Arrays.copyOfRange(args, 1, args.length)); try { SPLENDID splendid = new SPLENDID(configFile); splendid.execSparqlQueries(queryFiles);
} catch (ConfigurationException e) {
goerlitz/rdffederator
src/de/uni_koblenz/west/splendid/helpers/AnnotatingTreePrinter.java
// Path: src/de/uni_koblenz/west/splendid/estimation/AbstractCardinalityEstimator.java // public abstract class AbstractCardinalityEstimator extends QueryModelVisitorBase<RuntimeException> implements ModelEvaluator { // // protected Map<TupleExpr, Double> cardIndex = new HashMap<TupleExpr, Double>(); // // @Override // public Double process(TupleExpr expr) { // synchronized (this) { // expr.visit(this); // return cardIndex.get(expr); // } // } // // @Override // public void meet(Filter filter) { // // // check cardinality index first // if (getIndexCard(filter) != null) // return; // // // TODO: include condition in estimation // // for now use same card as sub expression // filter.getArg().visit(this); // // // add same cardinality as filter argument // setIndexCard(filter, getIndexCard(filter.getArg())); // } // // @Override // protected void meetUnaryTupleOperator(UnaryTupleOperator node) // throws RuntimeException { // if (node instanceof RemoteQuery) { // meet((RemoteQuery) node); // } else { // super.meetUnaryTupleOperator(node); // } // } // // protected void meet(RemoteQuery node) { // if (getIndexCard(node) != null) // return; // node.getArg().visit(this); // setIndexCard(node, getIndexCard(node.getArg())); // } // // protected Double getIndexCard(TupleExpr expr) { // return this.cardIndex.get(expr); // } // // protected void setIndexCard(TupleExpr expr, Double value) { // this.cardIndex.put(expr, value); // } // // } // // Path: src/de/uni_koblenz/west/splendid/estimation/AbstractCostEstimator.java // public abstract class AbstractCostEstimator extends QueryModelVisitorBase<RuntimeException> implements ModelEvaluator { // // protected double cost; // // protected AbstractCardinalityEstimator cardEst; // // public AbstractCardinalityEstimator getCardinalityEstimator() { // return cardEst; // } // // public void setCardinalityEstimator(AbstractCardinalityEstimator cardEst) { // this.cardEst = cardEst; // } // // public Double getCost(TupleExpr expr) { // cost = 0; // expr.visit(this); // return cost; // } // // @Override // public Double process(TupleExpr expr) { // synchronized (this) { // return getCost(expr); // } // } // // } // // Path: src/de/uni_koblenz/west/splendid/estimation/ModelEvaluator.java // public interface ModelEvaluator { // // public Double process(TupleExpr expr); // // public String getName(); // // } // // Path: src/de/uni_koblenz/west/splendid/model/RemoteQuery.java // public class RemoteQuery extends UnaryTupleOperator { // // public RemoteQuery(TupleExpr expr) { // super(expr); // } // // @Override // public <X extends Exception> void visit(QueryModelVisitor<X> visitor) throws X { // visitor.meetOther(this); // } // // public Set<Graph> getSources() { // StatementPattern p = StatementPatternCollector.process(this).get(0); // if (p instanceof MappedStatementPattern) // return ((MappedStatementPattern) p).getSources(); // else // return null; // } // // }
import org.openrdf.query.algebra.helpers.QueryModelVisitorBase; import org.openrdf.query.algebra.helpers.StatementPatternCollector; import de.uni_koblenz.west.splendid.estimation.AbstractCardinalityEstimator; import de.uni_koblenz.west.splendid.estimation.AbstractCostEstimator; import de.uni_koblenz.west.splendid.estimation.ModelEvaluator; import de.uni_koblenz.west.splendid.model.RemoteQuery; import org.openrdf.model.URI; import org.openrdf.model.Value; import org.openrdf.query.algebra.BinaryTupleOperator; import org.openrdf.query.algebra.Compare; import org.openrdf.query.algebra.Filter; import org.openrdf.query.algebra.QueryModelNode; import org.openrdf.query.algebra.StatementPattern; import org.openrdf.query.algebra.UnaryTupleOperator; import org.openrdf.query.algebra.ValueConstant; import org.openrdf.query.algebra.Var;
/* * This file is part of RDF Federator. * Copyright 2011 Olaf Goerlitz * * RDF Federator 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 3 of the License, or * (at your option) any later version. * * RDF Federator 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 RDF Federator. If not, see <http://www.gnu.org/licenses/>. * * RDF Federator uses libraries from the OpenRDF Sesame Project licensed * under the Aduna BSD-style license. */ package de.uni_koblenz.west.splendid.helpers; /** * Prints the tree structure of a query plan. * Can annotate individual nodes with the result of a model evaluator. * Highlights the sub tree marked as a remote query. * * @author Olaf Goerlitz */ public class AnnotatingTreePrinter extends QueryModelVisitorBase<RuntimeException> { private static final String LINE_SEPARATOR = System.getProperty("line.separator"); private static final String indentString = " "; private StringBuilder buffer; private int indentLevel = 0;
// Path: src/de/uni_koblenz/west/splendid/estimation/AbstractCardinalityEstimator.java // public abstract class AbstractCardinalityEstimator extends QueryModelVisitorBase<RuntimeException> implements ModelEvaluator { // // protected Map<TupleExpr, Double> cardIndex = new HashMap<TupleExpr, Double>(); // // @Override // public Double process(TupleExpr expr) { // synchronized (this) { // expr.visit(this); // return cardIndex.get(expr); // } // } // // @Override // public void meet(Filter filter) { // // // check cardinality index first // if (getIndexCard(filter) != null) // return; // // // TODO: include condition in estimation // // for now use same card as sub expression // filter.getArg().visit(this); // // // add same cardinality as filter argument // setIndexCard(filter, getIndexCard(filter.getArg())); // } // // @Override // protected void meetUnaryTupleOperator(UnaryTupleOperator node) // throws RuntimeException { // if (node instanceof RemoteQuery) { // meet((RemoteQuery) node); // } else { // super.meetUnaryTupleOperator(node); // } // } // // protected void meet(RemoteQuery node) { // if (getIndexCard(node) != null) // return; // node.getArg().visit(this); // setIndexCard(node, getIndexCard(node.getArg())); // } // // protected Double getIndexCard(TupleExpr expr) { // return this.cardIndex.get(expr); // } // // protected void setIndexCard(TupleExpr expr, Double value) { // this.cardIndex.put(expr, value); // } // // } // // Path: src/de/uni_koblenz/west/splendid/estimation/AbstractCostEstimator.java // public abstract class AbstractCostEstimator extends QueryModelVisitorBase<RuntimeException> implements ModelEvaluator { // // protected double cost; // // protected AbstractCardinalityEstimator cardEst; // // public AbstractCardinalityEstimator getCardinalityEstimator() { // return cardEst; // } // // public void setCardinalityEstimator(AbstractCardinalityEstimator cardEst) { // this.cardEst = cardEst; // } // // public Double getCost(TupleExpr expr) { // cost = 0; // expr.visit(this); // return cost; // } // // @Override // public Double process(TupleExpr expr) { // synchronized (this) { // return getCost(expr); // } // } // // } // // Path: src/de/uni_koblenz/west/splendid/estimation/ModelEvaluator.java // public interface ModelEvaluator { // // public Double process(TupleExpr expr); // // public String getName(); // // } // // Path: src/de/uni_koblenz/west/splendid/model/RemoteQuery.java // public class RemoteQuery extends UnaryTupleOperator { // // public RemoteQuery(TupleExpr expr) { // super(expr); // } // // @Override // public <X extends Exception> void visit(QueryModelVisitor<X> visitor) throws X { // visitor.meetOther(this); // } // // public Set<Graph> getSources() { // StatementPattern p = StatementPatternCollector.process(this).get(0); // if (p instanceof MappedStatementPattern) // return ((MappedStatementPattern) p).getSources(); // else // return null; // } // // } // Path: src/de/uni_koblenz/west/splendid/helpers/AnnotatingTreePrinter.java import org.openrdf.query.algebra.helpers.QueryModelVisitorBase; import org.openrdf.query.algebra.helpers.StatementPatternCollector; import de.uni_koblenz.west.splendid.estimation.AbstractCardinalityEstimator; import de.uni_koblenz.west.splendid.estimation.AbstractCostEstimator; import de.uni_koblenz.west.splendid.estimation.ModelEvaluator; import de.uni_koblenz.west.splendid.model.RemoteQuery; import org.openrdf.model.URI; import org.openrdf.model.Value; import org.openrdf.query.algebra.BinaryTupleOperator; import org.openrdf.query.algebra.Compare; import org.openrdf.query.algebra.Filter; import org.openrdf.query.algebra.QueryModelNode; import org.openrdf.query.algebra.StatementPattern; import org.openrdf.query.algebra.UnaryTupleOperator; import org.openrdf.query.algebra.ValueConstant; import org.openrdf.query.algebra.Var; /* * This file is part of RDF Federator. * Copyright 2011 Olaf Goerlitz * * RDF Federator 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 3 of the License, or * (at your option) any later version. * * RDF Federator 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 RDF Federator. If not, see <http://www.gnu.org/licenses/>. * * RDF Federator uses libraries from the OpenRDF Sesame Project licensed * under the Aduna BSD-style license. */ package de.uni_koblenz.west.splendid.helpers; /** * Prints the tree structure of a query plan. * Can annotate individual nodes with the result of a model evaluator. * Highlights the sub tree marked as a remote query. * * @author Olaf Goerlitz */ public class AnnotatingTreePrinter extends QueryModelVisitorBase<RuntimeException> { private static final String LINE_SEPARATOR = System.getProperty("line.separator"); private static final String indentString = " "; private StringBuilder buffer; private int indentLevel = 0;
private ModelEvaluator eval;
goerlitz/rdffederator
src/de/uni_koblenz/west/splendid/helpers/AnnotatingTreePrinter.java
// Path: src/de/uni_koblenz/west/splendid/estimation/AbstractCardinalityEstimator.java // public abstract class AbstractCardinalityEstimator extends QueryModelVisitorBase<RuntimeException> implements ModelEvaluator { // // protected Map<TupleExpr, Double> cardIndex = new HashMap<TupleExpr, Double>(); // // @Override // public Double process(TupleExpr expr) { // synchronized (this) { // expr.visit(this); // return cardIndex.get(expr); // } // } // // @Override // public void meet(Filter filter) { // // // check cardinality index first // if (getIndexCard(filter) != null) // return; // // // TODO: include condition in estimation // // for now use same card as sub expression // filter.getArg().visit(this); // // // add same cardinality as filter argument // setIndexCard(filter, getIndexCard(filter.getArg())); // } // // @Override // protected void meetUnaryTupleOperator(UnaryTupleOperator node) // throws RuntimeException { // if (node instanceof RemoteQuery) { // meet((RemoteQuery) node); // } else { // super.meetUnaryTupleOperator(node); // } // } // // protected void meet(RemoteQuery node) { // if (getIndexCard(node) != null) // return; // node.getArg().visit(this); // setIndexCard(node, getIndexCard(node.getArg())); // } // // protected Double getIndexCard(TupleExpr expr) { // return this.cardIndex.get(expr); // } // // protected void setIndexCard(TupleExpr expr, Double value) { // this.cardIndex.put(expr, value); // } // // } // // Path: src/de/uni_koblenz/west/splendid/estimation/AbstractCostEstimator.java // public abstract class AbstractCostEstimator extends QueryModelVisitorBase<RuntimeException> implements ModelEvaluator { // // protected double cost; // // protected AbstractCardinalityEstimator cardEst; // // public AbstractCardinalityEstimator getCardinalityEstimator() { // return cardEst; // } // // public void setCardinalityEstimator(AbstractCardinalityEstimator cardEst) { // this.cardEst = cardEst; // } // // public Double getCost(TupleExpr expr) { // cost = 0; // expr.visit(this); // return cost; // } // // @Override // public Double process(TupleExpr expr) { // synchronized (this) { // return getCost(expr); // } // } // // } // // Path: src/de/uni_koblenz/west/splendid/estimation/ModelEvaluator.java // public interface ModelEvaluator { // // public Double process(TupleExpr expr); // // public String getName(); // // } // // Path: src/de/uni_koblenz/west/splendid/model/RemoteQuery.java // public class RemoteQuery extends UnaryTupleOperator { // // public RemoteQuery(TupleExpr expr) { // super(expr); // } // // @Override // public <X extends Exception> void visit(QueryModelVisitor<X> visitor) throws X { // visitor.meetOther(this); // } // // public Set<Graph> getSources() { // StatementPattern p = StatementPatternCollector.process(this).get(0); // if (p instanceof MappedStatementPattern) // return ((MappedStatementPattern) p).getSources(); // else // return null; // } // // }
import org.openrdf.query.algebra.helpers.QueryModelVisitorBase; import org.openrdf.query.algebra.helpers.StatementPatternCollector; import de.uni_koblenz.west.splendid.estimation.AbstractCardinalityEstimator; import de.uni_koblenz.west.splendid.estimation.AbstractCostEstimator; import de.uni_koblenz.west.splendid.estimation.ModelEvaluator; import de.uni_koblenz.west.splendid.model.RemoteQuery; import org.openrdf.model.URI; import org.openrdf.model.Value; import org.openrdf.query.algebra.BinaryTupleOperator; import org.openrdf.query.algebra.Compare; import org.openrdf.query.algebra.Filter; import org.openrdf.query.algebra.QueryModelNode; import org.openrdf.query.algebra.StatementPattern; import org.openrdf.query.algebra.UnaryTupleOperator; import org.openrdf.query.algebra.ValueConstant; import org.openrdf.query.algebra.Var;
buffer.append(indentString); } } @Override public void meet(Compare node) throws RuntimeException { node.getLeftArg().visit(this); buffer.append(" ").append(node.getOperator().getSymbol()).append(" "); node.getRightArg().visit(this); } @Override public void meet(Filter node) throws RuntimeException { addIndent(); buffer.append("FILTER ("); node.getCondition().visit(this); buffer.append(")").append(LINE_SEPARATOR); indentLevel++; node.getArg().visit(this); indentLevel--; } @Override public void meet(StatementPattern node) throws RuntimeException { addIndent(); for (Var var : node.getVarList()) { var.visit(this); buffer.append(" "); }
// Path: src/de/uni_koblenz/west/splendid/estimation/AbstractCardinalityEstimator.java // public abstract class AbstractCardinalityEstimator extends QueryModelVisitorBase<RuntimeException> implements ModelEvaluator { // // protected Map<TupleExpr, Double> cardIndex = new HashMap<TupleExpr, Double>(); // // @Override // public Double process(TupleExpr expr) { // synchronized (this) { // expr.visit(this); // return cardIndex.get(expr); // } // } // // @Override // public void meet(Filter filter) { // // // check cardinality index first // if (getIndexCard(filter) != null) // return; // // // TODO: include condition in estimation // // for now use same card as sub expression // filter.getArg().visit(this); // // // add same cardinality as filter argument // setIndexCard(filter, getIndexCard(filter.getArg())); // } // // @Override // protected void meetUnaryTupleOperator(UnaryTupleOperator node) // throws RuntimeException { // if (node instanceof RemoteQuery) { // meet((RemoteQuery) node); // } else { // super.meetUnaryTupleOperator(node); // } // } // // protected void meet(RemoteQuery node) { // if (getIndexCard(node) != null) // return; // node.getArg().visit(this); // setIndexCard(node, getIndexCard(node.getArg())); // } // // protected Double getIndexCard(TupleExpr expr) { // return this.cardIndex.get(expr); // } // // protected void setIndexCard(TupleExpr expr, Double value) { // this.cardIndex.put(expr, value); // } // // } // // Path: src/de/uni_koblenz/west/splendid/estimation/AbstractCostEstimator.java // public abstract class AbstractCostEstimator extends QueryModelVisitorBase<RuntimeException> implements ModelEvaluator { // // protected double cost; // // protected AbstractCardinalityEstimator cardEst; // // public AbstractCardinalityEstimator getCardinalityEstimator() { // return cardEst; // } // // public void setCardinalityEstimator(AbstractCardinalityEstimator cardEst) { // this.cardEst = cardEst; // } // // public Double getCost(TupleExpr expr) { // cost = 0; // expr.visit(this); // return cost; // } // // @Override // public Double process(TupleExpr expr) { // synchronized (this) { // return getCost(expr); // } // } // // } // // Path: src/de/uni_koblenz/west/splendid/estimation/ModelEvaluator.java // public interface ModelEvaluator { // // public Double process(TupleExpr expr); // // public String getName(); // // } // // Path: src/de/uni_koblenz/west/splendid/model/RemoteQuery.java // public class RemoteQuery extends UnaryTupleOperator { // // public RemoteQuery(TupleExpr expr) { // super(expr); // } // // @Override // public <X extends Exception> void visit(QueryModelVisitor<X> visitor) throws X { // visitor.meetOther(this); // } // // public Set<Graph> getSources() { // StatementPattern p = StatementPatternCollector.process(this).get(0); // if (p instanceof MappedStatementPattern) // return ((MappedStatementPattern) p).getSources(); // else // return null; // } // // } // Path: src/de/uni_koblenz/west/splendid/helpers/AnnotatingTreePrinter.java import org.openrdf.query.algebra.helpers.QueryModelVisitorBase; import org.openrdf.query.algebra.helpers.StatementPatternCollector; import de.uni_koblenz.west.splendid.estimation.AbstractCardinalityEstimator; import de.uni_koblenz.west.splendid.estimation.AbstractCostEstimator; import de.uni_koblenz.west.splendid.estimation.ModelEvaluator; import de.uni_koblenz.west.splendid.model.RemoteQuery; import org.openrdf.model.URI; import org.openrdf.model.Value; import org.openrdf.query.algebra.BinaryTupleOperator; import org.openrdf.query.algebra.Compare; import org.openrdf.query.algebra.Filter; import org.openrdf.query.algebra.QueryModelNode; import org.openrdf.query.algebra.StatementPattern; import org.openrdf.query.algebra.UnaryTupleOperator; import org.openrdf.query.algebra.ValueConstant; import org.openrdf.query.algebra.Var; buffer.append(indentString); } } @Override public void meet(Compare node) throws RuntimeException { node.getLeftArg().visit(this); buffer.append(" ").append(node.getOperator().getSymbol()).append(" "); node.getRightArg().visit(this); } @Override public void meet(Filter node) throws RuntimeException { addIndent(); buffer.append("FILTER ("); node.getCondition().visit(this); buffer.append(")").append(LINE_SEPARATOR); indentLevel++; node.getArg().visit(this); indentLevel--; } @Override public void meet(StatementPattern node) throws RuntimeException { addIndent(); for (Var var : node.getVarList()) { var.visit(this); buffer.append(" "); }
if (eval instanceof AbstractCostEstimator) {
goerlitz/rdffederator
src/de/uni_koblenz/west/splendid/helpers/AnnotatingTreePrinter.java
// Path: src/de/uni_koblenz/west/splendid/estimation/AbstractCardinalityEstimator.java // public abstract class AbstractCardinalityEstimator extends QueryModelVisitorBase<RuntimeException> implements ModelEvaluator { // // protected Map<TupleExpr, Double> cardIndex = new HashMap<TupleExpr, Double>(); // // @Override // public Double process(TupleExpr expr) { // synchronized (this) { // expr.visit(this); // return cardIndex.get(expr); // } // } // // @Override // public void meet(Filter filter) { // // // check cardinality index first // if (getIndexCard(filter) != null) // return; // // // TODO: include condition in estimation // // for now use same card as sub expression // filter.getArg().visit(this); // // // add same cardinality as filter argument // setIndexCard(filter, getIndexCard(filter.getArg())); // } // // @Override // protected void meetUnaryTupleOperator(UnaryTupleOperator node) // throws RuntimeException { // if (node instanceof RemoteQuery) { // meet((RemoteQuery) node); // } else { // super.meetUnaryTupleOperator(node); // } // } // // protected void meet(RemoteQuery node) { // if (getIndexCard(node) != null) // return; // node.getArg().visit(this); // setIndexCard(node, getIndexCard(node.getArg())); // } // // protected Double getIndexCard(TupleExpr expr) { // return this.cardIndex.get(expr); // } // // protected void setIndexCard(TupleExpr expr, Double value) { // this.cardIndex.put(expr, value); // } // // } // // Path: src/de/uni_koblenz/west/splendid/estimation/AbstractCostEstimator.java // public abstract class AbstractCostEstimator extends QueryModelVisitorBase<RuntimeException> implements ModelEvaluator { // // protected double cost; // // protected AbstractCardinalityEstimator cardEst; // // public AbstractCardinalityEstimator getCardinalityEstimator() { // return cardEst; // } // // public void setCardinalityEstimator(AbstractCardinalityEstimator cardEst) { // this.cardEst = cardEst; // } // // public Double getCost(TupleExpr expr) { // cost = 0; // expr.visit(this); // return cost; // } // // @Override // public Double process(TupleExpr expr) { // synchronized (this) { // return getCost(expr); // } // } // // } // // Path: src/de/uni_koblenz/west/splendid/estimation/ModelEvaluator.java // public interface ModelEvaluator { // // public Double process(TupleExpr expr); // // public String getName(); // // } // // Path: src/de/uni_koblenz/west/splendid/model/RemoteQuery.java // public class RemoteQuery extends UnaryTupleOperator { // // public RemoteQuery(TupleExpr expr) { // super(expr); // } // // @Override // public <X extends Exception> void visit(QueryModelVisitor<X> visitor) throws X { // visitor.meetOther(this); // } // // public Set<Graph> getSources() { // StatementPattern p = StatementPatternCollector.process(this).get(0); // if (p instanceof MappedStatementPattern) // return ((MappedStatementPattern) p).getSources(); // else // return null; // } // // }
import org.openrdf.query.algebra.helpers.QueryModelVisitorBase; import org.openrdf.query.algebra.helpers.StatementPatternCollector; import de.uni_koblenz.west.splendid.estimation.AbstractCardinalityEstimator; import de.uni_koblenz.west.splendid.estimation.AbstractCostEstimator; import de.uni_koblenz.west.splendid.estimation.ModelEvaluator; import de.uni_koblenz.west.splendid.model.RemoteQuery; import org.openrdf.model.URI; import org.openrdf.model.Value; import org.openrdf.query.algebra.BinaryTupleOperator; import org.openrdf.query.algebra.Compare; import org.openrdf.query.algebra.Filter; import org.openrdf.query.algebra.QueryModelNode; import org.openrdf.query.algebra.StatementPattern; import org.openrdf.query.algebra.UnaryTupleOperator; import org.openrdf.query.algebra.ValueConstant; import org.openrdf.query.algebra.Var;
} } @Override public void meet(Compare node) throws RuntimeException { node.getLeftArg().visit(this); buffer.append(" ").append(node.getOperator().getSymbol()).append(" "); node.getRightArg().visit(this); } @Override public void meet(Filter node) throws RuntimeException { addIndent(); buffer.append("FILTER ("); node.getCondition().visit(this); buffer.append(")").append(LINE_SEPARATOR); indentLevel++; node.getArg().visit(this); indentLevel--; } @Override public void meet(StatementPattern node) throws RuntimeException { addIndent(); for (Var var : node.getVarList()) { var.visit(this); buffer.append(" "); } if (eval instanceof AbstractCostEstimator) {
// Path: src/de/uni_koblenz/west/splendid/estimation/AbstractCardinalityEstimator.java // public abstract class AbstractCardinalityEstimator extends QueryModelVisitorBase<RuntimeException> implements ModelEvaluator { // // protected Map<TupleExpr, Double> cardIndex = new HashMap<TupleExpr, Double>(); // // @Override // public Double process(TupleExpr expr) { // synchronized (this) { // expr.visit(this); // return cardIndex.get(expr); // } // } // // @Override // public void meet(Filter filter) { // // // check cardinality index first // if (getIndexCard(filter) != null) // return; // // // TODO: include condition in estimation // // for now use same card as sub expression // filter.getArg().visit(this); // // // add same cardinality as filter argument // setIndexCard(filter, getIndexCard(filter.getArg())); // } // // @Override // protected void meetUnaryTupleOperator(UnaryTupleOperator node) // throws RuntimeException { // if (node instanceof RemoteQuery) { // meet((RemoteQuery) node); // } else { // super.meetUnaryTupleOperator(node); // } // } // // protected void meet(RemoteQuery node) { // if (getIndexCard(node) != null) // return; // node.getArg().visit(this); // setIndexCard(node, getIndexCard(node.getArg())); // } // // protected Double getIndexCard(TupleExpr expr) { // return this.cardIndex.get(expr); // } // // protected void setIndexCard(TupleExpr expr, Double value) { // this.cardIndex.put(expr, value); // } // // } // // Path: src/de/uni_koblenz/west/splendid/estimation/AbstractCostEstimator.java // public abstract class AbstractCostEstimator extends QueryModelVisitorBase<RuntimeException> implements ModelEvaluator { // // protected double cost; // // protected AbstractCardinalityEstimator cardEst; // // public AbstractCardinalityEstimator getCardinalityEstimator() { // return cardEst; // } // // public void setCardinalityEstimator(AbstractCardinalityEstimator cardEst) { // this.cardEst = cardEst; // } // // public Double getCost(TupleExpr expr) { // cost = 0; // expr.visit(this); // return cost; // } // // @Override // public Double process(TupleExpr expr) { // synchronized (this) { // return getCost(expr); // } // } // // } // // Path: src/de/uni_koblenz/west/splendid/estimation/ModelEvaluator.java // public interface ModelEvaluator { // // public Double process(TupleExpr expr); // // public String getName(); // // } // // Path: src/de/uni_koblenz/west/splendid/model/RemoteQuery.java // public class RemoteQuery extends UnaryTupleOperator { // // public RemoteQuery(TupleExpr expr) { // super(expr); // } // // @Override // public <X extends Exception> void visit(QueryModelVisitor<X> visitor) throws X { // visitor.meetOther(this); // } // // public Set<Graph> getSources() { // StatementPattern p = StatementPatternCollector.process(this).get(0); // if (p instanceof MappedStatementPattern) // return ((MappedStatementPattern) p).getSources(); // else // return null; // } // // } // Path: src/de/uni_koblenz/west/splendid/helpers/AnnotatingTreePrinter.java import org.openrdf.query.algebra.helpers.QueryModelVisitorBase; import org.openrdf.query.algebra.helpers.StatementPatternCollector; import de.uni_koblenz.west.splendid.estimation.AbstractCardinalityEstimator; import de.uni_koblenz.west.splendid.estimation.AbstractCostEstimator; import de.uni_koblenz.west.splendid.estimation.ModelEvaluator; import de.uni_koblenz.west.splendid.model.RemoteQuery; import org.openrdf.model.URI; import org.openrdf.model.Value; import org.openrdf.query.algebra.BinaryTupleOperator; import org.openrdf.query.algebra.Compare; import org.openrdf.query.algebra.Filter; import org.openrdf.query.algebra.QueryModelNode; import org.openrdf.query.algebra.StatementPattern; import org.openrdf.query.algebra.UnaryTupleOperator; import org.openrdf.query.algebra.ValueConstant; import org.openrdf.query.algebra.Var; } } @Override public void meet(Compare node) throws RuntimeException { node.getLeftArg().visit(this); buffer.append(" ").append(node.getOperator().getSymbol()).append(" "); node.getRightArg().visit(this); } @Override public void meet(Filter node) throws RuntimeException { addIndent(); buffer.append("FILTER ("); node.getCondition().visit(this); buffer.append(")").append(LINE_SEPARATOR); indentLevel++; node.getArg().visit(this); indentLevel--; } @Override public void meet(StatementPattern node) throws RuntimeException { addIndent(); for (Var var : node.getVarList()) { var.visit(this); buffer.append(" "); } if (eval instanceof AbstractCostEstimator) {
AbstractCardinalityEstimator evalCard = ((AbstractCostEstimator) eval).getCardinalityEstimator();
goerlitz/rdffederator
src/de/uni_koblenz/west/splendid/helpers/AnnotatingTreePrinter.java
// Path: src/de/uni_koblenz/west/splendid/estimation/AbstractCardinalityEstimator.java // public abstract class AbstractCardinalityEstimator extends QueryModelVisitorBase<RuntimeException> implements ModelEvaluator { // // protected Map<TupleExpr, Double> cardIndex = new HashMap<TupleExpr, Double>(); // // @Override // public Double process(TupleExpr expr) { // synchronized (this) { // expr.visit(this); // return cardIndex.get(expr); // } // } // // @Override // public void meet(Filter filter) { // // // check cardinality index first // if (getIndexCard(filter) != null) // return; // // // TODO: include condition in estimation // // for now use same card as sub expression // filter.getArg().visit(this); // // // add same cardinality as filter argument // setIndexCard(filter, getIndexCard(filter.getArg())); // } // // @Override // protected void meetUnaryTupleOperator(UnaryTupleOperator node) // throws RuntimeException { // if (node instanceof RemoteQuery) { // meet((RemoteQuery) node); // } else { // super.meetUnaryTupleOperator(node); // } // } // // protected void meet(RemoteQuery node) { // if (getIndexCard(node) != null) // return; // node.getArg().visit(this); // setIndexCard(node, getIndexCard(node.getArg())); // } // // protected Double getIndexCard(TupleExpr expr) { // return this.cardIndex.get(expr); // } // // protected void setIndexCard(TupleExpr expr, Double value) { // this.cardIndex.put(expr, value); // } // // } // // Path: src/de/uni_koblenz/west/splendid/estimation/AbstractCostEstimator.java // public abstract class AbstractCostEstimator extends QueryModelVisitorBase<RuntimeException> implements ModelEvaluator { // // protected double cost; // // protected AbstractCardinalityEstimator cardEst; // // public AbstractCardinalityEstimator getCardinalityEstimator() { // return cardEst; // } // // public void setCardinalityEstimator(AbstractCardinalityEstimator cardEst) { // this.cardEst = cardEst; // } // // public Double getCost(TupleExpr expr) { // cost = 0; // expr.visit(this); // return cost; // } // // @Override // public Double process(TupleExpr expr) { // synchronized (this) { // return getCost(expr); // } // } // // } // // Path: src/de/uni_koblenz/west/splendid/estimation/ModelEvaluator.java // public interface ModelEvaluator { // // public Double process(TupleExpr expr); // // public String getName(); // // } // // Path: src/de/uni_koblenz/west/splendid/model/RemoteQuery.java // public class RemoteQuery extends UnaryTupleOperator { // // public RemoteQuery(TupleExpr expr) { // super(expr); // } // // @Override // public <X extends Exception> void visit(QueryModelVisitor<X> visitor) throws X { // visitor.meetOther(this); // } // // public Set<Graph> getSources() { // StatementPattern p = StatementPatternCollector.process(this).get(0); // if (p instanceof MappedStatementPattern) // return ((MappedStatementPattern) p).getSources(); // else // return null; // } // // }
import org.openrdf.query.algebra.helpers.QueryModelVisitorBase; import org.openrdf.query.algebra.helpers.StatementPatternCollector; import de.uni_koblenz.west.splendid.estimation.AbstractCardinalityEstimator; import de.uni_koblenz.west.splendid.estimation.AbstractCostEstimator; import de.uni_koblenz.west.splendid.estimation.ModelEvaluator; import de.uni_koblenz.west.splendid.model.RemoteQuery; import org.openrdf.model.URI; import org.openrdf.model.Value; import org.openrdf.query.algebra.BinaryTupleOperator; import org.openrdf.query.algebra.Compare; import org.openrdf.query.algebra.Filter; import org.openrdf.query.algebra.QueryModelNode; import org.openrdf.query.algebra.StatementPattern; import org.openrdf.query.algebra.UnaryTupleOperator; import org.openrdf.query.algebra.ValueConstant; import org.openrdf.query.algebra.Var;
@Override public void meet(ValueConstant node) throws RuntimeException { buffer.append(node.getValue()); } @Override protected void meetBinaryTupleOperator(BinaryTupleOperator node) throws RuntimeException { addIndent(); buffer.append(node.getSignature().toUpperCase()); if (eval != null) { buffer.append(" [").append(evalLabel).append(": ").append(eval.process(node)).append("]"); if (eval instanceof AbstractCostEstimator) { AbstractCardinalityEstimator evalCard = ((AbstractCostEstimator) eval).getCardinalityEstimator(); buffer.append(" [").append(evalCard.getName()).append(": ").append(evalCard.process(node)).append("]"); } } indentLevel++; buffer.append(LINE_SEPARATOR); node.getLeftArg().visit(this); buffer.append(LINE_SEPARATOR); node.getRightArg().visit(this); indentLevel--; } @Override protected void meetUnaryTupleOperator(UnaryTupleOperator node) throws RuntimeException {
// Path: src/de/uni_koblenz/west/splendid/estimation/AbstractCardinalityEstimator.java // public abstract class AbstractCardinalityEstimator extends QueryModelVisitorBase<RuntimeException> implements ModelEvaluator { // // protected Map<TupleExpr, Double> cardIndex = new HashMap<TupleExpr, Double>(); // // @Override // public Double process(TupleExpr expr) { // synchronized (this) { // expr.visit(this); // return cardIndex.get(expr); // } // } // // @Override // public void meet(Filter filter) { // // // check cardinality index first // if (getIndexCard(filter) != null) // return; // // // TODO: include condition in estimation // // for now use same card as sub expression // filter.getArg().visit(this); // // // add same cardinality as filter argument // setIndexCard(filter, getIndexCard(filter.getArg())); // } // // @Override // protected void meetUnaryTupleOperator(UnaryTupleOperator node) // throws RuntimeException { // if (node instanceof RemoteQuery) { // meet((RemoteQuery) node); // } else { // super.meetUnaryTupleOperator(node); // } // } // // protected void meet(RemoteQuery node) { // if (getIndexCard(node) != null) // return; // node.getArg().visit(this); // setIndexCard(node, getIndexCard(node.getArg())); // } // // protected Double getIndexCard(TupleExpr expr) { // return this.cardIndex.get(expr); // } // // protected void setIndexCard(TupleExpr expr, Double value) { // this.cardIndex.put(expr, value); // } // // } // // Path: src/de/uni_koblenz/west/splendid/estimation/AbstractCostEstimator.java // public abstract class AbstractCostEstimator extends QueryModelVisitorBase<RuntimeException> implements ModelEvaluator { // // protected double cost; // // protected AbstractCardinalityEstimator cardEst; // // public AbstractCardinalityEstimator getCardinalityEstimator() { // return cardEst; // } // // public void setCardinalityEstimator(AbstractCardinalityEstimator cardEst) { // this.cardEst = cardEst; // } // // public Double getCost(TupleExpr expr) { // cost = 0; // expr.visit(this); // return cost; // } // // @Override // public Double process(TupleExpr expr) { // synchronized (this) { // return getCost(expr); // } // } // // } // // Path: src/de/uni_koblenz/west/splendid/estimation/ModelEvaluator.java // public interface ModelEvaluator { // // public Double process(TupleExpr expr); // // public String getName(); // // } // // Path: src/de/uni_koblenz/west/splendid/model/RemoteQuery.java // public class RemoteQuery extends UnaryTupleOperator { // // public RemoteQuery(TupleExpr expr) { // super(expr); // } // // @Override // public <X extends Exception> void visit(QueryModelVisitor<X> visitor) throws X { // visitor.meetOther(this); // } // // public Set<Graph> getSources() { // StatementPattern p = StatementPatternCollector.process(this).get(0); // if (p instanceof MappedStatementPattern) // return ((MappedStatementPattern) p).getSources(); // else // return null; // } // // } // Path: src/de/uni_koblenz/west/splendid/helpers/AnnotatingTreePrinter.java import org.openrdf.query.algebra.helpers.QueryModelVisitorBase; import org.openrdf.query.algebra.helpers.StatementPatternCollector; import de.uni_koblenz.west.splendid.estimation.AbstractCardinalityEstimator; import de.uni_koblenz.west.splendid.estimation.AbstractCostEstimator; import de.uni_koblenz.west.splendid.estimation.ModelEvaluator; import de.uni_koblenz.west.splendid.model.RemoteQuery; import org.openrdf.model.URI; import org.openrdf.model.Value; import org.openrdf.query.algebra.BinaryTupleOperator; import org.openrdf.query.algebra.Compare; import org.openrdf.query.algebra.Filter; import org.openrdf.query.algebra.QueryModelNode; import org.openrdf.query.algebra.StatementPattern; import org.openrdf.query.algebra.UnaryTupleOperator; import org.openrdf.query.algebra.ValueConstant; import org.openrdf.query.algebra.Var; @Override public void meet(ValueConstant node) throws RuntimeException { buffer.append(node.getValue()); } @Override protected void meetBinaryTupleOperator(BinaryTupleOperator node) throws RuntimeException { addIndent(); buffer.append(node.getSignature().toUpperCase()); if (eval != null) { buffer.append(" [").append(evalLabel).append(": ").append(eval.process(node)).append("]"); if (eval instanceof AbstractCostEstimator) { AbstractCardinalityEstimator evalCard = ((AbstractCostEstimator) eval).getCardinalityEstimator(); buffer.append(" [").append(evalCard.getName()).append(": ").append(evalCard.process(node)).append("]"); } } indentLevel++; buffer.append(LINE_SEPARATOR); node.getLeftArg().visit(this); buffer.append(LINE_SEPARATOR); node.getRightArg().visit(this); indentLevel--; } @Override protected void meetUnaryTupleOperator(UnaryTupleOperator node) throws RuntimeException {
if (node instanceof RemoteQuery) {
goerlitz/rdffederator
src/de/uni_koblenz/west/splendid/config/VoidRepositoryFactory.java
// Path: src/de/uni_koblenz/west/splendid/VoidRepository.java // public class VoidRepository implements Repository { // // private static final Logger LOGGER = LoggerFactory.getLogger(VoidRepository.class); // // protected final ValueFactory vf = new ValueFactoryImpl(); // protected URI endpoint; // protected final URI voidURI; // // protected boolean initialized = false; // // public VoidRepository(VoidRepositoryConfig config) { // this.endpoint = config.getEndpoint(); // this.voidURI = config.getVoidURI(); // } // // public URI getEndpoint() { // return this.endpoint; // } // // // -------------------------------------------------------------- // // @Override // public void setDataDir(File dataDir) { // throw new UnsupportedOperationException("SPARQL endpoint repository has no data dir"); // } // // @Override // public File getDataDir() { // throw new UnsupportedOperationException("SPARQL endpoint repository has no data dir"); // } // // @Override // public boolean isWritable() throws RepositoryException { // return false; // } // // @Override // public ValueFactory getValueFactory() { // return this.vf; // } // // @Override // public void initialize() throws RepositoryException { // // if (this.initialized) { // LOGGER.info("Void repository has already been initialized"); // return; // } // // try { // this.endpoint = VoidStatistics.getInstance().load(this.voidURI, this.endpoint); // } catch (IOException e) { // throw new RepositoryException("can not read voiD description: " + this.voidURI + e.getMessage(), e); // } // // this.initialized = true; // } // // @Override // public void shutDown() throws RepositoryException { // // TODO: remove statistics from VOID repository? // } // // @Override // public RepositoryConnection getConnection() throws RepositoryException { // return new VoidRepositoryConnection(this); // } // // }
import org.openrdf.repository.Repository; import org.openrdf.repository.config.RepositoryConfigException; import org.openrdf.repository.config.RepositoryFactory; import org.openrdf.repository.config.RepositoryImplConfig; import de.uni_koblenz.west.splendid.VoidRepository;
/* * This file is part of RDF Federator. * Copyright 2010 Olaf Goerlitz * * RDF Federator 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 3 of the License, or * (at your option) any later version. * * RDF Federator 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 RDF Federator. If not, see <http://www.gnu.org/licenses/>. * * RDF Federator uses libraries from the OpenRDF Sesame Project licensed * under the Aduna BSD-style license. */ package de.uni_koblenz.west.splendid.config; //import org.openrdf.store.StoreConfigException; /** * A {@link RepositoryFactory} that creates {@link VoidRepository}s * based on the supplied configuration data. * * ATTENTION: This factory must be published with full package name in * META-INF/services/org.openrdf.repository.config.RepositoryFactory * * @author Olaf Goerlitz */ public class VoidRepositoryFactory implements RepositoryFactory { /** * The type of repositories that are created by this factory. * * @see RepositoryFactory#getRepositoryType() */ public static final String REPOSITORY_TYPE = "west:VoidRepository"; /** * Returns the repository's type: <tt>west:VoidRepository</tt>. */ public String getRepositoryType() { return REPOSITORY_TYPE; } /** * Provides a repository configuration object for the configuration data. * * @return a {@link VoidRepositoryConfig}. */ public RepositoryImplConfig getConfig() { return new VoidRepositoryConfig(); } /** * Returns a Repository instance that has been initialized using the * supplied configuration data. * * @param config * the repository configuration. * @return The created (but un-initialized) repository. * @throws StoreConfigException * If no repository could be created due to invalid or * incomplete configuration data. */ @Override public Repository getRepository(RepositoryImplConfig config) throws RepositoryConfigException { if (!REPOSITORY_TYPE.equals(config.getType())) { throw new RepositoryConfigException("Invalid repository type: " + config.getType()); } assert config instanceof VoidRepositoryConfig; VoidRepositoryConfig repConfig = (VoidRepositoryConfig) config; // return new VoidRepository(repConfig.getVoidURI(), repConfig.getEndpoint());
// Path: src/de/uni_koblenz/west/splendid/VoidRepository.java // public class VoidRepository implements Repository { // // private static final Logger LOGGER = LoggerFactory.getLogger(VoidRepository.class); // // protected final ValueFactory vf = new ValueFactoryImpl(); // protected URI endpoint; // protected final URI voidURI; // // protected boolean initialized = false; // // public VoidRepository(VoidRepositoryConfig config) { // this.endpoint = config.getEndpoint(); // this.voidURI = config.getVoidURI(); // } // // public URI getEndpoint() { // return this.endpoint; // } // // // -------------------------------------------------------------- // // @Override // public void setDataDir(File dataDir) { // throw new UnsupportedOperationException("SPARQL endpoint repository has no data dir"); // } // // @Override // public File getDataDir() { // throw new UnsupportedOperationException("SPARQL endpoint repository has no data dir"); // } // // @Override // public boolean isWritable() throws RepositoryException { // return false; // } // // @Override // public ValueFactory getValueFactory() { // return this.vf; // } // // @Override // public void initialize() throws RepositoryException { // // if (this.initialized) { // LOGGER.info("Void repository has already been initialized"); // return; // } // // try { // this.endpoint = VoidStatistics.getInstance().load(this.voidURI, this.endpoint); // } catch (IOException e) { // throw new RepositoryException("can not read voiD description: " + this.voidURI + e.getMessage(), e); // } // // this.initialized = true; // } // // @Override // public void shutDown() throws RepositoryException { // // TODO: remove statistics from VOID repository? // } // // @Override // public RepositoryConnection getConnection() throws RepositoryException { // return new VoidRepositoryConnection(this); // } // // } // Path: src/de/uni_koblenz/west/splendid/config/VoidRepositoryFactory.java import org.openrdf.repository.Repository; import org.openrdf.repository.config.RepositoryConfigException; import org.openrdf.repository.config.RepositoryFactory; import org.openrdf.repository.config.RepositoryImplConfig; import de.uni_koblenz.west.splendid.VoidRepository; /* * This file is part of RDF Federator. * Copyright 2010 Olaf Goerlitz * * RDF Federator 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 3 of the License, or * (at your option) any later version. * * RDF Federator 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 RDF Federator. If not, see <http://www.gnu.org/licenses/>. * * RDF Federator uses libraries from the OpenRDF Sesame Project licensed * under the Aduna BSD-style license. */ package de.uni_koblenz.west.splendid.config; //import org.openrdf.store.StoreConfigException; /** * A {@link RepositoryFactory} that creates {@link VoidRepository}s * based on the supplied configuration data. * * ATTENTION: This factory must be published with full package name in * META-INF/services/org.openrdf.repository.config.RepositoryFactory * * @author Olaf Goerlitz */ public class VoidRepositoryFactory implements RepositoryFactory { /** * The type of repositories that are created by this factory. * * @see RepositoryFactory#getRepositoryType() */ public static final String REPOSITORY_TYPE = "west:VoidRepository"; /** * Returns the repository's type: <tt>west:VoidRepository</tt>. */ public String getRepositoryType() { return REPOSITORY_TYPE; } /** * Provides a repository configuration object for the configuration data. * * @return a {@link VoidRepositoryConfig}. */ public RepositoryImplConfig getConfig() { return new VoidRepositoryConfig(); } /** * Returns a Repository instance that has been initialized using the * supplied configuration data. * * @param config * the repository configuration. * @return The created (but un-initialized) repository. * @throws StoreConfigException * If no repository could be created due to invalid or * incomplete configuration data. */ @Override public Repository getRepository(RepositoryImplConfig config) throws RepositoryConfigException { if (!REPOSITORY_TYPE.equals(config.getType())) { throw new RepositoryConfigException("Invalid repository type: " + config.getType()); } assert config instanceof VoidRepositoryConfig; VoidRepositoryConfig repConfig = (VoidRepositoryConfig) config; // return new VoidRepository(repConfig.getVoidURI(), repConfig.getEndpoint());
return new VoidRepository(repConfig);
goerlitz/rdffederator
src/de/uni_koblenz/west/splendid/statistics/util/VoidGenerator.java
// Path: src/de/uni_koblenz/west/splendid/vocabulary/VOID2.java // public enum VOID2 { // // // concepts // Dataset, // Linkset, // EquiWidthHist, // EuqiDepthHist, // // // predicates // vocabulary, // sparqlEndpoint, // distinctSubjects, // distinctObjects, // triples, // classes, // entities, // properties, // classPartition, // clazz("class"), // propertyPartition, // property, // target, // linkPredicate, // // histogram, // minValue, // maxValue, // bucketLoad, // buckets, // bucketDef; // // public static final String NAMESPACE = "http://rdfs.org/ns/void#"; // // private final String uri; // // private VOID2(String name) { // this.uri = NAMESPACE + name; // } // // private VOID2() { // this.uri = NAMESPACE + super.toString(); // } // // public String toString() { // return this.uri; // } // // }
import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.zip.GZIPInputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import org.openrdf.model.BNode; import org.openrdf.model.Literal; import org.openrdf.model.Resource; import org.openrdf.model.Statement; import org.openrdf.model.URI; import org.openrdf.model.Value; import org.openrdf.model.ValueFactory; import org.openrdf.model.impl.ValueFactoryImpl; import org.openrdf.model.vocabulary.RDF; import org.openrdf.rio.RDFFormat; import org.openrdf.rio.RDFHandlerException; import org.openrdf.rio.RDFParseException; import org.openrdf.rio.RDFParser; import org.openrdf.rio.RDFWriter; import org.openrdf.rio.Rio; import org.openrdf.rio.helpers.RDFHandlerBase; import de.uni_koblenz.west.splendid.vocabulary.VOID2;
lastPredicate = predicate; } /** * Analyzes the last statements (which have the same subject) * and counts the predicates per type. */ private void processStoredStatements() { if (lastPredicate == null) return; predicates.add(lastPredicate); // TODO: write predicate statistics // System.out.println(lastPredicate + " [" + predCount + "], distS: " + distSubject.size() + ", distObj: " + distObject.size()); writePredicateStatToVoid(lastPredicate, predCount, distSubject.size(), distObject.size()); // clear stored values; distSubject.clear(); distObject.clear(); predCount = 0; } private void writePredicateStatToVoid(URI predicate, long pCount, int distS, int distO) { BNode propPartition = vf.createBNode(); Literal count = vf.createLiteral(String.valueOf(pCount)); Literal distinctS = vf.createLiteral(String.valueOf(distS)); Literal distinctO = vf.createLiteral(String.valueOf(distO)); try {
// Path: src/de/uni_koblenz/west/splendid/vocabulary/VOID2.java // public enum VOID2 { // // // concepts // Dataset, // Linkset, // EquiWidthHist, // EuqiDepthHist, // // // predicates // vocabulary, // sparqlEndpoint, // distinctSubjects, // distinctObjects, // triples, // classes, // entities, // properties, // classPartition, // clazz("class"), // propertyPartition, // property, // target, // linkPredicate, // // histogram, // minValue, // maxValue, // bucketLoad, // buckets, // bucketDef; // // public static final String NAMESPACE = "http://rdfs.org/ns/void#"; // // private final String uri; // // private VOID2(String name) { // this.uri = NAMESPACE + name; // } // // private VOID2() { // this.uri = NAMESPACE + super.toString(); // } // // public String toString() { // return this.uri; // } // // } // Path: src/de/uni_koblenz/west/splendid/statistics/util/VoidGenerator.java import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.zip.GZIPInputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import org.openrdf.model.BNode; import org.openrdf.model.Literal; import org.openrdf.model.Resource; import org.openrdf.model.Statement; import org.openrdf.model.URI; import org.openrdf.model.Value; import org.openrdf.model.ValueFactory; import org.openrdf.model.impl.ValueFactoryImpl; import org.openrdf.model.vocabulary.RDF; import org.openrdf.rio.RDFFormat; import org.openrdf.rio.RDFHandlerException; import org.openrdf.rio.RDFParseException; import org.openrdf.rio.RDFParser; import org.openrdf.rio.RDFWriter; import org.openrdf.rio.Rio; import org.openrdf.rio.helpers.RDFHandlerBase; import de.uni_koblenz.west.splendid.vocabulary.VOID2; lastPredicate = predicate; } /** * Analyzes the last statements (which have the same subject) * and counts the predicates per type. */ private void processStoredStatements() { if (lastPredicate == null) return; predicates.add(lastPredicate); // TODO: write predicate statistics // System.out.println(lastPredicate + " [" + predCount + "], distS: " + distSubject.size() + ", distObj: " + distObject.size()); writePredicateStatToVoid(lastPredicate, predCount, distSubject.size(), distObject.size()); // clear stored values; distSubject.clear(); distObject.clear(); predCount = 0; } private void writePredicateStatToVoid(URI predicate, long pCount, int distS, int distO) { BNode propPartition = vf.createBNode(); Literal count = vf.createLiteral(String.valueOf(pCount)); Literal distinctS = vf.createLiteral(String.valueOf(distS)); Literal distinctO = vf.createLiteral(String.valueOf(distO)); try {
writer.handleStatement(vf.createStatement(dataset, vf.createURI(VOID2.propertyPartition.toString()), propPartition));
goerlitz/rdffederator
src/de/uni_koblenz/west/splendid/config/FederationSailConfig.java
// Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI MEMBER = vf.createURI(NAMESPACE + "member"); // // Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI QUERY_OPT = vf.createURI(NAMESPACE + "queryOptimization"); // // Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI SRC_SELECTION = vf.createURI(NAMESPACE + "sourceSelection");
import org.openrdf.repository.config.RepositoryConfigException; import org.openrdf.repository.config.RepositoryImplConfig; import org.openrdf.repository.config.RepositoryImplConfigBase; import org.openrdf.sail.config.SailConfigException; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.MEMBER; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.QUERY_OPT; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.SRC_SELECTION; import java.util.ArrayList; import java.util.List; import org.openrdf.model.Graph; import org.openrdf.model.Resource; import org.openrdf.model.Value;
/* * This file is part of RDF Federator. * Copyright 2010 Olaf Goerlitz * * RDF Federator 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 3 of the License, or * (at your option) any later version. * * RDF Federator 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 RDF Federator. If not, see <http://www.gnu.org/licenses/>. * * RDF Federator uses libraries from the OpenRDF Sesame Project licensed * under the Aduna BSD-style license. */ package de.uni_koblenz.west.splendid.config; /** * Configuration details for federation setup including member descriptions. * * @author Olaf Goerlitz */ public class FederationSailConfig extends AbstractSailConfig { private static final String DEFAULT_SOURCE_SELECTION = "INDEX_ASK"; private static final String DEFAULT_OPTIMIZER_STRATEGY = "DYNAMIC_PROGRAMMING"; private final List<RepositoryImplConfig> memberConfig = new ArrayList<RepositoryImplConfig>(); private SourceSelectorConfig selectorConfig; private QueryOptimizerConfig optimizerConfig; /** * Returns the configuration settings of the federation members. * * @return the member repository configuration settings. */ public List<RepositoryImplConfig> getMemberConfigs() { return this.memberConfig; } /** * Returns the configuration settings of the source selector. * * @return the source selection configuration settings. */ public SourceSelectorConfig getSelectorConfig() { return this.selectorConfig; } public QueryOptimizerConfig getOptimizerConfig() { return this.optimizerConfig; } // ------------------------------------------------------------------------- /** * Adds all Sail configuration settings to a configuration model. * * @param model the configuration model to be filled. * @return the resource representing this Sail configuration. */ @Override public Resource export(Graph model) { Resource self = super.export(model); for (RepositoryImplConfig member : this.memberConfig) {
// Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI MEMBER = vf.createURI(NAMESPACE + "member"); // // Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI QUERY_OPT = vf.createURI(NAMESPACE + "queryOptimization"); // // Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI SRC_SELECTION = vf.createURI(NAMESPACE + "sourceSelection"); // Path: src/de/uni_koblenz/west/splendid/config/FederationSailConfig.java import org.openrdf.repository.config.RepositoryConfigException; import org.openrdf.repository.config.RepositoryImplConfig; import org.openrdf.repository.config.RepositoryImplConfigBase; import org.openrdf.sail.config.SailConfigException; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.MEMBER; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.QUERY_OPT; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.SRC_SELECTION; import java.util.ArrayList; import java.util.List; import org.openrdf.model.Graph; import org.openrdf.model.Resource; import org.openrdf.model.Value; /* * This file is part of RDF Federator. * Copyright 2010 Olaf Goerlitz * * RDF Federator 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 3 of the License, or * (at your option) any later version. * * RDF Federator 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 RDF Federator. If not, see <http://www.gnu.org/licenses/>. * * RDF Federator uses libraries from the OpenRDF Sesame Project licensed * under the Aduna BSD-style license. */ package de.uni_koblenz.west.splendid.config; /** * Configuration details for federation setup including member descriptions. * * @author Olaf Goerlitz */ public class FederationSailConfig extends AbstractSailConfig { private static final String DEFAULT_SOURCE_SELECTION = "INDEX_ASK"; private static final String DEFAULT_OPTIMIZER_STRATEGY = "DYNAMIC_PROGRAMMING"; private final List<RepositoryImplConfig> memberConfig = new ArrayList<RepositoryImplConfig>(); private SourceSelectorConfig selectorConfig; private QueryOptimizerConfig optimizerConfig; /** * Returns the configuration settings of the federation members. * * @return the member repository configuration settings. */ public List<RepositoryImplConfig> getMemberConfigs() { return this.memberConfig; } /** * Returns the configuration settings of the source selector. * * @return the source selection configuration settings. */ public SourceSelectorConfig getSelectorConfig() { return this.selectorConfig; } public QueryOptimizerConfig getOptimizerConfig() { return this.optimizerConfig; } // ------------------------------------------------------------------------- /** * Adds all Sail configuration settings to a configuration model. * * @param model the configuration model to be filled. * @return the resource representing this Sail configuration. */ @Override public Resource export(Graph model) { Resource self = super.export(model); for (RepositoryImplConfig member : this.memberConfig) {
model.add(self, MEMBER, member.export(model));
goerlitz/rdffederator
src/de/uni_koblenz/west/splendid/config/FederationSailConfig.java
// Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI MEMBER = vf.createURI(NAMESPACE + "member"); // // Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI QUERY_OPT = vf.createURI(NAMESPACE + "queryOptimization"); // // Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI SRC_SELECTION = vf.createURI(NAMESPACE + "sourceSelection");
import org.openrdf.repository.config.RepositoryConfigException; import org.openrdf.repository.config.RepositoryImplConfig; import org.openrdf.repository.config.RepositoryImplConfigBase; import org.openrdf.sail.config.SailConfigException; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.MEMBER; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.QUERY_OPT; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.SRC_SELECTION; import java.util.ArrayList; import java.util.List; import org.openrdf.model.Graph; import org.openrdf.model.Resource; import org.openrdf.model.Value;
/* * This file is part of RDF Federator. * Copyright 2010 Olaf Goerlitz * * RDF Federator 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 3 of the License, or * (at your option) any later version. * * RDF Federator 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 RDF Federator. If not, see <http://www.gnu.org/licenses/>. * * RDF Federator uses libraries from the OpenRDF Sesame Project licensed * under the Aduna BSD-style license. */ package de.uni_koblenz.west.splendid.config; /** * Configuration details for federation setup including member descriptions. * * @author Olaf Goerlitz */ public class FederationSailConfig extends AbstractSailConfig { private static final String DEFAULT_SOURCE_SELECTION = "INDEX_ASK"; private static final String DEFAULT_OPTIMIZER_STRATEGY = "DYNAMIC_PROGRAMMING"; private final List<RepositoryImplConfig> memberConfig = new ArrayList<RepositoryImplConfig>(); private SourceSelectorConfig selectorConfig; private QueryOptimizerConfig optimizerConfig; /** * Returns the configuration settings of the federation members. * * @return the member repository configuration settings. */ public List<RepositoryImplConfig> getMemberConfigs() { return this.memberConfig; } /** * Returns the configuration settings of the source selector. * * @return the source selection configuration settings. */ public SourceSelectorConfig getSelectorConfig() { return this.selectorConfig; } public QueryOptimizerConfig getOptimizerConfig() { return this.optimizerConfig; } // ------------------------------------------------------------------------- /** * Adds all Sail configuration settings to a configuration model. * * @param model the configuration model to be filled. * @return the resource representing this Sail configuration. */ @Override public Resource export(Graph model) { Resource self = super.export(model); for (RepositoryImplConfig member : this.memberConfig) { model.add(self, MEMBER, member.export(model)); }
// Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI MEMBER = vf.createURI(NAMESPACE + "member"); // // Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI QUERY_OPT = vf.createURI(NAMESPACE + "queryOptimization"); // // Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI SRC_SELECTION = vf.createURI(NAMESPACE + "sourceSelection"); // Path: src/de/uni_koblenz/west/splendid/config/FederationSailConfig.java import org.openrdf.repository.config.RepositoryConfigException; import org.openrdf.repository.config.RepositoryImplConfig; import org.openrdf.repository.config.RepositoryImplConfigBase; import org.openrdf.sail.config.SailConfigException; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.MEMBER; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.QUERY_OPT; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.SRC_SELECTION; import java.util.ArrayList; import java.util.List; import org.openrdf.model.Graph; import org.openrdf.model.Resource; import org.openrdf.model.Value; /* * This file is part of RDF Federator. * Copyright 2010 Olaf Goerlitz * * RDF Federator 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 3 of the License, or * (at your option) any later version. * * RDF Federator 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 RDF Federator. If not, see <http://www.gnu.org/licenses/>. * * RDF Federator uses libraries from the OpenRDF Sesame Project licensed * under the Aduna BSD-style license. */ package de.uni_koblenz.west.splendid.config; /** * Configuration details for federation setup including member descriptions. * * @author Olaf Goerlitz */ public class FederationSailConfig extends AbstractSailConfig { private static final String DEFAULT_SOURCE_SELECTION = "INDEX_ASK"; private static final String DEFAULT_OPTIMIZER_STRATEGY = "DYNAMIC_PROGRAMMING"; private final List<RepositoryImplConfig> memberConfig = new ArrayList<RepositoryImplConfig>(); private SourceSelectorConfig selectorConfig; private QueryOptimizerConfig optimizerConfig; /** * Returns the configuration settings of the federation members. * * @return the member repository configuration settings. */ public List<RepositoryImplConfig> getMemberConfigs() { return this.memberConfig; } /** * Returns the configuration settings of the source selector. * * @return the source selection configuration settings. */ public SourceSelectorConfig getSelectorConfig() { return this.selectorConfig; } public QueryOptimizerConfig getOptimizerConfig() { return this.optimizerConfig; } // ------------------------------------------------------------------------- /** * Adds all Sail configuration settings to a configuration model. * * @param model the configuration model to be filled. * @return the resource representing this Sail configuration. */ @Override public Resource export(Graph model) { Resource self = super.export(model); for (RepositoryImplConfig member : this.memberConfig) { model.add(self, MEMBER, member.export(model)); }
model.add(self, SRC_SELECTION, this.selectorConfig.export(model));
goerlitz/rdffederator
src/de/uni_koblenz/west/splendid/config/FederationSailConfig.java
// Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI MEMBER = vf.createURI(NAMESPACE + "member"); // // Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI QUERY_OPT = vf.createURI(NAMESPACE + "queryOptimization"); // // Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI SRC_SELECTION = vf.createURI(NAMESPACE + "sourceSelection");
import org.openrdf.repository.config.RepositoryConfigException; import org.openrdf.repository.config.RepositoryImplConfig; import org.openrdf.repository.config.RepositoryImplConfigBase; import org.openrdf.sail.config.SailConfigException; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.MEMBER; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.QUERY_OPT; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.SRC_SELECTION; import java.util.ArrayList; import java.util.List; import org.openrdf.model.Graph; import org.openrdf.model.Resource; import org.openrdf.model.Value;
/* * This file is part of RDF Federator. * Copyright 2010 Olaf Goerlitz * * RDF Federator 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 3 of the License, or * (at your option) any later version. * * RDF Federator 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 RDF Federator. If not, see <http://www.gnu.org/licenses/>. * * RDF Federator uses libraries from the OpenRDF Sesame Project licensed * under the Aduna BSD-style license. */ package de.uni_koblenz.west.splendid.config; /** * Configuration details for federation setup including member descriptions. * * @author Olaf Goerlitz */ public class FederationSailConfig extends AbstractSailConfig { private static final String DEFAULT_SOURCE_SELECTION = "INDEX_ASK"; private static final String DEFAULT_OPTIMIZER_STRATEGY = "DYNAMIC_PROGRAMMING"; private final List<RepositoryImplConfig> memberConfig = new ArrayList<RepositoryImplConfig>(); private SourceSelectorConfig selectorConfig; private QueryOptimizerConfig optimizerConfig; /** * Returns the configuration settings of the federation members. * * @return the member repository configuration settings. */ public List<RepositoryImplConfig> getMemberConfigs() { return this.memberConfig; } /** * Returns the configuration settings of the source selector. * * @return the source selection configuration settings. */ public SourceSelectorConfig getSelectorConfig() { return this.selectorConfig; } public QueryOptimizerConfig getOptimizerConfig() { return this.optimizerConfig; } // ------------------------------------------------------------------------- /** * Adds all Sail configuration settings to a configuration model. * * @param model the configuration model to be filled. * @return the resource representing this Sail configuration. */ @Override public Resource export(Graph model) { Resource self = super.export(model); for (RepositoryImplConfig member : this.memberConfig) { model.add(self, MEMBER, member.export(model)); } model.add(self, SRC_SELECTION, this.selectorConfig.export(model));
// Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI MEMBER = vf.createURI(NAMESPACE + "member"); // // Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI QUERY_OPT = vf.createURI(NAMESPACE + "queryOptimization"); // // Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI SRC_SELECTION = vf.createURI(NAMESPACE + "sourceSelection"); // Path: src/de/uni_koblenz/west/splendid/config/FederationSailConfig.java import org.openrdf.repository.config.RepositoryConfigException; import org.openrdf.repository.config.RepositoryImplConfig; import org.openrdf.repository.config.RepositoryImplConfigBase; import org.openrdf.sail.config.SailConfigException; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.MEMBER; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.QUERY_OPT; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.SRC_SELECTION; import java.util.ArrayList; import java.util.List; import org.openrdf.model.Graph; import org.openrdf.model.Resource; import org.openrdf.model.Value; /* * This file is part of RDF Federator. * Copyright 2010 Olaf Goerlitz * * RDF Federator 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 3 of the License, or * (at your option) any later version. * * RDF Federator 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 RDF Federator. If not, see <http://www.gnu.org/licenses/>. * * RDF Federator uses libraries from the OpenRDF Sesame Project licensed * under the Aduna BSD-style license. */ package de.uni_koblenz.west.splendid.config; /** * Configuration details for federation setup including member descriptions. * * @author Olaf Goerlitz */ public class FederationSailConfig extends AbstractSailConfig { private static final String DEFAULT_SOURCE_SELECTION = "INDEX_ASK"; private static final String DEFAULT_OPTIMIZER_STRATEGY = "DYNAMIC_PROGRAMMING"; private final List<RepositoryImplConfig> memberConfig = new ArrayList<RepositoryImplConfig>(); private SourceSelectorConfig selectorConfig; private QueryOptimizerConfig optimizerConfig; /** * Returns the configuration settings of the federation members. * * @return the member repository configuration settings. */ public List<RepositoryImplConfig> getMemberConfigs() { return this.memberConfig; } /** * Returns the configuration settings of the source selector. * * @return the source selection configuration settings. */ public SourceSelectorConfig getSelectorConfig() { return this.selectorConfig; } public QueryOptimizerConfig getOptimizerConfig() { return this.optimizerConfig; } // ------------------------------------------------------------------------- /** * Adds all Sail configuration settings to a configuration model. * * @param model the configuration model to be filled. * @return the resource representing this Sail configuration. */ @Override public Resource export(Graph model) { Resource self = super.export(model); for (RepositoryImplConfig member : this.memberConfig) { model.add(self, MEMBER, member.export(model)); } model.add(self, SRC_SELECTION, this.selectorConfig.export(model));
model.add(self, QUERY_OPT, this.optimizerConfig.export(model));
goerlitz/rdffederator
src/de/uni_koblenz/west/splendid/sources/SourceSelector.java
// Path: src/de/uni_koblenz/west/splendid/model/MappedStatementPattern.java // public class MappedStatementPattern extends StatementPattern { // // private Set<Graph> sources = new HashSet<Graph>(); // // public MappedStatementPattern(StatementPattern pattern, Set<Graph> sources) { // super(pattern.getScope(), pattern.getSubjectVar(), pattern.getPredicateVar(), pattern.getObjectVar(), pattern.getContextVar()); // this.setSources(sources); // } // // public Set<Graph> getSources() { // return sources; // } // // public void setSources(Set<Graph> sources) { // if (sources == null) // throw new IllegalArgumentException("source set is null"); // this.sources = sources; // } // // public void addSource(Graph source) { // this.sources.add(source); // } // // public boolean removeSource(Graph source) { // return this.sources.remove(source); // } // // // ------------------------------------------------------------------------- // // @Override // public <X extends Exception> void visit(QueryModelVisitor<X> visitor) // throws X { // visitor.meet(this); // } // // @Override // public String toString() { // return OperatorTreePrinter.print(this); // } // // } // // Path: src/de/uni_koblenz/west/splendid/statistics/RDFStatistics.java // public interface RDFStatistics { // // /** // * Returns a set of data sources which can potentially return results for the supplied s, p, o values. // * // * @param sValue subject value. // * @param pValue predicate value. // * @param oValue object value. // * @param handleType defines whether rdf:type definitions should be evaluated. TODO: should not be method parameter. // * @return the set of matched data sources. // */ // public Set<Graph> findSources(String sValue, String pValue, String oValue, boolean handleType); // // /** // * Returns the number of triples in a data source. // * // * @param g the data source. // * @return the number of triples. // */ // public long getTripleCount(Graph g); // // /** // * Returns the number of triples with the specified predicate in a data source. // * // * @param g the data source. // * @param predicate the predicate. // * @return the number of triples. // */ // public long getPredicateCount(Graph g, String predicate); // // /** // * Returns the number of triples with rdf:type definition of the specified type in a data source. // * // * @param g the data source. // * @param type the desired type. // * @return the number of triples. // */ // public long getTypeCount(Graph g, String type); // // /** // * Returns the number of distinct predicates in a data source. // * // * @param g the data source. // * @return the number of distinct predicates. // */ // public long getDistinctPredicates(Graph g); // // /** // * Returns the number of distinct subjects in a data source. // * // * @param g the data source. // * @return the number of distinct subjects. // */ // public long getDistinctSubjects(Graph g); // // /** // * Returns the number of distinct subjects in a data source // * which occur in triples with the specified predicate. // * // * @param g the data source. // * @param predicate the predicate which occurs with the subjects. // * @return the number of distinct subjects. // */ // public long getDistinctSubjects(Graph g, String predicate); // // /** // * Returns the number of distinct objects in a data source. // * // * @param g the data source. // * @return the number of distinct objects. // */ // public long getDistinctObjects(Graph g); // // /** // * Returns the number of distinct subjects in a data source // * which occur in triples with the specified predicate. // * // * @param g the data source. // * @param predicate the predicate which occurs with the subjects. // * @return the number of distinct subjects. // */ // public long getDistinctObjects(Graph g, String predicate); // // }
import java.util.List; import org.openrdf.query.algebra.StatementPattern; import org.openrdf.sail.SailException; import de.uni_koblenz.west.splendid.model.MappedStatementPattern; import de.uni_koblenz.west.splendid.statistics.RDFStatistics;
/* * This file is part of RDF Federator. * Copyright 2011 Olaf Goerlitz * * RDF Federator 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 3 of the License, or * (at your option) any later version. * * RDF Federator 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 RDF Federator. If not, see <http://www.gnu.org/licenses/>. * * RDF Federator uses libraries from the OpenRDF Sesame Project licensed * under the Aduna BSD-style license. */ package de.uni_koblenz.west.splendid.sources; /** * Interface for source selection strategies. * * @author Olaf Goerlitz */ public interface SourceSelector { public void initialize() throws SailException;
// Path: src/de/uni_koblenz/west/splendid/model/MappedStatementPattern.java // public class MappedStatementPattern extends StatementPattern { // // private Set<Graph> sources = new HashSet<Graph>(); // // public MappedStatementPattern(StatementPattern pattern, Set<Graph> sources) { // super(pattern.getScope(), pattern.getSubjectVar(), pattern.getPredicateVar(), pattern.getObjectVar(), pattern.getContextVar()); // this.setSources(sources); // } // // public Set<Graph> getSources() { // return sources; // } // // public void setSources(Set<Graph> sources) { // if (sources == null) // throw new IllegalArgumentException("source set is null"); // this.sources = sources; // } // // public void addSource(Graph source) { // this.sources.add(source); // } // // public boolean removeSource(Graph source) { // return this.sources.remove(source); // } // // // ------------------------------------------------------------------------- // // @Override // public <X extends Exception> void visit(QueryModelVisitor<X> visitor) // throws X { // visitor.meet(this); // } // // @Override // public String toString() { // return OperatorTreePrinter.print(this); // } // // } // // Path: src/de/uni_koblenz/west/splendid/statistics/RDFStatistics.java // public interface RDFStatistics { // // /** // * Returns a set of data sources which can potentially return results for the supplied s, p, o values. // * // * @param sValue subject value. // * @param pValue predicate value. // * @param oValue object value. // * @param handleType defines whether rdf:type definitions should be evaluated. TODO: should not be method parameter. // * @return the set of matched data sources. // */ // public Set<Graph> findSources(String sValue, String pValue, String oValue, boolean handleType); // // /** // * Returns the number of triples in a data source. // * // * @param g the data source. // * @return the number of triples. // */ // public long getTripleCount(Graph g); // // /** // * Returns the number of triples with the specified predicate in a data source. // * // * @param g the data source. // * @param predicate the predicate. // * @return the number of triples. // */ // public long getPredicateCount(Graph g, String predicate); // // /** // * Returns the number of triples with rdf:type definition of the specified type in a data source. // * // * @param g the data source. // * @param type the desired type. // * @return the number of triples. // */ // public long getTypeCount(Graph g, String type); // // /** // * Returns the number of distinct predicates in a data source. // * // * @param g the data source. // * @return the number of distinct predicates. // */ // public long getDistinctPredicates(Graph g); // // /** // * Returns the number of distinct subjects in a data source. // * // * @param g the data source. // * @return the number of distinct subjects. // */ // public long getDistinctSubjects(Graph g); // // /** // * Returns the number of distinct subjects in a data source // * which occur in triples with the specified predicate. // * // * @param g the data source. // * @param predicate the predicate which occurs with the subjects. // * @return the number of distinct subjects. // */ // public long getDistinctSubjects(Graph g, String predicate); // // /** // * Returns the number of distinct objects in a data source. // * // * @param g the data source. // * @return the number of distinct objects. // */ // public long getDistinctObjects(Graph g); // // /** // * Returns the number of distinct subjects in a data source // * which occur in triples with the specified predicate. // * // * @param g the data source. // * @param predicate the predicate which occurs with the subjects. // * @return the number of distinct subjects. // */ // public long getDistinctObjects(Graph g, String predicate); // // } // Path: src/de/uni_koblenz/west/splendid/sources/SourceSelector.java import java.util.List; import org.openrdf.query.algebra.StatementPattern; import org.openrdf.sail.SailException; import de.uni_koblenz.west.splendid.model.MappedStatementPattern; import de.uni_koblenz.west.splendid.statistics.RDFStatistics; /* * This file is part of RDF Federator. * Copyright 2011 Olaf Goerlitz * * RDF Federator 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 3 of the License, or * (at your option) any later version. * * RDF Federator 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 RDF Federator. If not, see <http://www.gnu.org/licenses/>. * * RDF Federator uses libraries from the OpenRDF Sesame Project licensed * under the Aduna BSD-style license. */ package de.uni_koblenz.west.splendid.sources; /** * Interface for source selection strategies. * * @author Olaf Goerlitz */ public interface SourceSelector { public void initialize() throws SailException;
public void setStatistics(RDFStatistics stats);
goerlitz/rdffederator
src/de/uni_koblenz/west/splendid/sources/SourceSelector.java
// Path: src/de/uni_koblenz/west/splendid/model/MappedStatementPattern.java // public class MappedStatementPattern extends StatementPattern { // // private Set<Graph> sources = new HashSet<Graph>(); // // public MappedStatementPattern(StatementPattern pattern, Set<Graph> sources) { // super(pattern.getScope(), pattern.getSubjectVar(), pattern.getPredicateVar(), pattern.getObjectVar(), pattern.getContextVar()); // this.setSources(sources); // } // // public Set<Graph> getSources() { // return sources; // } // // public void setSources(Set<Graph> sources) { // if (sources == null) // throw new IllegalArgumentException("source set is null"); // this.sources = sources; // } // // public void addSource(Graph source) { // this.sources.add(source); // } // // public boolean removeSource(Graph source) { // return this.sources.remove(source); // } // // // ------------------------------------------------------------------------- // // @Override // public <X extends Exception> void visit(QueryModelVisitor<X> visitor) // throws X { // visitor.meet(this); // } // // @Override // public String toString() { // return OperatorTreePrinter.print(this); // } // // } // // Path: src/de/uni_koblenz/west/splendid/statistics/RDFStatistics.java // public interface RDFStatistics { // // /** // * Returns a set of data sources which can potentially return results for the supplied s, p, o values. // * // * @param sValue subject value. // * @param pValue predicate value. // * @param oValue object value. // * @param handleType defines whether rdf:type definitions should be evaluated. TODO: should not be method parameter. // * @return the set of matched data sources. // */ // public Set<Graph> findSources(String sValue, String pValue, String oValue, boolean handleType); // // /** // * Returns the number of triples in a data source. // * // * @param g the data source. // * @return the number of triples. // */ // public long getTripleCount(Graph g); // // /** // * Returns the number of triples with the specified predicate in a data source. // * // * @param g the data source. // * @param predicate the predicate. // * @return the number of triples. // */ // public long getPredicateCount(Graph g, String predicate); // // /** // * Returns the number of triples with rdf:type definition of the specified type in a data source. // * // * @param g the data source. // * @param type the desired type. // * @return the number of triples. // */ // public long getTypeCount(Graph g, String type); // // /** // * Returns the number of distinct predicates in a data source. // * // * @param g the data source. // * @return the number of distinct predicates. // */ // public long getDistinctPredicates(Graph g); // // /** // * Returns the number of distinct subjects in a data source. // * // * @param g the data source. // * @return the number of distinct subjects. // */ // public long getDistinctSubjects(Graph g); // // /** // * Returns the number of distinct subjects in a data source // * which occur in triples with the specified predicate. // * // * @param g the data source. // * @param predicate the predicate which occurs with the subjects. // * @return the number of distinct subjects. // */ // public long getDistinctSubjects(Graph g, String predicate); // // /** // * Returns the number of distinct objects in a data source. // * // * @param g the data source. // * @return the number of distinct objects. // */ // public long getDistinctObjects(Graph g); // // /** // * Returns the number of distinct subjects in a data source // * which occur in triples with the specified predicate. // * // * @param g the data source. // * @param predicate the predicate which occurs with the subjects. // * @return the number of distinct subjects. // */ // public long getDistinctObjects(Graph g, String predicate); // // }
import java.util.List; import org.openrdf.query.algebra.StatementPattern; import org.openrdf.sail.SailException; import de.uni_koblenz.west.splendid.model.MappedStatementPattern; import de.uni_koblenz.west.splendid.statistics.RDFStatistics;
/* * This file is part of RDF Federator. * Copyright 2011 Olaf Goerlitz * * RDF Federator 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 3 of the License, or * (at your option) any later version. * * RDF Federator 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 RDF Federator. If not, see <http://www.gnu.org/licenses/>. * * RDF Federator uses libraries from the OpenRDF Sesame Project licensed * under the Aduna BSD-style license. */ package de.uni_koblenz.west.splendid.sources; /** * Interface for source selection strategies. * * @author Olaf Goerlitz */ public interface SourceSelector { public void initialize() throws SailException; public void setStatistics(RDFStatistics stats); /** * Maps triple patterns to data sources which can contribute results. * * @param patterns the SPARQL triple patterns which need to be mapped. * @return a list triple patterns with mappings to sources. */
// Path: src/de/uni_koblenz/west/splendid/model/MappedStatementPattern.java // public class MappedStatementPattern extends StatementPattern { // // private Set<Graph> sources = new HashSet<Graph>(); // // public MappedStatementPattern(StatementPattern pattern, Set<Graph> sources) { // super(pattern.getScope(), pattern.getSubjectVar(), pattern.getPredicateVar(), pattern.getObjectVar(), pattern.getContextVar()); // this.setSources(sources); // } // // public Set<Graph> getSources() { // return sources; // } // // public void setSources(Set<Graph> sources) { // if (sources == null) // throw new IllegalArgumentException("source set is null"); // this.sources = sources; // } // // public void addSource(Graph source) { // this.sources.add(source); // } // // public boolean removeSource(Graph source) { // return this.sources.remove(source); // } // // // ------------------------------------------------------------------------- // // @Override // public <X extends Exception> void visit(QueryModelVisitor<X> visitor) // throws X { // visitor.meet(this); // } // // @Override // public String toString() { // return OperatorTreePrinter.print(this); // } // // } // // Path: src/de/uni_koblenz/west/splendid/statistics/RDFStatistics.java // public interface RDFStatistics { // // /** // * Returns a set of data sources which can potentially return results for the supplied s, p, o values. // * // * @param sValue subject value. // * @param pValue predicate value. // * @param oValue object value. // * @param handleType defines whether rdf:type definitions should be evaluated. TODO: should not be method parameter. // * @return the set of matched data sources. // */ // public Set<Graph> findSources(String sValue, String pValue, String oValue, boolean handleType); // // /** // * Returns the number of triples in a data source. // * // * @param g the data source. // * @return the number of triples. // */ // public long getTripleCount(Graph g); // // /** // * Returns the number of triples with the specified predicate in a data source. // * // * @param g the data source. // * @param predicate the predicate. // * @return the number of triples. // */ // public long getPredicateCount(Graph g, String predicate); // // /** // * Returns the number of triples with rdf:type definition of the specified type in a data source. // * // * @param g the data source. // * @param type the desired type. // * @return the number of triples. // */ // public long getTypeCount(Graph g, String type); // // /** // * Returns the number of distinct predicates in a data source. // * // * @param g the data source. // * @return the number of distinct predicates. // */ // public long getDistinctPredicates(Graph g); // // /** // * Returns the number of distinct subjects in a data source. // * // * @param g the data source. // * @return the number of distinct subjects. // */ // public long getDistinctSubjects(Graph g); // // /** // * Returns the number of distinct subjects in a data source // * which occur in triples with the specified predicate. // * // * @param g the data source. // * @param predicate the predicate which occurs with the subjects. // * @return the number of distinct subjects. // */ // public long getDistinctSubjects(Graph g, String predicate); // // /** // * Returns the number of distinct objects in a data source. // * // * @param g the data source. // * @return the number of distinct objects. // */ // public long getDistinctObjects(Graph g); // // /** // * Returns the number of distinct subjects in a data source // * which occur in triples with the specified predicate. // * // * @param g the data source. // * @param predicate the predicate which occurs with the subjects. // * @return the number of distinct subjects. // */ // public long getDistinctObjects(Graph g, String predicate); // // } // Path: src/de/uni_koblenz/west/splendid/sources/SourceSelector.java import java.util.List; import org.openrdf.query.algebra.StatementPattern; import org.openrdf.sail.SailException; import de.uni_koblenz.west.splendid.model.MappedStatementPattern; import de.uni_koblenz.west.splendid.statistics.RDFStatistics; /* * This file is part of RDF Federator. * Copyright 2011 Olaf Goerlitz * * RDF Federator 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 3 of the License, or * (at your option) any later version. * * RDF Federator 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 RDF Federator. If not, see <http://www.gnu.org/licenses/>. * * RDF Federator uses libraries from the OpenRDF Sesame Project licensed * under the Aduna BSD-style license. */ package de.uni_koblenz.west.splendid.sources; /** * Interface for source selection strategies. * * @author Olaf Goerlitz */ public interface SourceSelector { public void initialize() throws SailException; public void setStatistics(RDFStatistics stats); /** * Maps triple patterns to data sources which can contribute results. * * @param patterns the SPARQL triple patterns which need to be mapped. * @return a list triple patterns with mappings to sources. */
public List<MappedStatementPattern> mapSources(List<StatementPattern> patterns);
goerlitz/rdffederator
src/de/uni_koblenz/west/splendid/sources/IndexAskSelector.java
// Path: src/de/uni_koblenz/west/splendid/index/Graph.java // public class Graph { // // String name; // // public Graph(String name) { // this.name = name; // } // // @Override // public boolean equals(Object object) { // if (object instanceof Graph) // return this.name.equals(((Graph) object).name); // return false; // } // // @Override // public int hashCode() { // return this.name.hashCode(); // } // // public String toString() { // return this.name; // } // // public String getNamespaceURL() { // // TODO: implement proper hamespace handling // return this.name.replaceFirst("http://lodse.west.uni-koblenz.de:8080/openrdf-sesame/repositories/", "west:"); // } // // } // // Path: src/de/uni_koblenz/west/splendid/statistics/RDFStatistics.java // public interface RDFStatistics { // // /** // * Returns a set of data sources which can potentially return results for the supplied s, p, o values. // * // * @param sValue subject value. // * @param pValue predicate value. // * @param oValue object value. // * @param handleType defines whether rdf:type definitions should be evaluated. TODO: should not be method parameter. // * @return the set of matched data sources. // */ // public Set<Graph> findSources(String sValue, String pValue, String oValue, boolean handleType); // // /** // * Returns the number of triples in a data source. // * // * @param g the data source. // * @return the number of triples. // */ // public long getTripleCount(Graph g); // // /** // * Returns the number of triples with the specified predicate in a data source. // * // * @param g the data source. // * @param predicate the predicate. // * @return the number of triples. // */ // public long getPredicateCount(Graph g, String predicate); // // /** // * Returns the number of triples with rdf:type definition of the specified type in a data source. // * // * @param g the data source. // * @param type the desired type. // * @return the number of triples. // */ // public long getTypeCount(Graph g, String type); // // /** // * Returns the number of distinct predicates in a data source. // * // * @param g the data source. // * @return the number of distinct predicates. // */ // public long getDistinctPredicates(Graph g); // // /** // * Returns the number of distinct subjects in a data source. // * // * @param g the data source. // * @return the number of distinct subjects. // */ // public long getDistinctSubjects(Graph g); // // /** // * Returns the number of distinct subjects in a data source // * which occur in triples with the specified predicate. // * // * @param g the data source. // * @param predicate the predicate which occurs with the subjects. // * @return the number of distinct subjects. // */ // public long getDistinctSubjects(Graph g, String predicate); // // /** // * Returns the number of distinct objects in a data source. // * // * @param g the data source. // * @return the number of distinct objects. // */ // public long getDistinctObjects(Graph g); // // /** // * Returns the number of distinct subjects in a data source // * which occur in triples with the specified predicate. // * // * @param g the data source. // * @param predicate the predicate which occurs with the subjects. // * @return the number of distinct subjects. // */ // public long getDistinctObjects(Graph g, String predicate); // // }
import org.openrdf.query.algebra.StatementPattern; import de.uni_koblenz.west.splendid.index.Graph; import de.uni_koblenz.west.splendid.statistics.RDFStatistics; import java.util.Set;
/* * This file is part of RDF Federator. * Copyright 2011 Olaf Goerlitz * * RDF Federator 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 3 of the License, or * (at your option) any later version. * * RDF Federator 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 RDF Federator. If not, see <http://www.gnu.org/licenses/>. * * RDF Federator uses libraries from the OpenRDF Sesame Project licensed * under the Aduna BSD-style license. */ package de.uni_koblenz.west.splendid.sources; /** * A source selector which first uses the index to find data sources which can * return results and then contacts the SPARQL Endpoints asking them if they * can really return results for a triple pattern. * * @author Olaf Goerlitz */ public class IndexAskSelector extends AskSelector { private IndexSelector indexSel; /** * Creates a source finder using the supplied statistics and sources. * * @param stats the statistics to use. */ public IndexAskSelector(boolean useTypeStats) { this.indexSel = new IndexSelector(useTypeStats); } @Override
// Path: src/de/uni_koblenz/west/splendid/index/Graph.java // public class Graph { // // String name; // // public Graph(String name) { // this.name = name; // } // // @Override // public boolean equals(Object object) { // if (object instanceof Graph) // return this.name.equals(((Graph) object).name); // return false; // } // // @Override // public int hashCode() { // return this.name.hashCode(); // } // // public String toString() { // return this.name; // } // // public String getNamespaceURL() { // // TODO: implement proper hamespace handling // return this.name.replaceFirst("http://lodse.west.uni-koblenz.de:8080/openrdf-sesame/repositories/", "west:"); // } // // } // // Path: src/de/uni_koblenz/west/splendid/statistics/RDFStatistics.java // public interface RDFStatistics { // // /** // * Returns a set of data sources which can potentially return results for the supplied s, p, o values. // * // * @param sValue subject value. // * @param pValue predicate value. // * @param oValue object value. // * @param handleType defines whether rdf:type definitions should be evaluated. TODO: should not be method parameter. // * @return the set of matched data sources. // */ // public Set<Graph> findSources(String sValue, String pValue, String oValue, boolean handleType); // // /** // * Returns the number of triples in a data source. // * // * @param g the data source. // * @return the number of triples. // */ // public long getTripleCount(Graph g); // // /** // * Returns the number of triples with the specified predicate in a data source. // * // * @param g the data source. // * @param predicate the predicate. // * @return the number of triples. // */ // public long getPredicateCount(Graph g, String predicate); // // /** // * Returns the number of triples with rdf:type definition of the specified type in a data source. // * // * @param g the data source. // * @param type the desired type. // * @return the number of triples. // */ // public long getTypeCount(Graph g, String type); // // /** // * Returns the number of distinct predicates in a data source. // * // * @param g the data source. // * @return the number of distinct predicates. // */ // public long getDistinctPredicates(Graph g); // // /** // * Returns the number of distinct subjects in a data source. // * // * @param g the data source. // * @return the number of distinct subjects. // */ // public long getDistinctSubjects(Graph g); // // /** // * Returns the number of distinct subjects in a data source // * which occur in triples with the specified predicate. // * // * @param g the data source. // * @param predicate the predicate which occurs with the subjects. // * @return the number of distinct subjects. // */ // public long getDistinctSubjects(Graph g, String predicate); // // /** // * Returns the number of distinct objects in a data source. // * // * @param g the data source. // * @return the number of distinct objects. // */ // public long getDistinctObjects(Graph g); // // /** // * Returns the number of distinct subjects in a data source // * which occur in triples with the specified predicate. // * // * @param g the data source. // * @param predicate the predicate which occurs with the subjects. // * @return the number of distinct subjects. // */ // public long getDistinctObjects(Graph g, String predicate); // // } // Path: src/de/uni_koblenz/west/splendid/sources/IndexAskSelector.java import org.openrdf.query.algebra.StatementPattern; import de.uni_koblenz.west.splendid.index.Graph; import de.uni_koblenz.west.splendid.statistics.RDFStatistics; import java.util.Set; /* * This file is part of RDF Federator. * Copyright 2011 Olaf Goerlitz * * RDF Federator 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 3 of the License, or * (at your option) any later version. * * RDF Federator 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 RDF Federator. If not, see <http://www.gnu.org/licenses/>. * * RDF Federator uses libraries from the OpenRDF Sesame Project licensed * under the Aduna BSD-style license. */ package de.uni_koblenz.west.splendid.sources; /** * A source selector which first uses the index to find data sources which can * return results and then contacts the SPARQL Endpoints asking them if they * can really return results for a triple pattern. * * @author Olaf Goerlitz */ public class IndexAskSelector extends AskSelector { private IndexSelector indexSel; /** * Creates a source finder using the supplied statistics and sources. * * @param stats the statistics to use. */ public IndexAskSelector(boolean useTypeStats) { this.indexSel = new IndexSelector(useTypeStats); } @Override
public void setStatistics(RDFStatistics stats) {
goerlitz/rdffederator
src/de/uni_koblenz/west/splendid/sources/IndexAskSelector.java
// Path: src/de/uni_koblenz/west/splendid/index/Graph.java // public class Graph { // // String name; // // public Graph(String name) { // this.name = name; // } // // @Override // public boolean equals(Object object) { // if (object instanceof Graph) // return this.name.equals(((Graph) object).name); // return false; // } // // @Override // public int hashCode() { // return this.name.hashCode(); // } // // public String toString() { // return this.name; // } // // public String getNamespaceURL() { // // TODO: implement proper hamespace handling // return this.name.replaceFirst("http://lodse.west.uni-koblenz.de:8080/openrdf-sesame/repositories/", "west:"); // } // // } // // Path: src/de/uni_koblenz/west/splendid/statistics/RDFStatistics.java // public interface RDFStatistics { // // /** // * Returns a set of data sources which can potentially return results for the supplied s, p, o values. // * // * @param sValue subject value. // * @param pValue predicate value. // * @param oValue object value. // * @param handleType defines whether rdf:type definitions should be evaluated. TODO: should not be method parameter. // * @return the set of matched data sources. // */ // public Set<Graph> findSources(String sValue, String pValue, String oValue, boolean handleType); // // /** // * Returns the number of triples in a data source. // * // * @param g the data source. // * @return the number of triples. // */ // public long getTripleCount(Graph g); // // /** // * Returns the number of triples with the specified predicate in a data source. // * // * @param g the data source. // * @param predicate the predicate. // * @return the number of triples. // */ // public long getPredicateCount(Graph g, String predicate); // // /** // * Returns the number of triples with rdf:type definition of the specified type in a data source. // * // * @param g the data source. // * @param type the desired type. // * @return the number of triples. // */ // public long getTypeCount(Graph g, String type); // // /** // * Returns the number of distinct predicates in a data source. // * // * @param g the data source. // * @return the number of distinct predicates. // */ // public long getDistinctPredicates(Graph g); // // /** // * Returns the number of distinct subjects in a data source. // * // * @param g the data source. // * @return the number of distinct subjects. // */ // public long getDistinctSubjects(Graph g); // // /** // * Returns the number of distinct subjects in a data source // * which occur in triples with the specified predicate. // * // * @param g the data source. // * @param predicate the predicate which occurs with the subjects. // * @return the number of distinct subjects. // */ // public long getDistinctSubjects(Graph g, String predicate); // // /** // * Returns the number of distinct objects in a data source. // * // * @param g the data source. // * @return the number of distinct objects. // */ // public long getDistinctObjects(Graph g); // // /** // * Returns the number of distinct subjects in a data source // * which occur in triples with the specified predicate. // * // * @param g the data source. // * @param predicate the predicate which occurs with the subjects. // * @return the number of distinct subjects. // */ // public long getDistinctObjects(Graph g, String predicate); // // }
import org.openrdf.query.algebra.StatementPattern; import de.uni_koblenz.west.splendid.index.Graph; import de.uni_koblenz.west.splendid.statistics.RDFStatistics; import java.util.Set;
/* * This file is part of RDF Federator. * Copyright 2011 Olaf Goerlitz * * RDF Federator 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 3 of the License, or * (at your option) any later version. * * RDF Federator 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 RDF Federator. If not, see <http://www.gnu.org/licenses/>. * * RDF Federator uses libraries from the OpenRDF Sesame Project licensed * under the Aduna BSD-style license. */ package de.uni_koblenz.west.splendid.sources; /** * A source selector which first uses the index to find data sources which can * return results and then contacts the SPARQL Endpoints asking them if they * can really return results for a triple pattern. * * @author Olaf Goerlitz */ public class IndexAskSelector extends AskSelector { private IndexSelector indexSel; /** * Creates a source finder using the supplied statistics and sources. * * @param stats the statistics to use. */ public IndexAskSelector(boolean useTypeStats) { this.indexSel = new IndexSelector(useTypeStats); } @Override public void setStatistics(RDFStatistics stats) { super.setStatistics(stats); this.indexSel.setStatistics(stats); } @Override
// Path: src/de/uni_koblenz/west/splendid/index/Graph.java // public class Graph { // // String name; // // public Graph(String name) { // this.name = name; // } // // @Override // public boolean equals(Object object) { // if (object instanceof Graph) // return this.name.equals(((Graph) object).name); // return false; // } // // @Override // public int hashCode() { // return this.name.hashCode(); // } // // public String toString() { // return this.name; // } // // public String getNamespaceURL() { // // TODO: implement proper hamespace handling // return this.name.replaceFirst("http://lodse.west.uni-koblenz.de:8080/openrdf-sesame/repositories/", "west:"); // } // // } // // Path: src/de/uni_koblenz/west/splendid/statistics/RDFStatistics.java // public interface RDFStatistics { // // /** // * Returns a set of data sources which can potentially return results for the supplied s, p, o values. // * // * @param sValue subject value. // * @param pValue predicate value. // * @param oValue object value. // * @param handleType defines whether rdf:type definitions should be evaluated. TODO: should not be method parameter. // * @return the set of matched data sources. // */ // public Set<Graph> findSources(String sValue, String pValue, String oValue, boolean handleType); // // /** // * Returns the number of triples in a data source. // * // * @param g the data source. // * @return the number of triples. // */ // public long getTripleCount(Graph g); // // /** // * Returns the number of triples with the specified predicate in a data source. // * // * @param g the data source. // * @param predicate the predicate. // * @return the number of triples. // */ // public long getPredicateCount(Graph g, String predicate); // // /** // * Returns the number of triples with rdf:type definition of the specified type in a data source. // * // * @param g the data source. // * @param type the desired type. // * @return the number of triples. // */ // public long getTypeCount(Graph g, String type); // // /** // * Returns the number of distinct predicates in a data source. // * // * @param g the data source. // * @return the number of distinct predicates. // */ // public long getDistinctPredicates(Graph g); // // /** // * Returns the number of distinct subjects in a data source. // * // * @param g the data source. // * @return the number of distinct subjects. // */ // public long getDistinctSubjects(Graph g); // // /** // * Returns the number of distinct subjects in a data source // * which occur in triples with the specified predicate. // * // * @param g the data source. // * @param predicate the predicate which occurs with the subjects. // * @return the number of distinct subjects. // */ // public long getDistinctSubjects(Graph g, String predicate); // // /** // * Returns the number of distinct objects in a data source. // * // * @param g the data source. // * @return the number of distinct objects. // */ // public long getDistinctObjects(Graph g); // // /** // * Returns the number of distinct subjects in a data source // * which occur in triples with the specified predicate. // * // * @param g the data source. // * @param predicate the predicate which occurs with the subjects. // * @return the number of distinct subjects. // */ // public long getDistinctObjects(Graph g, String predicate); // // } // Path: src/de/uni_koblenz/west/splendid/sources/IndexAskSelector.java import org.openrdf.query.algebra.StatementPattern; import de.uni_koblenz.west.splendid.index.Graph; import de.uni_koblenz.west.splendid.statistics.RDFStatistics; import java.util.Set; /* * This file is part of RDF Federator. * Copyright 2011 Olaf Goerlitz * * RDF Federator 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 3 of the License, or * (at your option) any later version. * * RDF Federator 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 RDF Federator. If not, see <http://www.gnu.org/licenses/>. * * RDF Federator uses libraries from the OpenRDF Sesame Project licensed * under the Aduna BSD-style license. */ package de.uni_koblenz.west.splendid.sources; /** * A source selector which first uses the index to find data sources which can * return results and then contacts the SPARQL Endpoints asking them if they * can really return results for a triple pattern. * * @author Olaf Goerlitz */ public class IndexAskSelector extends AskSelector { private IndexSelector indexSel; /** * Creates a source finder using the supplied statistics and sources. * * @param stats the statistics to use. */ public IndexAskSelector(boolean useTypeStats) { this.indexSel = new IndexSelector(useTypeStats); } @Override public void setStatistics(RDFStatistics stats) { super.setStatistics(stats); this.indexSel.setStatistics(stats); } @Override
protected Set<Graph> getSources(StatementPattern pattern) {
goerlitz/rdffederator
src/de/uni_koblenz/west/splendid/estimation/SPLENDIDCostEstimator.java
// Path: src/de/uni_koblenz/west/splendid/model/BindJoin.java // public class BindJoin extends Join { // // public BindJoin(TupleExpr leftArg, TupleExpr rightArg) { // super(leftArg, rightArg); // } // // @Override // public boolean equals(Object other) { // return other instanceof BindJoin && super.equals(other); // } // // @Override // public int hashCode() { // return super.hashCode() ^ "BindJoin".hashCode(); // } // // @Override // public BindJoin clone() { // return (BindJoin)super.clone(); // } // // } // // Path: src/de/uni_koblenz/west/splendid/model/HashJoin.java // public class HashJoin extends Join { // // public HashJoin(TupleExpr leftArg, TupleExpr rightArg) { // super(leftArg, rightArg); // } // // @Override // public boolean equals(Object other) { // return other instanceof HashJoin && super.equals(other); // } // // @Override // public int hashCode() { // return super.hashCode() ^ "HashJoin".hashCode(); // } // // @Override // public HashJoin clone() { // return (HashJoin)super.clone(); // } // // } // // Path: src/de/uni_koblenz/west/splendid/model/RemoteQuery.java // public class RemoteQuery extends UnaryTupleOperator { // // public RemoteQuery(TupleExpr expr) { // super(expr); // } // // @Override // public <X extends Exception> void visit(QueryModelVisitor<X> visitor) throws X { // visitor.meetOther(this); // } // // public Set<Graph> getSources() { // StatementPattern p = StatementPatternCollector.process(this).get(0); // if (p instanceof MappedStatementPattern) // return ((MappedStatementPattern) p).getSources(); // else // return null; // } // // }
import org.openrdf.query.algebra.Join; import org.openrdf.query.algebra.UnaryTupleOperator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import de.uni_koblenz.west.splendid.model.BindJoin; import de.uni_koblenz.west.splendid.model.HashJoin; import de.uni_koblenz.west.splendid.model.RemoteQuery;
/* * This file is part of RDF Federator. * Copyright 2011 Olaf Goerlitz * * RDF Federator 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 3 of the License, or * (at your option) any later version. * * RDF Federator 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 RDF Federator. If not, see <http://www.gnu.org/licenses/>. * * RDF Federator uses libraries from the OpenRDF Sesame Project licensed * under the Aduna BSD-style license. */ package de.uni_koblenz.west.splendid.estimation; /** * Calculates the cost for executing the physical operators. * * @author Olaf Goerlitz */ public class SPLENDIDCostEstimator extends AbstractCostEstimator { private static final Logger LOGGER = LoggerFactory.getLogger(SPLENDIDCostEstimator.class); private static final int C_TRANSFER_QUERY = 5; private static final int C_TRANSFER_TUPLE = 1; public String getName() { return "SPLDCost"; } @Override public void meet(Join node) throws RuntimeException { // get cost of children first super.meet(node);
// Path: src/de/uni_koblenz/west/splendid/model/BindJoin.java // public class BindJoin extends Join { // // public BindJoin(TupleExpr leftArg, TupleExpr rightArg) { // super(leftArg, rightArg); // } // // @Override // public boolean equals(Object other) { // return other instanceof BindJoin && super.equals(other); // } // // @Override // public int hashCode() { // return super.hashCode() ^ "BindJoin".hashCode(); // } // // @Override // public BindJoin clone() { // return (BindJoin)super.clone(); // } // // } // // Path: src/de/uni_koblenz/west/splendid/model/HashJoin.java // public class HashJoin extends Join { // // public HashJoin(TupleExpr leftArg, TupleExpr rightArg) { // super(leftArg, rightArg); // } // // @Override // public boolean equals(Object other) { // return other instanceof HashJoin && super.equals(other); // } // // @Override // public int hashCode() { // return super.hashCode() ^ "HashJoin".hashCode(); // } // // @Override // public HashJoin clone() { // return (HashJoin)super.clone(); // } // // } // // Path: src/de/uni_koblenz/west/splendid/model/RemoteQuery.java // public class RemoteQuery extends UnaryTupleOperator { // // public RemoteQuery(TupleExpr expr) { // super(expr); // } // // @Override // public <X extends Exception> void visit(QueryModelVisitor<X> visitor) throws X { // visitor.meetOther(this); // } // // public Set<Graph> getSources() { // StatementPattern p = StatementPatternCollector.process(this).get(0); // if (p instanceof MappedStatementPattern) // return ((MappedStatementPattern) p).getSources(); // else // return null; // } // // } // Path: src/de/uni_koblenz/west/splendid/estimation/SPLENDIDCostEstimator.java import org.openrdf.query.algebra.Join; import org.openrdf.query.algebra.UnaryTupleOperator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import de.uni_koblenz.west.splendid.model.BindJoin; import de.uni_koblenz.west.splendid.model.HashJoin; import de.uni_koblenz.west.splendid.model.RemoteQuery; /* * This file is part of RDF Federator. * Copyright 2011 Olaf Goerlitz * * RDF Federator 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 3 of the License, or * (at your option) any later version. * * RDF Federator 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 RDF Federator. If not, see <http://www.gnu.org/licenses/>. * * RDF Federator uses libraries from the OpenRDF Sesame Project licensed * under the Aduna BSD-style license. */ package de.uni_koblenz.west.splendid.estimation; /** * Calculates the cost for executing the physical operators. * * @author Olaf Goerlitz */ public class SPLENDIDCostEstimator extends AbstractCostEstimator { private static final Logger LOGGER = LoggerFactory.getLogger(SPLENDIDCostEstimator.class); private static final int C_TRANSFER_QUERY = 5; private static final int C_TRANSFER_TUPLE = 1; public String getName() { return "SPLDCost"; } @Override public void meet(Join node) throws RuntimeException { // get cost of children first super.meet(node);
if (node instanceof HashJoin) {
goerlitz/rdffederator
src/de/uni_koblenz/west/splendid/estimation/SPLENDIDCostEstimator.java
// Path: src/de/uni_koblenz/west/splendid/model/BindJoin.java // public class BindJoin extends Join { // // public BindJoin(TupleExpr leftArg, TupleExpr rightArg) { // super(leftArg, rightArg); // } // // @Override // public boolean equals(Object other) { // return other instanceof BindJoin && super.equals(other); // } // // @Override // public int hashCode() { // return super.hashCode() ^ "BindJoin".hashCode(); // } // // @Override // public BindJoin clone() { // return (BindJoin)super.clone(); // } // // } // // Path: src/de/uni_koblenz/west/splendid/model/HashJoin.java // public class HashJoin extends Join { // // public HashJoin(TupleExpr leftArg, TupleExpr rightArg) { // super(leftArg, rightArg); // } // // @Override // public boolean equals(Object other) { // return other instanceof HashJoin && super.equals(other); // } // // @Override // public int hashCode() { // return super.hashCode() ^ "HashJoin".hashCode(); // } // // @Override // public HashJoin clone() { // return (HashJoin)super.clone(); // } // // } // // Path: src/de/uni_koblenz/west/splendid/model/RemoteQuery.java // public class RemoteQuery extends UnaryTupleOperator { // // public RemoteQuery(TupleExpr expr) { // super(expr); // } // // @Override // public <X extends Exception> void visit(QueryModelVisitor<X> visitor) throws X { // visitor.meetOther(this); // } // // public Set<Graph> getSources() { // StatementPattern p = StatementPatternCollector.process(this).get(0); // if (p instanceof MappedStatementPattern) // return ((MappedStatementPattern) p).getSources(); // else // return null; // } // // }
import org.openrdf.query.algebra.Join; import org.openrdf.query.algebra.UnaryTupleOperator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import de.uni_koblenz.west.splendid.model.BindJoin; import de.uni_koblenz.west.splendid.model.HashJoin; import de.uni_koblenz.west.splendid.model.RemoteQuery;
/* * This file is part of RDF Federator. * Copyright 2011 Olaf Goerlitz * * RDF Federator 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 3 of the License, or * (at your option) any later version. * * RDF Federator 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 RDF Federator. If not, see <http://www.gnu.org/licenses/>. * * RDF Federator uses libraries from the OpenRDF Sesame Project licensed * under the Aduna BSD-style license. */ package de.uni_koblenz.west.splendid.estimation; /** * Calculates the cost for executing the physical operators. * * @author Olaf Goerlitz */ public class SPLENDIDCostEstimator extends AbstractCostEstimator { private static final Logger LOGGER = LoggerFactory.getLogger(SPLENDIDCostEstimator.class); private static final int C_TRANSFER_QUERY = 5; private static final int C_TRANSFER_TUPLE = 1; public String getName() { return "SPLDCost"; } @Override public void meet(Join node) throws RuntimeException { // get cost of children first super.meet(node); if (node instanceof HashJoin) { meet((HashJoin) node);
// Path: src/de/uni_koblenz/west/splendid/model/BindJoin.java // public class BindJoin extends Join { // // public BindJoin(TupleExpr leftArg, TupleExpr rightArg) { // super(leftArg, rightArg); // } // // @Override // public boolean equals(Object other) { // return other instanceof BindJoin && super.equals(other); // } // // @Override // public int hashCode() { // return super.hashCode() ^ "BindJoin".hashCode(); // } // // @Override // public BindJoin clone() { // return (BindJoin)super.clone(); // } // // } // // Path: src/de/uni_koblenz/west/splendid/model/HashJoin.java // public class HashJoin extends Join { // // public HashJoin(TupleExpr leftArg, TupleExpr rightArg) { // super(leftArg, rightArg); // } // // @Override // public boolean equals(Object other) { // return other instanceof HashJoin && super.equals(other); // } // // @Override // public int hashCode() { // return super.hashCode() ^ "HashJoin".hashCode(); // } // // @Override // public HashJoin clone() { // return (HashJoin)super.clone(); // } // // } // // Path: src/de/uni_koblenz/west/splendid/model/RemoteQuery.java // public class RemoteQuery extends UnaryTupleOperator { // // public RemoteQuery(TupleExpr expr) { // super(expr); // } // // @Override // public <X extends Exception> void visit(QueryModelVisitor<X> visitor) throws X { // visitor.meetOther(this); // } // // public Set<Graph> getSources() { // StatementPattern p = StatementPatternCollector.process(this).get(0); // if (p instanceof MappedStatementPattern) // return ((MappedStatementPattern) p).getSources(); // else // return null; // } // // } // Path: src/de/uni_koblenz/west/splendid/estimation/SPLENDIDCostEstimator.java import org.openrdf.query.algebra.Join; import org.openrdf.query.algebra.UnaryTupleOperator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import de.uni_koblenz.west.splendid.model.BindJoin; import de.uni_koblenz.west.splendid.model.HashJoin; import de.uni_koblenz.west.splendid.model.RemoteQuery; /* * This file is part of RDF Federator. * Copyright 2011 Olaf Goerlitz * * RDF Federator 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 3 of the License, or * (at your option) any later version. * * RDF Federator 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 RDF Federator. If not, see <http://www.gnu.org/licenses/>. * * RDF Federator uses libraries from the OpenRDF Sesame Project licensed * under the Aduna BSD-style license. */ package de.uni_koblenz.west.splendid.estimation; /** * Calculates the cost for executing the physical operators. * * @author Olaf Goerlitz */ public class SPLENDIDCostEstimator extends AbstractCostEstimator { private static final Logger LOGGER = LoggerFactory.getLogger(SPLENDIDCostEstimator.class); private static final int C_TRANSFER_QUERY = 5; private static final int C_TRANSFER_TUPLE = 1; public String getName() { return "SPLDCost"; } @Override public void meet(Join node) throws RuntimeException { // get cost of children first super.meet(node); if (node instanceof HashJoin) { meet((HashJoin) node);
} else if (node instanceof BindJoin) {
goerlitz/rdffederator
src/de/uni_koblenz/west/splendid/estimation/SPLENDIDCostEstimator.java
// Path: src/de/uni_koblenz/west/splendid/model/BindJoin.java // public class BindJoin extends Join { // // public BindJoin(TupleExpr leftArg, TupleExpr rightArg) { // super(leftArg, rightArg); // } // // @Override // public boolean equals(Object other) { // return other instanceof BindJoin && super.equals(other); // } // // @Override // public int hashCode() { // return super.hashCode() ^ "BindJoin".hashCode(); // } // // @Override // public BindJoin clone() { // return (BindJoin)super.clone(); // } // // } // // Path: src/de/uni_koblenz/west/splendid/model/HashJoin.java // public class HashJoin extends Join { // // public HashJoin(TupleExpr leftArg, TupleExpr rightArg) { // super(leftArg, rightArg); // } // // @Override // public boolean equals(Object other) { // return other instanceof HashJoin && super.equals(other); // } // // @Override // public int hashCode() { // return super.hashCode() ^ "HashJoin".hashCode(); // } // // @Override // public HashJoin clone() { // return (HashJoin)super.clone(); // } // // } // // Path: src/de/uni_koblenz/west/splendid/model/RemoteQuery.java // public class RemoteQuery extends UnaryTupleOperator { // // public RemoteQuery(TupleExpr expr) { // super(expr); // } // // @Override // public <X extends Exception> void visit(QueryModelVisitor<X> visitor) throws X { // visitor.meetOther(this); // } // // public Set<Graph> getSources() { // StatementPattern p = StatementPatternCollector.process(this).get(0); // if (p instanceof MappedStatementPattern) // return ((MappedStatementPattern) p).getSources(); // else // return null; // } // // }
import org.openrdf.query.algebra.Join; import org.openrdf.query.algebra.UnaryTupleOperator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import de.uni_koblenz.west.splendid.model.BindJoin; import de.uni_koblenz.west.splendid.model.HashJoin; import de.uni_koblenz.west.splendid.model.RemoteQuery;
/* * This file is part of RDF Federator. * Copyright 2011 Olaf Goerlitz * * RDF Federator 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 3 of the License, or * (at your option) any later version. * * RDF Federator 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 RDF Federator. If not, see <http://www.gnu.org/licenses/>. * * RDF Federator uses libraries from the OpenRDF Sesame Project licensed * under the Aduna BSD-style license. */ package de.uni_koblenz.west.splendid.estimation; /** * Calculates the cost for executing the physical operators. * * @author Olaf Goerlitz */ public class SPLENDIDCostEstimator extends AbstractCostEstimator { private static final Logger LOGGER = LoggerFactory.getLogger(SPLENDIDCostEstimator.class); private static final int C_TRANSFER_QUERY = 5; private static final int C_TRANSFER_TUPLE = 1; public String getName() { return "SPLDCost"; } @Override public void meet(Join node) throws RuntimeException { // get cost of children first super.meet(node); if (node instanceof HashJoin) { meet((HashJoin) node); } else if (node instanceof BindJoin) { meet((BindJoin) node); } else { throw new IllegalArgumentException("no accepted join: " + node); } } @Override protected void meetUnaryTupleOperator(UnaryTupleOperator node) throws RuntimeException { // need to handle sub queries explicitly
// Path: src/de/uni_koblenz/west/splendid/model/BindJoin.java // public class BindJoin extends Join { // // public BindJoin(TupleExpr leftArg, TupleExpr rightArg) { // super(leftArg, rightArg); // } // // @Override // public boolean equals(Object other) { // return other instanceof BindJoin && super.equals(other); // } // // @Override // public int hashCode() { // return super.hashCode() ^ "BindJoin".hashCode(); // } // // @Override // public BindJoin clone() { // return (BindJoin)super.clone(); // } // // } // // Path: src/de/uni_koblenz/west/splendid/model/HashJoin.java // public class HashJoin extends Join { // // public HashJoin(TupleExpr leftArg, TupleExpr rightArg) { // super(leftArg, rightArg); // } // // @Override // public boolean equals(Object other) { // return other instanceof HashJoin && super.equals(other); // } // // @Override // public int hashCode() { // return super.hashCode() ^ "HashJoin".hashCode(); // } // // @Override // public HashJoin clone() { // return (HashJoin)super.clone(); // } // // } // // Path: src/de/uni_koblenz/west/splendid/model/RemoteQuery.java // public class RemoteQuery extends UnaryTupleOperator { // // public RemoteQuery(TupleExpr expr) { // super(expr); // } // // @Override // public <X extends Exception> void visit(QueryModelVisitor<X> visitor) throws X { // visitor.meetOther(this); // } // // public Set<Graph> getSources() { // StatementPattern p = StatementPatternCollector.process(this).get(0); // if (p instanceof MappedStatementPattern) // return ((MappedStatementPattern) p).getSources(); // else // return null; // } // // } // Path: src/de/uni_koblenz/west/splendid/estimation/SPLENDIDCostEstimator.java import org.openrdf.query.algebra.Join; import org.openrdf.query.algebra.UnaryTupleOperator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import de.uni_koblenz.west.splendid.model.BindJoin; import de.uni_koblenz.west.splendid.model.HashJoin; import de.uni_koblenz.west.splendid.model.RemoteQuery; /* * This file is part of RDF Federator. * Copyright 2011 Olaf Goerlitz * * RDF Federator 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 3 of the License, or * (at your option) any later version. * * RDF Federator 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 RDF Federator. If not, see <http://www.gnu.org/licenses/>. * * RDF Federator uses libraries from the OpenRDF Sesame Project licensed * under the Aduna BSD-style license. */ package de.uni_koblenz.west.splendid.estimation; /** * Calculates the cost for executing the physical operators. * * @author Olaf Goerlitz */ public class SPLENDIDCostEstimator extends AbstractCostEstimator { private static final Logger LOGGER = LoggerFactory.getLogger(SPLENDIDCostEstimator.class); private static final int C_TRANSFER_QUERY = 5; private static final int C_TRANSFER_TUPLE = 1; public String getName() { return "SPLDCost"; } @Override public void meet(Join node) throws RuntimeException { // get cost of children first super.meet(node); if (node instanceof HashJoin) { meet((HashJoin) node); } else if (node instanceof BindJoin) { meet((BindJoin) node); } else { throw new IllegalArgumentException("no accepted join: " + node); } } @Override protected void meetUnaryTupleOperator(UnaryTupleOperator node) throws RuntimeException { // need to handle sub queries explicitly
if (node instanceof RemoteQuery) {
goerlitz/rdffederator
src/de/uni_koblenz/west/splendid/config/QueryOptimizerConfig.java
// Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI ESTIMATOR = vf.createURI(NAMESPACE + "cardEstimator"); // // Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI EVAL_STRATEGY = vf.createURI(NAMESPACE + "evalStrategy"); // // Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI GROUP_BY_SAMEAS = vf.createURI(NAMESPACE + "groupBySameAs"); // // Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI GROUP_BY_SOURCE = vf.createURI(NAMESPACE + "groupBySource"); // // Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI OPT_TYPE = vf.createURI(NAMESPACE + "optimizerType"); // // Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI USE_BIND_JOIN = vf.createURI(NAMESPACE + "useBindJoin"); // // Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI USE_HASH_JOIN = vf.createURI(NAMESPACE + "useHashJoin");
import org.openrdf.model.Resource; import org.openrdf.model.ValueFactory; import org.openrdf.model.impl.ValueFactoryImpl; import org.openrdf.query.algebra.evaluation.EvaluationStrategy; import org.openrdf.sail.config.SailConfigException; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.ESTIMATOR; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.EVAL_STRATEGY; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.GROUP_BY_SAMEAS; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.GROUP_BY_SOURCE; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.OPT_TYPE; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.USE_BIND_JOIN; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.USE_HASH_JOIN; import org.openrdf.model.Graph; import org.openrdf.model.Literal;
/* * This file is part of RDF Federator. * Copyright 2010 Olaf Goerlitz * * RDF Federator 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 3 of the License, or * (at your option) any later version. * * RDF Federator 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 RDF Federator. If not, see <http://www.gnu.org/licenses/>. * * RDF Federator uses libraries from the OpenRDF Sesame Project licensed * under the Aduna BSD-style license. */ package de.uni_koblenz.west.splendid.config; /** * Configuration settings for the query optimizer. * * @author Olaf Goerlitz */ public class QueryOptimizerConfig extends AbstractSailConfig { private static final String DEFAULT_ESTIMATOR_TYPE = "INDEX_ASK"; private String estimatorType = DEFAULT_ESTIMATOR_TYPE; private boolean groupBySameAs = false; private boolean groupBySource = true; private boolean useBindJoin = true; private boolean useHashJoin = true; private EvaluationStrategy evalStrategy; protected QueryOptimizerConfig() {
// Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI ESTIMATOR = vf.createURI(NAMESPACE + "cardEstimator"); // // Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI EVAL_STRATEGY = vf.createURI(NAMESPACE + "evalStrategy"); // // Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI GROUP_BY_SAMEAS = vf.createURI(NAMESPACE + "groupBySameAs"); // // Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI GROUP_BY_SOURCE = vf.createURI(NAMESPACE + "groupBySource"); // // Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI OPT_TYPE = vf.createURI(NAMESPACE + "optimizerType"); // // Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI USE_BIND_JOIN = vf.createURI(NAMESPACE + "useBindJoin"); // // Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI USE_HASH_JOIN = vf.createURI(NAMESPACE + "useHashJoin"); // Path: src/de/uni_koblenz/west/splendid/config/QueryOptimizerConfig.java import org.openrdf.model.Resource; import org.openrdf.model.ValueFactory; import org.openrdf.model.impl.ValueFactoryImpl; import org.openrdf.query.algebra.evaluation.EvaluationStrategy; import org.openrdf.sail.config.SailConfigException; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.ESTIMATOR; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.EVAL_STRATEGY; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.GROUP_BY_SAMEAS; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.GROUP_BY_SOURCE; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.OPT_TYPE; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.USE_BIND_JOIN; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.USE_HASH_JOIN; import org.openrdf.model.Graph; import org.openrdf.model.Literal; /* * This file is part of RDF Federator. * Copyright 2010 Olaf Goerlitz * * RDF Federator 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 3 of the License, or * (at your option) any later version. * * RDF Federator 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 RDF Federator. If not, see <http://www.gnu.org/licenses/>. * * RDF Federator uses libraries from the OpenRDF Sesame Project licensed * under the Aduna BSD-style license. */ package de.uni_koblenz.west.splendid.config; /** * Configuration settings for the query optimizer. * * @author Olaf Goerlitz */ public class QueryOptimizerConfig extends AbstractSailConfig { private static final String DEFAULT_ESTIMATOR_TYPE = "INDEX_ASK"; private String estimatorType = DEFAULT_ESTIMATOR_TYPE; private boolean groupBySameAs = false; private boolean groupBySource = true; private boolean useBindJoin = true; private boolean useHashJoin = true; private EvaluationStrategy evalStrategy; protected QueryOptimizerConfig() {
super(OPT_TYPE);
goerlitz/rdffederator
src/de/uni_koblenz/west/splendid/config/QueryOptimizerConfig.java
// Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI ESTIMATOR = vf.createURI(NAMESPACE + "cardEstimator"); // // Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI EVAL_STRATEGY = vf.createURI(NAMESPACE + "evalStrategy"); // // Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI GROUP_BY_SAMEAS = vf.createURI(NAMESPACE + "groupBySameAs"); // // Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI GROUP_BY_SOURCE = vf.createURI(NAMESPACE + "groupBySource"); // // Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI OPT_TYPE = vf.createURI(NAMESPACE + "optimizerType"); // // Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI USE_BIND_JOIN = vf.createURI(NAMESPACE + "useBindJoin"); // // Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI USE_HASH_JOIN = vf.createURI(NAMESPACE + "useHashJoin");
import org.openrdf.model.Resource; import org.openrdf.model.ValueFactory; import org.openrdf.model.impl.ValueFactoryImpl; import org.openrdf.query.algebra.evaluation.EvaluationStrategy; import org.openrdf.sail.config.SailConfigException; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.ESTIMATOR; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.EVAL_STRATEGY; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.GROUP_BY_SAMEAS; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.GROUP_BY_SOURCE; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.OPT_TYPE; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.USE_BIND_JOIN; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.USE_HASH_JOIN; import org.openrdf.model.Graph; import org.openrdf.model.Literal;
return this.estimatorType; } public EvaluationStrategy getEvalStrategy() { return this.evalStrategy; } public boolean isGroupBySameAs() { return this.groupBySameAs; } public boolean isGroupBySource() { return this.groupBySource; } public boolean isUseBindJoin() { return this.useBindJoin; } public boolean isUseHashJoin() { return this.useHashJoin; } @Override public Resource export(Graph model) { ValueFactory vf = ValueFactoryImpl.getInstance(); Resource self = super.export(model);
// Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI ESTIMATOR = vf.createURI(NAMESPACE + "cardEstimator"); // // Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI EVAL_STRATEGY = vf.createURI(NAMESPACE + "evalStrategy"); // // Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI GROUP_BY_SAMEAS = vf.createURI(NAMESPACE + "groupBySameAs"); // // Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI GROUP_BY_SOURCE = vf.createURI(NAMESPACE + "groupBySource"); // // Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI OPT_TYPE = vf.createURI(NAMESPACE + "optimizerType"); // // Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI USE_BIND_JOIN = vf.createURI(NAMESPACE + "useBindJoin"); // // Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI USE_HASH_JOIN = vf.createURI(NAMESPACE + "useHashJoin"); // Path: src/de/uni_koblenz/west/splendid/config/QueryOptimizerConfig.java import org.openrdf.model.Resource; import org.openrdf.model.ValueFactory; import org.openrdf.model.impl.ValueFactoryImpl; import org.openrdf.query.algebra.evaluation.EvaluationStrategy; import org.openrdf.sail.config.SailConfigException; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.ESTIMATOR; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.EVAL_STRATEGY; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.GROUP_BY_SAMEAS; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.GROUP_BY_SOURCE; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.OPT_TYPE; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.USE_BIND_JOIN; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.USE_HASH_JOIN; import org.openrdf.model.Graph; import org.openrdf.model.Literal; return this.estimatorType; } public EvaluationStrategy getEvalStrategy() { return this.evalStrategy; } public boolean isGroupBySameAs() { return this.groupBySameAs; } public boolean isGroupBySource() { return this.groupBySource; } public boolean isUseBindJoin() { return this.useBindJoin; } public boolean isUseHashJoin() { return this.useHashJoin; } @Override public Resource export(Graph model) { ValueFactory vf = ValueFactoryImpl.getInstance(); Resource self = super.export(model);
model.add(self, ESTIMATOR, vf.createLiteral(this.estimatorType));
goerlitz/rdffederator
src/de/uni_koblenz/west/splendid/config/QueryOptimizerConfig.java
// Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI ESTIMATOR = vf.createURI(NAMESPACE + "cardEstimator"); // // Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI EVAL_STRATEGY = vf.createURI(NAMESPACE + "evalStrategy"); // // Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI GROUP_BY_SAMEAS = vf.createURI(NAMESPACE + "groupBySameAs"); // // Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI GROUP_BY_SOURCE = vf.createURI(NAMESPACE + "groupBySource"); // // Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI OPT_TYPE = vf.createURI(NAMESPACE + "optimizerType"); // // Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI USE_BIND_JOIN = vf.createURI(NAMESPACE + "useBindJoin"); // // Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI USE_HASH_JOIN = vf.createURI(NAMESPACE + "useHashJoin");
import org.openrdf.model.Resource; import org.openrdf.model.ValueFactory; import org.openrdf.model.impl.ValueFactoryImpl; import org.openrdf.query.algebra.evaluation.EvaluationStrategy; import org.openrdf.sail.config.SailConfigException; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.ESTIMATOR; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.EVAL_STRATEGY; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.GROUP_BY_SAMEAS; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.GROUP_BY_SOURCE; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.OPT_TYPE; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.USE_BIND_JOIN; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.USE_HASH_JOIN; import org.openrdf.model.Graph; import org.openrdf.model.Literal;
public EvaluationStrategy getEvalStrategy() { return this.evalStrategy; } public boolean isGroupBySameAs() { return this.groupBySameAs; } public boolean isGroupBySource() { return this.groupBySource; } public boolean isUseBindJoin() { return this.useBindJoin; } public boolean isUseHashJoin() { return this.useHashJoin; } @Override public Resource export(Graph model) { ValueFactory vf = ValueFactoryImpl.getInstance(); Resource self = super.export(model); model.add(self, ESTIMATOR, vf.createLiteral(this.estimatorType));
// Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI ESTIMATOR = vf.createURI(NAMESPACE + "cardEstimator"); // // Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI EVAL_STRATEGY = vf.createURI(NAMESPACE + "evalStrategy"); // // Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI GROUP_BY_SAMEAS = vf.createURI(NAMESPACE + "groupBySameAs"); // // Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI GROUP_BY_SOURCE = vf.createURI(NAMESPACE + "groupBySource"); // // Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI OPT_TYPE = vf.createURI(NAMESPACE + "optimizerType"); // // Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI USE_BIND_JOIN = vf.createURI(NAMESPACE + "useBindJoin"); // // Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI USE_HASH_JOIN = vf.createURI(NAMESPACE + "useHashJoin"); // Path: src/de/uni_koblenz/west/splendid/config/QueryOptimizerConfig.java import org.openrdf.model.Resource; import org.openrdf.model.ValueFactory; import org.openrdf.model.impl.ValueFactoryImpl; import org.openrdf.query.algebra.evaluation.EvaluationStrategy; import org.openrdf.sail.config.SailConfigException; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.ESTIMATOR; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.EVAL_STRATEGY; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.GROUP_BY_SAMEAS; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.GROUP_BY_SOURCE; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.OPT_TYPE; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.USE_BIND_JOIN; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.USE_HASH_JOIN; import org.openrdf.model.Graph; import org.openrdf.model.Literal; public EvaluationStrategy getEvalStrategy() { return this.evalStrategy; } public boolean isGroupBySameAs() { return this.groupBySameAs; } public boolean isGroupBySource() { return this.groupBySource; } public boolean isUseBindJoin() { return this.useBindJoin; } public boolean isUseHashJoin() { return this.useHashJoin; } @Override public Resource export(Graph model) { ValueFactory vf = ValueFactoryImpl.getInstance(); Resource self = super.export(model); model.add(self, ESTIMATOR, vf.createLiteral(this.estimatorType));
model.add(self, GROUP_BY_SAMEAS, vf.createLiteral(this.groupBySameAs));
goerlitz/rdffederator
src/de/uni_koblenz/west/splendid/config/QueryOptimizerConfig.java
// Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI ESTIMATOR = vf.createURI(NAMESPACE + "cardEstimator"); // // Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI EVAL_STRATEGY = vf.createURI(NAMESPACE + "evalStrategy"); // // Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI GROUP_BY_SAMEAS = vf.createURI(NAMESPACE + "groupBySameAs"); // // Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI GROUP_BY_SOURCE = vf.createURI(NAMESPACE + "groupBySource"); // // Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI OPT_TYPE = vf.createURI(NAMESPACE + "optimizerType"); // // Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI USE_BIND_JOIN = vf.createURI(NAMESPACE + "useBindJoin"); // // Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI USE_HASH_JOIN = vf.createURI(NAMESPACE + "useHashJoin");
import org.openrdf.model.Resource; import org.openrdf.model.ValueFactory; import org.openrdf.model.impl.ValueFactoryImpl; import org.openrdf.query.algebra.evaluation.EvaluationStrategy; import org.openrdf.sail.config.SailConfigException; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.ESTIMATOR; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.EVAL_STRATEGY; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.GROUP_BY_SAMEAS; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.GROUP_BY_SOURCE; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.OPT_TYPE; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.USE_BIND_JOIN; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.USE_HASH_JOIN; import org.openrdf.model.Graph; import org.openrdf.model.Literal;
public EvaluationStrategy getEvalStrategy() { return this.evalStrategy; } public boolean isGroupBySameAs() { return this.groupBySameAs; } public boolean isGroupBySource() { return this.groupBySource; } public boolean isUseBindJoin() { return this.useBindJoin; } public boolean isUseHashJoin() { return this.useHashJoin; } @Override public Resource export(Graph model) { ValueFactory vf = ValueFactoryImpl.getInstance(); Resource self = super.export(model); model.add(self, ESTIMATOR, vf.createLiteral(this.estimatorType)); model.add(self, GROUP_BY_SAMEAS, vf.createLiteral(this.groupBySameAs));
// Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI ESTIMATOR = vf.createURI(NAMESPACE + "cardEstimator"); // // Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI EVAL_STRATEGY = vf.createURI(NAMESPACE + "evalStrategy"); // // Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI GROUP_BY_SAMEAS = vf.createURI(NAMESPACE + "groupBySameAs"); // // Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI GROUP_BY_SOURCE = vf.createURI(NAMESPACE + "groupBySource"); // // Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI OPT_TYPE = vf.createURI(NAMESPACE + "optimizerType"); // // Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI USE_BIND_JOIN = vf.createURI(NAMESPACE + "useBindJoin"); // // Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI USE_HASH_JOIN = vf.createURI(NAMESPACE + "useHashJoin"); // Path: src/de/uni_koblenz/west/splendid/config/QueryOptimizerConfig.java import org.openrdf.model.Resource; import org.openrdf.model.ValueFactory; import org.openrdf.model.impl.ValueFactoryImpl; import org.openrdf.query.algebra.evaluation.EvaluationStrategy; import org.openrdf.sail.config.SailConfigException; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.ESTIMATOR; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.EVAL_STRATEGY; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.GROUP_BY_SAMEAS; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.GROUP_BY_SOURCE; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.OPT_TYPE; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.USE_BIND_JOIN; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.USE_HASH_JOIN; import org.openrdf.model.Graph; import org.openrdf.model.Literal; public EvaluationStrategy getEvalStrategy() { return this.evalStrategy; } public boolean isGroupBySameAs() { return this.groupBySameAs; } public boolean isGroupBySource() { return this.groupBySource; } public boolean isUseBindJoin() { return this.useBindJoin; } public boolean isUseHashJoin() { return this.useHashJoin; } @Override public Resource export(Graph model) { ValueFactory vf = ValueFactoryImpl.getInstance(); Resource self = super.export(model); model.add(self, ESTIMATOR, vf.createLiteral(this.estimatorType)); model.add(self, GROUP_BY_SAMEAS, vf.createLiteral(this.groupBySameAs));
model.add(self, GROUP_BY_SOURCE, vf.createLiteral(this.groupBySource));
goerlitz/rdffederator
src/de/uni_koblenz/west/splendid/config/QueryOptimizerConfig.java
// Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI ESTIMATOR = vf.createURI(NAMESPACE + "cardEstimator"); // // Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI EVAL_STRATEGY = vf.createURI(NAMESPACE + "evalStrategy"); // // Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI GROUP_BY_SAMEAS = vf.createURI(NAMESPACE + "groupBySameAs"); // // Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI GROUP_BY_SOURCE = vf.createURI(NAMESPACE + "groupBySource"); // // Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI OPT_TYPE = vf.createURI(NAMESPACE + "optimizerType"); // // Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI USE_BIND_JOIN = vf.createURI(NAMESPACE + "useBindJoin"); // // Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI USE_HASH_JOIN = vf.createURI(NAMESPACE + "useHashJoin");
import org.openrdf.model.Resource; import org.openrdf.model.ValueFactory; import org.openrdf.model.impl.ValueFactoryImpl; import org.openrdf.query.algebra.evaluation.EvaluationStrategy; import org.openrdf.sail.config.SailConfigException; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.ESTIMATOR; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.EVAL_STRATEGY; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.GROUP_BY_SAMEAS; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.GROUP_BY_SOURCE; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.OPT_TYPE; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.USE_BIND_JOIN; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.USE_HASH_JOIN; import org.openrdf.model.Graph; import org.openrdf.model.Literal;
} public boolean isGroupBySameAs() { return this.groupBySameAs; } public boolean isGroupBySource() { return this.groupBySource; } public boolean isUseBindJoin() { return this.useBindJoin; } public boolean isUseHashJoin() { return this.useHashJoin; } @Override public Resource export(Graph model) { ValueFactory vf = ValueFactoryImpl.getInstance(); Resource self = super.export(model); model.add(self, ESTIMATOR, vf.createLiteral(this.estimatorType)); model.add(self, GROUP_BY_SAMEAS, vf.createLiteral(this.groupBySameAs)); model.add(self, GROUP_BY_SOURCE, vf.createLiteral(this.groupBySource));
// Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI ESTIMATOR = vf.createURI(NAMESPACE + "cardEstimator"); // // Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI EVAL_STRATEGY = vf.createURI(NAMESPACE + "evalStrategy"); // // Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI GROUP_BY_SAMEAS = vf.createURI(NAMESPACE + "groupBySameAs"); // // Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI GROUP_BY_SOURCE = vf.createURI(NAMESPACE + "groupBySource"); // // Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI OPT_TYPE = vf.createURI(NAMESPACE + "optimizerType"); // // Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI USE_BIND_JOIN = vf.createURI(NAMESPACE + "useBindJoin"); // // Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI USE_HASH_JOIN = vf.createURI(NAMESPACE + "useHashJoin"); // Path: src/de/uni_koblenz/west/splendid/config/QueryOptimizerConfig.java import org.openrdf.model.Resource; import org.openrdf.model.ValueFactory; import org.openrdf.model.impl.ValueFactoryImpl; import org.openrdf.query.algebra.evaluation.EvaluationStrategy; import org.openrdf.sail.config.SailConfigException; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.ESTIMATOR; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.EVAL_STRATEGY; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.GROUP_BY_SAMEAS; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.GROUP_BY_SOURCE; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.OPT_TYPE; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.USE_BIND_JOIN; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.USE_HASH_JOIN; import org.openrdf.model.Graph; import org.openrdf.model.Literal; } public boolean isGroupBySameAs() { return this.groupBySameAs; } public boolean isGroupBySource() { return this.groupBySource; } public boolean isUseBindJoin() { return this.useBindJoin; } public boolean isUseHashJoin() { return this.useHashJoin; } @Override public Resource export(Graph model) { ValueFactory vf = ValueFactoryImpl.getInstance(); Resource self = super.export(model); model.add(self, ESTIMATOR, vf.createLiteral(this.estimatorType)); model.add(self, GROUP_BY_SAMEAS, vf.createLiteral(this.groupBySameAs)); model.add(self, GROUP_BY_SOURCE, vf.createLiteral(this.groupBySource));
model.add(self, USE_BIND_JOIN, vf.createLiteral(this.useBindJoin));
goerlitz/rdffederator
src/de/uni_koblenz/west/splendid/config/QueryOptimizerConfig.java
// Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI ESTIMATOR = vf.createURI(NAMESPACE + "cardEstimator"); // // Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI EVAL_STRATEGY = vf.createURI(NAMESPACE + "evalStrategy"); // // Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI GROUP_BY_SAMEAS = vf.createURI(NAMESPACE + "groupBySameAs"); // // Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI GROUP_BY_SOURCE = vf.createURI(NAMESPACE + "groupBySource"); // // Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI OPT_TYPE = vf.createURI(NAMESPACE + "optimizerType"); // // Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI USE_BIND_JOIN = vf.createURI(NAMESPACE + "useBindJoin"); // // Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI USE_HASH_JOIN = vf.createURI(NAMESPACE + "useHashJoin");
import org.openrdf.model.Resource; import org.openrdf.model.ValueFactory; import org.openrdf.model.impl.ValueFactoryImpl; import org.openrdf.query.algebra.evaluation.EvaluationStrategy; import org.openrdf.sail.config.SailConfigException; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.ESTIMATOR; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.EVAL_STRATEGY; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.GROUP_BY_SAMEAS; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.GROUP_BY_SOURCE; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.OPT_TYPE; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.USE_BIND_JOIN; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.USE_HASH_JOIN; import org.openrdf.model.Graph; import org.openrdf.model.Literal;
public boolean isGroupBySameAs() { return this.groupBySameAs; } public boolean isGroupBySource() { return this.groupBySource; } public boolean isUseBindJoin() { return this.useBindJoin; } public boolean isUseHashJoin() { return this.useHashJoin; } @Override public Resource export(Graph model) { ValueFactory vf = ValueFactoryImpl.getInstance(); Resource self = super.export(model); model.add(self, ESTIMATOR, vf.createLiteral(this.estimatorType)); model.add(self, GROUP_BY_SAMEAS, vf.createLiteral(this.groupBySameAs)); model.add(self, GROUP_BY_SOURCE, vf.createLiteral(this.groupBySource)); model.add(self, USE_BIND_JOIN, vf.createLiteral(this.useBindJoin));
// Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI ESTIMATOR = vf.createURI(NAMESPACE + "cardEstimator"); // // Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI EVAL_STRATEGY = vf.createURI(NAMESPACE + "evalStrategy"); // // Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI GROUP_BY_SAMEAS = vf.createURI(NAMESPACE + "groupBySameAs"); // // Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI GROUP_BY_SOURCE = vf.createURI(NAMESPACE + "groupBySource"); // // Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI OPT_TYPE = vf.createURI(NAMESPACE + "optimizerType"); // // Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI USE_BIND_JOIN = vf.createURI(NAMESPACE + "useBindJoin"); // // Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI USE_HASH_JOIN = vf.createURI(NAMESPACE + "useHashJoin"); // Path: src/de/uni_koblenz/west/splendid/config/QueryOptimizerConfig.java import org.openrdf.model.Resource; import org.openrdf.model.ValueFactory; import org.openrdf.model.impl.ValueFactoryImpl; import org.openrdf.query.algebra.evaluation.EvaluationStrategy; import org.openrdf.sail.config.SailConfigException; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.ESTIMATOR; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.EVAL_STRATEGY; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.GROUP_BY_SAMEAS; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.GROUP_BY_SOURCE; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.OPT_TYPE; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.USE_BIND_JOIN; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.USE_HASH_JOIN; import org.openrdf.model.Graph; import org.openrdf.model.Literal; public boolean isGroupBySameAs() { return this.groupBySameAs; } public boolean isGroupBySource() { return this.groupBySource; } public boolean isUseBindJoin() { return this.useBindJoin; } public boolean isUseHashJoin() { return this.useHashJoin; } @Override public Resource export(Graph model) { ValueFactory vf = ValueFactoryImpl.getInstance(); Resource self = super.export(model); model.add(self, ESTIMATOR, vf.createLiteral(this.estimatorType)); model.add(self, GROUP_BY_SAMEAS, vf.createLiteral(this.groupBySameAs)); model.add(self, GROUP_BY_SOURCE, vf.createLiteral(this.groupBySource)); model.add(self, USE_BIND_JOIN, vf.createLiteral(this.useBindJoin));
model.add(self, USE_HASH_JOIN, vf.createLiteral(this.useHashJoin));
goerlitz/rdffederator
src/de/uni_koblenz/west/splendid/config/QueryOptimizerConfig.java
// Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI ESTIMATOR = vf.createURI(NAMESPACE + "cardEstimator"); // // Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI EVAL_STRATEGY = vf.createURI(NAMESPACE + "evalStrategy"); // // Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI GROUP_BY_SAMEAS = vf.createURI(NAMESPACE + "groupBySameAs"); // // Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI GROUP_BY_SOURCE = vf.createURI(NAMESPACE + "groupBySource"); // // Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI OPT_TYPE = vf.createURI(NAMESPACE + "optimizerType"); // // Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI USE_BIND_JOIN = vf.createURI(NAMESPACE + "useBindJoin"); // // Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI USE_HASH_JOIN = vf.createURI(NAMESPACE + "useHashJoin");
import org.openrdf.model.Resource; import org.openrdf.model.ValueFactory; import org.openrdf.model.impl.ValueFactoryImpl; import org.openrdf.query.algebra.evaluation.EvaluationStrategy; import org.openrdf.sail.config.SailConfigException; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.ESTIMATOR; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.EVAL_STRATEGY; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.GROUP_BY_SAMEAS; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.GROUP_BY_SOURCE; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.OPT_TYPE; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.USE_BIND_JOIN; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.USE_HASH_JOIN; import org.openrdf.model.Graph; import org.openrdf.model.Literal;
return this.groupBySameAs; } public boolean isGroupBySource() { return this.groupBySource; } public boolean isUseBindJoin() { return this.useBindJoin; } public boolean isUseHashJoin() { return this.useHashJoin; } @Override public Resource export(Graph model) { ValueFactory vf = ValueFactoryImpl.getInstance(); Resource self = super.export(model); model.add(self, ESTIMATOR, vf.createLiteral(this.estimatorType)); model.add(self, GROUP_BY_SAMEAS, vf.createLiteral(this.groupBySameAs)); model.add(self, GROUP_BY_SOURCE, vf.createLiteral(this.groupBySource)); model.add(self, USE_BIND_JOIN, vf.createLiteral(this.useBindJoin)); model.add(self, USE_HASH_JOIN, vf.createLiteral(this.useHashJoin));
// Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI ESTIMATOR = vf.createURI(NAMESPACE + "cardEstimator"); // // Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI EVAL_STRATEGY = vf.createURI(NAMESPACE + "evalStrategy"); // // Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI GROUP_BY_SAMEAS = vf.createURI(NAMESPACE + "groupBySameAs"); // // Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI GROUP_BY_SOURCE = vf.createURI(NAMESPACE + "groupBySource"); // // Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI OPT_TYPE = vf.createURI(NAMESPACE + "optimizerType"); // // Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI USE_BIND_JOIN = vf.createURI(NAMESPACE + "useBindJoin"); // // Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI USE_HASH_JOIN = vf.createURI(NAMESPACE + "useHashJoin"); // Path: src/de/uni_koblenz/west/splendid/config/QueryOptimizerConfig.java import org.openrdf.model.Resource; import org.openrdf.model.ValueFactory; import org.openrdf.model.impl.ValueFactoryImpl; import org.openrdf.query.algebra.evaluation.EvaluationStrategy; import org.openrdf.sail.config.SailConfigException; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.ESTIMATOR; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.EVAL_STRATEGY; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.GROUP_BY_SAMEAS; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.GROUP_BY_SOURCE; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.OPT_TYPE; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.USE_BIND_JOIN; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.USE_HASH_JOIN; import org.openrdf.model.Graph; import org.openrdf.model.Literal; return this.groupBySameAs; } public boolean isGroupBySource() { return this.groupBySource; } public boolean isUseBindJoin() { return this.useBindJoin; } public boolean isUseHashJoin() { return this.useHashJoin; } @Override public Resource export(Graph model) { ValueFactory vf = ValueFactoryImpl.getInstance(); Resource self = super.export(model); model.add(self, ESTIMATOR, vf.createLiteral(this.estimatorType)); model.add(self, GROUP_BY_SAMEAS, vf.createLiteral(this.groupBySameAs)); model.add(self, GROUP_BY_SOURCE, vf.createLiteral(this.groupBySource)); model.add(self, USE_BIND_JOIN, vf.createLiteral(this.useBindJoin)); model.add(self, USE_HASH_JOIN, vf.createLiteral(this.useHashJoin));
model.add(self, EVAL_STRATEGY, vf.createLiteral(this.evalStrategy.getClass().getName()));
goerlitz/rdffederator
src/de/uni_koblenz/west/splendid/statistics/VoidStatistics.java
// Path: src/de/uni_koblenz/west/splendid/index/Graph.java // public class Graph { // // String name; // // public Graph(String name) { // this.name = name; // } // // @Override // public boolean equals(Object object) { // if (object instanceof Graph) // return this.name.equals(((Graph) object).name); // return false; // } // // @Override // public int hashCode() { // return this.name.hashCode(); // } // // public String toString() { // return this.name; // } // // public String getNamespaceURL() { // // TODO: implement proper hamespace handling // return this.name.replaceFirst("http://lodse.west.uni-koblenz.de:8080/openrdf-sesame/repositories/", "west:"); // } // // } // // Path: src/de/uni_koblenz/west/splendid/vocabulary/VOID2.java // public enum VOID2 { // // // concepts // Dataset, // Linkset, // EquiWidthHist, // EuqiDepthHist, // // // predicates // vocabulary, // sparqlEndpoint, // distinctSubjects, // distinctObjects, // triples, // classes, // entities, // properties, // classPartition, // clazz("class"), // propertyPartition, // property, // target, // linkPredicate, // // histogram, // minValue, // maxValue, // bucketLoad, // buckets, // bucketDef; // // public static final String NAMESPACE = "http://rdfs.org/ns/void#"; // // private final String uri; // // private VOID2(String name) { // this.uri = NAMESPACE + name; // } // // private VOID2() { // this.uri = NAMESPACE + super.toString(); // } // // public String toString() { // return this.uri; // } // // }
import static org.openrdf.query.QueryLanguage.SPARQL; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import org.openrdf.model.Resource; import org.openrdf.model.Statement; import org.openrdf.model.URI; import org.openrdf.model.ValueFactory; import org.openrdf.model.impl.ValueFactoryImpl; import org.openrdf.model.vocabulary.RDF; import org.openrdf.query.MalformedQueryException; import org.openrdf.query.QueryEvaluationException; import org.openrdf.query.TupleQuery; import org.openrdf.query.TupleQueryResult; import org.openrdf.repository.Repository; import org.openrdf.repository.RepositoryConnection; import org.openrdf.repository.RepositoryException; import org.openrdf.repository.RepositoryResult; import org.openrdf.repository.sail.SailRepository; import org.openrdf.rio.RDFFormat; import org.openrdf.rio.RDFParseException; import org.openrdf.rio.Rio; import org.openrdf.sail.memory.MemoryStore; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import de.uni_koblenz.west.splendid.index.Graph; import de.uni_koblenz.west.splendid.vocabulary.VOID2;
/* * This file is part of RDF Federator. * Copyright 2011 Olaf Goerlitz * * RDF Federator 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 3 of the License, or * (at your option) any later version. * * RDF Federator 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 RDF Federator. If not, see <http://www.gnu.org/licenses/>. * * RDF Federator uses libraries from the OpenRDF Sesame Project licensed * under the Aduna BSD-style license. */ package de.uni_koblenz.west.splendid.statistics; /** * voiD-based statistics implementation. * * @author Olaf Goerlitz */ public class VoidStatistics implements RDFStatistics { private static final Logger LOGGER = LoggerFactory.getLogger(VoidStatistics.class); private static final String USER_DIR = System.getProperty("user.dir") + File.separator;
// Path: src/de/uni_koblenz/west/splendid/index/Graph.java // public class Graph { // // String name; // // public Graph(String name) { // this.name = name; // } // // @Override // public boolean equals(Object object) { // if (object instanceof Graph) // return this.name.equals(((Graph) object).name); // return false; // } // // @Override // public int hashCode() { // return this.name.hashCode(); // } // // public String toString() { // return this.name; // } // // public String getNamespaceURL() { // // TODO: implement proper hamespace handling // return this.name.replaceFirst("http://lodse.west.uni-koblenz.de:8080/openrdf-sesame/repositories/", "west:"); // } // // } // // Path: src/de/uni_koblenz/west/splendid/vocabulary/VOID2.java // public enum VOID2 { // // // concepts // Dataset, // Linkset, // EquiWidthHist, // EuqiDepthHist, // // // predicates // vocabulary, // sparqlEndpoint, // distinctSubjects, // distinctObjects, // triples, // classes, // entities, // properties, // classPartition, // clazz("class"), // propertyPartition, // property, // target, // linkPredicate, // // histogram, // minValue, // maxValue, // bucketLoad, // buckets, // bucketDef; // // public static final String NAMESPACE = "http://rdfs.org/ns/void#"; // // private final String uri; // // private VOID2(String name) { // this.uri = NAMESPACE + name; // } // // private VOID2() { // this.uri = NAMESPACE + super.toString(); // } // // public String toString() { // return this.uri; // } // // } // Path: src/de/uni_koblenz/west/splendid/statistics/VoidStatistics.java import static org.openrdf.query.QueryLanguage.SPARQL; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import org.openrdf.model.Resource; import org.openrdf.model.Statement; import org.openrdf.model.URI; import org.openrdf.model.ValueFactory; import org.openrdf.model.impl.ValueFactoryImpl; import org.openrdf.model.vocabulary.RDF; import org.openrdf.query.MalformedQueryException; import org.openrdf.query.QueryEvaluationException; import org.openrdf.query.TupleQuery; import org.openrdf.query.TupleQueryResult; import org.openrdf.repository.Repository; import org.openrdf.repository.RepositoryConnection; import org.openrdf.repository.RepositoryException; import org.openrdf.repository.RepositoryResult; import org.openrdf.repository.sail.SailRepository; import org.openrdf.rio.RDFFormat; import org.openrdf.rio.RDFParseException; import org.openrdf.rio.Rio; import org.openrdf.sail.memory.MemoryStore; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import de.uni_koblenz.west.splendid.index.Graph; import de.uni_koblenz.west.splendid.vocabulary.VOID2; /* * This file is part of RDF Federator. * Copyright 2011 Olaf Goerlitz * * RDF Federator 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 3 of the License, or * (at your option) any later version. * * RDF Federator 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 RDF Federator. If not, see <http://www.gnu.org/licenses/>. * * RDF Federator uses libraries from the OpenRDF Sesame Project licensed * under the Aduna BSD-style license. */ package de.uni_koblenz.west.splendid.statistics; /** * voiD-based statistics implementation. * * @author Olaf Goerlitz */ public class VoidStatistics implements RDFStatistics { private static final Logger LOGGER = LoggerFactory.getLogger(VoidStatistics.class); private static final String USER_DIR = System.getProperty("user.dir") + File.separator;
private static final String VOID_PREFIX = "PREFIX void: <" + VOID2.NAMESPACE + ">\n";
goerlitz/rdffederator
src/de/uni_koblenz/west/splendid/statistics/VoidStatistics.java
// Path: src/de/uni_koblenz/west/splendid/index/Graph.java // public class Graph { // // String name; // // public Graph(String name) { // this.name = name; // } // // @Override // public boolean equals(Object object) { // if (object instanceof Graph) // return this.name.equals(((Graph) object).name); // return false; // } // // @Override // public int hashCode() { // return this.name.hashCode(); // } // // public String toString() { // return this.name; // } // // public String getNamespaceURL() { // // TODO: implement proper hamespace handling // return this.name.replaceFirst("http://lodse.west.uni-koblenz.de:8080/openrdf-sesame/repositories/", "west:"); // } // // } // // Path: src/de/uni_koblenz/west/splendid/vocabulary/VOID2.java // public enum VOID2 { // // // concepts // Dataset, // Linkset, // EquiWidthHist, // EuqiDepthHist, // // // predicates // vocabulary, // sparqlEndpoint, // distinctSubjects, // distinctObjects, // triples, // classes, // entities, // properties, // classPartition, // clazz("class"), // propertyPartition, // property, // target, // linkPredicate, // // histogram, // minValue, // maxValue, // bucketLoad, // buckets, // bucketDef; // // public static final String NAMESPACE = "http://rdfs.org/ns/void#"; // // private final String uri; // // private VOID2(String name) { // this.uri = NAMESPACE + name; // } // // private VOID2() { // this.uri = NAMESPACE + super.toString(); // } // // public String toString() { // return this.uri; // } // // }
import static org.openrdf.query.QueryLanguage.SPARQL; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import org.openrdf.model.Resource; import org.openrdf.model.Statement; import org.openrdf.model.URI; import org.openrdf.model.ValueFactory; import org.openrdf.model.impl.ValueFactoryImpl; import org.openrdf.model.vocabulary.RDF; import org.openrdf.query.MalformedQueryException; import org.openrdf.query.QueryEvaluationException; import org.openrdf.query.TupleQuery; import org.openrdf.query.TupleQueryResult; import org.openrdf.repository.Repository; import org.openrdf.repository.RepositoryConnection; import org.openrdf.repository.RepositoryException; import org.openrdf.repository.RepositoryResult; import org.openrdf.repository.sail.SailRepository; import org.openrdf.rio.RDFFormat; import org.openrdf.rio.RDFParseException; import org.openrdf.rio.Rio; import org.openrdf.sail.memory.MemoryStore; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import de.uni_koblenz.west.splendid.index.Graph; import de.uni_koblenz.west.splendid.vocabulary.VOID2;
LOGGER.error("malformed query, " + e.getMessage() + "\n" + query, e); } catch (QueryEvaluationException e) { LOGGER.error("failed to evaluate query on voiD repository, " + e.getMessage() + "\n" + query, e); } finally { con.close(); } } catch (RepositoryException e) { LOGGER.error("failed to open/close voiD repository connection, " + e.getMessage() + "\n" + query, e); } return null; } private List<URI> getEndpoints(URI voidURI, RepositoryConnection con) throws RepositoryException { ValueFactory uf = this.voidRepository.getValueFactory(); URI voidDataset = uf.createURI(VOID2.Dataset.toString()); URI sparqlEndpoint = uf.createURI(VOID2.sparqlEndpoint.toString()); List<URI> endpoints = new ArrayList<URI>(); for (Statement dataset : con.getStatements(null, RDF.TYPE, voidDataset, false, voidURI).asList()) { for (Statement endpoint : con.getStatements(dataset.getSubject(), sparqlEndpoint, null, false, voidURI).asList()) { // TODO: endpoint may be a literal endpoints.add((URI) endpoint.getObject()); } } return endpoints; } // ------------------------------------------------------------------------- @Override
// Path: src/de/uni_koblenz/west/splendid/index/Graph.java // public class Graph { // // String name; // // public Graph(String name) { // this.name = name; // } // // @Override // public boolean equals(Object object) { // if (object instanceof Graph) // return this.name.equals(((Graph) object).name); // return false; // } // // @Override // public int hashCode() { // return this.name.hashCode(); // } // // public String toString() { // return this.name; // } // // public String getNamespaceURL() { // // TODO: implement proper hamespace handling // return this.name.replaceFirst("http://lodse.west.uni-koblenz.de:8080/openrdf-sesame/repositories/", "west:"); // } // // } // // Path: src/de/uni_koblenz/west/splendid/vocabulary/VOID2.java // public enum VOID2 { // // // concepts // Dataset, // Linkset, // EquiWidthHist, // EuqiDepthHist, // // // predicates // vocabulary, // sparqlEndpoint, // distinctSubjects, // distinctObjects, // triples, // classes, // entities, // properties, // classPartition, // clazz("class"), // propertyPartition, // property, // target, // linkPredicate, // // histogram, // minValue, // maxValue, // bucketLoad, // buckets, // bucketDef; // // public static final String NAMESPACE = "http://rdfs.org/ns/void#"; // // private final String uri; // // private VOID2(String name) { // this.uri = NAMESPACE + name; // } // // private VOID2() { // this.uri = NAMESPACE + super.toString(); // } // // public String toString() { // return this.uri; // } // // } // Path: src/de/uni_koblenz/west/splendid/statistics/VoidStatistics.java import static org.openrdf.query.QueryLanguage.SPARQL; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import org.openrdf.model.Resource; import org.openrdf.model.Statement; import org.openrdf.model.URI; import org.openrdf.model.ValueFactory; import org.openrdf.model.impl.ValueFactoryImpl; import org.openrdf.model.vocabulary.RDF; import org.openrdf.query.MalformedQueryException; import org.openrdf.query.QueryEvaluationException; import org.openrdf.query.TupleQuery; import org.openrdf.query.TupleQueryResult; import org.openrdf.repository.Repository; import org.openrdf.repository.RepositoryConnection; import org.openrdf.repository.RepositoryException; import org.openrdf.repository.RepositoryResult; import org.openrdf.repository.sail.SailRepository; import org.openrdf.rio.RDFFormat; import org.openrdf.rio.RDFParseException; import org.openrdf.rio.Rio; import org.openrdf.sail.memory.MemoryStore; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import de.uni_koblenz.west.splendid.index.Graph; import de.uni_koblenz.west.splendid.vocabulary.VOID2; LOGGER.error("malformed query, " + e.getMessage() + "\n" + query, e); } catch (QueryEvaluationException e) { LOGGER.error("failed to evaluate query on voiD repository, " + e.getMessage() + "\n" + query, e); } finally { con.close(); } } catch (RepositoryException e) { LOGGER.error("failed to open/close voiD repository connection, " + e.getMessage() + "\n" + query, e); } return null; } private List<URI> getEndpoints(URI voidURI, RepositoryConnection con) throws RepositoryException { ValueFactory uf = this.voidRepository.getValueFactory(); URI voidDataset = uf.createURI(VOID2.Dataset.toString()); URI sparqlEndpoint = uf.createURI(VOID2.sparqlEndpoint.toString()); List<URI> endpoints = new ArrayList<URI>(); for (Statement dataset : con.getStatements(null, RDF.TYPE, voidDataset, false, voidURI).asList()) { for (Statement endpoint : con.getStatements(dataset.getSubject(), sparqlEndpoint, null, false, voidURI).asList()) { // TODO: endpoint may be a literal endpoints.add((URI) endpoint.getObject()); } } return endpoints; } // ------------------------------------------------------------------------- @Override
public Set<Graph> findSources(String sValue, String pValue, String oValue, boolean handleType) {
goerlitz/rdffederator
src/de/uni_koblenz/west/splendid/config/VoidRepositoryConfig.java
// Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI VOID_URI = vf.createURI(NAMESPACE + "voidDescription"); // // Path: src/de/uni_koblenz/west/splendid/config/VoidRepositorySchema.java // public static final URI ENDPOINT = vf.createURI(NAMESPACE, "sparqlEndpoint");
import org.openrdf.model.Statement; import org.openrdf.model.URI; import org.openrdf.model.Value; import org.openrdf.repository.config.RepositoryConfigException; import org.openrdf.repository.config.RepositoryImplConfigBase; import org.openrdf.sail.config.SailConfigException; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.VOID_URI; import static de.uni_koblenz.west.splendid.config.VoidRepositorySchema.ENDPOINT; import java.util.Iterator; import org.openrdf.model.Graph; import org.openrdf.model.Resource;
/* * This file is part of RDF Federator. * Copyright 2010 Olaf Goerlitz * * RDF Federator 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 3 of the License, or * (at your option) any later version. * * RDF Federator 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 RDF Federator. If not, see <http://www.gnu.org/licenses/>. * * RDF Federator uses libraries from the OpenRDF Sesame Project licensed * under the Aduna BSD-style license. */ package de.uni_koblenz.west.splendid.config; //import org.openrdf.model.Model; //import org.openrdf.model.util.ModelException; //import org.openrdf.store.StoreConfigException; /** * Configuration details for a void repository. * * @author Olaf Goerlitz */ public class VoidRepositoryConfig extends RepositoryImplConfigBase { private URI voidUri; private URI endpoint; /** * Returns the location of the VOID file. * * @return the location of the VOID file or null if it is not set. */ public URI getVoidURI() { return this.voidUri; } /** * Returns the location of the SPARQL endpoint. * * @return the location of the SPARQL endpoint or null if it is not set. */ public URI getEndpoint() { return this.endpoint; } // ------------------------------------------------------------------------- /** * Adds all Repository configuration settings to a configuration model. * * @param model the configuration model to be filled. * @return the resource representing this repository configuration. */ @Override // public Resource export(Model model) { // Sesame 3 public Resource export(Graph model) { // Sesame 2 Resource implNode = super.export(model);
// Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI VOID_URI = vf.createURI(NAMESPACE + "voidDescription"); // // Path: src/de/uni_koblenz/west/splendid/config/VoidRepositorySchema.java // public static final URI ENDPOINT = vf.createURI(NAMESPACE, "sparqlEndpoint"); // Path: src/de/uni_koblenz/west/splendid/config/VoidRepositoryConfig.java import org.openrdf.model.Statement; import org.openrdf.model.URI; import org.openrdf.model.Value; import org.openrdf.repository.config.RepositoryConfigException; import org.openrdf.repository.config.RepositoryImplConfigBase; import org.openrdf.sail.config.SailConfigException; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.VOID_URI; import static de.uni_koblenz.west.splendid.config.VoidRepositorySchema.ENDPOINT; import java.util.Iterator; import org.openrdf.model.Graph; import org.openrdf.model.Resource; /* * This file is part of RDF Federator. * Copyright 2010 Olaf Goerlitz * * RDF Federator 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 3 of the License, or * (at your option) any later version. * * RDF Federator 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 RDF Federator. If not, see <http://www.gnu.org/licenses/>. * * RDF Federator uses libraries from the OpenRDF Sesame Project licensed * under the Aduna BSD-style license. */ package de.uni_koblenz.west.splendid.config; //import org.openrdf.model.Model; //import org.openrdf.model.util.ModelException; //import org.openrdf.store.StoreConfigException; /** * Configuration details for a void repository. * * @author Olaf Goerlitz */ public class VoidRepositoryConfig extends RepositoryImplConfigBase { private URI voidUri; private URI endpoint; /** * Returns the location of the VOID file. * * @return the location of the VOID file or null if it is not set. */ public URI getVoidURI() { return this.voidUri; } /** * Returns the location of the SPARQL endpoint. * * @return the location of the SPARQL endpoint or null if it is not set. */ public URI getEndpoint() { return this.endpoint; } // ------------------------------------------------------------------------- /** * Adds all Repository configuration settings to a configuration model. * * @param model the configuration model to be filled. * @return the resource representing this repository configuration. */ @Override // public Resource export(Model model) { // Sesame 3 public Resource export(Graph model) { // Sesame 2 Resource implNode = super.export(model);
model.add(implNode, VOID_URI, this.voidUri);
goerlitz/rdffederator
src/de/uni_koblenz/west/splendid/config/VoidRepositoryConfig.java
// Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI VOID_URI = vf.createURI(NAMESPACE + "voidDescription"); // // Path: src/de/uni_koblenz/west/splendid/config/VoidRepositorySchema.java // public static final URI ENDPOINT = vf.createURI(NAMESPACE, "sparqlEndpoint");
import org.openrdf.model.Statement; import org.openrdf.model.URI; import org.openrdf.model.Value; import org.openrdf.repository.config.RepositoryConfigException; import org.openrdf.repository.config.RepositoryImplConfigBase; import org.openrdf.sail.config.SailConfigException; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.VOID_URI; import static de.uni_koblenz.west.splendid.config.VoidRepositorySchema.ENDPOINT; import java.util.Iterator; import org.openrdf.model.Graph; import org.openrdf.model.Resource;
/* * This file is part of RDF Federator. * Copyright 2010 Olaf Goerlitz * * RDF Federator 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 3 of the License, or * (at your option) any later version. * * RDF Federator 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 RDF Federator. If not, see <http://www.gnu.org/licenses/>. * * RDF Federator uses libraries from the OpenRDF Sesame Project licensed * under the Aduna BSD-style license. */ package de.uni_koblenz.west.splendid.config; //import org.openrdf.model.Model; //import org.openrdf.model.util.ModelException; //import org.openrdf.store.StoreConfigException; /** * Configuration details for a void repository. * * @author Olaf Goerlitz */ public class VoidRepositoryConfig extends RepositoryImplConfigBase { private URI voidUri; private URI endpoint; /** * Returns the location of the VOID file. * * @return the location of the VOID file or null if it is not set. */ public URI getVoidURI() { return this.voidUri; } /** * Returns the location of the SPARQL endpoint. * * @return the location of the SPARQL endpoint or null if it is not set. */ public URI getEndpoint() { return this.endpoint; } // ------------------------------------------------------------------------- /** * Adds all Repository configuration settings to a configuration model. * * @param model the configuration model to be filled. * @return the resource representing this repository configuration. */ @Override // public Resource export(Model model) { // Sesame 3 public Resource export(Graph model) { // Sesame 2 Resource implNode = super.export(model); model.add(implNode, VOID_URI, this.voidUri); if (this.endpoint != null)
// Path: src/de/uni_koblenz/west/splendid/config/FederationSailSchema.java // public static final URI VOID_URI = vf.createURI(NAMESPACE + "voidDescription"); // // Path: src/de/uni_koblenz/west/splendid/config/VoidRepositorySchema.java // public static final URI ENDPOINT = vf.createURI(NAMESPACE, "sparqlEndpoint"); // Path: src/de/uni_koblenz/west/splendid/config/VoidRepositoryConfig.java import org.openrdf.model.Statement; import org.openrdf.model.URI; import org.openrdf.model.Value; import org.openrdf.repository.config.RepositoryConfigException; import org.openrdf.repository.config.RepositoryImplConfigBase; import org.openrdf.sail.config.SailConfigException; import static de.uni_koblenz.west.splendid.config.FederationSailSchema.VOID_URI; import static de.uni_koblenz.west.splendid.config.VoidRepositorySchema.ENDPOINT; import java.util.Iterator; import org.openrdf.model.Graph; import org.openrdf.model.Resource; /* * This file is part of RDF Federator. * Copyright 2010 Olaf Goerlitz * * RDF Federator 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 3 of the License, or * (at your option) any later version. * * RDF Federator 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 RDF Federator. If not, see <http://www.gnu.org/licenses/>. * * RDF Federator uses libraries from the OpenRDF Sesame Project licensed * under the Aduna BSD-style license. */ package de.uni_koblenz.west.splendid.config; //import org.openrdf.model.Model; //import org.openrdf.model.util.ModelException; //import org.openrdf.store.StoreConfigException; /** * Configuration details for a void repository. * * @author Olaf Goerlitz */ public class VoidRepositoryConfig extends RepositoryImplConfigBase { private URI voidUri; private URI endpoint; /** * Returns the location of the VOID file. * * @return the location of the VOID file or null if it is not set. */ public URI getVoidURI() { return this.voidUri; } /** * Returns the location of the SPARQL endpoint. * * @return the location of the SPARQL endpoint or null if it is not set. */ public URI getEndpoint() { return this.endpoint; } // ------------------------------------------------------------------------- /** * Adds all Repository configuration settings to a configuration model. * * @param model the configuration model to be filled. * @return the resource representing this repository configuration. */ @Override // public Resource export(Model model) { // Sesame 3 public Resource export(Graph model) { // Sesame 2 Resource implNode = super.export(model); model.add(implNode, VOID_URI, this.voidUri); if (this.endpoint != null)
model.add(implNode, ENDPOINT, this.endpoint);
goerlitz/rdffederator
src/de/uni_koblenz/west/splendid/optimizer/DynamicProgrammingOptimizer.java
// Path: src/de/uni_koblenz/west/splendid/helpers/FilterConditionCollector.java // public class FilterConditionCollector extends QueryModelVisitorBase<RuntimeException> { // // public static List<ValueExpr> process(QueryModelNode node) { // FilterConditionCollector collector = new FilterConditionCollector(); // node.visit(collector); // return collector.conditions; // } // // private List<ValueExpr> conditions = new ArrayList<ValueExpr>(); // // @Override // public void meet(Filter node) // { // node.getArg().visit(this); // conditions.add(node.getCondition()); // } // // } // // Path: src/de/uni_koblenz/west/splendid/helpers/Format.java // public class Format { // // private static final StringBuffer b = new StringBuffer(); // private static final Formatter f = new Formatter(b, Locale.US); // // public static synchronized String d(double value, int length) { // String style = "%." + length + "f"; // b.setLength(0); // return f.format(style, value).toString(); // } // // } // // Path: src/de/uni_koblenz/west/splendid/model/BindJoin.java // public class BindJoin extends Join { // // public BindJoin(TupleExpr leftArg, TupleExpr rightArg) { // super(leftArg, rightArg); // } // // @Override // public boolean equals(Object other) { // return other instanceof BindJoin && super.equals(other); // } // // @Override // public int hashCode() { // return super.hashCode() ^ "BindJoin".hashCode(); // } // // @Override // public BindJoin clone() { // return (BindJoin)super.clone(); // } // // } // // Path: src/de/uni_koblenz/west/splendid/model/HashJoin.java // public class HashJoin extends Join { // // public HashJoin(TupleExpr leftArg, TupleExpr rightArg) { // super(leftArg, rightArg); // } // // @Override // public boolean equals(Object other) { // return other instanceof HashJoin && super.equals(other); // } // // @Override // public int hashCode() { // return super.hashCode() ^ "HashJoin".hashCode(); // } // // @Override // public HashJoin clone() { // return (HashJoin)super.clone(); // } // // }
import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.openrdf.query.algebra.Filter; import org.openrdf.query.algebra.Join; import org.openrdf.query.algebra.StatementPattern; import org.openrdf.query.algebra.TupleExpr; import org.openrdf.query.algebra.ValueExpr; import org.openrdf.query.algebra.helpers.StatementPatternCollector; import org.openrdf.query.algebra.helpers.VarNameCollector; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import de.uni_koblenz.west.splendid.helpers.FilterConditionCollector; import de.uni_koblenz.west.splendid.helpers.Format; import de.uni_koblenz.west.splendid.model.BindJoin; import de.uni_koblenz.west.splendid.model.HashJoin;
/* * This file is part of RDF Federator. * Copyright 2011 Olaf Goerlitz * * RDF Federator 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 3 of the License, or * (at your option) any later version. * * RDF Federator 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 RDF Federator. If not, see <http://www.gnu.org/licenses/>. * * RDF Federator uses libraries from the OpenRDF Sesame Project licensed * under the Aduna BSD-style license. */ package de.uni_koblenz.west.splendid.optimizer; /** * @author Olaf Goerlitz */ public class DynamicProgrammingOptimizer extends AbstractFederationOptimizer { private static final Logger LOGGER = LoggerFactory.getLogger(DynamicProgrammingOptimizer.class); private boolean bindJoin; private boolean hashJoin; public DynamicProgrammingOptimizer(boolean hashJoin, boolean bindJoin) { if (hashJoin == false && bindJoin == false) throw new IllegalArgumentException("cannot create joins: all physical join types are disabled"); this.bindJoin = bindJoin; this.hashJoin = hashJoin; } @Override public TupleExpr optimizeBGP(TupleExpr bgp) { long time = System.currentTimeMillis(); PlanCollection optPlans = new PlanCollection();
// Path: src/de/uni_koblenz/west/splendid/helpers/FilterConditionCollector.java // public class FilterConditionCollector extends QueryModelVisitorBase<RuntimeException> { // // public static List<ValueExpr> process(QueryModelNode node) { // FilterConditionCollector collector = new FilterConditionCollector(); // node.visit(collector); // return collector.conditions; // } // // private List<ValueExpr> conditions = new ArrayList<ValueExpr>(); // // @Override // public void meet(Filter node) // { // node.getArg().visit(this); // conditions.add(node.getCondition()); // } // // } // // Path: src/de/uni_koblenz/west/splendid/helpers/Format.java // public class Format { // // private static final StringBuffer b = new StringBuffer(); // private static final Formatter f = new Formatter(b, Locale.US); // // public static synchronized String d(double value, int length) { // String style = "%." + length + "f"; // b.setLength(0); // return f.format(style, value).toString(); // } // // } // // Path: src/de/uni_koblenz/west/splendid/model/BindJoin.java // public class BindJoin extends Join { // // public BindJoin(TupleExpr leftArg, TupleExpr rightArg) { // super(leftArg, rightArg); // } // // @Override // public boolean equals(Object other) { // return other instanceof BindJoin && super.equals(other); // } // // @Override // public int hashCode() { // return super.hashCode() ^ "BindJoin".hashCode(); // } // // @Override // public BindJoin clone() { // return (BindJoin)super.clone(); // } // // } // // Path: src/de/uni_koblenz/west/splendid/model/HashJoin.java // public class HashJoin extends Join { // // public HashJoin(TupleExpr leftArg, TupleExpr rightArg) { // super(leftArg, rightArg); // } // // @Override // public boolean equals(Object other) { // return other instanceof HashJoin && super.equals(other); // } // // @Override // public int hashCode() { // return super.hashCode() ^ "HashJoin".hashCode(); // } // // @Override // public HashJoin clone() { // return (HashJoin)super.clone(); // } // // } // Path: src/de/uni_koblenz/west/splendid/optimizer/DynamicProgrammingOptimizer.java import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.openrdf.query.algebra.Filter; import org.openrdf.query.algebra.Join; import org.openrdf.query.algebra.StatementPattern; import org.openrdf.query.algebra.TupleExpr; import org.openrdf.query.algebra.ValueExpr; import org.openrdf.query.algebra.helpers.StatementPatternCollector; import org.openrdf.query.algebra.helpers.VarNameCollector; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import de.uni_koblenz.west.splendid.helpers.FilterConditionCollector; import de.uni_koblenz.west.splendid.helpers.Format; import de.uni_koblenz.west.splendid.model.BindJoin; import de.uni_koblenz.west.splendid.model.HashJoin; /* * This file is part of RDF Federator. * Copyright 2011 Olaf Goerlitz * * RDF Federator 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 3 of the License, or * (at your option) any later version. * * RDF Federator 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 RDF Federator. If not, see <http://www.gnu.org/licenses/>. * * RDF Federator uses libraries from the OpenRDF Sesame Project licensed * under the Aduna BSD-style license. */ package de.uni_koblenz.west.splendid.optimizer; /** * @author Olaf Goerlitz */ public class DynamicProgrammingOptimizer extends AbstractFederationOptimizer { private static final Logger LOGGER = LoggerFactory.getLogger(DynamicProgrammingOptimizer.class); private boolean bindJoin; private boolean hashJoin; public DynamicProgrammingOptimizer(boolean hashJoin, boolean bindJoin) { if (hashJoin == false && bindJoin == false) throw new IllegalArgumentException("cannot create joins: all physical join types are disabled"); this.bindJoin = bindJoin; this.hashJoin = hashJoin; } @Override public TupleExpr optimizeBGP(TupleExpr bgp) { long time = System.currentTimeMillis(); PlanCollection optPlans = new PlanCollection();
List<ValueExpr> conditions = FilterConditionCollector.process(bgp);
goerlitz/rdffederator
src/de/uni_koblenz/west/splendid/optimizer/DynamicProgrammingOptimizer.java
// Path: src/de/uni_koblenz/west/splendid/helpers/FilterConditionCollector.java // public class FilterConditionCollector extends QueryModelVisitorBase<RuntimeException> { // // public static List<ValueExpr> process(QueryModelNode node) { // FilterConditionCollector collector = new FilterConditionCollector(); // node.visit(collector); // return collector.conditions; // } // // private List<ValueExpr> conditions = new ArrayList<ValueExpr>(); // // @Override // public void meet(Filter node) // { // node.getArg().visit(this); // conditions.add(node.getCondition()); // } // // } // // Path: src/de/uni_koblenz/west/splendid/helpers/Format.java // public class Format { // // private static final StringBuffer b = new StringBuffer(); // private static final Formatter f = new Formatter(b, Locale.US); // // public static synchronized String d(double value, int length) { // String style = "%." + length + "f"; // b.setLength(0); // return f.format(style, value).toString(); // } // // } // // Path: src/de/uni_koblenz/west/splendid/model/BindJoin.java // public class BindJoin extends Join { // // public BindJoin(TupleExpr leftArg, TupleExpr rightArg) { // super(leftArg, rightArg); // } // // @Override // public boolean equals(Object other) { // return other instanceof BindJoin && super.equals(other); // } // // @Override // public int hashCode() { // return super.hashCode() ^ "BindJoin".hashCode(); // } // // @Override // public BindJoin clone() { // return (BindJoin)super.clone(); // } // // } // // Path: src/de/uni_koblenz/west/splendid/model/HashJoin.java // public class HashJoin extends Join { // // public HashJoin(TupleExpr leftArg, TupleExpr rightArg) { // super(leftArg, rightArg); // } // // @Override // public boolean equals(Object other) { // return other instanceof HashJoin && super.equals(other); // } // // @Override // public int hashCode() { // return super.hashCode() ^ "HashJoin".hashCode(); // } // // @Override // public HashJoin clone() { // return (HashJoin)super.clone(); // } // // }
import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.openrdf.query.algebra.Filter; import org.openrdf.query.algebra.Join; import org.openrdf.query.algebra.StatementPattern; import org.openrdf.query.algebra.TupleExpr; import org.openrdf.query.algebra.ValueExpr; import org.openrdf.query.algebra.helpers.StatementPatternCollector; import org.openrdf.query.algebra.helpers.VarNameCollector; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import de.uni_koblenz.west.splendid.helpers.FilterConditionCollector; import de.uni_koblenz.west.splendid.helpers.Format; import de.uni_koblenz.west.splendid.model.BindJoin; import de.uni_koblenz.west.splendid.model.HashJoin;
// avoid joins with cross products (without a common join variable) if (vars.size() == 0) continue; // create all physical join variations for (TupleExpr join : createPhysicalJoins(leftArg, plan)) { join = applyFilters(join, filters); newPlans.add(join); } } // only cross products possible if (newPlans.size() == 0) { for (TupleExpr plan : rightArgs) { // create all physical join variations for (TupleExpr join : createPhysicalJoins(leftArg, plan)) { join = applyFilters(join, filters); newPlans.add(join); } } } return newPlans; } private List<Join> createPhysicalJoins(TupleExpr leftArg, TupleExpr rightArg) { List<Join> joins = new ArrayList<Join>(); if (bindJoin) { // need to clone the argument to maintain the proper parent reference TupleExpr left = leftArg.clone(); TupleExpr right = rightArg.clone();
// Path: src/de/uni_koblenz/west/splendid/helpers/FilterConditionCollector.java // public class FilterConditionCollector extends QueryModelVisitorBase<RuntimeException> { // // public static List<ValueExpr> process(QueryModelNode node) { // FilterConditionCollector collector = new FilterConditionCollector(); // node.visit(collector); // return collector.conditions; // } // // private List<ValueExpr> conditions = new ArrayList<ValueExpr>(); // // @Override // public void meet(Filter node) // { // node.getArg().visit(this); // conditions.add(node.getCondition()); // } // // } // // Path: src/de/uni_koblenz/west/splendid/helpers/Format.java // public class Format { // // private static final StringBuffer b = new StringBuffer(); // private static final Formatter f = new Formatter(b, Locale.US); // // public static synchronized String d(double value, int length) { // String style = "%." + length + "f"; // b.setLength(0); // return f.format(style, value).toString(); // } // // } // // Path: src/de/uni_koblenz/west/splendid/model/BindJoin.java // public class BindJoin extends Join { // // public BindJoin(TupleExpr leftArg, TupleExpr rightArg) { // super(leftArg, rightArg); // } // // @Override // public boolean equals(Object other) { // return other instanceof BindJoin && super.equals(other); // } // // @Override // public int hashCode() { // return super.hashCode() ^ "BindJoin".hashCode(); // } // // @Override // public BindJoin clone() { // return (BindJoin)super.clone(); // } // // } // // Path: src/de/uni_koblenz/west/splendid/model/HashJoin.java // public class HashJoin extends Join { // // public HashJoin(TupleExpr leftArg, TupleExpr rightArg) { // super(leftArg, rightArg); // } // // @Override // public boolean equals(Object other) { // return other instanceof HashJoin && super.equals(other); // } // // @Override // public int hashCode() { // return super.hashCode() ^ "HashJoin".hashCode(); // } // // @Override // public HashJoin clone() { // return (HashJoin)super.clone(); // } // // } // Path: src/de/uni_koblenz/west/splendid/optimizer/DynamicProgrammingOptimizer.java import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.openrdf.query.algebra.Filter; import org.openrdf.query.algebra.Join; import org.openrdf.query.algebra.StatementPattern; import org.openrdf.query.algebra.TupleExpr; import org.openrdf.query.algebra.ValueExpr; import org.openrdf.query.algebra.helpers.StatementPatternCollector; import org.openrdf.query.algebra.helpers.VarNameCollector; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import de.uni_koblenz.west.splendid.helpers.FilterConditionCollector; import de.uni_koblenz.west.splendid.helpers.Format; import de.uni_koblenz.west.splendid.model.BindJoin; import de.uni_koblenz.west.splendid.model.HashJoin; // avoid joins with cross products (without a common join variable) if (vars.size() == 0) continue; // create all physical join variations for (TupleExpr join : createPhysicalJoins(leftArg, plan)) { join = applyFilters(join, filters); newPlans.add(join); } } // only cross products possible if (newPlans.size() == 0) { for (TupleExpr plan : rightArgs) { // create all physical join variations for (TupleExpr join : createPhysicalJoins(leftArg, plan)) { join = applyFilters(join, filters); newPlans.add(join); } } } return newPlans; } private List<Join> createPhysicalJoins(TupleExpr leftArg, TupleExpr rightArg) { List<Join> joins = new ArrayList<Join>(); if (bindJoin) { // need to clone the argument to maintain the proper parent reference TupleExpr left = leftArg.clone(); TupleExpr right = rightArg.clone();
Join join = new BindJoin(left, right);
goerlitz/rdffederator
src/de/uni_koblenz/west/splendid/optimizer/DynamicProgrammingOptimizer.java
// Path: src/de/uni_koblenz/west/splendid/helpers/FilterConditionCollector.java // public class FilterConditionCollector extends QueryModelVisitorBase<RuntimeException> { // // public static List<ValueExpr> process(QueryModelNode node) { // FilterConditionCollector collector = new FilterConditionCollector(); // node.visit(collector); // return collector.conditions; // } // // private List<ValueExpr> conditions = new ArrayList<ValueExpr>(); // // @Override // public void meet(Filter node) // { // node.getArg().visit(this); // conditions.add(node.getCondition()); // } // // } // // Path: src/de/uni_koblenz/west/splendid/helpers/Format.java // public class Format { // // private static final StringBuffer b = new StringBuffer(); // private static final Formatter f = new Formatter(b, Locale.US); // // public static synchronized String d(double value, int length) { // String style = "%." + length + "f"; // b.setLength(0); // return f.format(style, value).toString(); // } // // } // // Path: src/de/uni_koblenz/west/splendid/model/BindJoin.java // public class BindJoin extends Join { // // public BindJoin(TupleExpr leftArg, TupleExpr rightArg) { // super(leftArg, rightArg); // } // // @Override // public boolean equals(Object other) { // return other instanceof BindJoin && super.equals(other); // } // // @Override // public int hashCode() { // return super.hashCode() ^ "BindJoin".hashCode(); // } // // @Override // public BindJoin clone() { // return (BindJoin)super.clone(); // } // // } // // Path: src/de/uni_koblenz/west/splendid/model/HashJoin.java // public class HashJoin extends Join { // // public HashJoin(TupleExpr leftArg, TupleExpr rightArg) { // super(leftArg, rightArg); // } // // @Override // public boolean equals(Object other) { // return other instanceof HashJoin && super.equals(other); // } // // @Override // public int hashCode() { // return super.hashCode() ^ "HashJoin".hashCode(); // } // // @Override // public HashJoin clone() { // return (HashJoin)super.clone(); // } // // }
import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.openrdf.query.algebra.Filter; import org.openrdf.query.algebra.Join; import org.openrdf.query.algebra.StatementPattern; import org.openrdf.query.algebra.TupleExpr; import org.openrdf.query.algebra.ValueExpr; import org.openrdf.query.algebra.helpers.StatementPatternCollector; import org.openrdf.query.algebra.helpers.VarNameCollector; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import de.uni_koblenz.west.splendid.helpers.FilterConditionCollector; import de.uni_koblenz.west.splendid.helpers.Format; import de.uni_koblenz.west.splendid.model.BindJoin; import de.uni_koblenz.west.splendid.model.HashJoin;
// only cross products possible if (newPlans.size() == 0) { for (TupleExpr plan : rightArgs) { // create all physical join variations for (TupleExpr join : createPhysicalJoins(leftArg, plan)) { join = applyFilters(join, filters); newPlans.add(join); } } } return newPlans; } private List<Join> createPhysicalJoins(TupleExpr leftArg, TupleExpr rightArg) { List<Join> joins = new ArrayList<Join>(); if (bindJoin) { // need to clone the argument to maintain the proper parent reference TupleExpr left = leftArg.clone(); TupleExpr right = rightArg.clone(); Join join = new BindJoin(left, right); left.setParentNode(join); right.setParentNode(join); joins.add(join); } if (hashJoin) { // need to clone the argument to maintain the proper parent reference TupleExpr left = leftArg.clone(); TupleExpr right = rightArg.clone();
// Path: src/de/uni_koblenz/west/splendid/helpers/FilterConditionCollector.java // public class FilterConditionCollector extends QueryModelVisitorBase<RuntimeException> { // // public static List<ValueExpr> process(QueryModelNode node) { // FilterConditionCollector collector = new FilterConditionCollector(); // node.visit(collector); // return collector.conditions; // } // // private List<ValueExpr> conditions = new ArrayList<ValueExpr>(); // // @Override // public void meet(Filter node) // { // node.getArg().visit(this); // conditions.add(node.getCondition()); // } // // } // // Path: src/de/uni_koblenz/west/splendid/helpers/Format.java // public class Format { // // private static final StringBuffer b = new StringBuffer(); // private static final Formatter f = new Formatter(b, Locale.US); // // public static synchronized String d(double value, int length) { // String style = "%." + length + "f"; // b.setLength(0); // return f.format(style, value).toString(); // } // // } // // Path: src/de/uni_koblenz/west/splendid/model/BindJoin.java // public class BindJoin extends Join { // // public BindJoin(TupleExpr leftArg, TupleExpr rightArg) { // super(leftArg, rightArg); // } // // @Override // public boolean equals(Object other) { // return other instanceof BindJoin && super.equals(other); // } // // @Override // public int hashCode() { // return super.hashCode() ^ "BindJoin".hashCode(); // } // // @Override // public BindJoin clone() { // return (BindJoin)super.clone(); // } // // } // // Path: src/de/uni_koblenz/west/splendid/model/HashJoin.java // public class HashJoin extends Join { // // public HashJoin(TupleExpr leftArg, TupleExpr rightArg) { // super(leftArg, rightArg); // } // // @Override // public boolean equals(Object other) { // return other instanceof HashJoin && super.equals(other); // } // // @Override // public int hashCode() { // return super.hashCode() ^ "HashJoin".hashCode(); // } // // @Override // public HashJoin clone() { // return (HashJoin)super.clone(); // } // // } // Path: src/de/uni_koblenz/west/splendid/optimizer/DynamicProgrammingOptimizer.java import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.openrdf.query.algebra.Filter; import org.openrdf.query.algebra.Join; import org.openrdf.query.algebra.StatementPattern; import org.openrdf.query.algebra.TupleExpr; import org.openrdf.query.algebra.ValueExpr; import org.openrdf.query.algebra.helpers.StatementPatternCollector; import org.openrdf.query.algebra.helpers.VarNameCollector; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import de.uni_koblenz.west.splendid.helpers.FilterConditionCollector; import de.uni_koblenz.west.splendid.helpers.Format; import de.uni_koblenz.west.splendid.model.BindJoin; import de.uni_koblenz.west.splendid.model.HashJoin; // only cross products possible if (newPlans.size() == 0) { for (TupleExpr plan : rightArgs) { // create all physical join variations for (TupleExpr join : createPhysicalJoins(leftArg, plan)) { join = applyFilters(join, filters); newPlans.add(join); } } } return newPlans; } private List<Join> createPhysicalJoins(TupleExpr leftArg, TupleExpr rightArg) { List<Join> joins = new ArrayList<Join>(); if (bindJoin) { // need to clone the argument to maintain the proper parent reference TupleExpr left = leftArg.clone(); TupleExpr right = rightArg.clone(); Join join = new BindJoin(left, right); left.setParentNode(join); right.setParentNode(join); joins.add(join); } if (hashJoin) { // need to clone the argument to maintain the proper parent reference TupleExpr left = leftArg.clone(); TupleExpr right = rightArg.clone();
Join join = new HashJoin(left, right);
goerlitz/rdffederator
src/de/uni_koblenz/west/splendid/optimizer/DynamicProgrammingOptimizer.java
// Path: src/de/uni_koblenz/west/splendid/helpers/FilterConditionCollector.java // public class FilterConditionCollector extends QueryModelVisitorBase<RuntimeException> { // // public static List<ValueExpr> process(QueryModelNode node) { // FilterConditionCollector collector = new FilterConditionCollector(); // node.visit(collector); // return collector.conditions; // } // // private List<ValueExpr> conditions = new ArrayList<ValueExpr>(); // // @Override // public void meet(Filter node) // { // node.getArg().visit(this); // conditions.add(node.getCondition()); // } // // } // // Path: src/de/uni_koblenz/west/splendid/helpers/Format.java // public class Format { // // private static final StringBuffer b = new StringBuffer(); // private static final Formatter f = new Formatter(b, Locale.US); // // public static synchronized String d(double value, int length) { // String style = "%." + length + "f"; // b.setLength(0); // return f.format(style, value).toString(); // } // // } // // Path: src/de/uni_koblenz/west/splendid/model/BindJoin.java // public class BindJoin extends Join { // // public BindJoin(TupleExpr leftArg, TupleExpr rightArg) { // super(leftArg, rightArg); // } // // @Override // public boolean equals(Object other) { // return other instanceof BindJoin && super.equals(other); // } // // @Override // public int hashCode() { // return super.hashCode() ^ "BindJoin".hashCode(); // } // // @Override // public BindJoin clone() { // return (BindJoin)super.clone(); // } // // } // // Path: src/de/uni_koblenz/west/splendid/model/HashJoin.java // public class HashJoin extends Join { // // public HashJoin(TupleExpr leftArg, TupleExpr rightArg) { // super(leftArg, rightArg); // } // // @Override // public boolean equals(Object other) { // return other instanceof HashJoin && super.equals(other); // } // // @Override // public int hashCode() { // return super.hashCode() ^ "HashJoin".hashCode(); // } // // @Override // public HashJoin clone() { // return (HashJoin)super.clone(); // } // // }
import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.openrdf.query.algebra.Filter; import org.openrdf.query.algebra.Join; import org.openrdf.query.algebra.StatementPattern; import org.openrdf.query.algebra.TupleExpr; import org.openrdf.query.algebra.ValueExpr; import org.openrdf.query.algebra.helpers.StatementPatternCollector; import org.openrdf.query.algebra.helpers.VarNameCollector; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import de.uni_koblenz.west.splendid.helpers.FilterConditionCollector; import de.uni_koblenz.west.splendid.helpers.Format; import de.uni_koblenz.west.splendid.model.BindJoin; import de.uni_koblenz.west.splendid.model.HashJoin;
// LOGGER.debug("pruning " + plans.size() + " " + arity + " plans in " + equivalentPlans.size() + " equivalence classes"); // if (LOGGER.isTraceEnabled()) { // int eqs = 0; // for (Set<O> equalSet : equivalentPlans) { // eqs++; // for (O plan : equalSet) { // String pStr = plan.toString().replace("\n", " "); // LOGGER.trace("SET [" + eqs + "] " + pStr); // } // } // } // } // Compare all plan from same equivalence class to find best one for (Set<TupleExpr> equalSet : equivalentPlans) { int planCount = 0; eqClass++; TupleExpr bestPlan = null; double lowestCost = Double.MAX_VALUE; for (TupleExpr plan : equalSet) { planCount++; double cost = costEstimator.process(plan); if (bestPlan == null || cost < lowestCost) { if (LOGGER.isTraceEnabled() && bestPlan != null) {
// Path: src/de/uni_koblenz/west/splendid/helpers/FilterConditionCollector.java // public class FilterConditionCollector extends QueryModelVisitorBase<RuntimeException> { // // public static List<ValueExpr> process(QueryModelNode node) { // FilterConditionCollector collector = new FilterConditionCollector(); // node.visit(collector); // return collector.conditions; // } // // private List<ValueExpr> conditions = new ArrayList<ValueExpr>(); // // @Override // public void meet(Filter node) // { // node.getArg().visit(this); // conditions.add(node.getCondition()); // } // // } // // Path: src/de/uni_koblenz/west/splendid/helpers/Format.java // public class Format { // // private static final StringBuffer b = new StringBuffer(); // private static final Formatter f = new Formatter(b, Locale.US); // // public static synchronized String d(double value, int length) { // String style = "%." + length + "f"; // b.setLength(0); // return f.format(style, value).toString(); // } // // } // // Path: src/de/uni_koblenz/west/splendid/model/BindJoin.java // public class BindJoin extends Join { // // public BindJoin(TupleExpr leftArg, TupleExpr rightArg) { // super(leftArg, rightArg); // } // // @Override // public boolean equals(Object other) { // return other instanceof BindJoin && super.equals(other); // } // // @Override // public int hashCode() { // return super.hashCode() ^ "BindJoin".hashCode(); // } // // @Override // public BindJoin clone() { // return (BindJoin)super.clone(); // } // // } // // Path: src/de/uni_koblenz/west/splendid/model/HashJoin.java // public class HashJoin extends Join { // // public HashJoin(TupleExpr leftArg, TupleExpr rightArg) { // super(leftArg, rightArg); // } // // @Override // public boolean equals(Object other) { // return other instanceof HashJoin && super.equals(other); // } // // @Override // public int hashCode() { // return super.hashCode() ^ "HashJoin".hashCode(); // } // // @Override // public HashJoin clone() { // return (HashJoin)super.clone(); // } // // } // Path: src/de/uni_koblenz/west/splendid/optimizer/DynamicProgrammingOptimizer.java import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.openrdf.query.algebra.Filter; import org.openrdf.query.algebra.Join; import org.openrdf.query.algebra.StatementPattern; import org.openrdf.query.algebra.TupleExpr; import org.openrdf.query.algebra.ValueExpr; import org.openrdf.query.algebra.helpers.StatementPatternCollector; import org.openrdf.query.algebra.helpers.VarNameCollector; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import de.uni_koblenz.west.splendid.helpers.FilterConditionCollector; import de.uni_koblenz.west.splendid.helpers.Format; import de.uni_koblenz.west.splendid.model.BindJoin; import de.uni_koblenz.west.splendid.model.HashJoin; // LOGGER.debug("pruning " + plans.size() + " " + arity + " plans in " + equivalentPlans.size() + " equivalence classes"); // if (LOGGER.isTraceEnabled()) { // int eqs = 0; // for (Set<O> equalSet : equivalentPlans) { // eqs++; // for (O plan : equalSet) { // String pStr = plan.toString().replace("\n", " "); // LOGGER.trace("SET [" + eqs + "] " + pStr); // } // } // } // } // Compare all plan from same equivalence class to find best one for (Set<TupleExpr> equalSet : equivalentPlans) { int planCount = 0; eqClass++; TupleExpr bestPlan = null; double lowestCost = Double.MAX_VALUE; for (TupleExpr plan : equalSet) { planCount++; double cost = costEstimator.process(plan); if (bestPlan == null || cost < lowestCost) { if (LOGGER.isTraceEnabled() && bestPlan != null) {
LOGGER.trace("found better plan (" + Format.d(cost, 2) + " < " + Format.d(lowestCost, 2) + "): " + planCount + " of " + equalSet.size() + " in class " + eqClass);
goerlitz/rdffederator
src/de/uni_koblenz/west/splendid/model/RemoteQuery.java
// Path: src/de/uni_koblenz/west/splendid/index/Graph.java // public class Graph { // // String name; // // public Graph(String name) { // this.name = name; // } // // @Override // public boolean equals(Object object) { // if (object instanceof Graph) // return this.name.equals(((Graph) object).name); // return false; // } // // @Override // public int hashCode() { // return this.name.hashCode(); // } // // public String toString() { // return this.name; // } // // public String getNamespaceURL() { // // TODO: implement proper hamespace handling // return this.name.replaceFirst("http://lodse.west.uni-koblenz.de:8080/openrdf-sesame/repositories/", "west:"); // } // // }
import java.util.Set; import org.openrdf.query.algebra.QueryModelVisitor; import org.openrdf.query.algebra.StatementPattern; import org.openrdf.query.algebra.TupleExpr; import org.openrdf.query.algebra.UnaryTupleOperator; import org.openrdf.query.algebra.helpers.StatementPatternCollector; import de.uni_koblenz.west.splendid.index.Graph;
/* * This file is part of RDF Federator. * Copyright 2011 Olaf Goerlitz * * RDF Federator 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 3 of the License, or * (at your option) any later version. * * RDF Federator 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 RDF Federator. If not, see <http://www.gnu.org/licenses/>. * * RDF Federator uses libraries from the OpenRDF Sesame Project licensed * under the Aduna BSD-style license. */ package de.uni_koblenz.west.splendid.model; /** * Query Model Node which marks a sub tree to be a group of StatementPatterns which are executed class which defines that all child arguments should be executed * in one block on a SPARQL endpoint. * * @author Olaf Goerlitz */ public class RemoteQuery extends UnaryTupleOperator { public RemoteQuery(TupleExpr expr) { super(expr); } @Override public <X extends Exception> void visit(QueryModelVisitor<X> visitor) throws X { visitor.meetOther(this); }
// Path: src/de/uni_koblenz/west/splendid/index/Graph.java // public class Graph { // // String name; // // public Graph(String name) { // this.name = name; // } // // @Override // public boolean equals(Object object) { // if (object instanceof Graph) // return this.name.equals(((Graph) object).name); // return false; // } // // @Override // public int hashCode() { // return this.name.hashCode(); // } // // public String toString() { // return this.name; // } // // public String getNamespaceURL() { // // TODO: implement proper hamespace handling // return this.name.replaceFirst("http://lodse.west.uni-koblenz.de:8080/openrdf-sesame/repositories/", "west:"); // } // // } // Path: src/de/uni_koblenz/west/splendid/model/RemoteQuery.java import java.util.Set; import org.openrdf.query.algebra.QueryModelVisitor; import org.openrdf.query.algebra.StatementPattern; import org.openrdf.query.algebra.TupleExpr; import org.openrdf.query.algebra.UnaryTupleOperator; import org.openrdf.query.algebra.helpers.StatementPatternCollector; import de.uni_koblenz.west.splendid.index.Graph; /* * This file is part of RDF Federator. * Copyright 2011 Olaf Goerlitz * * RDF Federator 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 3 of the License, or * (at your option) any later version. * * RDF Federator 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 RDF Federator. If not, see <http://www.gnu.org/licenses/>. * * RDF Federator uses libraries from the OpenRDF Sesame Project licensed * under the Aduna BSD-style license. */ package de.uni_koblenz.west.splendid.model; /** * Query Model Node which marks a sub tree to be a group of StatementPatterns which are executed class which defines that all child arguments should be executed * in one block on a SPARQL endpoint. * * @author Olaf Goerlitz */ public class RemoteQuery extends UnaryTupleOperator { public RemoteQuery(TupleExpr expr) { super(expr); } @Override public <X extends Exception> void visit(QueryModelVisitor<X> visitor) throws X { visitor.meetOther(this); }
public Set<Graph> getSources() {
goerlitz/rdffederator
src/de/uni_koblenz/west/splendid/sources/IndexSelector.java
// Path: src/de/uni_koblenz/west/splendid/index/Graph.java // public class Graph { // // String name; // // public Graph(String name) { // this.name = name; // } // // @Override // public boolean equals(Object object) { // if (object instanceof Graph) // return this.name.equals(((Graph) object).name); // return false; // } // // @Override // public int hashCode() { // return this.name.hashCode(); // } // // public String toString() { // return this.name; // } // // public String getNamespaceURL() { // // TODO: implement proper hamespace handling // return this.name.replaceFirst("http://lodse.west.uni-koblenz.de:8080/openrdf-sesame/repositories/", "west:"); // } // // }
import org.openrdf.model.Value; import org.openrdf.query.algebra.StatementPattern; import de.uni_koblenz.west.splendid.index.Graph; import java.util.Set;
/* * This file is part of RDF Federator. * Copyright 2011 Olaf Goerlitz * * RDF Federator 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 3 of the License, or * (at your option) any later version. * * RDF Federator 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 RDF Federator. If not, see <http://www.gnu.org/licenses/>. * * RDF Federator uses libraries from the OpenRDF Sesame Project licensed * under the Aduna BSD-style license. */ package de.uni_koblenz.west.splendid.sources; /** * Source selection for the supplied basic graph patterns. * Pattern subsets are built for the same set of matched sources. * * @author Olaf Goerlitz */ public class IndexSelector extends SourceSelectorBase { private boolean useTypeStats = true; /** * Creates a source finder using the supplied statistics. * * @param stats the statistics to use. */ public IndexSelector(boolean useTypeStats) { this.useTypeStats = useTypeStats; } /** * Find matching sources for the supplied pattern. * * @param patterns the pattern that need to matched to sources. * @return the set of source which can contribute results for the pattern. */ @Override
// Path: src/de/uni_koblenz/west/splendid/index/Graph.java // public class Graph { // // String name; // // public Graph(String name) { // this.name = name; // } // // @Override // public boolean equals(Object object) { // if (object instanceof Graph) // return this.name.equals(((Graph) object).name); // return false; // } // // @Override // public int hashCode() { // return this.name.hashCode(); // } // // public String toString() { // return this.name; // } // // public String getNamespaceURL() { // // TODO: implement proper hamespace handling // return this.name.replaceFirst("http://lodse.west.uni-koblenz.de:8080/openrdf-sesame/repositories/", "west:"); // } // // } // Path: src/de/uni_koblenz/west/splendid/sources/IndexSelector.java import org.openrdf.model.Value; import org.openrdf.query.algebra.StatementPattern; import de.uni_koblenz.west.splendid.index.Graph; import java.util.Set; /* * This file is part of RDF Federator. * Copyright 2011 Olaf Goerlitz * * RDF Federator 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 3 of the License, or * (at your option) any later version. * * RDF Federator 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 RDF Federator. If not, see <http://www.gnu.org/licenses/>. * * RDF Federator uses libraries from the OpenRDF Sesame Project licensed * under the Aduna BSD-style license. */ package de.uni_koblenz.west.splendid.sources; /** * Source selection for the supplied basic graph patterns. * Pattern subsets are built for the same set of matched sources. * * @author Olaf Goerlitz */ public class IndexSelector extends SourceSelectorBase { private boolean useTypeStats = true; /** * Creates a source finder using the supplied statistics. * * @param stats the statistics to use. */ public IndexSelector(boolean useTypeStats) { this.useTypeStats = useTypeStats; } /** * Find matching sources for the supplied pattern. * * @param patterns the pattern that need to matched to sources. * @return the set of source which can contribute results for the pattern. */ @Override
protected Set<Graph> getSources(StatementPattern pattern) {
ralscha/spring4ws-demos
src/main/java/ch/rasc/s4ws/portfolio/service/PortfolioServiceImpl.java
// Path: src/main/java/ch/rasc/s4ws/portfolio/Portfolio.java // public class Portfolio { // // private final Map<String, PortfolioPosition> positionLookup = new LinkedHashMap<>(); // // public List<PortfolioPosition> getPositions() { // return new ArrayList<>(this.positionLookup.values()); // } // // public void addPosition(PortfolioPosition position) { // this.positionLookup.put(position.getTicker(), position); // } // // public PortfolioPosition getPortfolioPosition(String ticker) { // return this.positionLookup.get(ticker); // } // // /** // * @return the updated position or null // */ // public PortfolioPosition buy(String ticker, int sharesToBuy) { // PortfolioPosition position = this.positionLookup.get(ticker); // if (position == null || sharesToBuy < 1) { // return null; // } // position = new PortfolioPosition(position, sharesToBuy); // this.positionLookup.put(ticker, position); // return position; // } // // /** // * @return the updated position or null // */ // public PortfolioPosition sell(String ticker, int sharesToSell) { // PortfolioPosition position = this.positionLookup.get(ticker); // if (position == null || sharesToSell < 1 || position.getShares() < sharesToSell) { // return null; // } // position = new PortfolioPosition(position, -sharesToSell); // this.positionLookup.put(ticker, position); // return position; // } // // } // // Path: src/main/java/ch/rasc/s4ws/portfolio/PortfolioPosition.java // public class PortfolioPosition { // // private final String company; // // private final String ticker; // // private final double price; // // private final int shares; // // private final long updateTime; // // public PortfolioPosition(String company, String ticker, double price, int shares) { // this.company = company; // this.ticker = ticker; // this.price = price; // this.shares = shares; // this.updateTime = System.currentTimeMillis(); // } // // public PortfolioPosition(PortfolioPosition other, int sharesToAddOrSubtract) { // this.company = other.company; // this.ticker = other.ticker; // this.price = other.price; // this.shares = other.shares + sharesToAddOrSubtract; // this.updateTime = System.currentTimeMillis(); // } // // public String getCompany() { // return this.company; // } // // public String getTicker() { // return this.ticker; // } // // public double getPrice() { // return this.price; // } // // public int getShares() { // return this.shares; // } // // public long getUpdateTime() { // return this.updateTime; // } // // @Override // public String toString() { // return "PortfolioPosition [company=" + this.company + ", ticker=" + this.ticker // + ", price=" + this.price + ", shares=" + this.shares + "]"; // } // // }
import java.util.HashMap; import java.util.Map; import org.springframework.stereotype.Service; import ch.rasc.s4ws.portfolio.Portfolio; import ch.rasc.s4ws.portfolio.PortfolioPosition;
/* * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.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://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ch.rasc.s4ws.portfolio.service; /** * @author Rob Winch */ @Service public class PortfolioServiceImpl implements PortfolioService { // user -> Portfolio
// Path: src/main/java/ch/rasc/s4ws/portfolio/Portfolio.java // public class Portfolio { // // private final Map<String, PortfolioPosition> positionLookup = new LinkedHashMap<>(); // // public List<PortfolioPosition> getPositions() { // return new ArrayList<>(this.positionLookup.values()); // } // // public void addPosition(PortfolioPosition position) { // this.positionLookup.put(position.getTicker(), position); // } // // public PortfolioPosition getPortfolioPosition(String ticker) { // return this.positionLookup.get(ticker); // } // // /** // * @return the updated position or null // */ // public PortfolioPosition buy(String ticker, int sharesToBuy) { // PortfolioPosition position = this.positionLookup.get(ticker); // if (position == null || sharesToBuy < 1) { // return null; // } // position = new PortfolioPosition(position, sharesToBuy); // this.positionLookup.put(ticker, position); // return position; // } // // /** // * @return the updated position or null // */ // public PortfolioPosition sell(String ticker, int sharesToSell) { // PortfolioPosition position = this.positionLookup.get(ticker); // if (position == null || sharesToSell < 1 || position.getShares() < sharesToSell) { // return null; // } // position = new PortfolioPosition(position, -sharesToSell); // this.positionLookup.put(ticker, position); // return position; // } // // } // // Path: src/main/java/ch/rasc/s4ws/portfolio/PortfolioPosition.java // public class PortfolioPosition { // // private final String company; // // private final String ticker; // // private final double price; // // private final int shares; // // private final long updateTime; // // public PortfolioPosition(String company, String ticker, double price, int shares) { // this.company = company; // this.ticker = ticker; // this.price = price; // this.shares = shares; // this.updateTime = System.currentTimeMillis(); // } // // public PortfolioPosition(PortfolioPosition other, int sharesToAddOrSubtract) { // this.company = other.company; // this.ticker = other.ticker; // this.price = other.price; // this.shares = other.shares + sharesToAddOrSubtract; // this.updateTime = System.currentTimeMillis(); // } // // public String getCompany() { // return this.company; // } // // public String getTicker() { // return this.ticker; // } // // public double getPrice() { // return this.price; // } // // public int getShares() { // return this.shares; // } // // public long getUpdateTime() { // return this.updateTime; // } // // @Override // public String toString() { // return "PortfolioPosition [company=" + this.company + ", ticker=" + this.ticker // + ", price=" + this.price + ", shares=" + this.shares + "]"; // } // // } // Path: src/main/java/ch/rasc/s4ws/portfolio/service/PortfolioServiceImpl.java import java.util.HashMap; import java.util.Map; import org.springframework.stereotype.Service; import ch.rasc.s4ws.portfolio.Portfolio; import ch.rasc.s4ws.portfolio.PortfolioPosition; /* * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.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://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ch.rasc.s4ws.portfolio.service; /** * @author Rob Winch */ @Service public class PortfolioServiceImpl implements PortfolioService { // user -> Portfolio
private final Map<String, Portfolio> portfolioLookup = new HashMap<>();
ralscha/spring4ws-demos
src/main/java/ch/rasc/s4ws/portfolio/service/PortfolioServiceImpl.java
// Path: src/main/java/ch/rasc/s4ws/portfolio/Portfolio.java // public class Portfolio { // // private final Map<String, PortfolioPosition> positionLookup = new LinkedHashMap<>(); // // public List<PortfolioPosition> getPositions() { // return new ArrayList<>(this.positionLookup.values()); // } // // public void addPosition(PortfolioPosition position) { // this.positionLookup.put(position.getTicker(), position); // } // // public PortfolioPosition getPortfolioPosition(String ticker) { // return this.positionLookup.get(ticker); // } // // /** // * @return the updated position or null // */ // public PortfolioPosition buy(String ticker, int sharesToBuy) { // PortfolioPosition position = this.positionLookup.get(ticker); // if (position == null || sharesToBuy < 1) { // return null; // } // position = new PortfolioPosition(position, sharesToBuy); // this.positionLookup.put(ticker, position); // return position; // } // // /** // * @return the updated position or null // */ // public PortfolioPosition sell(String ticker, int sharesToSell) { // PortfolioPosition position = this.positionLookup.get(ticker); // if (position == null || sharesToSell < 1 || position.getShares() < sharesToSell) { // return null; // } // position = new PortfolioPosition(position, -sharesToSell); // this.positionLookup.put(ticker, position); // return position; // } // // } // // Path: src/main/java/ch/rasc/s4ws/portfolio/PortfolioPosition.java // public class PortfolioPosition { // // private final String company; // // private final String ticker; // // private final double price; // // private final int shares; // // private final long updateTime; // // public PortfolioPosition(String company, String ticker, double price, int shares) { // this.company = company; // this.ticker = ticker; // this.price = price; // this.shares = shares; // this.updateTime = System.currentTimeMillis(); // } // // public PortfolioPosition(PortfolioPosition other, int sharesToAddOrSubtract) { // this.company = other.company; // this.ticker = other.ticker; // this.price = other.price; // this.shares = other.shares + sharesToAddOrSubtract; // this.updateTime = System.currentTimeMillis(); // } // // public String getCompany() { // return this.company; // } // // public String getTicker() { // return this.ticker; // } // // public double getPrice() { // return this.price; // } // // public int getShares() { // return this.shares; // } // // public long getUpdateTime() { // return this.updateTime; // } // // @Override // public String toString() { // return "PortfolioPosition [company=" + this.company + ", ticker=" + this.ticker // + ", price=" + this.price + ", shares=" + this.shares + "]"; // } // // }
import java.util.HashMap; import java.util.Map; import org.springframework.stereotype.Service; import ch.rasc.s4ws.portfolio.Portfolio; import ch.rasc.s4ws.portfolio.PortfolioPosition;
/* * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.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://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ch.rasc.s4ws.portfolio.service; /** * @author Rob Winch */ @Service public class PortfolioServiceImpl implements PortfolioService { // user -> Portfolio private final Map<String, Portfolio> portfolioLookup = new HashMap<>(); public PortfolioServiceImpl() { Portfolio portfolio = new Portfolio(); portfolio.addPosition(
// Path: src/main/java/ch/rasc/s4ws/portfolio/Portfolio.java // public class Portfolio { // // private final Map<String, PortfolioPosition> positionLookup = new LinkedHashMap<>(); // // public List<PortfolioPosition> getPositions() { // return new ArrayList<>(this.positionLookup.values()); // } // // public void addPosition(PortfolioPosition position) { // this.positionLookup.put(position.getTicker(), position); // } // // public PortfolioPosition getPortfolioPosition(String ticker) { // return this.positionLookup.get(ticker); // } // // /** // * @return the updated position or null // */ // public PortfolioPosition buy(String ticker, int sharesToBuy) { // PortfolioPosition position = this.positionLookup.get(ticker); // if (position == null || sharesToBuy < 1) { // return null; // } // position = new PortfolioPosition(position, sharesToBuy); // this.positionLookup.put(ticker, position); // return position; // } // // /** // * @return the updated position or null // */ // public PortfolioPosition sell(String ticker, int sharesToSell) { // PortfolioPosition position = this.positionLookup.get(ticker); // if (position == null || sharesToSell < 1 || position.getShares() < sharesToSell) { // return null; // } // position = new PortfolioPosition(position, -sharesToSell); // this.positionLookup.put(ticker, position); // return position; // } // // } // // Path: src/main/java/ch/rasc/s4ws/portfolio/PortfolioPosition.java // public class PortfolioPosition { // // private final String company; // // private final String ticker; // // private final double price; // // private final int shares; // // private final long updateTime; // // public PortfolioPosition(String company, String ticker, double price, int shares) { // this.company = company; // this.ticker = ticker; // this.price = price; // this.shares = shares; // this.updateTime = System.currentTimeMillis(); // } // // public PortfolioPosition(PortfolioPosition other, int sharesToAddOrSubtract) { // this.company = other.company; // this.ticker = other.ticker; // this.price = other.price; // this.shares = other.shares + sharesToAddOrSubtract; // this.updateTime = System.currentTimeMillis(); // } // // public String getCompany() { // return this.company; // } // // public String getTicker() { // return this.ticker; // } // // public double getPrice() { // return this.price; // } // // public int getShares() { // return this.shares; // } // // public long getUpdateTime() { // return this.updateTime; // } // // @Override // public String toString() { // return "PortfolioPosition [company=" + this.company + ", ticker=" + this.ticker // + ", price=" + this.price + ", shares=" + this.shares + "]"; // } // // } // Path: src/main/java/ch/rasc/s4ws/portfolio/service/PortfolioServiceImpl.java import java.util.HashMap; import java.util.Map; import org.springframework.stereotype.Service; import ch.rasc.s4ws.portfolio.Portfolio; import ch.rasc.s4ws.portfolio.PortfolioPosition; /* * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.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://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ch.rasc.s4ws.portfolio.service; /** * @author Rob Winch */ @Service public class PortfolioServiceImpl implements PortfolioService { // user -> Portfolio private final Map<String, Portfolio> portfolioLookup = new HashMap<>(); public PortfolioServiceImpl() { Portfolio portfolio = new Portfolio(); portfolio.addPosition(
new PortfolioPosition("Citrix Systems, Inc.", "CTXS", 24.30, 75));
ralscha/spring4ws-demos
src/main/java/ch/rasc/s4ws/portfolio/service/TradeServiceImpl.java
// Path: src/main/java/ch/rasc/s4ws/portfolio/Portfolio.java // public class Portfolio { // // private final Map<String, PortfolioPosition> positionLookup = new LinkedHashMap<>(); // // public List<PortfolioPosition> getPositions() { // return new ArrayList<>(this.positionLookup.values()); // } // // public void addPosition(PortfolioPosition position) { // this.positionLookup.put(position.getTicker(), position); // } // // public PortfolioPosition getPortfolioPosition(String ticker) { // return this.positionLookup.get(ticker); // } // // /** // * @return the updated position or null // */ // public PortfolioPosition buy(String ticker, int sharesToBuy) { // PortfolioPosition position = this.positionLookup.get(ticker); // if (position == null || sharesToBuy < 1) { // return null; // } // position = new PortfolioPosition(position, sharesToBuy); // this.positionLookup.put(ticker, position); // return position; // } // // /** // * @return the updated position or null // */ // public PortfolioPosition sell(String ticker, int sharesToSell) { // PortfolioPosition position = this.positionLookup.get(ticker); // if (position == null || sharesToSell < 1 || position.getShares() < sharesToSell) { // return null; // } // position = new PortfolioPosition(position, -sharesToSell); // this.positionLookup.put(ticker, position); // return position; // } // // } // // Path: src/main/java/ch/rasc/s4ws/portfolio/PortfolioPosition.java // public class PortfolioPosition { // // private final String company; // // private final String ticker; // // private final double price; // // private final int shares; // // private final long updateTime; // // public PortfolioPosition(String company, String ticker, double price, int shares) { // this.company = company; // this.ticker = ticker; // this.price = price; // this.shares = shares; // this.updateTime = System.currentTimeMillis(); // } // // public PortfolioPosition(PortfolioPosition other, int sharesToAddOrSubtract) { // this.company = other.company; // this.ticker = other.ticker; // this.price = other.price; // this.shares = other.shares + sharesToAddOrSubtract; // this.updateTime = System.currentTimeMillis(); // } // // public String getCompany() { // return this.company; // } // // public String getTicker() { // return this.ticker; // } // // public double getPrice() { // return this.price; // } // // public int getShares() { // return this.shares; // } // // public long getUpdateTime() { // return this.updateTime; // } // // @Override // public String toString() { // return "PortfolioPosition [company=" + this.company + ", ticker=" + this.ticker // + ", price=" + this.price + ", shares=" + this.shares + "]"; // } // // } // // Path: src/main/java/ch/rasc/s4ws/portfolio/service/Trade.java // public enum TradeAction { // Buy, Sell; // }
import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.messaging.simp.SimpMessageSendingOperations; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; import ch.rasc.s4ws.portfolio.Portfolio; import ch.rasc.s4ws.portfolio.PortfolioPosition; import ch.rasc.s4ws.portfolio.service.Trade.TradeAction;
/* * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.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://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ch.rasc.s4ws.portfolio.service; @Service public class TradeServiceImpl implements TradeService { private static final Log logger = LogFactory.getLog(TradeServiceImpl.class); private final SimpMessageSendingOperations messagingTemplate; private final PortfolioService portfolioService; private final List<TradeResult> tradeResults = new CopyOnWriteArrayList<>(); @Autowired public TradeServiceImpl(SimpMessageSendingOperations messagingTemplate, PortfolioService portfolioService) { this.messagingTemplate = messagingTemplate; this.portfolioService = portfolioService; } /** * In real application a trade is probably executed in an external system, i.e. * asynchronously. */ @Override public void executeTrade(Trade trade) {
// Path: src/main/java/ch/rasc/s4ws/portfolio/Portfolio.java // public class Portfolio { // // private final Map<String, PortfolioPosition> positionLookup = new LinkedHashMap<>(); // // public List<PortfolioPosition> getPositions() { // return new ArrayList<>(this.positionLookup.values()); // } // // public void addPosition(PortfolioPosition position) { // this.positionLookup.put(position.getTicker(), position); // } // // public PortfolioPosition getPortfolioPosition(String ticker) { // return this.positionLookup.get(ticker); // } // // /** // * @return the updated position or null // */ // public PortfolioPosition buy(String ticker, int sharesToBuy) { // PortfolioPosition position = this.positionLookup.get(ticker); // if (position == null || sharesToBuy < 1) { // return null; // } // position = new PortfolioPosition(position, sharesToBuy); // this.positionLookup.put(ticker, position); // return position; // } // // /** // * @return the updated position or null // */ // public PortfolioPosition sell(String ticker, int sharesToSell) { // PortfolioPosition position = this.positionLookup.get(ticker); // if (position == null || sharesToSell < 1 || position.getShares() < sharesToSell) { // return null; // } // position = new PortfolioPosition(position, -sharesToSell); // this.positionLookup.put(ticker, position); // return position; // } // // } // // Path: src/main/java/ch/rasc/s4ws/portfolio/PortfolioPosition.java // public class PortfolioPosition { // // private final String company; // // private final String ticker; // // private final double price; // // private final int shares; // // private final long updateTime; // // public PortfolioPosition(String company, String ticker, double price, int shares) { // this.company = company; // this.ticker = ticker; // this.price = price; // this.shares = shares; // this.updateTime = System.currentTimeMillis(); // } // // public PortfolioPosition(PortfolioPosition other, int sharesToAddOrSubtract) { // this.company = other.company; // this.ticker = other.ticker; // this.price = other.price; // this.shares = other.shares + sharesToAddOrSubtract; // this.updateTime = System.currentTimeMillis(); // } // // public String getCompany() { // return this.company; // } // // public String getTicker() { // return this.ticker; // } // // public double getPrice() { // return this.price; // } // // public int getShares() { // return this.shares; // } // // public long getUpdateTime() { // return this.updateTime; // } // // @Override // public String toString() { // return "PortfolioPosition [company=" + this.company + ", ticker=" + this.ticker // + ", price=" + this.price + ", shares=" + this.shares + "]"; // } // // } // // Path: src/main/java/ch/rasc/s4ws/portfolio/service/Trade.java // public enum TradeAction { // Buy, Sell; // } // Path: src/main/java/ch/rasc/s4ws/portfolio/service/TradeServiceImpl.java import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.messaging.simp.SimpMessageSendingOperations; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; import ch.rasc.s4ws.portfolio.Portfolio; import ch.rasc.s4ws.portfolio.PortfolioPosition; import ch.rasc.s4ws.portfolio.service.Trade.TradeAction; /* * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.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://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ch.rasc.s4ws.portfolio.service; @Service public class TradeServiceImpl implements TradeService { private static final Log logger = LogFactory.getLog(TradeServiceImpl.class); private final SimpMessageSendingOperations messagingTemplate; private final PortfolioService portfolioService; private final List<TradeResult> tradeResults = new CopyOnWriteArrayList<>(); @Autowired public TradeServiceImpl(SimpMessageSendingOperations messagingTemplate, PortfolioService portfolioService) { this.messagingTemplate = messagingTemplate; this.portfolioService = portfolioService; } /** * In real application a trade is probably executed in an external system, i.e. * asynchronously. */ @Override public void executeTrade(Trade trade) {
Portfolio portfolio = this.portfolioService.findPortfolio(trade.getUsername());
ralscha/spring4ws-demos
src/main/java/ch/rasc/s4ws/portfolio/service/TradeServiceImpl.java
// Path: src/main/java/ch/rasc/s4ws/portfolio/Portfolio.java // public class Portfolio { // // private final Map<String, PortfolioPosition> positionLookup = new LinkedHashMap<>(); // // public List<PortfolioPosition> getPositions() { // return new ArrayList<>(this.positionLookup.values()); // } // // public void addPosition(PortfolioPosition position) { // this.positionLookup.put(position.getTicker(), position); // } // // public PortfolioPosition getPortfolioPosition(String ticker) { // return this.positionLookup.get(ticker); // } // // /** // * @return the updated position or null // */ // public PortfolioPosition buy(String ticker, int sharesToBuy) { // PortfolioPosition position = this.positionLookup.get(ticker); // if (position == null || sharesToBuy < 1) { // return null; // } // position = new PortfolioPosition(position, sharesToBuy); // this.positionLookup.put(ticker, position); // return position; // } // // /** // * @return the updated position or null // */ // public PortfolioPosition sell(String ticker, int sharesToSell) { // PortfolioPosition position = this.positionLookup.get(ticker); // if (position == null || sharesToSell < 1 || position.getShares() < sharesToSell) { // return null; // } // position = new PortfolioPosition(position, -sharesToSell); // this.positionLookup.put(ticker, position); // return position; // } // // } // // Path: src/main/java/ch/rasc/s4ws/portfolio/PortfolioPosition.java // public class PortfolioPosition { // // private final String company; // // private final String ticker; // // private final double price; // // private final int shares; // // private final long updateTime; // // public PortfolioPosition(String company, String ticker, double price, int shares) { // this.company = company; // this.ticker = ticker; // this.price = price; // this.shares = shares; // this.updateTime = System.currentTimeMillis(); // } // // public PortfolioPosition(PortfolioPosition other, int sharesToAddOrSubtract) { // this.company = other.company; // this.ticker = other.ticker; // this.price = other.price; // this.shares = other.shares + sharesToAddOrSubtract; // this.updateTime = System.currentTimeMillis(); // } // // public String getCompany() { // return this.company; // } // // public String getTicker() { // return this.ticker; // } // // public double getPrice() { // return this.price; // } // // public int getShares() { // return this.shares; // } // // public long getUpdateTime() { // return this.updateTime; // } // // @Override // public String toString() { // return "PortfolioPosition [company=" + this.company + ", ticker=" + this.ticker // + ", price=" + this.price + ", shares=" + this.shares + "]"; // } // // } // // Path: src/main/java/ch/rasc/s4ws/portfolio/service/Trade.java // public enum TradeAction { // Buy, Sell; // }
import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.messaging.simp.SimpMessageSendingOperations; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; import ch.rasc.s4ws.portfolio.Portfolio; import ch.rasc.s4ws.portfolio.PortfolioPosition; import ch.rasc.s4ws.portfolio.service.Trade.TradeAction;
/* * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.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://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ch.rasc.s4ws.portfolio.service; @Service public class TradeServiceImpl implements TradeService { private static final Log logger = LogFactory.getLog(TradeServiceImpl.class); private final SimpMessageSendingOperations messagingTemplate; private final PortfolioService portfolioService; private final List<TradeResult> tradeResults = new CopyOnWriteArrayList<>(); @Autowired public TradeServiceImpl(SimpMessageSendingOperations messagingTemplate, PortfolioService portfolioService) { this.messagingTemplate = messagingTemplate; this.portfolioService = portfolioService; } /** * In real application a trade is probably executed in an external system, i.e. * asynchronously. */ @Override public void executeTrade(Trade trade) { Portfolio portfolio = this.portfolioService.findPortfolio(trade.getUsername()); String ticker = trade.getTicker(); int sharesToTrade = trade.getShares();
// Path: src/main/java/ch/rasc/s4ws/portfolio/Portfolio.java // public class Portfolio { // // private final Map<String, PortfolioPosition> positionLookup = new LinkedHashMap<>(); // // public List<PortfolioPosition> getPositions() { // return new ArrayList<>(this.positionLookup.values()); // } // // public void addPosition(PortfolioPosition position) { // this.positionLookup.put(position.getTicker(), position); // } // // public PortfolioPosition getPortfolioPosition(String ticker) { // return this.positionLookup.get(ticker); // } // // /** // * @return the updated position or null // */ // public PortfolioPosition buy(String ticker, int sharesToBuy) { // PortfolioPosition position = this.positionLookup.get(ticker); // if (position == null || sharesToBuy < 1) { // return null; // } // position = new PortfolioPosition(position, sharesToBuy); // this.positionLookup.put(ticker, position); // return position; // } // // /** // * @return the updated position or null // */ // public PortfolioPosition sell(String ticker, int sharesToSell) { // PortfolioPosition position = this.positionLookup.get(ticker); // if (position == null || sharesToSell < 1 || position.getShares() < sharesToSell) { // return null; // } // position = new PortfolioPosition(position, -sharesToSell); // this.positionLookup.put(ticker, position); // return position; // } // // } // // Path: src/main/java/ch/rasc/s4ws/portfolio/PortfolioPosition.java // public class PortfolioPosition { // // private final String company; // // private final String ticker; // // private final double price; // // private final int shares; // // private final long updateTime; // // public PortfolioPosition(String company, String ticker, double price, int shares) { // this.company = company; // this.ticker = ticker; // this.price = price; // this.shares = shares; // this.updateTime = System.currentTimeMillis(); // } // // public PortfolioPosition(PortfolioPosition other, int sharesToAddOrSubtract) { // this.company = other.company; // this.ticker = other.ticker; // this.price = other.price; // this.shares = other.shares + sharesToAddOrSubtract; // this.updateTime = System.currentTimeMillis(); // } // // public String getCompany() { // return this.company; // } // // public String getTicker() { // return this.ticker; // } // // public double getPrice() { // return this.price; // } // // public int getShares() { // return this.shares; // } // // public long getUpdateTime() { // return this.updateTime; // } // // @Override // public String toString() { // return "PortfolioPosition [company=" + this.company + ", ticker=" + this.ticker // + ", price=" + this.price + ", shares=" + this.shares + "]"; // } // // } // // Path: src/main/java/ch/rasc/s4ws/portfolio/service/Trade.java // public enum TradeAction { // Buy, Sell; // } // Path: src/main/java/ch/rasc/s4ws/portfolio/service/TradeServiceImpl.java import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.messaging.simp.SimpMessageSendingOperations; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; import ch.rasc.s4ws.portfolio.Portfolio; import ch.rasc.s4ws.portfolio.PortfolioPosition; import ch.rasc.s4ws.portfolio.service.Trade.TradeAction; /* * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.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://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ch.rasc.s4ws.portfolio.service; @Service public class TradeServiceImpl implements TradeService { private static final Log logger = LogFactory.getLog(TradeServiceImpl.class); private final SimpMessageSendingOperations messagingTemplate; private final PortfolioService portfolioService; private final List<TradeResult> tradeResults = new CopyOnWriteArrayList<>(); @Autowired public TradeServiceImpl(SimpMessageSendingOperations messagingTemplate, PortfolioService portfolioService) { this.messagingTemplate = messagingTemplate; this.portfolioService = portfolioService; } /** * In real application a trade is probably executed in an external system, i.e. * asynchronously. */ @Override public void executeTrade(Trade trade) { Portfolio portfolio = this.portfolioService.findPortfolio(trade.getUsername()); String ticker = trade.getTicker(); int sharesToTrade = trade.getShares();
PortfolioPosition newPosition = trade.getAction() == TradeAction.Buy
ralscha/spring4ws-demos
src/main/java/ch/rasc/s4ws/portfolio/service/TradeServiceImpl.java
// Path: src/main/java/ch/rasc/s4ws/portfolio/Portfolio.java // public class Portfolio { // // private final Map<String, PortfolioPosition> positionLookup = new LinkedHashMap<>(); // // public List<PortfolioPosition> getPositions() { // return new ArrayList<>(this.positionLookup.values()); // } // // public void addPosition(PortfolioPosition position) { // this.positionLookup.put(position.getTicker(), position); // } // // public PortfolioPosition getPortfolioPosition(String ticker) { // return this.positionLookup.get(ticker); // } // // /** // * @return the updated position or null // */ // public PortfolioPosition buy(String ticker, int sharesToBuy) { // PortfolioPosition position = this.positionLookup.get(ticker); // if (position == null || sharesToBuy < 1) { // return null; // } // position = new PortfolioPosition(position, sharesToBuy); // this.positionLookup.put(ticker, position); // return position; // } // // /** // * @return the updated position or null // */ // public PortfolioPosition sell(String ticker, int sharesToSell) { // PortfolioPosition position = this.positionLookup.get(ticker); // if (position == null || sharesToSell < 1 || position.getShares() < sharesToSell) { // return null; // } // position = new PortfolioPosition(position, -sharesToSell); // this.positionLookup.put(ticker, position); // return position; // } // // } // // Path: src/main/java/ch/rasc/s4ws/portfolio/PortfolioPosition.java // public class PortfolioPosition { // // private final String company; // // private final String ticker; // // private final double price; // // private final int shares; // // private final long updateTime; // // public PortfolioPosition(String company, String ticker, double price, int shares) { // this.company = company; // this.ticker = ticker; // this.price = price; // this.shares = shares; // this.updateTime = System.currentTimeMillis(); // } // // public PortfolioPosition(PortfolioPosition other, int sharesToAddOrSubtract) { // this.company = other.company; // this.ticker = other.ticker; // this.price = other.price; // this.shares = other.shares + sharesToAddOrSubtract; // this.updateTime = System.currentTimeMillis(); // } // // public String getCompany() { // return this.company; // } // // public String getTicker() { // return this.ticker; // } // // public double getPrice() { // return this.price; // } // // public int getShares() { // return this.shares; // } // // public long getUpdateTime() { // return this.updateTime; // } // // @Override // public String toString() { // return "PortfolioPosition [company=" + this.company + ", ticker=" + this.ticker // + ", price=" + this.price + ", shares=" + this.shares + "]"; // } // // } // // Path: src/main/java/ch/rasc/s4ws/portfolio/service/Trade.java // public enum TradeAction { // Buy, Sell; // }
import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.messaging.simp.SimpMessageSendingOperations; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; import ch.rasc.s4ws.portfolio.Portfolio; import ch.rasc.s4ws.portfolio.PortfolioPosition; import ch.rasc.s4ws.portfolio.service.Trade.TradeAction;
/* * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.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://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ch.rasc.s4ws.portfolio.service; @Service public class TradeServiceImpl implements TradeService { private static final Log logger = LogFactory.getLog(TradeServiceImpl.class); private final SimpMessageSendingOperations messagingTemplate; private final PortfolioService portfolioService; private final List<TradeResult> tradeResults = new CopyOnWriteArrayList<>(); @Autowired public TradeServiceImpl(SimpMessageSendingOperations messagingTemplate, PortfolioService portfolioService) { this.messagingTemplate = messagingTemplate; this.portfolioService = portfolioService; } /** * In real application a trade is probably executed in an external system, i.e. * asynchronously. */ @Override public void executeTrade(Trade trade) { Portfolio portfolio = this.portfolioService.findPortfolio(trade.getUsername()); String ticker = trade.getTicker(); int sharesToTrade = trade.getShares();
// Path: src/main/java/ch/rasc/s4ws/portfolio/Portfolio.java // public class Portfolio { // // private final Map<String, PortfolioPosition> positionLookup = new LinkedHashMap<>(); // // public List<PortfolioPosition> getPositions() { // return new ArrayList<>(this.positionLookup.values()); // } // // public void addPosition(PortfolioPosition position) { // this.positionLookup.put(position.getTicker(), position); // } // // public PortfolioPosition getPortfolioPosition(String ticker) { // return this.positionLookup.get(ticker); // } // // /** // * @return the updated position or null // */ // public PortfolioPosition buy(String ticker, int sharesToBuy) { // PortfolioPosition position = this.positionLookup.get(ticker); // if (position == null || sharesToBuy < 1) { // return null; // } // position = new PortfolioPosition(position, sharesToBuy); // this.positionLookup.put(ticker, position); // return position; // } // // /** // * @return the updated position or null // */ // public PortfolioPosition sell(String ticker, int sharesToSell) { // PortfolioPosition position = this.positionLookup.get(ticker); // if (position == null || sharesToSell < 1 || position.getShares() < sharesToSell) { // return null; // } // position = new PortfolioPosition(position, -sharesToSell); // this.positionLookup.put(ticker, position); // return position; // } // // } // // Path: src/main/java/ch/rasc/s4ws/portfolio/PortfolioPosition.java // public class PortfolioPosition { // // private final String company; // // private final String ticker; // // private final double price; // // private final int shares; // // private final long updateTime; // // public PortfolioPosition(String company, String ticker, double price, int shares) { // this.company = company; // this.ticker = ticker; // this.price = price; // this.shares = shares; // this.updateTime = System.currentTimeMillis(); // } // // public PortfolioPosition(PortfolioPosition other, int sharesToAddOrSubtract) { // this.company = other.company; // this.ticker = other.ticker; // this.price = other.price; // this.shares = other.shares + sharesToAddOrSubtract; // this.updateTime = System.currentTimeMillis(); // } // // public String getCompany() { // return this.company; // } // // public String getTicker() { // return this.ticker; // } // // public double getPrice() { // return this.price; // } // // public int getShares() { // return this.shares; // } // // public long getUpdateTime() { // return this.updateTime; // } // // @Override // public String toString() { // return "PortfolioPosition [company=" + this.company + ", ticker=" + this.ticker // + ", price=" + this.price + ", shares=" + this.shares + "]"; // } // // } // // Path: src/main/java/ch/rasc/s4ws/portfolio/service/Trade.java // public enum TradeAction { // Buy, Sell; // } // Path: src/main/java/ch/rasc/s4ws/portfolio/service/TradeServiceImpl.java import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.messaging.simp.SimpMessageSendingOperations; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; import ch.rasc.s4ws.portfolio.Portfolio; import ch.rasc.s4ws.portfolio.PortfolioPosition; import ch.rasc.s4ws.portfolio.service.Trade.TradeAction; /* * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.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://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ch.rasc.s4ws.portfolio.service; @Service public class TradeServiceImpl implements TradeService { private static final Log logger = LogFactory.getLog(TradeServiceImpl.class); private final SimpMessageSendingOperations messagingTemplate; private final PortfolioService portfolioService; private final List<TradeResult> tradeResults = new CopyOnWriteArrayList<>(); @Autowired public TradeServiceImpl(SimpMessageSendingOperations messagingTemplate, PortfolioService portfolioService) { this.messagingTemplate = messagingTemplate; this.portfolioService = portfolioService; } /** * In real application a trade is probably executed in an external system, i.e. * asynchronously. */ @Override public void executeTrade(Trade trade) { Portfolio portfolio = this.portfolioService.findPortfolio(trade.getUsername()); String ticker = trade.getTicker(); int sharesToTrade = trade.getShares();
PortfolioPosition newPosition = trade.getAction() == TradeAction.Buy
ralscha/spring4ws-demos
src/main/java/ch/rasc/s4ws/drawboard/Room.java
// Path: src/main/java/ch/rasc/s4ws/drawboard/DrawMessage.java // public static class ParseException extends Exception { // private static final long serialVersionUID = -6651972769789842960L; // // public ParseException(Throwable root) { // super(root); // } // // public ParseException(String message) { // super(message); // } // }
import java.awt.Color; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import javax.imageio.ImageIO; import org.springframework.context.ApplicationEventPublisher; import org.springframework.context.event.EventListener; import ch.rasc.s4ws.drawboard.DrawMessage.ParseException;
@EventListener public void handleIncomingData(IncomingMessageEvent incomingMessageEvent) { String msg = incomingMessageEvent.getPayload(); String sessionId = incomingMessageEvent.getSessionId(); char messageType = msg.charAt(0); String messageContent = msg.substring(1); if (messageType == '1') { try { int indexOfChar = messageContent.indexOf('|'); Long msgId = Long.valueOf(messageContent.substring(0, indexOfChar)); this.playerMap.put(sessionId, msgId); DrawMessage drawMessage = DrawMessage .parseFromString(messageContent.substring(indexOfChar + 1)); drawMessage.draw(this.roomGraphics); String drawMessageString = drawMessage.toString(); for (String playerSessionId : this.playerMap.keySet()) { this.publisher.publishEvent(new SendMessageEvent(playerSessionId, null, "1" + this.playerMap.get(playerSessionId) + "," + drawMessageString)); } } catch (NumberFormatException e) { e.printStackTrace(); }
// Path: src/main/java/ch/rasc/s4ws/drawboard/DrawMessage.java // public static class ParseException extends Exception { // private static final long serialVersionUID = -6651972769789842960L; // // public ParseException(Throwable root) { // super(root); // } // // public ParseException(String message) { // super(message); // } // } // Path: src/main/java/ch/rasc/s4ws/drawboard/Room.java import java.awt.Color; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import javax.imageio.ImageIO; import org.springframework.context.ApplicationEventPublisher; import org.springframework.context.event.EventListener; import ch.rasc.s4ws.drawboard.DrawMessage.ParseException; @EventListener public void handleIncomingData(IncomingMessageEvent incomingMessageEvent) { String msg = incomingMessageEvent.getPayload(); String sessionId = incomingMessageEvent.getSessionId(); char messageType = msg.charAt(0); String messageContent = msg.substring(1); if (messageType == '1') { try { int indexOfChar = messageContent.indexOf('|'); Long msgId = Long.valueOf(messageContent.substring(0, indexOfChar)); this.playerMap.put(sessionId, msgId); DrawMessage drawMessage = DrawMessage .parseFromString(messageContent.substring(indexOfChar + 1)); drawMessage.draw(this.roomGraphics); String drawMessageString = drawMessage.toString(); for (String playerSessionId : this.playerMap.keySet()) { this.publisher.publishEvent(new SendMessageEvent(playerSessionId, null, "1" + this.playerMap.get(playerSessionId) + "," + drawMessageString)); } } catch (NumberFormatException e) { e.printStackTrace(); }
catch (ParseException e) {
martinschaef/bixie
src/main/java/bixie/transformation/loopunwinding/AbstractLoopUnwinding.java
// Path: src/main/java/bixie/checker/GlobalsCache.java // public class GlobalsCache { // // private static GlobalsCache instance = null; // // public static GlobalsCache v() { // if (instance==null) { // instance = new GlobalsCache(); // } // return instance; // } // // public static void resetInstance() { // instance = null; // } // // private GlobalsCache() { // // } // // /** // * @return the programFactory // */ // public ProgramFactory getProgramFactory() { // return programFactory; // } // // /** // * @param programFactory the programFactory to set // */ // public void setProgramFactory(ProgramFactory programFactory) { // this.programFactory = programFactory; // } // // private ProgramFactory programFactory; // // }
import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import util.Log; import bixie.checker.GlobalsCache; import boogie.ProgramFactory; import boogie.ast.Attribute; import boogie.controlflow.BasicBlock; import boogie.controlflow.CfgProcedure; import boogie.controlflow.expression.CfgBooleanLiteral; import boogie.controlflow.statement.CfgAssertStatement; import boogie.controlflow.util.LoopInfo;
// fix the successors of the cloned nodes. for (BasicBlock b : loop.loopBody) { BasicBlock clone = clonemap.get(b); for (BasicBlock s : new HashSet<BasicBlock>(b.getSuccessors())) { if (clonemap.containsKey(s)) { clone.connectToSuccessor(clonemap.get(s)); } else { // add the missing edge that was not cloned clone.connectToSuccessor(s); } } } // now redirect all back edges to the original loop head. for (BasicBlock b : loop.loopingPred) { if (!clonemap.containsKey(b)) { Log.error("something fishy with that loop!"); continue; } BasicBlock clone = clonemap.get(b); clone.disconnectFromSuccessor(cloneHead); clone.connectToSuccessor(loop.loopHead); } loop.UpdateLoopEntries(); unwind(loop, unwindings - 1); } private void markAsClone(BasicBlock clone) {
// Path: src/main/java/bixie/checker/GlobalsCache.java // public class GlobalsCache { // // private static GlobalsCache instance = null; // // public static GlobalsCache v() { // if (instance==null) { // instance = new GlobalsCache(); // } // return instance; // } // // public static void resetInstance() { // instance = null; // } // // private GlobalsCache() { // // } // // /** // * @return the programFactory // */ // public ProgramFactory getProgramFactory() { // return programFactory; // } // // /** // * @param programFactory the programFactory to set // */ // public void setProgramFactory(ProgramFactory programFactory) { // this.programFactory = programFactory; // } // // private ProgramFactory programFactory; // // } // Path: src/main/java/bixie/transformation/loopunwinding/AbstractLoopUnwinding.java import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import util.Log; import bixie.checker.GlobalsCache; import boogie.ProgramFactory; import boogie.ast.Attribute; import boogie.controlflow.BasicBlock; import boogie.controlflow.CfgProcedure; import boogie.controlflow.expression.CfgBooleanLiteral; import boogie.controlflow.statement.CfgAssertStatement; import boogie.controlflow.util.LoopInfo; // fix the successors of the cloned nodes. for (BasicBlock b : loop.loopBody) { BasicBlock clone = clonemap.get(b); for (BasicBlock s : new HashSet<BasicBlock>(b.getSuccessors())) { if (clonemap.containsKey(s)) { clone.connectToSuccessor(clonemap.get(s)); } else { // add the missing edge that was not cloned clone.connectToSuccessor(s); } } } // now redirect all back edges to the original loop head. for (BasicBlock b : loop.loopingPred) { if (!clonemap.containsKey(b)) { Log.error("something fishy with that loop!"); continue; } BasicBlock clone = clonemap.get(b); clone.disconnectFromSuccessor(cloneHead); clone.connectToSuccessor(loop.loopHead); } loop.UpdateLoopEntries(); unwind(loop, unwindings - 1); } private void markAsClone(BasicBlock clone) {
ProgramFactory pf = GlobalsCache.v().getProgramFactory();
martinschaef/bixie
src/main/java/bixie/prover/princess/PrincessFun.java
// Path: src/main/java/bixie/prover/ProverFun.java // public interface ProverFun { // // ProverExpr mkExpr(ProverExpr[] args); // // } // // Path: src/main/java/bixie/prover/ProverType.java // public interface ProverType { // // }
import scala.collection.mutable.ArrayBuffer; import ap.basetypes.IdealInt$; import ap.parser.IExpression$; import ap.parser.IFunApp; import ap.parser.IFunction; import ap.parser.IIntLit; import ap.parser.ITerm; import ap.parser.ITermITE; import bixie.prover.ProverExpr; import bixie.prover.ProverFun; import bixie.prover.ProverType;
package bixie.prover.princess; class PrincessFun implements ProverFun { private final IFunction fun;
// Path: src/main/java/bixie/prover/ProverFun.java // public interface ProverFun { // // ProverExpr mkExpr(ProverExpr[] args); // // } // // Path: src/main/java/bixie/prover/ProverType.java // public interface ProverType { // // } // Path: src/main/java/bixie/prover/princess/PrincessFun.java import scala.collection.mutable.ArrayBuffer; import ap.basetypes.IdealInt$; import ap.parser.IExpression$; import ap.parser.IFunApp; import ap.parser.IFunction; import ap.parser.IIntLit; import ap.parser.ITerm; import ap.parser.ITermITE; import bixie.prover.ProverExpr; import bixie.prover.ProverFun; import bixie.prover.ProverType; package bixie.prover.princess; class PrincessFun implements ProverFun { private final IFunction fun;
private final ProverType resType;
martinschaef/bixie
src/test/java/bixie/ic_test/ComplexFlowTest.java
// Path: src/main/java/bixie/Bixie.java // public class Bixie { // // /** // * // */ // public Bixie() { // // TODO Auto-generated constructor stub // } // // /** // * @param args // */ // public static void main(String[] args) { // bixie.Options options = bixie.Options.v(); // CmdLineParser parser = new CmdLineParser(options); // // if (args.length == 0) { // parser.printUsage(System.err); // return; // } // // try { // parser.parseArgument(args); // // Bixie bixie = new Bixie(); // if (options.getBoogieFile() != null && options.getJarFile() != null) { // Log.error("Can only take either Java or Boogie input. Not both"); // return; // } else if (options.getBoogieFile() != null) { // bixie.run(options.getBoogieFile(), options.getOutputFile()); // } else { // String cp = options.getClasspath(); // if (cp != null && !cp.contains(options.getJarFile())) { // cp += File.pathSeparatorChar + options.getJarFile(); // } // bixie.translateAndRun(options.getJarFile(), cp, // options.getOutputFile()); // } // } catch (CmdLineException e) { // bixie.util.Log.error(e.toString()); // parser.printUsage(System.err); // } catch (Throwable e) { // bixie.util.Log.error(e.toString()); // } // } // // public void run(String input, String output) { // bixie.Options.v().setOutputFile(output); // if (input != null && input.endsWith(".bpl")) { // try { // ProgramFactory pf = new ProgramFactory(input); // ReportPrinter jp = runChecker(pf); // report2File(jp); // } catch (Exception e) { // // TODO Auto-generated catch block // bixie.util.Log.error(e.toString()); // } // } else { // bixie.util.Log.error("Not a valid Boogie file: " + input); // } // } // // protected void report2File(ReportPrinter reportPrinter) { // try (PrintWriter out = new PrintWriter(new OutputStreamWriter( // new FileOutputStream(bixie.Options.v().getOutputFile()), // "UTF-8"));) { // String str = reportPrinter.printSummary(); // if (str!=null && !str.isEmpty()) { // out.println(str); // bixie.util.Log.info(str); // } // } catch (Exception e) { // // TODO Auto-generated catch block // bixie.util.Log.error(e.toString()); // } // } // // public void translateAndRun(String input, String classpath, String output) { // ReportPrinter reportPrinter = translateAndRun(input, classpath); // if (reportPrinter!=null) { // bixie.Options.v().setOutputFile(output); // report2File(reportPrinter); // } else { // Log.error("Could not generate report."); // } // } // // public ReportPrinter translateAndRun(String input, String classpath) { // return translateAndRun(input, classpath, new BasicReportPrinter()); // } // // public ReportPrinter translateAndRun(String input, String classpath, // ReportPrinter reportPrinter) { // bixie.util.Log.info("Translating"); // org.joogie.Dispatcher.setClassPath(classpath); // ProgramFactory pf = org.joogie.Dispatcher.run(input); // if (pf == null) { // bixie.util.Log.error("Internal Error: Parsing failed"); // return null; // } // ReportPrinter jp = runChecker(pf, reportPrinter); // return jp; // } // // public ReportPrinter runChecker(ProgramFactory pf) { // return runChecker(pf, new BasicReportPrinter()); // } // // public ReportPrinter runChecker(ProgramFactory pf, // ReportPrinter reportPrinter) { // bixie.util.Log.info("Checking"); // // try { // ProgramAnalysis.runFullProgramAnalysis(pf, reportPrinter); // } catch (Exception e) { // bixie.util.Log.error(e.toString()); // } // // return reportPrinter; // } // // }
import static org.junit.Assert.fail; import java.io.File; import java.io.IOException; import org.junit.Test; import bixie.Bixie;
/** * */ package bixie.ic_test; /** * @author schaef * */ public class ComplexFlowTest extends AbstractIcTest { @Test public void test() { final File source_file = new File(testRoot + "ic_java/complex_flow/Complex01.java"); File classFileDir = null; try { classFileDir = compileJavaFile(source_file);
// Path: src/main/java/bixie/Bixie.java // public class Bixie { // // /** // * // */ // public Bixie() { // // TODO Auto-generated constructor stub // } // // /** // * @param args // */ // public static void main(String[] args) { // bixie.Options options = bixie.Options.v(); // CmdLineParser parser = new CmdLineParser(options); // // if (args.length == 0) { // parser.printUsage(System.err); // return; // } // // try { // parser.parseArgument(args); // // Bixie bixie = new Bixie(); // if (options.getBoogieFile() != null && options.getJarFile() != null) { // Log.error("Can only take either Java or Boogie input. Not both"); // return; // } else if (options.getBoogieFile() != null) { // bixie.run(options.getBoogieFile(), options.getOutputFile()); // } else { // String cp = options.getClasspath(); // if (cp != null && !cp.contains(options.getJarFile())) { // cp += File.pathSeparatorChar + options.getJarFile(); // } // bixie.translateAndRun(options.getJarFile(), cp, // options.getOutputFile()); // } // } catch (CmdLineException e) { // bixie.util.Log.error(e.toString()); // parser.printUsage(System.err); // } catch (Throwable e) { // bixie.util.Log.error(e.toString()); // } // } // // public void run(String input, String output) { // bixie.Options.v().setOutputFile(output); // if (input != null && input.endsWith(".bpl")) { // try { // ProgramFactory pf = new ProgramFactory(input); // ReportPrinter jp = runChecker(pf); // report2File(jp); // } catch (Exception e) { // // TODO Auto-generated catch block // bixie.util.Log.error(e.toString()); // } // } else { // bixie.util.Log.error("Not a valid Boogie file: " + input); // } // } // // protected void report2File(ReportPrinter reportPrinter) { // try (PrintWriter out = new PrintWriter(new OutputStreamWriter( // new FileOutputStream(bixie.Options.v().getOutputFile()), // "UTF-8"));) { // String str = reportPrinter.printSummary(); // if (str!=null && !str.isEmpty()) { // out.println(str); // bixie.util.Log.info(str); // } // } catch (Exception e) { // // TODO Auto-generated catch block // bixie.util.Log.error(e.toString()); // } // } // // public void translateAndRun(String input, String classpath, String output) { // ReportPrinter reportPrinter = translateAndRun(input, classpath); // if (reportPrinter!=null) { // bixie.Options.v().setOutputFile(output); // report2File(reportPrinter); // } else { // Log.error("Could not generate report."); // } // } // // public ReportPrinter translateAndRun(String input, String classpath) { // return translateAndRun(input, classpath, new BasicReportPrinter()); // } // // public ReportPrinter translateAndRun(String input, String classpath, // ReportPrinter reportPrinter) { // bixie.util.Log.info("Translating"); // org.joogie.Dispatcher.setClassPath(classpath); // ProgramFactory pf = org.joogie.Dispatcher.run(input); // if (pf == null) { // bixie.util.Log.error("Internal Error: Parsing failed"); // return null; // } // ReportPrinter jp = runChecker(pf, reportPrinter); // return jp; // } // // public ReportPrinter runChecker(ProgramFactory pf) { // return runChecker(pf, new BasicReportPrinter()); // } // // public ReportPrinter runChecker(ProgramFactory pf, // ReportPrinter reportPrinter) { // bixie.util.Log.info("Checking"); // // try { // ProgramAnalysis.runFullProgramAnalysis(pf, reportPrinter); // } catch (Exception e) { // bixie.util.Log.error(e.toString()); // } // // return reportPrinter; // } // // } // Path: src/test/java/bixie/ic_test/ComplexFlowTest.java import static org.junit.Assert.fail; import java.io.File; import java.io.IOException; import org.junit.Test; import bixie.Bixie; /** * */ package bixie.ic_test; /** * @author schaef * */ public class ComplexFlowTest extends AbstractIcTest { @Test public void test() { final File source_file = new File(testRoot + "ic_java/complex_flow/Complex01.java"); File classFileDir = null; try { classFileDir = compileJavaFile(source_file);
Bixie.main(new String[]{
martinschaef/bixie
src/test/java/bixie/ic_test/JavaTruePositives.java
// Path: src/main/java/bixie/Bixie.java // public class Bixie { // // /** // * // */ // public Bixie() { // // TODO Auto-generated constructor stub // } // // /** // * @param args // */ // public static void main(String[] args) { // bixie.Options options = bixie.Options.v(); // CmdLineParser parser = new CmdLineParser(options); // // if (args.length == 0) { // parser.printUsage(System.err); // return; // } // // try { // parser.parseArgument(args); // // Bixie bixie = new Bixie(); // if (options.getBoogieFile() != null && options.getJarFile() != null) { // Log.error("Can only take either Java or Boogie input. Not both"); // return; // } else if (options.getBoogieFile() != null) { // bixie.run(options.getBoogieFile(), options.getOutputFile()); // } else { // String cp = options.getClasspath(); // if (cp != null && !cp.contains(options.getJarFile())) { // cp += File.pathSeparatorChar + options.getJarFile(); // } // bixie.translateAndRun(options.getJarFile(), cp, // options.getOutputFile()); // } // } catch (CmdLineException e) { // bixie.util.Log.error(e.toString()); // parser.printUsage(System.err); // } catch (Throwable e) { // bixie.util.Log.error(e.toString()); // } // } // // public void run(String input, String output) { // bixie.Options.v().setOutputFile(output); // if (input != null && input.endsWith(".bpl")) { // try { // ProgramFactory pf = new ProgramFactory(input); // ReportPrinter jp = runChecker(pf); // report2File(jp); // } catch (Exception e) { // // TODO Auto-generated catch block // bixie.util.Log.error(e.toString()); // } // } else { // bixie.util.Log.error("Not a valid Boogie file: " + input); // } // } // // protected void report2File(ReportPrinter reportPrinter) { // try (PrintWriter out = new PrintWriter(new OutputStreamWriter( // new FileOutputStream(bixie.Options.v().getOutputFile()), // "UTF-8"));) { // String str = reportPrinter.printSummary(); // if (str!=null && !str.isEmpty()) { // out.println(str); // bixie.util.Log.info(str); // } // } catch (Exception e) { // // TODO Auto-generated catch block // bixie.util.Log.error(e.toString()); // } // } // // public void translateAndRun(String input, String classpath, String output) { // ReportPrinter reportPrinter = translateAndRun(input, classpath); // if (reportPrinter!=null) { // bixie.Options.v().setOutputFile(output); // report2File(reportPrinter); // } else { // Log.error("Could not generate report."); // } // } // // public ReportPrinter translateAndRun(String input, String classpath) { // return translateAndRun(input, classpath, new BasicReportPrinter()); // } // // public ReportPrinter translateAndRun(String input, String classpath, // ReportPrinter reportPrinter) { // bixie.util.Log.info("Translating"); // org.joogie.Dispatcher.setClassPath(classpath); // ProgramFactory pf = org.joogie.Dispatcher.run(input); // if (pf == null) { // bixie.util.Log.error("Internal Error: Parsing failed"); // return null; // } // ReportPrinter jp = runChecker(pf, reportPrinter); // return jp; // } // // public ReportPrinter runChecker(ProgramFactory pf) { // return runChecker(pf, new BasicReportPrinter()); // } // // public ReportPrinter runChecker(ProgramFactory pf, // ReportPrinter reportPrinter) { // bixie.util.Log.info("Checking"); // // try { // ProgramAnalysis.runFullProgramAnalysis(pf, reportPrinter); // } catch (Exception e) { // bixie.util.Log.error(e.toString()); // } // // return reportPrinter; // } // // }
import static org.junit.Assert.assertTrue; import java.io.File; import java.io.IOException; import java.util.Collection; import java.util.LinkedList; import java.util.List; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import bixie.Bixie;
} return filenames; } public JavaTruePositives(File source, String name) { this.sourceFile = source; this.goldenFile = new File(source.getAbsolutePath().replace(".java", ".gold")); } @Test public void test1() { testWithChecker(1); } @Test public void test2() { testWithChecker(2); } public void testWithChecker(int i) { System.out.println("Running test: "+sourceFile.getName()); File classFileDir = null; File outFile = null; try { outFile = File.createTempFile("bixie_test", ".txt"); classFileDir = compileJavaFile(this.sourceFile); if (classFileDir==null || !classFileDir.isDirectory()) { assertTrue(false); }
// Path: src/main/java/bixie/Bixie.java // public class Bixie { // // /** // * // */ // public Bixie() { // // TODO Auto-generated constructor stub // } // // /** // * @param args // */ // public static void main(String[] args) { // bixie.Options options = bixie.Options.v(); // CmdLineParser parser = new CmdLineParser(options); // // if (args.length == 0) { // parser.printUsage(System.err); // return; // } // // try { // parser.parseArgument(args); // // Bixie bixie = new Bixie(); // if (options.getBoogieFile() != null && options.getJarFile() != null) { // Log.error("Can only take either Java or Boogie input. Not both"); // return; // } else if (options.getBoogieFile() != null) { // bixie.run(options.getBoogieFile(), options.getOutputFile()); // } else { // String cp = options.getClasspath(); // if (cp != null && !cp.contains(options.getJarFile())) { // cp += File.pathSeparatorChar + options.getJarFile(); // } // bixie.translateAndRun(options.getJarFile(), cp, // options.getOutputFile()); // } // } catch (CmdLineException e) { // bixie.util.Log.error(e.toString()); // parser.printUsage(System.err); // } catch (Throwable e) { // bixie.util.Log.error(e.toString()); // } // } // // public void run(String input, String output) { // bixie.Options.v().setOutputFile(output); // if (input != null && input.endsWith(".bpl")) { // try { // ProgramFactory pf = new ProgramFactory(input); // ReportPrinter jp = runChecker(pf); // report2File(jp); // } catch (Exception e) { // // TODO Auto-generated catch block // bixie.util.Log.error(e.toString()); // } // } else { // bixie.util.Log.error("Not a valid Boogie file: " + input); // } // } // // protected void report2File(ReportPrinter reportPrinter) { // try (PrintWriter out = new PrintWriter(new OutputStreamWriter( // new FileOutputStream(bixie.Options.v().getOutputFile()), // "UTF-8"));) { // String str = reportPrinter.printSummary(); // if (str!=null && !str.isEmpty()) { // out.println(str); // bixie.util.Log.info(str); // } // } catch (Exception e) { // // TODO Auto-generated catch block // bixie.util.Log.error(e.toString()); // } // } // // public void translateAndRun(String input, String classpath, String output) { // ReportPrinter reportPrinter = translateAndRun(input, classpath); // if (reportPrinter!=null) { // bixie.Options.v().setOutputFile(output); // report2File(reportPrinter); // } else { // Log.error("Could not generate report."); // } // } // // public ReportPrinter translateAndRun(String input, String classpath) { // return translateAndRun(input, classpath, new BasicReportPrinter()); // } // // public ReportPrinter translateAndRun(String input, String classpath, // ReportPrinter reportPrinter) { // bixie.util.Log.info("Translating"); // org.joogie.Dispatcher.setClassPath(classpath); // ProgramFactory pf = org.joogie.Dispatcher.run(input); // if (pf == null) { // bixie.util.Log.error("Internal Error: Parsing failed"); // return null; // } // ReportPrinter jp = runChecker(pf, reportPrinter); // return jp; // } // // public ReportPrinter runChecker(ProgramFactory pf) { // return runChecker(pf, new BasicReportPrinter()); // } // // public ReportPrinter runChecker(ProgramFactory pf, // ReportPrinter reportPrinter) { // bixie.util.Log.info("Checking"); // // try { // ProgramAnalysis.runFullProgramAnalysis(pf, reportPrinter); // } catch (Exception e) { // bixie.util.Log.error(e.toString()); // } // // return reportPrinter; // } // // } // Path: src/test/java/bixie/ic_test/JavaTruePositives.java import static org.junit.Assert.assertTrue; import java.io.File; import java.io.IOException; import java.util.Collection; import java.util.LinkedList; import java.util.List; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import bixie.Bixie; } return filenames; } public JavaTruePositives(File source, String name) { this.sourceFile = source; this.goldenFile = new File(source.getAbsolutePath().replace(".java", ".gold")); } @Test public void test1() { testWithChecker(1); } @Test public void test2() { testWithChecker(2); } public void testWithChecker(int i) { System.out.println("Running test: "+sourceFile.getName()); File classFileDir = null; File outFile = null; try { outFile = File.createTempFile("bixie_test", ".txt"); classFileDir = compileJavaFile(this.sourceFile); if (classFileDir==null || !classFileDir.isDirectory()) { assertTrue(false); }
Bixie bx = new Bixie();
martinschaef/bixie
src/main/java/bixie/prover/princess/FormulaExpr.java
// Path: src/main/java/bixie/prover/ProverType.java // public interface ProverType { // // }
import java.math.BigInteger; import ap.SimpleAPI$; import ap.parser.IBoolLit; import ap.parser.IFormula; import bixie.prover.ProverExpr; import bixie.prover.ProverType;
package bixie.prover.princess; class FormulaExpr implements ProverExpr { protected final IFormula formula; FormulaExpr(IFormula formula) { this.formula = formula; } public String toString() { return SimpleAPI$.MODULE$.pp(formula); }
// Path: src/main/java/bixie/prover/ProverType.java // public interface ProverType { // // } // Path: src/main/java/bixie/prover/princess/FormulaExpr.java import java.math.BigInteger; import ap.SimpleAPI$; import ap.parser.IBoolLit; import ap.parser.IFormula; import bixie.prover.ProverExpr; import bixie.prover.ProverType; package bixie.prover.princess; class FormulaExpr implements ProverExpr { protected final IFormula formula; FormulaExpr(IFormula formula) { this.formula = formula; } public String toString() { return SimpleAPI$.MODULE$.pp(formula); }
public ProverType getType() {
martinschaef/bixie
src/test/java/bixie/ic_test/FaultLocalization.java
// Path: src/main/java/bixie/Bixie.java // public class Bixie { // // /** // * // */ // public Bixie() { // // TODO Auto-generated constructor stub // } // // /** // * @param args // */ // public static void main(String[] args) { // bixie.Options options = bixie.Options.v(); // CmdLineParser parser = new CmdLineParser(options); // // if (args.length == 0) { // parser.printUsage(System.err); // return; // } // // try { // parser.parseArgument(args); // // Bixie bixie = new Bixie(); // if (options.getBoogieFile() != null && options.getJarFile() != null) { // Log.error("Can only take either Java or Boogie input. Not both"); // return; // } else if (options.getBoogieFile() != null) { // bixie.run(options.getBoogieFile(), options.getOutputFile()); // } else { // String cp = options.getClasspath(); // if (cp != null && !cp.contains(options.getJarFile())) { // cp += File.pathSeparatorChar + options.getJarFile(); // } // bixie.translateAndRun(options.getJarFile(), cp, // options.getOutputFile()); // } // } catch (CmdLineException e) { // bixie.util.Log.error(e.toString()); // parser.printUsage(System.err); // } catch (Throwable e) { // bixie.util.Log.error(e.toString()); // } // } // // public void run(String input, String output) { // bixie.Options.v().setOutputFile(output); // if (input != null && input.endsWith(".bpl")) { // try { // ProgramFactory pf = new ProgramFactory(input); // ReportPrinter jp = runChecker(pf); // report2File(jp); // } catch (Exception e) { // // TODO Auto-generated catch block // bixie.util.Log.error(e.toString()); // } // } else { // bixie.util.Log.error("Not a valid Boogie file: " + input); // } // } // // protected void report2File(ReportPrinter reportPrinter) { // try (PrintWriter out = new PrintWriter(new OutputStreamWriter( // new FileOutputStream(bixie.Options.v().getOutputFile()), // "UTF-8"));) { // String str = reportPrinter.printSummary(); // if (str!=null && !str.isEmpty()) { // out.println(str); // bixie.util.Log.info(str); // } // } catch (Exception e) { // // TODO Auto-generated catch block // bixie.util.Log.error(e.toString()); // } // } // // public void translateAndRun(String input, String classpath, String output) { // ReportPrinter reportPrinter = translateAndRun(input, classpath); // if (reportPrinter!=null) { // bixie.Options.v().setOutputFile(output); // report2File(reportPrinter); // } else { // Log.error("Could not generate report."); // } // } // // public ReportPrinter translateAndRun(String input, String classpath) { // return translateAndRun(input, classpath, new BasicReportPrinter()); // } // // public ReportPrinter translateAndRun(String input, String classpath, // ReportPrinter reportPrinter) { // bixie.util.Log.info("Translating"); // org.joogie.Dispatcher.setClassPath(classpath); // ProgramFactory pf = org.joogie.Dispatcher.run(input); // if (pf == null) { // bixie.util.Log.error("Internal Error: Parsing failed"); // return null; // } // ReportPrinter jp = runChecker(pf, reportPrinter); // return jp; // } // // public ReportPrinter runChecker(ProgramFactory pf) { // return runChecker(pf, new BasicReportPrinter()); // } // // public ReportPrinter runChecker(ProgramFactory pf, // ReportPrinter reportPrinter) { // bixie.util.Log.info("Checking"); // // try { // ProgramAnalysis.runFullProgramAnalysis(pf, reportPrinter); // } catch (Exception e) { // bixie.util.Log.error(e.toString()); // } // // return reportPrinter; // } // // }
import static org.junit.Assert.assertTrue; import java.io.File; import java.io.IOException; import java.util.Collection; import java.util.LinkedList; import java.util.List; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import bixie.Bixie;
// Handle the case where dir is not really a directory. // Checking dir.isDirectory() above would not be sufficient // to avoid race conditions with another process that deletes // directories. throw new RuntimeException("Test data not found!"); } return filenames; } public FaultLocalization(File source, String name) { this.sourceFile = source; this.goldenFile = new File(source.getAbsolutePath().replace(".java", ".gold")); } @Test public void test1() { testWithChecker(1); } public void testWithChecker(int i) { System.out.println("Running test: "+sourceFile.getName()); File classFileDir = null; File outFile = null; try { outFile = File.createTempFile("bixie_test", ".txt"); classFileDir = compileJavaFile(this.sourceFile); if (classFileDir==null || !classFileDir.isDirectory()) { assertTrue(false); }
// Path: src/main/java/bixie/Bixie.java // public class Bixie { // // /** // * // */ // public Bixie() { // // TODO Auto-generated constructor stub // } // // /** // * @param args // */ // public static void main(String[] args) { // bixie.Options options = bixie.Options.v(); // CmdLineParser parser = new CmdLineParser(options); // // if (args.length == 0) { // parser.printUsage(System.err); // return; // } // // try { // parser.parseArgument(args); // // Bixie bixie = new Bixie(); // if (options.getBoogieFile() != null && options.getJarFile() != null) { // Log.error("Can only take either Java or Boogie input. Not both"); // return; // } else if (options.getBoogieFile() != null) { // bixie.run(options.getBoogieFile(), options.getOutputFile()); // } else { // String cp = options.getClasspath(); // if (cp != null && !cp.contains(options.getJarFile())) { // cp += File.pathSeparatorChar + options.getJarFile(); // } // bixie.translateAndRun(options.getJarFile(), cp, // options.getOutputFile()); // } // } catch (CmdLineException e) { // bixie.util.Log.error(e.toString()); // parser.printUsage(System.err); // } catch (Throwable e) { // bixie.util.Log.error(e.toString()); // } // } // // public void run(String input, String output) { // bixie.Options.v().setOutputFile(output); // if (input != null && input.endsWith(".bpl")) { // try { // ProgramFactory pf = new ProgramFactory(input); // ReportPrinter jp = runChecker(pf); // report2File(jp); // } catch (Exception e) { // // TODO Auto-generated catch block // bixie.util.Log.error(e.toString()); // } // } else { // bixie.util.Log.error("Not a valid Boogie file: " + input); // } // } // // protected void report2File(ReportPrinter reportPrinter) { // try (PrintWriter out = new PrintWriter(new OutputStreamWriter( // new FileOutputStream(bixie.Options.v().getOutputFile()), // "UTF-8"));) { // String str = reportPrinter.printSummary(); // if (str!=null && !str.isEmpty()) { // out.println(str); // bixie.util.Log.info(str); // } // } catch (Exception e) { // // TODO Auto-generated catch block // bixie.util.Log.error(e.toString()); // } // } // // public void translateAndRun(String input, String classpath, String output) { // ReportPrinter reportPrinter = translateAndRun(input, classpath); // if (reportPrinter!=null) { // bixie.Options.v().setOutputFile(output); // report2File(reportPrinter); // } else { // Log.error("Could not generate report."); // } // } // // public ReportPrinter translateAndRun(String input, String classpath) { // return translateAndRun(input, classpath, new BasicReportPrinter()); // } // // public ReportPrinter translateAndRun(String input, String classpath, // ReportPrinter reportPrinter) { // bixie.util.Log.info("Translating"); // org.joogie.Dispatcher.setClassPath(classpath); // ProgramFactory pf = org.joogie.Dispatcher.run(input); // if (pf == null) { // bixie.util.Log.error("Internal Error: Parsing failed"); // return null; // } // ReportPrinter jp = runChecker(pf, reportPrinter); // return jp; // } // // public ReportPrinter runChecker(ProgramFactory pf) { // return runChecker(pf, new BasicReportPrinter()); // } // // public ReportPrinter runChecker(ProgramFactory pf, // ReportPrinter reportPrinter) { // bixie.util.Log.info("Checking"); // // try { // ProgramAnalysis.runFullProgramAnalysis(pf, reportPrinter); // } catch (Exception e) { // bixie.util.Log.error(e.toString()); // } // // return reportPrinter; // } // // } // Path: src/test/java/bixie/ic_test/FaultLocalization.java import static org.junit.Assert.assertTrue; import java.io.File; import java.io.IOException; import java.util.Collection; import java.util.LinkedList; import java.util.List; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import bixie.Bixie; // Handle the case where dir is not really a directory. // Checking dir.isDirectory() above would not be sufficient // to avoid race conditions with another process that deletes // directories. throw new RuntimeException("Test data not found!"); } return filenames; } public FaultLocalization(File source, String name) { this.sourceFile = source; this.goldenFile = new File(source.getAbsolutePath().replace(".java", ".gold")); } @Test public void test1() { testWithChecker(1); } public void testWithChecker(int i) { System.out.println("Running test: "+sourceFile.getName()); File classFileDir = null; File outFile = null; try { outFile = File.createTempFile("bixie_test", ".txt"); classFileDir = compileJavaFile(this.sourceFile); if (classFileDir==null || !classFileDir.isDirectory()) { assertTrue(false); }
Bixie bx = new Bixie();
martinschaef/bixie
src/test/java/bixie/ic_test/MainClassTest.java
// Path: src/main/java/bixie/Bixie.java // public class Bixie { // // /** // * // */ // public Bixie() { // // TODO Auto-generated constructor stub // } // // /** // * @param args // */ // public static void main(String[] args) { // bixie.Options options = bixie.Options.v(); // CmdLineParser parser = new CmdLineParser(options); // // if (args.length == 0) { // parser.printUsage(System.err); // return; // } // // try { // parser.parseArgument(args); // // Bixie bixie = new Bixie(); // if (options.getBoogieFile() != null && options.getJarFile() != null) { // Log.error("Can only take either Java or Boogie input. Not both"); // return; // } else if (options.getBoogieFile() != null) { // bixie.run(options.getBoogieFile(), options.getOutputFile()); // } else { // String cp = options.getClasspath(); // if (cp != null && !cp.contains(options.getJarFile())) { // cp += File.pathSeparatorChar + options.getJarFile(); // } // bixie.translateAndRun(options.getJarFile(), cp, // options.getOutputFile()); // } // } catch (CmdLineException e) { // bixie.util.Log.error(e.toString()); // parser.printUsage(System.err); // } catch (Throwable e) { // bixie.util.Log.error(e.toString()); // } // } // // public void run(String input, String output) { // bixie.Options.v().setOutputFile(output); // if (input != null && input.endsWith(".bpl")) { // try { // ProgramFactory pf = new ProgramFactory(input); // ReportPrinter jp = runChecker(pf); // report2File(jp); // } catch (Exception e) { // // TODO Auto-generated catch block // bixie.util.Log.error(e.toString()); // } // } else { // bixie.util.Log.error("Not a valid Boogie file: " + input); // } // } // // protected void report2File(ReportPrinter reportPrinter) { // try (PrintWriter out = new PrintWriter(new OutputStreamWriter( // new FileOutputStream(bixie.Options.v().getOutputFile()), // "UTF-8"));) { // String str = reportPrinter.printSummary(); // if (str!=null && !str.isEmpty()) { // out.println(str); // bixie.util.Log.info(str); // } // } catch (Exception e) { // // TODO Auto-generated catch block // bixie.util.Log.error(e.toString()); // } // } // // public void translateAndRun(String input, String classpath, String output) { // ReportPrinter reportPrinter = translateAndRun(input, classpath); // if (reportPrinter!=null) { // bixie.Options.v().setOutputFile(output); // report2File(reportPrinter); // } else { // Log.error("Could not generate report."); // } // } // // public ReportPrinter translateAndRun(String input, String classpath) { // return translateAndRun(input, classpath, new BasicReportPrinter()); // } // // public ReportPrinter translateAndRun(String input, String classpath, // ReportPrinter reportPrinter) { // bixie.util.Log.info("Translating"); // org.joogie.Dispatcher.setClassPath(classpath); // ProgramFactory pf = org.joogie.Dispatcher.run(input); // if (pf == null) { // bixie.util.Log.error("Internal Error: Parsing failed"); // return null; // } // ReportPrinter jp = runChecker(pf, reportPrinter); // return jp; // } // // public ReportPrinter runChecker(ProgramFactory pf) { // return runChecker(pf, new BasicReportPrinter()); // } // // public ReportPrinter runChecker(ProgramFactory pf, // ReportPrinter reportPrinter) { // bixie.util.Log.info("Checking"); // // try { // ProgramAnalysis.runFullProgramAnalysis(pf, reportPrinter); // } catch (Exception e) { // bixie.util.Log.error(e.toString()); // } // // return reportPrinter; // } // // }
import static org.junit.Assert.fail; import java.io.File; import java.io.IOException; import org.junit.Test; import bixie.Bixie;
/** * */ package bixie.ic_test; /** * @author schaef * */ public class MainClassTest extends AbstractIcTest { @Test public void test() { final File source_file = new File(testRoot + "ic_java/true_positives/TruePositives02.java"); File classFileDir = null; try { classFileDir = compileJavaFile(source_file);
// Path: src/main/java/bixie/Bixie.java // public class Bixie { // // /** // * // */ // public Bixie() { // // TODO Auto-generated constructor stub // } // // /** // * @param args // */ // public static void main(String[] args) { // bixie.Options options = bixie.Options.v(); // CmdLineParser parser = new CmdLineParser(options); // // if (args.length == 0) { // parser.printUsage(System.err); // return; // } // // try { // parser.parseArgument(args); // // Bixie bixie = new Bixie(); // if (options.getBoogieFile() != null && options.getJarFile() != null) { // Log.error("Can only take either Java or Boogie input. Not both"); // return; // } else if (options.getBoogieFile() != null) { // bixie.run(options.getBoogieFile(), options.getOutputFile()); // } else { // String cp = options.getClasspath(); // if (cp != null && !cp.contains(options.getJarFile())) { // cp += File.pathSeparatorChar + options.getJarFile(); // } // bixie.translateAndRun(options.getJarFile(), cp, // options.getOutputFile()); // } // } catch (CmdLineException e) { // bixie.util.Log.error(e.toString()); // parser.printUsage(System.err); // } catch (Throwable e) { // bixie.util.Log.error(e.toString()); // } // } // // public void run(String input, String output) { // bixie.Options.v().setOutputFile(output); // if (input != null && input.endsWith(".bpl")) { // try { // ProgramFactory pf = new ProgramFactory(input); // ReportPrinter jp = runChecker(pf); // report2File(jp); // } catch (Exception e) { // // TODO Auto-generated catch block // bixie.util.Log.error(e.toString()); // } // } else { // bixie.util.Log.error("Not a valid Boogie file: " + input); // } // } // // protected void report2File(ReportPrinter reportPrinter) { // try (PrintWriter out = new PrintWriter(new OutputStreamWriter( // new FileOutputStream(bixie.Options.v().getOutputFile()), // "UTF-8"));) { // String str = reportPrinter.printSummary(); // if (str!=null && !str.isEmpty()) { // out.println(str); // bixie.util.Log.info(str); // } // } catch (Exception e) { // // TODO Auto-generated catch block // bixie.util.Log.error(e.toString()); // } // } // // public void translateAndRun(String input, String classpath, String output) { // ReportPrinter reportPrinter = translateAndRun(input, classpath); // if (reportPrinter!=null) { // bixie.Options.v().setOutputFile(output); // report2File(reportPrinter); // } else { // Log.error("Could not generate report."); // } // } // // public ReportPrinter translateAndRun(String input, String classpath) { // return translateAndRun(input, classpath, new BasicReportPrinter()); // } // // public ReportPrinter translateAndRun(String input, String classpath, // ReportPrinter reportPrinter) { // bixie.util.Log.info("Translating"); // org.joogie.Dispatcher.setClassPath(classpath); // ProgramFactory pf = org.joogie.Dispatcher.run(input); // if (pf == null) { // bixie.util.Log.error("Internal Error: Parsing failed"); // return null; // } // ReportPrinter jp = runChecker(pf, reportPrinter); // return jp; // } // // public ReportPrinter runChecker(ProgramFactory pf) { // return runChecker(pf, new BasicReportPrinter()); // } // // public ReportPrinter runChecker(ProgramFactory pf, // ReportPrinter reportPrinter) { // bixie.util.Log.info("Checking"); // // try { // ProgramAnalysis.runFullProgramAnalysis(pf, reportPrinter); // } catch (Exception e) { // bixie.util.Log.error(e.toString()); // } // // return reportPrinter; // } // // } // Path: src/test/java/bixie/ic_test/MainClassTest.java import static org.junit.Assert.fail; import java.io.File; import java.io.IOException; import org.junit.Test; import bixie.Bixie; /** * */ package bixie.ic_test; /** * @author schaef * */ public class MainClassTest extends AbstractIcTest { @Test public void test() { final File source_file = new File(testRoot + "ic_java/true_positives/TruePositives02.java"); File classFileDir = null; try { classFileDir = compileJavaFile(source_file);
Bixie.main(new String[]{
martinschaef/bixie
src/main/java/bixie/prover/Main.java
// Path: src/main/java/bixie/prover/princess/PrincessProverFactory.java // public class PrincessProverFactory implements ProverFactory { // // @Override // public Prover spawn() { // return new PrincessProver(); // } // // @Override // public Prover spawnWithLog(String basename) { // return new PrincessProver(basename); // } // // }
import java.util.HashMap; import java.util.Map; import bixie.prover.princess.PrincessProverFactory;
ProverExpr var = m.get(name); if (var == null) { var = p.mkVariable(name, type); m.put(name, var); } if (!var.getType().equals(type)) { throw new RuntimeException("Wrong type on var: " + name); } return var; } public void runTests(ProverFactory factory) { final Prover p = factory.spawn(); test01(p); p.reset(); test02(p); p.reset(); test03(p); p.reset(); test04(p); p.reset(); test05(p); p.reset(); test06(p); p.reset(); p.shutdown(); } public static void main(String[] args) {
// Path: src/main/java/bixie/prover/princess/PrincessProverFactory.java // public class PrincessProverFactory implements ProverFactory { // // @Override // public Prover spawn() { // return new PrincessProver(); // } // // @Override // public Prover spawnWithLog(String basename) { // return new PrincessProver(basename); // } // // } // Path: src/main/java/bixie/prover/Main.java import java.util.HashMap; import java.util.Map; import bixie.prover.princess.PrincessProverFactory; ProverExpr var = m.get(name); if (var == null) { var = p.mkVariable(name, type); m.put(name, var); } if (!var.getType().equals(type)) { throw new RuntimeException("Wrong type on var: " + name); } return var; } public void runTests(ProverFactory factory) { final Prover p = factory.spawn(); test01(p); p.reset(); test02(p); p.reset(); test03(p); p.reset(); test04(p); p.reset(); test05(p); p.reset(); test06(p); p.reset(); p.shutdown(); } public static void main(String[] args) {
final ProverFactory factory = new PrincessProverFactory();
xandradx/ovirt-engine-disaster-recovery
app/controllers/Security.java
// Path: app/models/User.java // @Entity // public class User extends BaseModel { // // @Required // @MaxSize(45) // @Unique // @Column(length=45, nullable=false, unique=true) // public String username; // // @Column(length=255, nullable=true) // public String password; // // @Required // @MaxSize(45) // @Column(length=45, nullable=false) // public String firstName; // // @Required // @MaxSize(45) // @Column(length=45, nullable=false) // public String lastName; // // public boolean needsPasswordReset = false; // // @Column(name="last_access") // public Date lastAccess; // // @Column(name="last_activity") // public Date lastActivity; // // @ManyToOne(optional=false) // public UserRole role; // // private void encryptPassword() { // if (this.password!=null) { // this.password = Crypto.encryptAES(this.password); // } // } // // private void decryptPassword() { // if (this.password!=null) { // this.password = Crypto.decryptAES(this.password); // } // } // // public String getFullName() { // String name = ""; // // if (this.firstName!=null && !this.firstName.isEmpty()) { // name = firstName; // } // // if (this.lastName!=null && !this.lastName.isEmpty()) { // // if (!name.isEmpty()) { // name += " "; // } // // name += lastName; // } // // return name; // } // // @Override // protected void onPrePersist() { // super.onPrePersist(); // encryptPassword(); // } // // @Override // protected void onPreUpdate() { // super.onPreUpdate(); // encryptPassword(); // } // // @Override // protected void onPostLoad() { // super.onPostLoad(); // decryptPassword(); // } // }
import models.User; import play.i18n.Messages; import java.util.Date;
package controllers; public class Security extends Secure.Security { static String authenticate(String username, String password) {
// Path: app/models/User.java // @Entity // public class User extends BaseModel { // // @Required // @MaxSize(45) // @Unique // @Column(length=45, nullable=false, unique=true) // public String username; // // @Column(length=255, nullable=true) // public String password; // // @Required // @MaxSize(45) // @Column(length=45, nullable=false) // public String firstName; // // @Required // @MaxSize(45) // @Column(length=45, nullable=false) // public String lastName; // // public boolean needsPasswordReset = false; // // @Column(name="last_access") // public Date lastAccess; // // @Column(name="last_activity") // public Date lastActivity; // // @ManyToOne(optional=false) // public UserRole role; // // private void encryptPassword() { // if (this.password!=null) { // this.password = Crypto.encryptAES(this.password); // } // } // // private void decryptPassword() { // if (this.password!=null) { // this.password = Crypto.decryptAES(this.password); // } // } // // public String getFullName() { // String name = ""; // // if (this.firstName!=null && !this.firstName.isEmpty()) { // name = firstName; // } // // if (this.lastName!=null && !this.lastName.isEmpty()) { // // if (!name.isEmpty()) { // name += " "; // } // // name += lastName; // } // // return name; // } // // @Override // protected void onPrePersist() { // super.onPrePersist(); // encryptPassword(); // } // // @Override // protected void onPreUpdate() { // super.onPreUpdate(); // encryptPassword(); // } // // @Override // protected void onPostLoad() { // super.onPostLoad(); // decryptPassword(); // } // } // Path: app/controllers/Security.java import models.User; import play.i18n.Messages; import java.util.Date; package controllers; public class Security extends Secure.Security { static String authenticate(String username, String password) {
User user = User.find("username = :u").bind("u", username).first();
xandradx/ovirt-engine-disaster-recovery
app/jobs/OperationCreationJob.java
// Path: app/models/DisasterRecoveryOperation.java // @Entity // public class DisasterRecoveryOperation extends BaseModel { // // public enum OperationStatus { // PROGRESS, // SUCCESS, // FAILED // } // // public DisasterRecoveryOperation(RemoteHost.RecoveryType type) { // this.status = OperationStatus.PROGRESS; // this.type = type; // } // // public RemoteHost.RecoveryType type; // // @OneToMany(mappedBy = "operation") // public List<OperationLog> logs = new ArrayList<OperationLog>(); // // public OperationStatus status; // // public void addMessageLog(String message) { // addLog(OperationLog.MessageType.MESSAGE, message); // } // // public void addErrorLog(String message) { // addLog(OperationLog.MessageType.ERROR, message); // } // // private void addLog(OperationLog.MessageType type, String message) { // OperationLog log = new OperationLog(type); // log.message = message; // log.operation = this; // log.save(); // } // // } // // Path: app/models/RemoteHost.java // @Entity // public class RemoteHost extends BaseModel { // // public enum RecoveryType { // FAILOVER, // FAILBACK, // NONE // } // // @Required // @Column(nullable = false) // public RecoveryType type; // // @Required // @MaxSize(255) // @Column(length=255, name="host_name", nullable = false) // public String hostName; // }
import models.DisasterRecoveryOperation; import models.RemoteHost; import play.jobs.Job;
/* * Copyright 2016 ITM, S.A. * * Licensed under the Apache License, Version 2.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://www.apache.org/licenses/LICENSE-2.0`](http://www.apache.org/licenses/LICENSE-2.0) * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package jobs; /** * Created by jandrad on 23/01/16. */ public class OperationCreationJob extends Job { private RemoteHost.RecoveryType type; public OperationCreationJob(RemoteHost.RecoveryType type) { this.type = type; } @Override
// Path: app/models/DisasterRecoveryOperation.java // @Entity // public class DisasterRecoveryOperation extends BaseModel { // // public enum OperationStatus { // PROGRESS, // SUCCESS, // FAILED // } // // public DisasterRecoveryOperation(RemoteHost.RecoveryType type) { // this.status = OperationStatus.PROGRESS; // this.type = type; // } // // public RemoteHost.RecoveryType type; // // @OneToMany(mappedBy = "operation") // public List<OperationLog> logs = new ArrayList<OperationLog>(); // // public OperationStatus status; // // public void addMessageLog(String message) { // addLog(OperationLog.MessageType.MESSAGE, message); // } // // public void addErrorLog(String message) { // addLog(OperationLog.MessageType.ERROR, message); // } // // private void addLog(OperationLog.MessageType type, String message) { // OperationLog log = new OperationLog(type); // log.message = message; // log.operation = this; // log.save(); // } // // } // // Path: app/models/RemoteHost.java // @Entity // public class RemoteHost extends BaseModel { // // public enum RecoveryType { // FAILOVER, // FAILBACK, // NONE // } // // @Required // @Column(nullable = false) // public RecoveryType type; // // @Required // @MaxSize(255) // @Column(length=255, name="host_name", nullable = false) // public String hostName; // } // Path: app/jobs/OperationCreationJob.java import models.DisasterRecoveryOperation; import models.RemoteHost; import play.jobs.Job; /* * Copyright 2016 ITM, S.A. * * Licensed under the Apache License, Version 2.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://www.apache.org/licenses/LICENSE-2.0`](http://www.apache.org/licenses/LICENSE-2.0) * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package jobs; /** * Created by jandrad on 23/01/16. */ public class OperationCreationJob extends Job { private RemoteHost.RecoveryType type; public OperationCreationJob(RemoteHost.RecoveryType type) { this.type = type; } @Override
public DisasterRecoveryOperation doJobWithResult() throws Exception {
xandradx/ovirt-engine-disaster-recovery
app/drp/OvirtApi.java
// Path: app/drp/exceptions/InvalidConfigurationException.java // public class InvalidConfigurationException extends Exception{ // // public InvalidConfigurationException(String message) { // super(message); // } // } // // Path: app/models/Configuration.java // @Entity // public class Configuration extends Model { // // // @Required // @MaxSize(200) // @Column(length = 200) // public String apiURL; // // @Required // @MaxSize(100) // @Column(length = 100) // public String apiUser; // // @Required // @MaxSize(100) // @Column(length = 100) // public String apiPassword; // // public boolean validateCertificate; // // public Blob trustStore; // // @MaxSize(200) // @Column(length = 20) // public String trustStorePassword; // // public boolean startVMManager; // // @Required // @MaxSize(50) // @Column(length = 50) // public String managerIp; // // @MaxSize(100) // @Column(length = 100) // public String managerUser; // // @MaxSize(100) // @Column(length = 100) // public String managerKeyLocation; // // @MaxSize(100) // @Column(length = 100) // public String managerBinLocation; // // @MaxSize(100) // @Column(length = 100) // public String managerCommand; // // private Configuration() { // // } // // public static Configuration generalConfiguration() { // // Configuration configuration = Configuration.find("").first(); // if (configuration == null) { // configuration = new Configuration(); // configuration.save(); // } // // return configuration; // } // // public void applyConfiguration(Configuration configuration) { // apiURL = configuration.apiURL; // apiUser = configuration.apiUser; // apiPassword = configuration.apiPassword; // validateCertificate = configuration.validateCertificate; // managerIp = configuration.managerIp; // managerUser = configuration.managerUser; // managerKeyLocation = configuration.managerKeyLocation; // managerBinLocation = configuration.managerBinLocation; // managerCommand = configuration.managerCommand; // trustStorePassword = configuration.trustStorePassword; // startVMManager = configuration.startVMManager; // // // if (configuration.trustStore!=null && configuration.trustStore.exists()) { // if (trustStore!=null && trustStore.exists()) { // trustStore.getFile().delete(); // } // // trustStore = configuration.trustStore; // } // } // // public boolean hasManagerStartup() { // return this.startVMManager && // this.managerUser != null && !this.managerUser.isEmpty() && // this.managerKeyLocation != null && !this.managerKeyLocation.isEmpty() && // this.managerBinLocation != null && !this.managerBinLocation.isEmpty() && // this.managerCommand != null && !this.managerCommand.isEmpty(); // } // // @PreUpdate // @PrePersist // public void encryptPassword() { // if (apiPassword!=null) { // apiPassword = Crypto.encryptAES(apiPassword); // } // } // // @PostLoad // public void decryptPassword() { // if (apiPassword!=null) { // apiPassword = Crypto.decryptAES(apiPassword); // } // } // }
import drp.exceptions.InvalidConfigurationException; import models.Configuration; import org.ovirt.engine.sdk.Api; import org.ovirt.engine.sdk.ApiBuilder; import org.ovirt.engine.sdk.exceptions.ServerException; import org.ovirt.engine.sdk.exceptions.UnsecuredConnectionAttemptError; import play.i18n.Messages; import java.io.File; import java.io.IOException;
/* * Copyright 2016 ITM, S.A. * * Licensed under the Apache License, Version 2.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://www.apache.org/licenses/LICENSE-2.0`](http://www.apache.org/licenses/LICENSE-2.0) * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package drp; /** * Created by jandrad on 24/01/16. */ public class OvirtApi { public static Api getApi() throws UnsecuredConnectionAttemptError, IOException, ServerException, InvalidConfigurationException {
// Path: app/drp/exceptions/InvalidConfigurationException.java // public class InvalidConfigurationException extends Exception{ // // public InvalidConfigurationException(String message) { // super(message); // } // } // // Path: app/models/Configuration.java // @Entity // public class Configuration extends Model { // // // @Required // @MaxSize(200) // @Column(length = 200) // public String apiURL; // // @Required // @MaxSize(100) // @Column(length = 100) // public String apiUser; // // @Required // @MaxSize(100) // @Column(length = 100) // public String apiPassword; // // public boolean validateCertificate; // // public Blob trustStore; // // @MaxSize(200) // @Column(length = 20) // public String trustStorePassword; // // public boolean startVMManager; // // @Required // @MaxSize(50) // @Column(length = 50) // public String managerIp; // // @MaxSize(100) // @Column(length = 100) // public String managerUser; // // @MaxSize(100) // @Column(length = 100) // public String managerKeyLocation; // // @MaxSize(100) // @Column(length = 100) // public String managerBinLocation; // // @MaxSize(100) // @Column(length = 100) // public String managerCommand; // // private Configuration() { // // } // // public static Configuration generalConfiguration() { // // Configuration configuration = Configuration.find("").first(); // if (configuration == null) { // configuration = new Configuration(); // configuration.save(); // } // // return configuration; // } // // public void applyConfiguration(Configuration configuration) { // apiURL = configuration.apiURL; // apiUser = configuration.apiUser; // apiPassword = configuration.apiPassword; // validateCertificate = configuration.validateCertificate; // managerIp = configuration.managerIp; // managerUser = configuration.managerUser; // managerKeyLocation = configuration.managerKeyLocation; // managerBinLocation = configuration.managerBinLocation; // managerCommand = configuration.managerCommand; // trustStorePassword = configuration.trustStorePassword; // startVMManager = configuration.startVMManager; // // // if (configuration.trustStore!=null && configuration.trustStore.exists()) { // if (trustStore!=null && trustStore.exists()) { // trustStore.getFile().delete(); // } // // trustStore = configuration.trustStore; // } // } // // public boolean hasManagerStartup() { // return this.startVMManager && // this.managerUser != null && !this.managerUser.isEmpty() && // this.managerKeyLocation != null && !this.managerKeyLocation.isEmpty() && // this.managerBinLocation != null && !this.managerBinLocation.isEmpty() && // this.managerCommand != null && !this.managerCommand.isEmpty(); // } // // @PreUpdate // @PrePersist // public void encryptPassword() { // if (apiPassword!=null) { // apiPassword = Crypto.encryptAES(apiPassword); // } // } // // @PostLoad // public void decryptPassword() { // if (apiPassword!=null) { // apiPassword = Crypto.decryptAES(apiPassword); // } // } // } // Path: app/drp/OvirtApi.java import drp.exceptions.InvalidConfigurationException; import models.Configuration; import org.ovirt.engine.sdk.Api; import org.ovirt.engine.sdk.ApiBuilder; import org.ovirt.engine.sdk.exceptions.ServerException; import org.ovirt.engine.sdk.exceptions.UnsecuredConnectionAttemptError; import play.i18n.Messages; import java.io.File; import java.io.IOException; /* * Copyright 2016 ITM, S.A. * * Licensed under the Apache License, Version 2.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://www.apache.org/licenses/LICENSE-2.0`](http://www.apache.org/licenses/LICENSE-2.0) * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package drp; /** * Created by jandrad on 24/01/16. */ public class OvirtApi { public static Api getApi() throws UnsecuredConnectionAttemptError, IOException, ServerException, InvalidConfigurationException {
Configuration configuration = Configuration.generalConfiguration();
xandradx/ovirt-engine-disaster-recovery
app/controllers/Profile.java
// Path: app/models/User.java // @Entity // public class User extends BaseModel { // // @Required // @MaxSize(45) // @Unique // @Column(length=45, nullable=false, unique=true) // public String username; // // @Column(length=255, nullable=true) // public String password; // // @Required // @MaxSize(45) // @Column(length=45, nullable=false) // public String firstName; // // @Required // @MaxSize(45) // @Column(length=45, nullable=false) // public String lastName; // // public boolean needsPasswordReset = false; // // @Column(name="last_access") // public Date lastAccess; // // @Column(name="last_activity") // public Date lastActivity; // // @ManyToOne(optional=false) // public UserRole role; // // private void encryptPassword() { // if (this.password!=null) { // this.password = Crypto.encryptAES(this.password); // } // } // // private void decryptPassword() { // if (this.password!=null) { // this.password = Crypto.decryptAES(this.password); // } // } // // public String getFullName() { // String name = ""; // // if (this.firstName!=null && !this.firstName.isEmpty()) { // name = firstName; // } // // if (this.lastName!=null && !this.lastName.isEmpty()) { // // if (!name.isEmpty()) { // name += " "; // } // // name += lastName; // } // // return name; // } // // @Override // protected void onPrePersist() { // super.onPrePersist(); // encryptPassword(); // } // // @Override // protected void onPreUpdate() { // super.onPreUpdate(); // encryptPassword(); // } // // @Override // protected void onPostLoad() { // super.onPostLoad(); // decryptPassword(); // } // }
import models.User; import play.data.validation.Equals; import play.data.validation.MaxSize; import play.data.validation.MinSize; import play.data.validation.Required; import play.i18n.Messages; import play.mvc.With;
/* * Copyright 2016 ITM, S.A. * * Licensed under the Apache License, Version 2.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://www.apache.org/licenses/LICENSE-2.0`](http://www.apache.org/licenses/LICENSE-2.0) * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package controllers; /** * Created by jandrad on 21/09/15. */ @With(Secure.class) public class Profile extends AuthenticatedController { public static void index() {
// Path: app/models/User.java // @Entity // public class User extends BaseModel { // // @Required // @MaxSize(45) // @Unique // @Column(length=45, nullable=false, unique=true) // public String username; // // @Column(length=255, nullable=true) // public String password; // // @Required // @MaxSize(45) // @Column(length=45, nullable=false) // public String firstName; // // @Required // @MaxSize(45) // @Column(length=45, nullable=false) // public String lastName; // // public boolean needsPasswordReset = false; // // @Column(name="last_access") // public Date lastAccess; // // @Column(name="last_activity") // public Date lastActivity; // // @ManyToOne(optional=false) // public UserRole role; // // private void encryptPassword() { // if (this.password!=null) { // this.password = Crypto.encryptAES(this.password); // } // } // // private void decryptPassword() { // if (this.password!=null) { // this.password = Crypto.decryptAES(this.password); // } // } // // public String getFullName() { // String name = ""; // // if (this.firstName!=null && !this.firstName.isEmpty()) { // name = firstName; // } // // if (this.lastName!=null && !this.lastName.isEmpty()) { // // if (!name.isEmpty()) { // name += " "; // } // // name += lastName; // } // // return name; // } // // @Override // protected void onPrePersist() { // super.onPrePersist(); // encryptPassword(); // } // // @Override // protected void onPreUpdate() { // super.onPreUpdate(); // encryptPassword(); // } // // @Override // protected void onPostLoad() { // super.onPostLoad(); // decryptPassword(); // } // } // Path: app/controllers/Profile.java import models.User; import play.data.validation.Equals; import play.data.validation.MaxSize; import play.data.validation.MinSize; import play.data.validation.Required; import play.i18n.Messages; import play.mvc.With; /* * Copyright 2016 ITM, S.A. * * Licensed under the Apache License, Version 2.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://www.apache.org/licenses/LICENSE-2.0`](http://www.apache.org/licenses/LICENSE-2.0) * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package controllers; /** * Created by jandrad on 21/09/15. */ @With(Secure.class) public class Profile extends AuthenticatedController { public static void index() {
User user = getUser();
xandradx/ovirt-engine-disaster-recovery
app/dto/DtoHelper.java
// Path: app/dto/objects/ConnectionDto.java // public class ConnectionDto { // // protected String ipAddress; // protected String iqn; // // public ConnectionDto(String ipAddress, String iqn) { // this.ipAddress = ipAddress; // this.iqn = iqn; // } // // public String getIpAddress() { // return ipAddress; // } // // public void setIpAddress(String ipAddress) { // this.ipAddress = ipAddress; // } // // public String getIqn() { // return iqn; // } // // public void setIqn(String iqn) { // this.iqn = iqn; // } // } // // Path: app/dto/objects/DataCenterDto.java // public class DataCenterDto { // // protected String name; // protected String status; // // public DataCenterDto(String name, String status) { // this.name = name; // this.status = status; // } // // public String getName() { // return name; // } // // public String getStatus() { // return status; // } // } // // Path: app/dto/objects/HostDto.java // public class HostDto { // // protected String name; // protected String ip; // protected String identifier; // protected String status; // protected RemoteHost.RecoveryType type; // // public HostDto(String name, String ip, String identifier, String status) { // this.name = name; // this.ip = ip; // this.identifier = identifier; // this.status = status; // } // // public String getName() { // return name; // } // // public String getIp() { // return ip; // } // // public String getIdentifier() { // return identifier; // } // // public String getStatus() { // return status; // } // // public RemoteHost.RecoveryType getType() { // return type; // } // // public void setType(RemoteHost.RecoveryType type) { // this.type = type; // } // } // // Path: app/models/RemoteHost.java // @Entity // public class RemoteHost extends BaseModel { // // public enum RecoveryType { // FAILOVER, // FAILBACK, // NONE // } // // @Required // @Column(nullable = false) // public RecoveryType type; // // @Required // @MaxSize(255) // @Column(length=255, name="host_name", nullable = false) // public String hostName; // }
import dto.objects.ConnectionDto; import dto.objects.DataCenterDto; import dto.objects.HostDto; import models.RemoteHost; import org.ovirt.engine.sdk.decorators.DataCenter; import org.ovirt.engine.sdk.decorators.Host; import org.ovirt.engine.sdk.decorators.StorageConnection; import play.i18n.Messages; import java.util.List;
/* * Copyright 2016 ITM, S.A. * * Licensed under the Apache License, Version 2.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://www.apache.org/licenses/LICENSE-2.0`](http://www.apache.org/licenses/LICENSE-2.0) * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dto; /** * Created by jandrad on 26/01/16. */ public class DtoHelper { public static HostDto getHostDto(Host host) { return new HostDto(host.getName(), host.getAddress(), host.getDescription(), Messages.get(host.getStatus().getState())); }
// Path: app/dto/objects/ConnectionDto.java // public class ConnectionDto { // // protected String ipAddress; // protected String iqn; // // public ConnectionDto(String ipAddress, String iqn) { // this.ipAddress = ipAddress; // this.iqn = iqn; // } // // public String getIpAddress() { // return ipAddress; // } // // public void setIpAddress(String ipAddress) { // this.ipAddress = ipAddress; // } // // public String getIqn() { // return iqn; // } // // public void setIqn(String iqn) { // this.iqn = iqn; // } // } // // Path: app/dto/objects/DataCenterDto.java // public class DataCenterDto { // // protected String name; // protected String status; // // public DataCenterDto(String name, String status) { // this.name = name; // this.status = status; // } // // public String getName() { // return name; // } // // public String getStatus() { // return status; // } // } // // Path: app/dto/objects/HostDto.java // public class HostDto { // // protected String name; // protected String ip; // protected String identifier; // protected String status; // protected RemoteHost.RecoveryType type; // // public HostDto(String name, String ip, String identifier, String status) { // this.name = name; // this.ip = ip; // this.identifier = identifier; // this.status = status; // } // // public String getName() { // return name; // } // // public String getIp() { // return ip; // } // // public String getIdentifier() { // return identifier; // } // // public String getStatus() { // return status; // } // // public RemoteHost.RecoveryType getType() { // return type; // } // // public void setType(RemoteHost.RecoveryType type) { // this.type = type; // } // } // // Path: app/models/RemoteHost.java // @Entity // public class RemoteHost extends BaseModel { // // public enum RecoveryType { // FAILOVER, // FAILBACK, // NONE // } // // @Required // @Column(nullable = false) // public RecoveryType type; // // @Required // @MaxSize(255) // @Column(length=255, name="host_name", nullable = false) // public String hostName; // } // Path: app/dto/DtoHelper.java import dto.objects.ConnectionDto; import dto.objects.DataCenterDto; import dto.objects.HostDto; import models.RemoteHost; import org.ovirt.engine.sdk.decorators.DataCenter; import org.ovirt.engine.sdk.decorators.Host; import org.ovirt.engine.sdk.decorators.StorageConnection; import play.i18n.Messages; import java.util.List; /* * Copyright 2016 ITM, S.A. * * Licensed under the Apache License, Version 2.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://www.apache.org/licenses/LICENSE-2.0`](http://www.apache.org/licenses/LICENSE-2.0) * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dto; /** * Created by jandrad on 26/01/16. */ public class DtoHelper { public static HostDto getHostDto(Host host) { return new HostDto(host.getName(), host.getAddress(), host.getDescription(), Messages.get(host.getStatus().getState())); }
public static ConnectionDto getConnectionDto(StorageConnection connection) {
xandradx/ovirt-engine-disaster-recovery
app/dto/DtoHelper.java
// Path: app/dto/objects/ConnectionDto.java // public class ConnectionDto { // // protected String ipAddress; // protected String iqn; // // public ConnectionDto(String ipAddress, String iqn) { // this.ipAddress = ipAddress; // this.iqn = iqn; // } // // public String getIpAddress() { // return ipAddress; // } // // public void setIpAddress(String ipAddress) { // this.ipAddress = ipAddress; // } // // public String getIqn() { // return iqn; // } // // public void setIqn(String iqn) { // this.iqn = iqn; // } // } // // Path: app/dto/objects/DataCenterDto.java // public class DataCenterDto { // // protected String name; // protected String status; // // public DataCenterDto(String name, String status) { // this.name = name; // this.status = status; // } // // public String getName() { // return name; // } // // public String getStatus() { // return status; // } // } // // Path: app/dto/objects/HostDto.java // public class HostDto { // // protected String name; // protected String ip; // protected String identifier; // protected String status; // protected RemoteHost.RecoveryType type; // // public HostDto(String name, String ip, String identifier, String status) { // this.name = name; // this.ip = ip; // this.identifier = identifier; // this.status = status; // } // // public String getName() { // return name; // } // // public String getIp() { // return ip; // } // // public String getIdentifier() { // return identifier; // } // // public String getStatus() { // return status; // } // // public RemoteHost.RecoveryType getType() { // return type; // } // // public void setType(RemoteHost.RecoveryType type) { // this.type = type; // } // } // // Path: app/models/RemoteHost.java // @Entity // public class RemoteHost extends BaseModel { // // public enum RecoveryType { // FAILOVER, // FAILBACK, // NONE // } // // @Required // @Column(nullable = false) // public RecoveryType type; // // @Required // @MaxSize(255) // @Column(length=255, name="host_name", nullable = false) // public String hostName; // }
import dto.objects.ConnectionDto; import dto.objects.DataCenterDto; import dto.objects.HostDto; import models.RemoteHost; import org.ovirt.engine.sdk.decorators.DataCenter; import org.ovirt.engine.sdk.decorators.Host; import org.ovirt.engine.sdk.decorators.StorageConnection; import play.i18n.Messages; import java.util.List;
/* * Copyright 2016 ITM, S.A. * * Licensed under the Apache License, Version 2.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://www.apache.org/licenses/LICENSE-2.0`](http://www.apache.org/licenses/LICENSE-2.0) * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dto; /** * Created by jandrad on 26/01/16. */ public class DtoHelper { public static HostDto getHostDto(Host host) { return new HostDto(host.getName(), host.getAddress(), host.getDescription(), Messages.get(host.getStatus().getState())); } public static ConnectionDto getConnectionDto(StorageConnection connection) { return new ConnectionDto(connection.getAddress(), connection.getTarget()); }
// Path: app/dto/objects/ConnectionDto.java // public class ConnectionDto { // // protected String ipAddress; // protected String iqn; // // public ConnectionDto(String ipAddress, String iqn) { // this.ipAddress = ipAddress; // this.iqn = iqn; // } // // public String getIpAddress() { // return ipAddress; // } // // public void setIpAddress(String ipAddress) { // this.ipAddress = ipAddress; // } // // public String getIqn() { // return iqn; // } // // public void setIqn(String iqn) { // this.iqn = iqn; // } // } // // Path: app/dto/objects/DataCenterDto.java // public class DataCenterDto { // // protected String name; // protected String status; // // public DataCenterDto(String name, String status) { // this.name = name; // this.status = status; // } // // public String getName() { // return name; // } // // public String getStatus() { // return status; // } // } // // Path: app/dto/objects/HostDto.java // public class HostDto { // // protected String name; // protected String ip; // protected String identifier; // protected String status; // protected RemoteHost.RecoveryType type; // // public HostDto(String name, String ip, String identifier, String status) { // this.name = name; // this.ip = ip; // this.identifier = identifier; // this.status = status; // } // // public String getName() { // return name; // } // // public String getIp() { // return ip; // } // // public String getIdentifier() { // return identifier; // } // // public String getStatus() { // return status; // } // // public RemoteHost.RecoveryType getType() { // return type; // } // // public void setType(RemoteHost.RecoveryType type) { // this.type = type; // } // } // // Path: app/models/RemoteHost.java // @Entity // public class RemoteHost extends BaseModel { // // public enum RecoveryType { // FAILOVER, // FAILBACK, // NONE // } // // @Required // @Column(nullable = false) // public RecoveryType type; // // @Required // @MaxSize(255) // @Column(length=255, name="host_name", nullable = false) // public String hostName; // } // Path: app/dto/DtoHelper.java import dto.objects.ConnectionDto; import dto.objects.DataCenterDto; import dto.objects.HostDto; import models.RemoteHost; import org.ovirt.engine.sdk.decorators.DataCenter; import org.ovirt.engine.sdk.decorators.Host; import org.ovirt.engine.sdk.decorators.StorageConnection; import play.i18n.Messages; import java.util.List; /* * Copyright 2016 ITM, S.A. * * Licensed under the Apache License, Version 2.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://www.apache.org/licenses/LICENSE-2.0`](http://www.apache.org/licenses/LICENSE-2.0) * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dto; /** * Created by jandrad on 26/01/16. */ public class DtoHelper { public static HostDto getHostDto(Host host) { return new HostDto(host.getName(), host.getAddress(), host.getDescription(), Messages.get(host.getStatus().getState())); } public static ConnectionDto getConnectionDto(StorageConnection connection) { return new ConnectionDto(connection.getAddress(), connection.getTarget()); }
public static DataCenterDto getDataCenterDto(DataCenter dataCenter) {
xandradx/ovirt-engine-disaster-recovery
app/dto/DtoHelper.java
// Path: app/dto/objects/ConnectionDto.java // public class ConnectionDto { // // protected String ipAddress; // protected String iqn; // // public ConnectionDto(String ipAddress, String iqn) { // this.ipAddress = ipAddress; // this.iqn = iqn; // } // // public String getIpAddress() { // return ipAddress; // } // // public void setIpAddress(String ipAddress) { // this.ipAddress = ipAddress; // } // // public String getIqn() { // return iqn; // } // // public void setIqn(String iqn) { // this.iqn = iqn; // } // } // // Path: app/dto/objects/DataCenterDto.java // public class DataCenterDto { // // protected String name; // protected String status; // // public DataCenterDto(String name, String status) { // this.name = name; // this.status = status; // } // // public String getName() { // return name; // } // // public String getStatus() { // return status; // } // } // // Path: app/dto/objects/HostDto.java // public class HostDto { // // protected String name; // protected String ip; // protected String identifier; // protected String status; // protected RemoteHost.RecoveryType type; // // public HostDto(String name, String ip, String identifier, String status) { // this.name = name; // this.ip = ip; // this.identifier = identifier; // this.status = status; // } // // public String getName() { // return name; // } // // public String getIp() { // return ip; // } // // public String getIdentifier() { // return identifier; // } // // public String getStatus() { // return status; // } // // public RemoteHost.RecoveryType getType() { // return type; // } // // public void setType(RemoteHost.RecoveryType type) { // this.type = type; // } // } // // Path: app/models/RemoteHost.java // @Entity // public class RemoteHost extends BaseModel { // // public enum RecoveryType { // FAILOVER, // FAILBACK, // NONE // } // // @Required // @Column(nullable = false) // public RecoveryType type; // // @Required // @MaxSize(255) // @Column(length=255, name="host_name", nullable = false) // public String hostName; // }
import dto.objects.ConnectionDto; import dto.objects.DataCenterDto; import dto.objects.HostDto; import models.RemoteHost; import org.ovirt.engine.sdk.decorators.DataCenter; import org.ovirt.engine.sdk.decorators.Host; import org.ovirt.engine.sdk.decorators.StorageConnection; import play.i18n.Messages; import java.util.List;
/* * Copyright 2016 ITM, S.A. * * Licensed under the Apache License, Version 2.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://www.apache.org/licenses/LICENSE-2.0`](http://www.apache.org/licenses/LICENSE-2.0) * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dto; /** * Created by jandrad on 26/01/16. */ public class DtoHelper { public static HostDto getHostDto(Host host) { return new HostDto(host.getName(), host.getAddress(), host.getDescription(), Messages.get(host.getStatus().getState())); } public static ConnectionDto getConnectionDto(StorageConnection connection) { return new ConnectionDto(connection.getAddress(), connection.getTarget()); } public static DataCenterDto getDataCenterDto(DataCenter dataCenter) { return new DataCenterDto(dataCenter.getName(), Messages.get(dataCenter.getStatus().getState())); }
// Path: app/dto/objects/ConnectionDto.java // public class ConnectionDto { // // protected String ipAddress; // protected String iqn; // // public ConnectionDto(String ipAddress, String iqn) { // this.ipAddress = ipAddress; // this.iqn = iqn; // } // // public String getIpAddress() { // return ipAddress; // } // // public void setIpAddress(String ipAddress) { // this.ipAddress = ipAddress; // } // // public String getIqn() { // return iqn; // } // // public void setIqn(String iqn) { // this.iqn = iqn; // } // } // // Path: app/dto/objects/DataCenterDto.java // public class DataCenterDto { // // protected String name; // protected String status; // // public DataCenterDto(String name, String status) { // this.name = name; // this.status = status; // } // // public String getName() { // return name; // } // // public String getStatus() { // return status; // } // } // // Path: app/dto/objects/HostDto.java // public class HostDto { // // protected String name; // protected String ip; // protected String identifier; // protected String status; // protected RemoteHost.RecoveryType type; // // public HostDto(String name, String ip, String identifier, String status) { // this.name = name; // this.ip = ip; // this.identifier = identifier; // this.status = status; // } // // public String getName() { // return name; // } // // public String getIp() { // return ip; // } // // public String getIdentifier() { // return identifier; // } // // public String getStatus() { // return status; // } // // public RemoteHost.RecoveryType getType() { // return type; // } // // public void setType(RemoteHost.RecoveryType type) { // this.type = type; // } // } // // Path: app/models/RemoteHost.java // @Entity // public class RemoteHost extends BaseModel { // // public enum RecoveryType { // FAILOVER, // FAILBACK, // NONE // } // // @Required // @Column(nullable = false) // public RecoveryType type; // // @Required // @MaxSize(255) // @Column(length=255, name="host_name", nullable = false) // public String hostName; // } // Path: app/dto/DtoHelper.java import dto.objects.ConnectionDto; import dto.objects.DataCenterDto; import dto.objects.HostDto; import models.RemoteHost; import org.ovirt.engine.sdk.decorators.DataCenter; import org.ovirt.engine.sdk.decorators.Host; import org.ovirt.engine.sdk.decorators.StorageConnection; import play.i18n.Messages; import java.util.List; /* * Copyright 2016 ITM, S.A. * * Licensed under the Apache License, Version 2.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://www.apache.org/licenses/LICENSE-2.0`](http://www.apache.org/licenses/LICENSE-2.0) * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dto; /** * Created by jandrad on 26/01/16. */ public class DtoHelper { public static HostDto getHostDto(Host host) { return new HostDto(host.getName(), host.getAddress(), host.getDescription(), Messages.get(host.getStatus().getState())); } public static ConnectionDto getConnectionDto(StorageConnection connection) { return new ConnectionDto(connection.getAddress(), connection.getTarget()); } public static DataCenterDto getDataCenterDto(DataCenter dataCenter) { return new DataCenterDto(dataCenter.getName(), Messages.get(dataCenter.getStatus().getState())); }
public static RemoteHost.RecoveryType getRecoveryType(HostDto dto, List<RemoteHost> remoteHosts) {
xandradx/ovirt-engine-disaster-recovery
app/jobs/StartupJob.java
// Path: app/models/DisasterRecoveryOperation.java // @Entity // public class DisasterRecoveryOperation extends BaseModel { // // public enum OperationStatus { // PROGRESS, // SUCCESS, // FAILED // } // // public DisasterRecoveryOperation(RemoteHost.RecoveryType type) { // this.status = OperationStatus.PROGRESS; // this.type = type; // } // // public RemoteHost.RecoveryType type; // // @OneToMany(mappedBy = "operation") // public List<OperationLog> logs = new ArrayList<OperationLog>(); // // public OperationStatus status; // // public void addMessageLog(String message) { // addLog(OperationLog.MessageType.MESSAGE, message); // } // // public void addErrorLog(String message) { // addLog(OperationLog.MessageType.ERROR, message); // } // // private void addLog(OperationLog.MessageType type, String message) { // OperationLog log = new OperationLog(type); // log.message = message; // log.operation = this; // log.save(); // } // // } // // Path: app/models/UserRole.java // @Entity // public class UserRole extends Model { // // public enum RoleCode { // ADMINISTRATOR, // TECNICO // } // // @Required // @MaxSize(45) // @Column(length=45, nullable=false) // public String name; // // @Required // @Column(nullable=false) // public RoleCode code; // // @MaxSize(100) // @Column(length=100, nullable=true) // public String description; // // }
import models.DisasterRecoveryOperation; import models.UserRole; import play.jobs.Job; import play.jobs.OnApplicationStart; import play.test.Fixtures; import java.util.List;
package jobs; @OnApplicationStart public class StartupJob extends Job { @Override public void doJob() throws Exception {
// Path: app/models/DisasterRecoveryOperation.java // @Entity // public class DisasterRecoveryOperation extends BaseModel { // // public enum OperationStatus { // PROGRESS, // SUCCESS, // FAILED // } // // public DisasterRecoveryOperation(RemoteHost.RecoveryType type) { // this.status = OperationStatus.PROGRESS; // this.type = type; // } // // public RemoteHost.RecoveryType type; // // @OneToMany(mappedBy = "operation") // public List<OperationLog> logs = new ArrayList<OperationLog>(); // // public OperationStatus status; // // public void addMessageLog(String message) { // addLog(OperationLog.MessageType.MESSAGE, message); // } // // public void addErrorLog(String message) { // addLog(OperationLog.MessageType.ERROR, message); // } // // private void addLog(OperationLog.MessageType type, String message) { // OperationLog log = new OperationLog(type); // log.message = message; // log.operation = this; // log.save(); // } // // } // // Path: app/models/UserRole.java // @Entity // public class UserRole extends Model { // // public enum RoleCode { // ADMINISTRATOR, // TECNICO // } // // @Required // @MaxSize(45) // @Column(length=45, nullable=false) // public String name; // // @Required // @Column(nullable=false) // public RoleCode code; // // @MaxSize(100) // @Column(length=100, nullable=true) // public String description; // // } // Path: app/jobs/StartupJob.java import models.DisasterRecoveryOperation; import models.UserRole; import play.jobs.Job; import play.jobs.OnApplicationStart; import play.test.Fixtures; import java.util.List; package jobs; @OnApplicationStart public class StartupJob extends Job { @Override public void doJob() throws Exception {
if (UserRole.count() == 0) {
xandradx/ovirt-engine-disaster-recovery
app/jobs/StartupJob.java
// Path: app/models/DisasterRecoveryOperation.java // @Entity // public class DisasterRecoveryOperation extends BaseModel { // // public enum OperationStatus { // PROGRESS, // SUCCESS, // FAILED // } // // public DisasterRecoveryOperation(RemoteHost.RecoveryType type) { // this.status = OperationStatus.PROGRESS; // this.type = type; // } // // public RemoteHost.RecoveryType type; // // @OneToMany(mappedBy = "operation") // public List<OperationLog> logs = new ArrayList<OperationLog>(); // // public OperationStatus status; // // public void addMessageLog(String message) { // addLog(OperationLog.MessageType.MESSAGE, message); // } // // public void addErrorLog(String message) { // addLog(OperationLog.MessageType.ERROR, message); // } // // private void addLog(OperationLog.MessageType type, String message) { // OperationLog log = new OperationLog(type); // log.message = message; // log.operation = this; // log.save(); // } // // } // // Path: app/models/UserRole.java // @Entity // public class UserRole extends Model { // // public enum RoleCode { // ADMINISTRATOR, // TECNICO // } // // @Required // @MaxSize(45) // @Column(length=45, nullable=false) // public String name; // // @Required // @Column(nullable=false) // public RoleCode code; // // @MaxSize(100) // @Column(length=100, nullable=true) // public String description; // // }
import models.DisasterRecoveryOperation; import models.UserRole; import play.jobs.Job; import play.jobs.OnApplicationStart; import play.test.Fixtures; import java.util.List;
package jobs; @OnApplicationStart public class StartupJob extends Job { @Override public void doJob() throws Exception { if (UserRole.count() == 0) { Fixtures.loadModels("initial-data.yml"); }
// Path: app/models/DisasterRecoveryOperation.java // @Entity // public class DisasterRecoveryOperation extends BaseModel { // // public enum OperationStatus { // PROGRESS, // SUCCESS, // FAILED // } // // public DisasterRecoveryOperation(RemoteHost.RecoveryType type) { // this.status = OperationStatus.PROGRESS; // this.type = type; // } // // public RemoteHost.RecoveryType type; // // @OneToMany(mappedBy = "operation") // public List<OperationLog> logs = new ArrayList<OperationLog>(); // // public OperationStatus status; // // public void addMessageLog(String message) { // addLog(OperationLog.MessageType.MESSAGE, message); // } // // public void addErrorLog(String message) { // addLog(OperationLog.MessageType.ERROR, message); // } // // private void addLog(OperationLog.MessageType type, String message) { // OperationLog log = new OperationLog(type); // log.message = message; // log.operation = this; // log.save(); // } // // } // // Path: app/models/UserRole.java // @Entity // public class UserRole extends Model { // // public enum RoleCode { // ADMINISTRATOR, // TECNICO // } // // @Required // @MaxSize(45) // @Column(length=45, nullable=false) // public String name; // // @Required // @Column(nullable=false) // public RoleCode code; // // @MaxSize(100) // @Column(length=100, nullable=true) // public String description; // // } // Path: app/jobs/StartupJob.java import models.DisasterRecoveryOperation; import models.UserRole; import play.jobs.Job; import play.jobs.OnApplicationStart; import play.test.Fixtures; import java.util.List; package jobs; @OnApplicationStart public class StartupJob extends Job { @Override public void doJob() throws Exception { if (UserRole.count() == 0) { Fixtures.loadModels("initial-data.yml"); }
List<DisasterRecoveryOperation> operations = DisasterRecoveryOperation.find("active = :a AND status = :s").bind("a", true).bind("s", DisasterRecoveryOperation.OperationStatus.PROGRESS).fetch();
xandradx/ovirt-engine-disaster-recovery
app/drp/DisasterRecoveryActions.java
// Path: app/drp/objects/DatabaseManager.java // public class DatabaseManager { // // private String dbHost; // private String dbPort; // private String dbName; // private String dbUser; // private String dbPassword; // // public DatabaseManager(String host, String port, String name, String user, String password) { // dbHost = host; // dbPort = port; // dbName = name; // dbUser = user; // dbPassword = password; // } // // public String getDbHost() { // return dbHost; // } // // public String getDbPort() { // return dbPort; // } // // public String getDbName() { // return dbName; // } // // public String getDbUser() { // return dbUser; // } // // public String getDbPassword() { // return dbPassword; // } // } // // Path: app/drp/objects/OperationListener.java // public interface OperationListener { // // public enum MessageType { // INFO, // SUCCESS, // ERROR // } // // void onMessage(Exception e, String message, MessageType type); // void onFinished(String message, boolean success); // void onRefreshHosts(); // void onRefreshDatacenters(); // } // // Path: app/models/DatabaseConnection.java // @Entity // public class DatabaseConnection extends BaseModel { // // @Required // @MaxSize(20) // @Column(name="origin_connection", nullable = false, length = 20) // public String originConnection; // // // @Required // @MaxSize(20) // @Column(name="destination_connection", nullable = false, length = 20) // public String destinationConnection; // // } // // Path: app/models/DatabaseIQN.java // @Entity // public class DatabaseIQN extends BaseModel { // // @Required // @MaxSize(255) // @Column(name="origin_iqn", nullable = false, length = 255) // public String originIQN; // // // @Required // @MaxSize(255) // @Column(name="destination_iqn", nullable = false, length = 255) // public String destinationIQN; // }
import java.util.List; import java.util.function.Consumer; import java.util.stream.Collectors; import drp.exceptions.*; import drp.objects.DatabaseManager; import drp.objects.OperationListener; import models.DatabaseConnection; import models.DatabaseIQN; import org.ovirt.engine.sdk.Api; import org.ovirt.engine.sdk.decorators.Host; import org.ovirt.engine.sdk.entities.Action; import org.ovirt.engine.sdk.entities.PowerManagement; import org.ovirt.engine.sdk.entities.StorageConnection; import org.ovirt.engine.sdk.exceptions.ServerException; import play.Logger; import play.i18n.Messages; import java.io.IOException; import java.sql.*;
try { Logger.debug("Deactivating host: %s", host.getName()); Action requestAction = new Action(); Action resultAction = host.deactivate(requestAction); if (!"complete".equals(resultAction.getStatus().getState())) { throw new HostDeactivateException(Messages.get("drp.deactivateexception",host.getName())); } } catch (Exception e) { throw new HostDeactivateException(Messages.get("drp.deactivateexception",host.getName())); } } public static void activateHost(Host host) throws HostActivateException{ if (host == null) { throw new HostActivateException(Messages.get("drp.activateexceptioninvalidhost")); } try { Logger.debug("Activating host: %s", host.getName()); Action requestAction = new Action(); Action resultAction = host.activate(requestAction); if (!"complete".equals(resultAction.getStatus().getState())) { throw new HostActivateException(Messages.get("drp.activateexception", host.getName())); } } catch (Exception e) { throw new HostActivateException(Messages.get("drp.activateexception",host.getName())); } }
// Path: app/drp/objects/DatabaseManager.java // public class DatabaseManager { // // private String dbHost; // private String dbPort; // private String dbName; // private String dbUser; // private String dbPassword; // // public DatabaseManager(String host, String port, String name, String user, String password) { // dbHost = host; // dbPort = port; // dbName = name; // dbUser = user; // dbPassword = password; // } // // public String getDbHost() { // return dbHost; // } // // public String getDbPort() { // return dbPort; // } // // public String getDbName() { // return dbName; // } // // public String getDbUser() { // return dbUser; // } // // public String getDbPassword() { // return dbPassword; // } // } // // Path: app/drp/objects/OperationListener.java // public interface OperationListener { // // public enum MessageType { // INFO, // SUCCESS, // ERROR // } // // void onMessage(Exception e, String message, MessageType type); // void onFinished(String message, boolean success); // void onRefreshHosts(); // void onRefreshDatacenters(); // } // // Path: app/models/DatabaseConnection.java // @Entity // public class DatabaseConnection extends BaseModel { // // @Required // @MaxSize(20) // @Column(name="origin_connection", nullable = false, length = 20) // public String originConnection; // // // @Required // @MaxSize(20) // @Column(name="destination_connection", nullable = false, length = 20) // public String destinationConnection; // // } // // Path: app/models/DatabaseIQN.java // @Entity // public class DatabaseIQN extends BaseModel { // // @Required // @MaxSize(255) // @Column(name="origin_iqn", nullable = false, length = 255) // public String originIQN; // // // @Required // @MaxSize(255) // @Column(name="destination_iqn", nullable = false, length = 255) // public String destinationIQN; // } // Path: app/drp/DisasterRecoveryActions.java import java.util.List; import java.util.function.Consumer; import java.util.stream.Collectors; import drp.exceptions.*; import drp.objects.DatabaseManager; import drp.objects.OperationListener; import models.DatabaseConnection; import models.DatabaseIQN; import org.ovirt.engine.sdk.Api; import org.ovirt.engine.sdk.decorators.Host; import org.ovirt.engine.sdk.entities.Action; import org.ovirt.engine.sdk.entities.PowerManagement; import org.ovirt.engine.sdk.entities.StorageConnection; import org.ovirt.engine.sdk.exceptions.ServerException; import play.Logger; import play.i18n.Messages; import java.io.IOException; import java.sql.*; try { Logger.debug("Deactivating host: %s", host.getName()); Action requestAction = new Action(); Action resultAction = host.deactivate(requestAction); if (!"complete".equals(resultAction.getStatus().getState())) { throw new HostDeactivateException(Messages.get("drp.deactivateexception",host.getName())); } } catch (Exception e) { throw new HostDeactivateException(Messages.get("drp.deactivateexception",host.getName())); } } public static void activateHost(Host host) throws HostActivateException{ if (host == null) { throw new HostActivateException(Messages.get("drp.activateexceptioninvalidhost")); } try { Logger.debug("Activating host: %s", host.getName()); Action requestAction = new Action(); Action resultAction = host.activate(requestAction); if (!"complete".equals(resultAction.getStatus().getState())) { throw new HostActivateException(Messages.get("drp.activateexception", host.getName())); } } catch (Exception e) { throw new HostActivateException(Messages.get("drp.activateexception",host.getName())); } }
public static void updateConnections(Api api, List<DatabaseConnection> connections, List<DatabaseIQN> iqns, boolean revert, OperationListener listener) throws ConnectionUpdateException {
xandradx/ovirt-engine-disaster-recovery
app/drp/DisasterRecoveryActions.java
// Path: app/drp/objects/DatabaseManager.java // public class DatabaseManager { // // private String dbHost; // private String dbPort; // private String dbName; // private String dbUser; // private String dbPassword; // // public DatabaseManager(String host, String port, String name, String user, String password) { // dbHost = host; // dbPort = port; // dbName = name; // dbUser = user; // dbPassword = password; // } // // public String getDbHost() { // return dbHost; // } // // public String getDbPort() { // return dbPort; // } // // public String getDbName() { // return dbName; // } // // public String getDbUser() { // return dbUser; // } // // public String getDbPassword() { // return dbPassword; // } // } // // Path: app/drp/objects/OperationListener.java // public interface OperationListener { // // public enum MessageType { // INFO, // SUCCESS, // ERROR // } // // void onMessage(Exception e, String message, MessageType type); // void onFinished(String message, boolean success); // void onRefreshHosts(); // void onRefreshDatacenters(); // } // // Path: app/models/DatabaseConnection.java // @Entity // public class DatabaseConnection extends BaseModel { // // @Required // @MaxSize(20) // @Column(name="origin_connection", nullable = false, length = 20) // public String originConnection; // // // @Required // @MaxSize(20) // @Column(name="destination_connection", nullable = false, length = 20) // public String destinationConnection; // // } // // Path: app/models/DatabaseIQN.java // @Entity // public class DatabaseIQN extends BaseModel { // // @Required // @MaxSize(255) // @Column(name="origin_iqn", nullable = false, length = 255) // public String originIQN; // // // @Required // @MaxSize(255) // @Column(name="destination_iqn", nullable = false, length = 255) // public String destinationIQN; // }
import java.util.List; import java.util.function.Consumer; import java.util.stream.Collectors; import drp.exceptions.*; import drp.objects.DatabaseManager; import drp.objects.OperationListener; import models.DatabaseConnection; import models.DatabaseIQN; import org.ovirt.engine.sdk.Api; import org.ovirt.engine.sdk.decorators.Host; import org.ovirt.engine.sdk.entities.Action; import org.ovirt.engine.sdk.entities.PowerManagement; import org.ovirt.engine.sdk.entities.StorageConnection; import org.ovirt.engine.sdk.exceptions.ServerException; import play.Logger; import play.i18n.Messages; import java.io.IOException; import java.sql.*;
try { Logger.debug("Deactivating host: %s", host.getName()); Action requestAction = new Action(); Action resultAction = host.deactivate(requestAction); if (!"complete".equals(resultAction.getStatus().getState())) { throw new HostDeactivateException(Messages.get("drp.deactivateexception",host.getName())); } } catch (Exception e) { throw new HostDeactivateException(Messages.get("drp.deactivateexception",host.getName())); } } public static void activateHost(Host host) throws HostActivateException{ if (host == null) { throw new HostActivateException(Messages.get("drp.activateexceptioninvalidhost")); } try { Logger.debug("Activating host: %s", host.getName()); Action requestAction = new Action(); Action resultAction = host.activate(requestAction); if (!"complete".equals(resultAction.getStatus().getState())) { throw new HostActivateException(Messages.get("drp.activateexception", host.getName())); } } catch (Exception e) { throw new HostActivateException(Messages.get("drp.activateexception",host.getName())); } }
// Path: app/drp/objects/DatabaseManager.java // public class DatabaseManager { // // private String dbHost; // private String dbPort; // private String dbName; // private String dbUser; // private String dbPassword; // // public DatabaseManager(String host, String port, String name, String user, String password) { // dbHost = host; // dbPort = port; // dbName = name; // dbUser = user; // dbPassword = password; // } // // public String getDbHost() { // return dbHost; // } // // public String getDbPort() { // return dbPort; // } // // public String getDbName() { // return dbName; // } // // public String getDbUser() { // return dbUser; // } // // public String getDbPassword() { // return dbPassword; // } // } // // Path: app/drp/objects/OperationListener.java // public interface OperationListener { // // public enum MessageType { // INFO, // SUCCESS, // ERROR // } // // void onMessage(Exception e, String message, MessageType type); // void onFinished(String message, boolean success); // void onRefreshHosts(); // void onRefreshDatacenters(); // } // // Path: app/models/DatabaseConnection.java // @Entity // public class DatabaseConnection extends BaseModel { // // @Required // @MaxSize(20) // @Column(name="origin_connection", nullable = false, length = 20) // public String originConnection; // // // @Required // @MaxSize(20) // @Column(name="destination_connection", nullable = false, length = 20) // public String destinationConnection; // // } // // Path: app/models/DatabaseIQN.java // @Entity // public class DatabaseIQN extends BaseModel { // // @Required // @MaxSize(255) // @Column(name="origin_iqn", nullable = false, length = 255) // public String originIQN; // // // @Required // @MaxSize(255) // @Column(name="destination_iqn", nullable = false, length = 255) // public String destinationIQN; // } // Path: app/drp/DisasterRecoveryActions.java import java.util.List; import java.util.function.Consumer; import java.util.stream.Collectors; import drp.exceptions.*; import drp.objects.DatabaseManager; import drp.objects.OperationListener; import models.DatabaseConnection; import models.DatabaseIQN; import org.ovirt.engine.sdk.Api; import org.ovirt.engine.sdk.decorators.Host; import org.ovirt.engine.sdk.entities.Action; import org.ovirt.engine.sdk.entities.PowerManagement; import org.ovirt.engine.sdk.entities.StorageConnection; import org.ovirt.engine.sdk.exceptions.ServerException; import play.Logger; import play.i18n.Messages; import java.io.IOException; import java.sql.*; try { Logger.debug("Deactivating host: %s", host.getName()); Action requestAction = new Action(); Action resultAction = host.deactivate(requestAction); if (!"complete".equals(resultAction.getStatus().getState())) { throw new HostDeactivateException(Messages.get("drp.deactivateexception",host.getName())); } } catch (Exception e) { throw new HostDeactivateException(Messages.get("drp.deactivateexception",host.getName())); } } public static void activateHost(Host host) throws HostActivateException{ if (host == null) { throw new HostActivateException(Messages.get("drp.activateexceptioninvalidhost")); } try { Logger.debug("Activating host: %s", host.getName()); Action requestAction = new Action(); Action resultAction = host.activate(requestAction); if (!"complete".equals(resultAction.getStatus().getState())) { throw new HostActivateException(Messages.get("drp.activateexception", host.getName())); } } catch (Exception e) { throw new HostActivateException(Messages.get("drp.activateexception",host.getName())); } }
public static void updateConnections(Api api, List<DatabaseConnection> connections, List<DatabaseIQN> iqns, boolean revert, OperationListener listener) throws ConnectionUpdateException {
xandradx/ovirt-engine-disaster-recovery
app/drp/DisasterRecoveryActions.java
// Path: app/drp/objects/DatabaseManager.java // public class DatabaseManager { // // private String dbHost; // private String dbPort; // private String dbName; // private String dbUser; // private String dbPassword; // // public DatabaseManager(String host, String port, String name, String user, String password) { // dbHost = host; // dbPort = port; // dbName = name; // dbUser = user; // dbPassword = password; // } // // public String getDbHost() { // return dbHost; // } // // public String getDbPort() { // return dbPort; // } // // public String getDbName() { // return dbName; // } // // public String getDbUser() { // return dbUser; // } // // public String getDbPassword() { // return dbPassword; // } // } // // Path: app/drp/objects/OperationListener.java // public interface OperationListener { // // public enum MessageType { // INFO, // SUCCESS, // ERROR // } // // void onMessage(Exception e, String message, MessageType type); // void onFinished(String message, boolean success); // void onRefreshHosts(); // void onRefreshDatacenters(); // } // // Path: app/models/DatabaseConnection.java // @Entity // public class DatabaseConnection extends BaseModel { // // @Required // @MaxSize(20) // @Column(name="origin_connection", nullable = false, length = 20) // public String originConnection; // // // @Required // @MaxSize(20) // @Column(name="destination_connection", nullable = false, length = 20) // public String destinationConnection; // // } // // Path: app/models/DatabaseIQN.java // @Entity // public class DatabaseIQN extends BaseModel { // // @Required // @MaxSize(255) // @Column(name="origin_iqn", nullable = false, length = 255) // public String originIQN; // // // @Required // @MaxSize(255) // @Column(name="destination_iqn", nullable = false, length = 255) // public String destinationIQN; // }
import java.util.List; import java.util.function.Consumer; import java.util.stream.Collectors; import drp.exceptions.*; import drp.objects.DatabaseManager; import drp.objects.OperationListener; import models.DatabaseConnection; import models.DatabaseIQN; import org.ovirt.engine.sdk.Api; import org.ovirt.engine.sdk.decorators.Host; import org.ovirt.engine.sdk.entities.Action; import org.ovirt.engine.sdk.entities.PowerManagement; import org.ovirt.engine.sdk.entities.StorageConnection; import org.ovirt.engine.sdk.exceptions.ServerException; import play.Logger; import play.i18n.Messages; import java.io.IOException; import java.sql.*;
try { Logger.debug("Deactivating host: %s", host.getName()); Action requestAction = new Action(); Action resultAction = host.deactivate(requestAction); if (!"complete".equals(resultAction.getStatus().getState())) { throw new HostDeactivateException(Messages.get("drp.deactivateexception",host.getName())); } } catch (Exception e) { throw new HostDeactivateException(Messages.get("drp.deactivateexception",host.getName())); } } public static void activateHost(Host host) throws HostActivateException{ if (host == null) { throw new HostActivateException(Messages.get("drp.activateexceptioninvalidhost")); } try { Logger.debug("Activating host: %s", host.getName()); Action requestAction = new Action(); Action resultAction = host.activate(requestAction); if (!"complete".equals(resultAction.getStatus().getState())) { throw new HostActivateException(Messages.get("drp.activateexception", host.getName())); } } catch (Exception e) { throw new HostActivateException(Messages.get("drp.activateexception",host.getName())); } }
// Path: app/drp/objects/DatabaseManager.java // public class DatabaseManager { // // private String dbHost; // private String dbPort; // private String dbName; // private String dbUser; // private String dbPassword; // // public DatabaseManager(String host, String port, String name, String user, String password) { // dbHost = host; // dbPort = port; // dbName = name; // dbUser = user; // dbPassword = password; // } // // public String getDbHost() { // return dbHost; // } // // public String getDbPort() { // return dbPort; // } // // public String getDbName() { // return dbName; // } // // public String getDbUser() { // return dbUser; // } // // public String getDbPassword() { // return dbPassword; // } // } // // Path: app/drp/objects/OperationListener.java // public interface OperationListener { // // public enum MessageType { // INFO, // SUCCESS, // ERROR // } // // void onMessage(Exception e, String message, MessageType type); // void onFinished(String message, boolean success); // void onRefreshHosts(); // void onRefreshDatacenters(); // } // // Path: app/models/DatabaseConnection.java // @Entity // public class DatabaseConnection extends BaseModel { // // @Required // @MaxSize(20) // @Column(name="origin_connection", nullable = false, length = 20) // public String originConnection; // // // @Required // @MaxSize(20) // @Column(name="destination_connection", nullable = false, length = 20) // public String destinationConnection; // // } // // Path: app/models/DatabaseIQN.java // @Entity // public class DatabaseIQN extends BaseModel { // // @Required // @MaxSize(255) // @Column(name="origin_iqn", nullable = false, length = 255) // public String originIQN; // // // @Required // @MaxSize(255) // @Column(name="destination_iqn", nullable = false, length = 255) // public String destinationIQN; // } // Path: app/drp/DisasterRecoveryActions.java import java.util.List; import java.util.function.Consumer; import java.util.stream.Collectors; import drp.exceptions.*; import drp.objects.DatabaseManager; import drp.objects.OperationListener; import models.DatabaseConnection; import models.DatabaseIQN; import org.ovirt.engine.sdk.Api; import org.ovirt.engine.sdk.decorators.Host; import org.ovirt.engine.sdk.entities.Action; import org.ovirt.engine.sdk.entities.PowerManagement; import org.ovirt.engine.sdk.entities.StorageConnection; import org.ovirt.engine.sdk.exceptions.ServerException; import play.Logger; import play.i18n.Messages; import java.io.IOException; import java.sql.*; try { Logger.debug("Deactivating host: %s", host.getName()); Action requestAction = new Action(); Action resultAction = host.deactivate(requestAction); if (!"complete".equals(resultAction.getStatus().getState())) { throw new HostDeactivateException(Messages.get("drp.deactivateexception",host.getName())); } } catch (Exception e) { throw new HostDeactivateException(Messages.get("drp.deactivateexception",host.getName())); } } public static void activateHost(Host host) throws HostActivateException{ if (host == null) { throw new HostActivateException(Messages.get("drp.activateexceptioninvalidhost")); } try { Logger.debug("Activating host: %s", host.getName()); Action requestAction = new Action(); Action resultAction = host.activate(requestAction); if (!"complete".equals(resultAction.getStatus().getState())) { throw new HostActivateException(Messages.get("drp.activateexception", host.getName())); } } catch (Exception e) { throw new HostActivateException(Messages.get("drp.activateexception",host.getName())); } }
public static void updateConnections(Api api, List<DatabaseConnection> connections, List<DatabaseIQN> iqns, boolean revert, OperationListener listener) throws ConnectionUpdateException {
xandradx/ovirt-engine-disaster-recovery
app/controllers/Users.java
// Path: app/helpers/GlobalConstants.java // public class GlobalConstants { // // public static final String ROLE_ADMIN = "ADMINISTRATOR"; // public static final String ROLE_TECH = "TECNICO"; // // private GlobalConstants() { // // } // } // // Path: app/models/User.java // @Entity // public class User extends BaseModel { // // @Required // @MaxSize(45) // @Unique // @Column(length=45, nullable=false, unique=true) // public String username; // // @Column(length=255, nullable=true) // public String password; // // @Required // @MaxSize(45) // @Column(length=45, nullable=false) // public String firstName; // // @Required // @MaxSize(45) // @Column(length=45, nullable=false) // public String lastName; // // public boolean needsPasswordReset = false; // // @Column(name="last_access") // public Date lastAccess; // // @Column(name="last_activity") // public Date lastActivity; // // @ManyToOne(optional=false) // public UserRole role; // // private void encryptPassword() { // if (this.password!=null) { // this.password = Crypto.encryptAES(this.password); // } // } // // private void decryptPassword() { // if (this.password!=null) { // this.password = Crypto.decryptAES(this.password); // } // } // // public String getFullName() { // String name = ""; // // if (this.firstName!=null && !this.firstName.isEmpty()) { // name = firstName; // } // // if (this.lastName!=null && !this.lastName.isEmpty()) { // // if (!name.isEmpty()) { // name += " "; // } // // name += lastName; // } // // return name; // } // // @Override // protected void onPrePersist() { // super.onPrePersist(); // encryptPassword(); // } // // @Override // protected void onPreUpdate() { // super.onPreUpdate(); // encryptPassword(); // } // // @Override // protected void onPostLoad() { // super.onPostLoad(); // decryptPassword(); // } // } // // Path: app/models/UserRole.java // @Entity // public class UserRole extends Model { // // public enum RoleCode { // ADMINISTRATOR, // TECNICO // } // // @Required // @MaxSize(45) // @Column(length=45, nullable=false) // public String name; // // @Required // @Column(nullable=false) // public RoleCode code; // // @MaxSize(100) // @Column(length=100, nullable=true) // public String description; // // }
import helpers.GlobalConstants; import models.User; import models.UserRole; import play.data.validation.Valid; import play.i18n.Messages; import play.mvc.With; import java.util.List;
package controllers; @With(Secure.class) @Check(GlobalConstants.ROLE_ADMIN) public class Users extends AuthenticatedController { public static void index() {
// Path: app/helpers/GlobalConstants.java // public class GlobalConstants { // // public static final String ROLE_ADMIN = "ADMINISTRATOR"; // public static final String ROLE_TECH = "TECNICO"; // // private GlobalConstants() { // // } // } // // Path: app/models/User.java // @Entity // public class User extends BaseModel { // // @Required // @MaxSize(45) // @Unique // @Column(length=45, nullable=false, unique=true) // public String username; // // @Column(length=255, nullable=true) // public String password; // // @Required // @MaxSize(45) // @Column(length=45, nullable=false) // public String firstName; // // @Required // @MaxSize(45) // @Column(length=45, nullable=false) // public String lastName; // // public boolean needsPasswordReset = false; // // @Column(name="last_access") // public Date lastAccess; // // @Column(name="last_activity") // public Date lastActivity; // // @ManyToOne(optional=false) // public UserRole role; // // private void encryptPassword() { // if (this.password!=null) { // this.password = Crypto.encryptAES(this.password); // } // } // // private void decryptPassword() { // if (this.password!=null) { // this.password = Crypto.decryptAES(this.password); // } // } // // public String getFullName() { // String name = ""; // // if (this.firstName!=null && !this.firstName.isEmpty()) { // name = firstName; // } // // if (this.lastName!=null && !this.lastName.isEmpty()) { // // if (!name.isEmpty()) { // name += " "; // } // // name += lastName; // } // // return name; // } // // @Override // protected void onPrePersist() { // super.onPrePersist(); // encryptPassword(); // } // // @Override // protected void onPreUpdate() { // super.onPreUpdate(); // encryptPassword(); // } // // @Override // protected void onPostLoad() { // super.onPostLoad(); // decryptPassword(); // } // } // // Path: app/models/UserRole.java // @Entity // public class UserRole extends Model { // // public enum RoleCode { // ADMINISTRATOR, // TECNICO // } // // @Required // @MaxSize(45) // @Column(length=45, nullable=false) // public String name; // // @Required // @Column(nullable=false) // public RoleCode code; // // @MaxSize(100) // @Column(length=100, nullable=true) // public String description; // // } // Path: app/controllers/Users.java import helpers.GlobalConstants; import models.User; import models.UserRole; import play.data.validation.Valid; import play.i18n.Messages; import play.mvc.With; import java.util.List; package controllers; @With(Secure.class) @Check(GlobalConstants.ROLE_ADMIN) public class Users extends AuthenticatedController { public static void index() {
User connectedUser = getUser();
xandradx/ovirt-engine-disaster-recovery
app/controllers/Users.java
// Path: app/helpers/GlobalConstants.java // public class GlobalConstants { // // public static final String ROLE_ADMIN = "ADMINISTRATOR"; // public static final String ROLE_TECH = "TECNICO"; // // private GlobalConstants() { // // } // } // // Path: app/models/User.java // @Entity // public class User extends BaseModel { // // @Required // @MaxSize(45) // @Unique // @Column(length=45, nullable=false, unique=true) // public String username; // // @Column(length=255, nullable=true) // public String password; // // @Required // @MaxSize(45) // @Column(length=45, nullable=false) // public String firstName; // // @Required // @MaxSize(45) // @Column(length=45, nullable=false) // public String lastName; // // public boolean needsPasswordReset = false; // // @Column(name="last_access") // public Date lastAccess; // // @Column(name="last_activity") // public Date lastActivity; // // @ManyToOne(optional=false) // public UserRole role; // // private void encryptPassword() { // if (this.password!=null) { // this.password = Crypto.encryptAES(this.password); // } // } // // private void decryptPassword() { // if (this.password!=null) { // this.password = Crypto.decryptAES(this.password); // } // } // // public String getFullName() { // String name = ""; // // if (this.firstName!=null && !this.firstName.isEmpty()) { // name = firstName; // } // // if (this.lastName!=null && !this.lastName.isEmpty()) { // // if (!name.isEmpty()) { // name += " "; // } // // name += lastName; // } // // return name; // } // // @Override // protected void onPrePersist() { // super.onPrePersist(); // encryptPassword(); // } // // @Override // protected void onPreUpdate() { // super.onPreUpdate(); // encryptPassword(); // } // // @Override // protected void onPostLoad() { // super.onPostLoad(); // decryptPassword(); // } // } // // Path: app/models/UserRole.java // @Entity // public class UserRole extends Model { // // public enum RoleCode { // ADMINISTRATOR, // TECNICO // } // // @Required // @MaxSize(45) // @Column(length=45, nullable=false) // public String name; // // @Required // @Column(nullable=false) // public RoleCode code; // // @MaxSize(100) // @Column(length=100, nullable=true) // public String description; // // }
import helpers.GlobalConstants; import models.User; import models.UserRole; import play.data.validation.Valid; import play.i18n.Messages; import play.mvc.With; import java.util.List;
package controllers; @With(Secure.class) @Check(GlobalConstants.ROLE_ADMIN) public class Users extends AuthenticatedController { public static void index() { User connectedUser = getUser(); List<User> users = User.find("id != :i").bind("i",connectedUser.id).fetch(); render(users); } public static void create() {
// Path: app/helpers/GlobalConstants.java // public class GlobalConstants { // // public static final String ROLE_ADMIN = "ADMINISTRATOR"; // public static final String ROLE_TECH = "TECNICO"; // // private GlobalConstants() { // // } // } // // Path: app/models/User.java // @Entity // public class User extends BaseModel { // // @Required // @MaxSize(45) // @Unique // @Column(length=45, nullable=false, unique=true) // public String username; // // @Column(length=255, nullable=true) // public String password; // // @Required // @MaxSize(45) // @Column(length=45, nullable=false) // public String firstName; // // @Required // @MaxSize(45) // @Column(length=45, nullable=false) // public String lastName; // // public boolean needsPasswordReset = false; // // @Column(name="last_access") // public Date lastAccess; // // @Column(name="last_activity") // public Date lastActivity; // // @ManyToOne(optional=false) // public UserRole role; // // private void encryptPassword() { // if (this.password!=null) { // this.password = Crypto.encryptAES(this.password); // } // } // // private void decryptPassword() { // if (this.password!=null) { // this.password = Crypto.decryptAES(this.password); // } // } // // public String getFullName() { // String name = ""; // // if (this.firstName!=null && !this.firstName.isEmpty()) { // name = firstName; // } // // if (this.lastName!=null && !this.lastName.isEmpty()) { // // if (!name.isEmpty()) { // name += " "; // } // // name += lastName; // } // // return name; // } // // @Override // protected void onPrePersist() { // super.onPrePersist(); // encryptPassword(); // } // // @Override // protected void onPreUpdate() { // super.onPreUpdate(); // encryptPassword(); // } // // @Override // protected void onPostLoad() { // super.onPostLoad(); // decryptPassword(); // } // } // // Path: app/models/UserRole.java // @Entity // public class UserRole extends Model { // // public enum RoleCode { // ADMINISTRATOR, // TECNICO // } // // @Required // @MaxSize(45) // @Column(length=45, nullable=false) // public String name; // // @Required // @Column(nullable=false) // public RoleCode code; // // @MaxSize(100) // @Column(length=100, nullable=true) // public String description; // // } // Path: app/controllers/Users.java import helpers.GlobalConstants; import models.User; import models.UserRole; import play.data.validation.Valid; import play.i18n.Messages; import play.mvc.With; import java.util.List; package controllers; @With(Secure.class) @Check(GlobalConstants.ROLE_ADMIN) public class Users extends AuthenticatedController { public static void index() { User connectedUser = getUser(); List<User> users = User.find("id != :i").bind("i",connectedUser.id).fetch(); render(users); } public static void create() {
List<UserRole> roles = UserRole.findAll();
xandradx/ovirt-engine-disaster-recovery
app/controllers/Application.java
// Path: app/helpers/GlobalConstants.java // public class GlobalConstants { // // public static final String ROLE_ADMIN = "ADMINISTRATOR"; // public static final String ROLE_TECH = "TECNICO"; // // private GlobalConstants() { // // } // } // // Path: app/models/User.java // @Entity // public class User extends BaseModel { // // @Required // @MaxSize(45) // @Unique // @Column(length=45, nullable=false, unique=true) // public String username; // // @Column(length=255, nullable=true) // public String password; // // @Required // @MaxSize(45) // @Column(length=45, nullable=false) // public String firstName; // // @Required // @MaxSize(45) // @Column(length=45, nullable=false) // public String lastName; // // public boolean needsPasswordReset = false; // // @Column(name="last_access") // public Date lastAccess; // // @Column(name="last_activity") // public Date lastActivity; // // @ManyToOne(optional=false) // public UserRole role; // // private void encryptPassword() { // if (this.password!=null) { // this.password = Crypto.encryptAES(this.password); // } // } // // private void decryptPassword() { // if (this.password!=null) { // this.password = Crypto.decryptAES(this.password); // } // } // // public String getFullName() { // String name = ""; // // if (this.firstName!=null && !this.firstName.isEmpty()) { // name = firstName; // } // // if (this.lastName!=null && !this.lastName.isEmpty()) { // // if (!name.isEmpty()) { // name += " "; // } // // name += lastName; // } // // return name; // } // // @Override // protected void onPrePersist() { // super.onPrePersist(); // encryptPassword(); // } // // @Override // protected void onPreUpdate() { // super.onPreUpdate(); // encryptPassword(); // } // // @Override // protected void onPostLoad() { // super.onPostLoad(); // decryptPassword(); // } // }
import helpers.GlobalConstants; import models.User; import play.mvc.With;
package controllers; @With(Secure.class) @Check({GlobalConstants.ROLE_ADMIN, GlobalConstants.ROLE_TECH}) public class Application extends AuthenticatedController { public static void index() {
// Path: app/helpers/GlobalConstants.java // public class GlobalConstants { // // public static final String ROLE_ADMIN = "ADMINISTRATOR"; // public static final String ROLE_TECH = "TECNICO"; // // private GlobalConstants() { // // } // } // // Path: app/models/User.java // @Entity // public class User extends BaseModel { // // @Required // @MaxSize(45) // @Unique // @Column(length=45, nullable=false, unique=true) // public String username; // // @Column(length=255, nullable=true) // public String password; // // @Required // @MaxSize(45) // @Column(length=45, nullable=false) // public String firstName; // // @Required // @MaxSize(45) // @Column(length=45, nullable=false) // public String lastName; // // public boolean needsPasswordReset = false; // // @Column(name="last_access") // public Date lastAccess; // // @Column(name="last_activity") // public Date lastActivity; // // @ManyToOne(optional=false) // public UserRole role; // // private void encryptPassword() { // if (this.password!=null) { // this.password = Crypto.encryptAES(this.password); // } // } // // private void decryptPassword() { // if (this.password!=null) { // this.password = Crypto.decryptAES(this.password); // } // } // // public String getFullName() { // String name = ""; // // if (this.firstName!=null && !this.firstName.isEmpty()) { // name = firstName; // } // // if (this.lastName!=null && !this.lastName.isEmpty()) { // // if (!name.isEmpty()) { // name += " "; // } // // name += lastName; // } // // return name; // } // // @Override // protected void onPrePersist() { // super.onPrePersist(); // encryptPassword(); // } // // @Override // protected void onPreUpdate() { // super.onPreUpdate(); // encryptPassword(); // } // // @Override // protected void onPostLoad() { // super.onPostLoad(); // decryptPassword(); // } // } // Path: app/controllers/Application.java import helpers.GlobalConstants; import models.User; import play.mvc.With; package controllers; @With(Secure.class) @Check({GlobalConstants.ROLE_ADMIN, GlobalConstants.ROLE_TECH}) public class Application extends AuthenticatedController { public static void index() {
User user = getUser();
xandradx/ovirt-engine-disaster-recovery
app/dto/objects/HostDto.java
// Path: app/models/RemoteHost.java // @Entity // public class RemoteHost extends BaseModel { // // public enum RecoveryType { // FAILOVER, // FAILBACK, // NONE // } // // @Required // @Column(nullable = false) // public RecoveryType type; // // @Required // @MaxSize(255) // @Column(length=255, name="host_name", nullable = false) // public String hostName; // }
import models.RemoteHost;
/* * Copyright 2016 ITM, S.A. * * Licensed under the Apache License, Version 2.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://www.apache.org/licenses/LICENSE-2.0`](http://www.apache.org/licenses/LICENSE-2.0) * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dto.objects; /** * Created by jandrad on 26/01/16. */ public class HostDto { protected String name; protected String ip; protected String identifier; protected String status;
// Path: app/models/RemoteHost.java // @Entity // public class RemoteHost extends BaseModel { // // public enum RecoveryType { // FAILOVER, // FAILBACK, // NONE // } // // @Required // @Column(nullable = false) // public RecoveryType type; // // @Required // @MaxSize(255) // @Column(length=255, name="host_name", nullable = false) // public String hostName; // } // Path: app/dto/objects/HostDto.java import models.RemoteHost; /* * Copyright 2016 ITM, S.A. * * Licensed under the Apache License, Version 2.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://www.apache.org/licenses/LICENSE-2.0`](http://www.apache.org/licenses/LICENSE-2.0) * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dto.objects; /** * Created by jandrad on 26/01/16. */ public class HostDto { protected String name; protected String ip; protected String identifier; protected String status;
protected RemoteHost.RecoveryType type;
xandradx/ovirt-engine-disaster-recovery
app/controllers/AuthenticatedController.java
// Path: app/models/User.java // @Entity // public class User extends BaseModel { // // @Required // @MaxSize(45) // @Unique // @Column(length=45, nullable=false, unique=true) // public String username; // // @Column(length=255, nullable=true) // public String password; // // @Required // @MaxSize(45) // @Column(length=45, nullable=false) // public String firstName; // // @Required // @MaxSize(45) // @Column(length=45, nullable=false) // public String lastName; // // public boolean needsPasswordReset = false; // // @Column(name="last_access") // public Date lastAccess; // // @Column(name="last_activity") // public Date lastActivity; // // @ManyToOne(optional=false) // public UserRole role; // // private void encryptPassword() { // if (this.password!=null) { // this.password = Crypto.encryptAES(this.password); // } // } // // private void decryptPassword() { // if (this.password!=null) { // this.password = Crypto.decryptAES(this.password); // } // } // // public String getFullName() { // String name = ""; // // if (this.firstName!=null && !this.firstName.isEmpty()) { // name = firstName; // } // // if (this.lastName!=null && !this.lastName.isEmpty()) { // // if (!name.isEmpty()) { // name += " "; // } // // name += lastName; // } // // return name; // } // // @Override // protected void onPrePersist() { // super.onPrePersist(); // encryptPassword(); // } // // @Override // protected void onPreUpdate() { // super.onPreUpdate(); // encryptPassword(); // } // // @Override // protected void onPostLoad() { // super.onPostLoad(); // decryptPassword(); // } // } // // Path: app/models/UserRole.java // @Entity // public class UserRole extends Model { // // public enum RoleCode { // ADMINISTRATOR, // TECNICO // } // // @Required // @MaxSize(45) // @Column(length=45, nullable=false) // public String name; // // @Required // @Column(nullable=false) // public RoleCode code; // // @MaxSize(100) // @Column(length=100, nullable=true) // public String description; // // }
import models.User; import models.UserRole; import play.mvc.Before; import play.mvc.Controller; import play.mvc.With; import java.util.Date;
package controllers; @With(Secure.class) public class AuthenticatedController extends Controller { @Before() public static void getUserInfo() {
// Path: app/models/User.java // @Entity // public class User extends BaseModel { // // @Required // @MaxSize(45) // @Unique // @Column(length=45, nullable=false, unique=true) // public String username; // // @Column(length=255, nullable=true) // public String password; // // @Required // @MaxSize(45) // @Column(length=45, nullable=false) // public String firstName; // // @Required // @MaxSize(45) // @Column(length=45, nullable=false) // public String lastName; // // public boolean needsPasswordReset = false; // // @Column(name="last_access") // public Date lastAccess; // // @Column(name="last_activity") // public Date lastActivity; // // @ManyToOne(optional=false) // public UserRole role; // // private void encryptPassword() { // if (this.password!=null) { // this.password = Crypto.encryptAES(this.password); // } // } // // private void decryptPassword() { // if (this.password!=null) { // this.password = Crypto.decryptAES(this.password); // } // } // // public String getFullName() { // String name = ""; // // if (this.firstName!=null && !this.firstName.isEmpty()) { // name = firstName; // } // // if (this.lastName!=null && !this.lastName.isEmpty()) { // // if (!name.isEmpty()) { // name += " "; // } // // name += lastName; // } // // return name; // } // // @Override // protected void onPrePersist() { // super.onPrePersist(); // encryptPassword(); // } // // @Override // protected void onPreUpdate() { // super.onPreUpdate(); // encryptPassword(); // } // // @Override // protected void onPostLoad() { // super.onPostLoad(); // decryptPassword(); // } // } // // Path: app/models/UserRole.java // @Entity // public class UserRole extends Model { // // public enum RoleCode { // ADMINISTRATOR, // TECNICO // } // // @Required // @MaxSize(45) // @Column(length=45, nullable=false) // public String name; // // @Required // @Column(nullable=false) // public RoleCode code; // // @MaxSize(100) // @Column(length=100, nullable=true) // public String description; // // } // Path: app/controllers/AuthenticatedController.java import models.User; import models.UserRole; import play.mvc.Before; import play.mvc.Controller; import play.mvc.With; import java.util.Date; package controllers; @With(Secure.class) public class AuthenticatedController extends Controller { @Before() public static void getUserInfo() {
User user = User.find("username = :u").bind("u", Security.connected()).first();
xandradx/ovirt-engine-disaster-recovery
app/controllers/AuthenticatedController.java
// Path: app/models/User.java // @Entity // public class User extends BaseModel { // // @Required // @MaxSize(45) // @Unique // @Column(length=45, nullable=false, unique=true) // public String username; // // @Column(length=255, nullable=true) // public String password; // // @Required // @MaxSize(45) // @Column(length=45, nullable=false) // public String firstName; // // @Required // @MaxSize(45) // @Column(length=45, nullable=false) // public String lastName; // // public boolean needsPasswordReset = false; // // @Column(name="last_access") // public Date lastAccess; // // @Column(name="last_activity") // public Date lastActivity; // // @ManyToOne(optional=false) // public UserRole role; // // private void encryptPassword() { // if (this.password!=null) { // this.password = Crypto.encryptAES(this.password); // } // } // // private void decryptPassword() { // if (this.password!=null) { // this.password = Crypto.decryptAES(this.password); // } // } // // public String getFullName() { // String name = ""; // // if (this.firstName!=null && !this.firstName.isEmpty()) { // name = firstName; // } // // if (this.lastName!=null && !this.lastName.isEmpty()) { // // if (!name.isEmpty()) { // name += " "; // } // // name += lastName; // } // // return name; // } // // @Override // protected void onPrePersist() { // super.onPrePersist(); // encryptPassword(); // } // // @Override // protected void onPreUpdate() { // super.onPreUpdate(); // encryptPassword(); // } // // @Override // protected void onPostLoad() { // super.onPostLoad(); // decryptPassword(); // } // } // // Path: app/models/UserRole.java // @Entity // public class UserRole extends Model { // // public enum RoleCode { // ADMINISTRATOR, // TECNICO // } // // @Required // @MaxSize(45) // @Column(length=45, nullable=false) // public String name; // // @Required // @Column(nullable=false) // public RoleCode code; // // @MaxSize(100) // @Column(length=100, nullable=true) // public String description; // // }
import models.User; import models.UserRole; import play.mvc.Before; import play.mvc.Controller; import play.mvc.With; import java.util.Date;
package controllers; @With(Secure.class) public class AuthenticatedController extends Controller { @Before() public static void getUserInfo() { User user = User.find("username = :u").bind("u", Security.connected()).first(); if (user!=null) { user.lastActivity = new Date(); user.save(); setUser(user); if (!request.action.equals("Profile.passwordChange") && !request.action.equals("Profile.changePassword") && user.needsPasswordReset) { Profile.passwordChange(); } } } protected static void setUser(User user) {
// Path: app/models/User.java // @Entity // public class User extends BaseModel { // // @Required // @MaxSize(45) // @Unique // @Column(length=45, nullable=false, unique=true) // public String username; // // @Column(length=255, nullable=true) // public String password; // // @Required // @MaxSize(45) // @Column(length=45, nullable=false) // public String firstName; // // @Required // @MaxSize(45) // @Column(length=45, nullable=false) // public String lastName; // // public boolean needsPasswordReset = false; // // @Column(name="last_access") // public Date lastAccess; // // @Column(name="last_activity") // public Date lastActivity; // // @ManyToOne(optional=false) // public UserRole role; // // private void encryptPassword() { // if (this.password!=null) { // this.password = Crypto.encryptAES(this.password); // } // } // // private void decryptPassword() { // if (this.password!=null) { // this.password = Crypto.decryptAES(this.password); // } // } // // public String getFullName() { // String name = ""; // // if (this.firstName!=null && !this.firstName.isEmpty()) { // name = firstName; // } // // if (this.lastName!=null && !this.lastName.isEmpty()) { // // if (!name.isEmpty()) { // name += " "; // } // // name += lastName; // } // // return name; // } // // @Override // protected void onPrePersist() { // super.onPrePersist(); // encryptPassword(); // } // // @Override // protected void onPreUpdate() { // super.onPreUpdate(); // encryptPassword(); // } // // @Override // protected void onPostLoad() { // super.onPostLoad(); // decryptPassword(); // } // } // // Path: app/models/UserRole.java // @Entity // public class UserRole extends Model { // // public enum RoleCode { // ADMINISTRATOR, // TECNICO // } // // @Required // @MaxSize(45) // @Column(length=45, nullable=false) // public String name; // // @Required // @Column(nullable=false) // public RoleCode code; // // @MaxSize(100) // @Column(length=100, nullable=true) // public String description; // // } // Path: app/controllers/AuthenticatedController.java import models.User; import models.UserRole; import play.mvc.Before; import play.mvc.Controller; import play.mvc.With; import java.util.Date; package controllers; @With(Secure.class) public class AuthenticatedController extends Controller { @Before() public static void getUserInfo() { User user = User.find("username = :u").bind("u", Security.connected()).first(); if (user!=null) { user.lastActivity = new Date(); user.save(); setUser(user); if (!request.action.equals("Profile.passwordChange") && !request.action.equals("Profile.changePassword") && user.needsPasswordReset) { Profile.passwordChange(); } } } protected static void setUser(User user) {
boolean isAdmin = (user.role!=null && user.role.code == UserRole.RoleCode.ADMINISTRATOR);
xandradx/ovirt-engine-disaster-recovery
app/jobs/services/ConnectionStatusJob.java
// Path: app/dto/objects/ConnectionDto.java // public class ConnectionDto { // // protected String ipAddress; // protected String iqn; // // public ConnectionDto(String ipAddress, String iqn) { // this.ipAddress = ipAddress; // this.iqn = iqn; // } // // public String getIpAddress() { // return ipAddress; // } // // public void setIpAddress(String ipAddress) { // this.ipAddress = ipAddress; // } // // public String getIqn() { // return iqn; // } // // public void setIqn(String iqn) { // this.iqn = iqn; // } // } // // Path: app/dto/response/ServiceResponse.java // public class ServiceResponse<T> { // // private boolean success; // private String userMessage; // private String errorMessage; // private String sessionId; // // private T data; // // public static <T> ServiceResponse<T> success(String userMessage) { // return ServiceResponse.successToken(userMessage, null, null); // } // // public static <T> ServiceResponse<T> success(T data) { // return ServiceResponse.successToken(null, data, null); // } // // public static <T> ServiceResponse<T> success(String userMessage, T data) { // return ServiceResponse.successToken(userMessage, data, null); // } // // public static <T> ServiceResponse<T> successToken(String userMessage, T data, String token) { // ServiceResponse<T> response = new ServiceResponse<T>(); // response.setSuccess(true); // response.setData(data); // response.setUserMessage(userMessage); // response.setSessionId(token); // return response; // } // // public static <T> ServiceResponse<T> error(String errorMessage) { // return error(errorMessage, null); // } // // public static <T> ServiceResponse<T> error(String errorMessage, String sessionId) { // ServiceResponse<T> response = new ServiceResponse<T>(); // response.setSuccess(false); // response.setErrorMessage(errorMessage); // response.setSessionId(sessionId); // return response; // } // // protected ServiceResponse() { // this.success = false; // } // // protected ServiceResponse(String sessionId) { // this.success = true; // this.sessionId = sessionId; // } // // protected ServiceResponse(String sessionId, T data) { // this.success = true; // this.sessionId = sessionId; // this.data = data; // } // // public T getData() { // return data; // } // // public void setData(T data) { // this.data = data; // } // // public boolean isSuccess() { // return success; // } // // public void setSuccess(boolean success) { // this.success = success; // } // // public String getUserMessage() { // return userMessage; // } // // public void setUserMessage(String userMessage) { // this.userMessage = userMessage; // } // // public String getErrorMessage() { // return errorMessage; // } // // public void setErrorMessage(String errorMessage) { // this.errorMessage = errorMessage; // } // // public String getSessionId() { // return sessionId; // } // // public void setSessionId(String sessionId) { // this.sessionId = sessionId; // } // // public String toJsonString() { // return new Gson().toJson(this); // } // } // // Path: app/models/DatabaseConnection.java // @Entity // public class DatabaseConnection extends BaseModel { // // @Required // @MaxSize(20) // @Column(name="origin_connection", nullable = false, length = 20) // public String originConnection; // // // @Required // @MaxSize(20) // @Column(name="destination_connection", nullable = false, length = 20) // public String destinationConnection; // // } // // Path: app/models/DatabaseIQN.java // @Entity // public class DatabaseIQN extends BaseModel { // // @Required // @MaxSize(255) // @Column(name="origin_iqn", nullable = false, length = 255) // public String originIQN; // // // @Required // @MaxSize(255) // @Column(name="destination_iqn", nullable = false, length = 255) // public String destinationIQN; // }
import dto.objects.ConnectionDto; import dto.response.ServiceResponse; import models.DatabaseConnection; import models.DatabaseIQN; import play.jobs.Job; import play.libs.F; import java.util.ArrayList; import java.util.List;
/* * Copyright 2016 ITM, S.A. * * Licensed under the Apache License, Version 2.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://www.apache.org/licenses/LICENSE-2.0`](http://www.apache.org/licenses/LICENSE-2.0) * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package jobs.services; /** * Created by jandrad on 2/02/16. */ public class ConnectionStatusJob extends Job<ConnectionStatusJob.ConnectionStatus> { public enum ConnectionStatus { UNKNOWN, PRODUCTION, CONTINGENCY } @Override public ConnectionStatus doJobWithResult() throws Exception {
// Path: app/dto/objects/ConnectionDto.java // public class ConnectionDto { // // protected String ipAddress; // protected String iqn; // // public ConnectionDto(String ipAddress, String iqn) { // this.ipAddress = ipAddress; // this.iqn = iqn; // } // // public String getIpAddress() { // return ipAddress; // } // // public void setIpAddress(String ipAddress) { // this.ipAddress = ipAddress; // } // // public String getIqn() { // return iqn; // } // // public void setIqn(String iqn) { // this.iqn = iqn; // } // } // // Path: app/dto/response/ServiceResponse.java // public class ServiceResponse<T> { // // private boolean success; // private String userMessage; // private String errorMessage; // private String sessionId; // // private T data; // // public static <T> ServiceResponse<T> success(String userMessage) { // return ServiceResponse.successToken(userMessage, null, null); // } // // public static <T> ServiceResponse<T> success(T data) { // return ServiceResponse.successToken(null, data, null); // } // // public static <T> ServiceResponse<T> success(String userMessage, T data) { // return ServiceResponse.successToken(userMessage, data, null); // } // // public static <T> ServiceResponse<T> successToken(String userMessage, T data, String token) { // ServiceResponse<T> response = new ServiceResponse<T>(); // response.setSuccess(true); // response.setData(data); // response.setUserMessage(userMessage); // response.setSessionId(token); // return response; // } // // public static <T> ServiceResponse<T> error(String errorMessage) { // return error(errorMessage, null); // } // // public static <T> ServiceResponse<T> error(String errorMessage, String sessionId) { // ServiceResponse<T> response = new ServiceResponse<T>(); // response.setSuccess(false); // response.setErrorMessage(errorMessage); // response.setSessionId(sessionId); // return response; // } // // protected ServiceResponse() { // this.success = false; // } // // protected ServiceResponse(String sessionId) { // this.success = true; // this.sessionId = sessionId; // } // // protected ServiceResponse(String sessionId, T data) { // this.success = true; // this.sessionId = sessionId; // this.data = data; // } // // public T getData() { // return data; // } // // public void setData(T data) { // this.data = data; // } // // public boolean isSuccess() { // return success; // } // // public void setSuccess(boolean success) { // this.success = success; // } // // public String getUserMessage() { // return userMessage; // } // // public void setUserMessage(String userMessage) { // this.userMessage = userMessage; // } // // public String getErrorMessage() { // return errorMessage; // } // // public void setErrorMessage(String errorMessage) { // this.errorMessage = errorMessage; // } // // public String getSessionId() { // return sessionId; // } // // public void setSessionId(String sessionId) { // this.sessionId = sessionId; // } // // public String toJsonString() { // return new Gson().toJson(this); // } // } // // Path: app/models/DatabaseConnection.java // @Entity // public class DatabaseConnection extends BaseModel { // // @Required // @MaxSize(20) // @Column(name="origin_connection", nullable = false, length = 20) // public String originConnection; // // // @Required // @MaxSize(20) // @Column(name="destination_connection", nullable = false, length = 20) // public String destinationConnection; // // } // // Path: app/models/DatabaseIQN.java // @Entity // public class DatabaseIQN extends BaseModel { // // @Required // @MaxSize(255) // @Column(name="origin_iqn", nullable = false, length = 255) // public String originIQN; // // // @Required // @MaxSize(255) // @Column(name="destination_iqn", nullable = false, length = 255) // public String destinationIQN; // } // Path: app/jobs/services/ConnectionStatusJob.java import dto.objects.ConnectionDto; import dto.response.ServiceResponse; import models.DatabaseConnection; import models.DatabaseIQN; import play.jobs.Job; import play.libs.F; import java.util.ArrayList; import java.util.List; /* * Copyright 2016 ITM, S.A. * * Licensed under the Apache License, Version 2.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://www.apache.org/licenses/LICENSE-2.0`](http://www.apache.org/licenses/LICENSE-2.0) * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package jobs.services; /** * Created by jandrad on 2/02/16. */ public class ConnectionStatusJob extends Job<ConnectionStatusJob.ConnectionStatus> { public enum ConnectionStatus { UNKNOWN, PRODUCTION, CONTINGENCY } @Override public ConnectionStatus doJobWithResult() throws Exception {
F.Promise<ServiceResponse> storageResponse = new StorageConnectionsJob().now();
xandradx/ovirt-engine-disaster-recovery
app/jobs/services/ConnectionStatusJob.java
// Path: app/dto/objects/ConnectionDto.java // public class ConnectionDto { // // protected String ipAddress; // protected String iqn; // // public ConnectionDto(String ipAddress, String iqn) { // this.ipAddress = ipAddress; // this.iqn = iqn; // } // // public String getIpAddress() { // return ipAddress; // } // // public void setIpAddress(String ipAddress) { // this.ipAddress = ipAddress; // } // // public String getIqn() { // return iqn; // } // // public void setIqn(String iqn) { // this.iqn = iqn; // } // } // // Path: app/dto/response/ServiceResponse.java // public class ServiceResponse<T> { // // private boolean success; // private String userMessage; // private String errorMessage; // private String sessionId; // // private T data; // // public static <T> ServiceResponse<T> success(String userMessage) { // return ServiceResponse.successToken(userMessage, null, null); // } // // public static <T> ServiceResponse<T> success(T data) { // return ServiceResponse.successToken(null, data, null); // } // // public static <T> ServiceResponse<T> success(String userMessage, T data) { // return ServiceResponse.successToken(userMessage, data, null); // } // // public static <T> ServiceResponse<T> successToken(String userMessage, T data, String token) { // ServiceResponse<T> response = new ServiceResponse<T>(); // response.setSuccess(true); // response.setData(data); // response.setUserMessage(userMessage); // response.setSessionId(token); // return response; // } // // public static <T> ServiceResponse<T> error(String errorMessage) { // return error(errorMessage, null); // } // // public static <T> ServiceResponse<T> error(String errorMessage, String sessionId) { // ServiceResponse<T> response = new ServiceResponse<T>(); // response.setSuccess(false); // response.setErrorMessage(errorMessage); // response.setSessionId(sessionId); // return response; // } // // protected ServiceResponse() { // this.success = false; // } // // protected ServiceResponse(String sessionId) { // this.success = true; // this.sessionId = sessionId; // } // // protected ServiceResponse(String sessionId, T data) { // this.success = true; // this.sessionId = sessionId; // this.data = data; // } // // public T getData() { // return data; // } // // public void setData(T data) { // this.data = data; // } // // public boolean isSuccess() { // return success; // } // // public void setSuccess(boolean success) { // this.success = success; // } // // public String getUserMessage() { // return userMessage; // } // // public void setUserMessage(String userMessage) { // this.userMessage = userMessage; // } // // public String getErrorMessage() { // return errorMessage; // } // // public void setErrorMessage(String errorMessage) { // this.errorMessage = errorMessage; // } // // public String getSessionId() { // return sessionId; // } // // public void setSessionId(String sessionId) { // this.sessionId = sessionId; // } // // public String toJsonString() { // return new Gson().toJson(this); // } // } // // Path: app/models/DatabaseConnection.java // @Entity // public class DatabaseConnection extends BaseModel { // // @Required // @MaxSize(20) // @Column(name="origin_connection", nullable = false, length = 20) // public String originConnection; // // // @Required // @MaxSize(20) // @Column(name="destination_connection", nullable = false, length = 20) // public String destinationConnection; // // } // // Path: app/models/DatabaseIQN.java // @Entity // public class DatabaseIQN extends BaseModel { // // @Required // @MaxSize(255) // @Column(name="origin_iqn", nullable = false, length = 255) // public String originIQN; // // // @Required // @MaxSize(255) // @Column(name="destination_iqn", nullable = false, length = 255) // public String destinationIQN; // }
import dto.objects.ConnectionDto; import dto.response.ServiceResponse; import models.DatabaseConnection; import models.DatabaseIQN; import play.jobs.Job; import play.libs.F; import java.util.ArrayList; import java.util.List;
/* * Copyright 2016 ITM, S.A. * * Licensed under the Apache License, Version 2.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://www.apache.org/licenses/LICENSE-2.0`](http://www.apache.org/licenses/LICENSE-2.0) * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package jobs.services; /** * Created by jandrad on 2/02/16. */ public class ConnectionStatusJob extends Job<ConnectionStatusJob.ConnectionStatus> { public enum ConnectionStatus { UNKNOWN, PRODUCTION, CONTINGENCY } @Override public ConnectionStatus doJobWithResult() throws Exception { F.Promise<ServiceResponse> storageResponse = new StorageConnectionsJob().now(); ServiceResponse serviceResponse = storageResponse.get(); if (serviceResponse.isSuccess()) { int contingency = 0; int production = 0; int unknown = 0; //Get connections
// Path: app/dto/objects/ConnectionDto.java // public class ConnectionDto { // // protected String ipAddress; // protected String iqn; // // public ConnectionDto(String ipAddress, String iqn) { // this.ipAddress = ipAddress; // this.iqn = iqn; // } // // public String getIpAddress() { // return ipAddress; // } // // public void setIpAddress(String ipAddress) { // this.ipAddress = ipAddress; // } // // public String getIqn() { // return iqn; // } // // public void setIqn(String iqn) { // this.iqn = iqn; // } // } // // Path: app/dto/response/ServiceResponse.java // public class ServiceResponse<T> { // // private boolean success; // private String userMessage; // private String errorMessage; // private String sessionId; // // private T data; // // public static <T> ServiceResponse<T> success(String userMessage) { // return ServiceResponse.successToken(userMessage, null, null); // } // // public static <T> ServiceResponse<T> success(T data) { // return ServiceResponse.successToken(null, data, null); // } // // public static <T> ServiceResponse<T> success(String userMessage, T data) { // return ServiceResponse.successToken(userMessage, data, null); // } // // public static <T> ServiceResponse<T> successToken(String userMessage, T data, String token) { // ServiceResponse<T> response = new ServiceResponse<T>(); // response.setSuccess(true); // response.setData(data); // response.setUserMessage(userMessage); // response.setSessionId(token); // return response; // } // // public static <T> ServiceResponse<T> error(String errorMessage) { // return error(errorMessage, null); // } // // public static <T> ServiceResponse<T> error(String errorMessage, String sessionId) { // ServiceResponse<T> response = new ServiceResponse<T>(); // response.setSuccess(false); // response.setErrorMessage(errorMessage); // response.setSessionId(sessionId); // return response; // } // // protected ServiceResponse() { // this.success = false; // } // // protected ServiceResponse(String sessionId) { // this.success = true; // this.sessionId = sessionId; // } // // protected ServiceResponse(String sessionId, T data) { // this.success = true; // this.sessionId = sessionId; // this.data = data; // } // // public T getData() { // return data; // } // // public void setData(T data) { // this.data = data; // } // // public boolean isSuccess() { // return success; // } // // public void setSuccess(boolean success) { // this.success = success; // } // // public String getUserMessage() { // return userMessage; // } // // public void setUserMessage(String userMessage) { // this.userMessage = userMessage; // } // // public String getErrorMessage() { // return errorMessage; // } // // public void setErrorMessage(String errorMessage) { // this.errorMessage = errorMessage; // } // // public String getSessionId() { // return sessionId; // } // // public void setSessionId(String sessionId) { // this.sessionId = sessionId; // } // // public String toJsonString() { // return new Gson().toJson(this); // } // } // // Path: app/models/DatabaseConnection.java // @Entity // public class DatabaseConnection extends BaseModel { // // @Required // @MaxSize(20) // @Column(name="origin_connection", nullable = false, length = 20) // public String originConnection; // // // @Required // @MaxSize(20) // @Column(name="destination_connection", nullable = false, length = 20) // public String destinationConnection; // // } // // Path: app/models/DatabaseIQN.java // @Entity // public class DatabaseIQN extends BaseModel { // // @Required // @MaxSize(255) // @Column(name="origin_iqn", nullable = false, length = 255) // public String originIQN; // // // @Required // @MaxSize(255) // @Column(name="destination_iqn", nullable = false, length = 255) // public String destinationIQN; // } // Path: app/jobs/services/ConnectionStatusJob.java import dto.objects.ConnectionDto; import dto.response.ServiceResponse; import models.DatabaseConnection; import models.DatabaseIQN; import play.jobs.Job; import play.libs.F; import java.util.ArrayList; import java.util.List; /* * Copyright 2016 ITM, S.A. * * Licensed under the Apache License, Version 2.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://www.apache.org/licenses/LICENSE-2.0`](http://www.apache.org/licenses/LICENSE-2.0) * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package jobs.services; /** * Created by jandrad on 2/02/16. */ public class ConnectionStatusJob extends Job<ConnectionStatusJob.ConnectionStatus> { public enum ConnectionStatus { UNKNOWN, PRODUCTION, CONTINGENCY } @Override public ConnectionStatus doJobWithResult() throws Exception { F.Promise<ServiceResponse> storageResponse = new StorageConnectionsJob().now(); ServiceResponse serviceResponse = storageResponse.get(); if (serviceResponse.isSuccess()) { int contingency = 0; int production = 0; int unknown = 0; //Get connections
List<DatabaseConnection> connections = DatabaseConnection.find("active = :a").bind("a", true).fetch();
apsun/QuoteLock
src/com/crossbowffs/quotelock/utils/IOUtils.java
// Path: src/com/crossbowffs/quotelock/consts/Urls.java // public final class Urls { // public static final String XPOSED_FORUM = "http://forum.xda-developers.com/xposed"; // public static final String GITHUB_QUOTELOCK = "https://github.com/apsun/QuoteLock"; // public static final String GITHUB_QUOTELOCK_ISSUES = GITHUB_QUOTELOCK + "/issues"; // // private Urls() { } // }
import com.crossbowffs.quotelock.BuildConfig; import com.crossbowffs.quotelock.consts.Urls; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL;
package com.crossbowffs.quotelock.utils; public class IOUtils { public static String streamToString(InputStream inputStream, String encoding, int bufferSize) throws IOException { char[] buffer = new char[bufferSize]; StringBuilder sb = new StringBuilder(); try (InputStreamReader reader = new InputStreamReader(inputStream, encoding)) { while (true) { int count = reader.read(buffer, 0, bufferSize); if (count < 0) break; sb.append(buffer, 0, count); } } return sb.toString(); } public static String streamToString(InputStream inputStream) throws IOException { return streamToString(inputStream, "UTF-8", 2048); } public static String downloadString(String urlString) throws IOException { URL url = new URL(urlString);
// Path: src/com/crossbowffs/quotelock/consts/Urls.java // public final class Urls { // public static final String XPOSED_FORUM = "http://forum.xda-developers.com/xposed"; // public static final String GITHUB_QUOTELOCK = "https://github.com/apsun/QuoteLock"; // public static final String GITHUB_QUOTELOCK_ISSUES = GITHUB_QUOTELOCK + "/issues"; // // private Urls() { } // } // Path: src/com/crossbowffs/quotelock/utils/IOUtils.java import com.crossbowffs.quotelock.BuildConfig; import com.crossbowffs.quotelock.consts.Urls; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; package com.crossbowffs.quotelock.utils; public class IOUtils { public static String streamToString(InputStream inputStream, String encoding, int bufferSize) throws IOException { char[] buffer = new char[bufferSize]; StringBuilder sb = new StringBuilder(); try (InputStreamReader reader = new InputStreamReader(inputStream, encoding)) { while (true) { int count = reader.read(buffer, 0, bufferSize); if (count < 0) break; sb.append(buffer, 0, count); } } return sb.toString(); } public static String streamToString(InputStream inputStream) throws IOException { return streamToString(inputStream, "UTF-8", 2048); } public static String downloadString(String urlString) throws IOException { URL url = new URL(urlString);
String ua = String.format("QuoteLock/%s (+%s)", BuildConfig.VERSION_NAME, Urls.GITHUB_QUOTELOCK);
apsun/QuoteLock
src/com/crossbowffs/quotelock/utils/JobUtils.java
// Path: src/com/crossbowffs/quotelock/app/QuoteDownloaderService.java // public class QuoteDownloaderService extends JobService { // private static final String TAG = QuoteDownloaderService.class.getSimpleName(); // // private class ServiceQuoteDownloaderTask extends QuoteDownloaderTask { // private final JobParameters mJobParameters; // // private ServiceQuoteDownloaderTask(JobParameters parameters) { // super(QuoteDownloaderService.this); // mJobParameters = parameters; // } // // @Override // protected void onPostExecute(QuoteData quote) { // super.onPostExecute(quote); // // We must back-off the job upon failure instead of creating // // a new one; otherwise, the update time compensation algorithm // // will schedule the next update immediately after this one. // jobFinished(mJobParameters, quote == null); // if (quote != null) { // JobUtils.createQuoteDownloadJob(mContext, true); // } // mUpdaterTask = null; // } // // @Override // protected void onCancelled(QuoteData quote) { // super.onCancelled(quote); // // No need to call #jobFinished, since #onStopJob will // // handle the back-off for us. // // jobFinished(mJobParameters, true); // mUpdaterTask = null; // } // } // // private QuoteDownloaderTask mUpdaterTask; // // @Override // public boolean onStartJob(JobParameters params) { // Xlog.d(TAG, "Quote downloader job started"); // // if (params.getJobId() != JobUtils.JOB_ID) { // Xlog.e(TAG, "Job ID mismatch, ignoring"); // return false; // } // // if (!JobUtils.shouldRefreshQuote(this)) { // Xlog.d(TAG, "Should not refresh quote now, ignoring"); // return false; // } // // mUpdaterTask = new ServiceQuoteDownloaderTask(params); // mUpdaterTask.execute(); // return true; // } // // @Override // public boolean onStopJob(JobParameters params) { // QuoteDownloaderTask task = mUpdaterTask; // if (task != null) { // // If the job already finished, we have either already // // rescheduled or backed-off the task, so we do not submit // // a new reschedule attempt from this method. If the job was // // not canceled however, we need this method to reschedule // // the job for us, so we return true. // boolean canceled = task.cancel(true); // if (canceled) { // Xlog.e(TAG, "Aborted download job"); // return true; // } else { // Xlog.e(TAG, "Attempted to abort completed download job"); // return false; // } // } else { // // Since the task is null, we either aborted the job in #onStartJob // // (so we shouldn't reschedule) or the job already finished // // (so rescheduling has already been taken care of). // // Apparently, this always happens when we create a new job, so we can // // ignore this warning. // Xlog.w(TAG, "Attempted to abort job, but updater task is null"); // return false; // } // } // } // // Path: src/com/crossbowffs/quotelock/consts/PrefKeys.java // public final class PrefKeys { // public static final String PREF_COMMON = "common"; // public static final String PREF_COMMON_REFRESH_RATE = "pref_common_refresh_rate"; // public static final String PREF_COMMON_REFRESH_RATE_DEFAULT = "900"; // public static final String PREF_COMMON_UNMETERED_ONLY = "pref_common_unmetered_only"; // public static final boolean PREF_COMMON_UNMETERED_ONLY_DEFAULT = false; // public static final String PREF_COMMON_QUOTE_MODULE = "pref_common_quote_module"; // public static final String PREF_COMMON_QUOTE_MODULE_DEFAULT = VnaasQuoteModule.class.getName(); // public static final String PREF_COMMON_MODULE_PREFERENCES = "pref_module_preferences"; // public static final String PREF_COMMON_REQUIRES_INTERNET = "pref_common_requires_internet"; // public static final String PREF_COMMON_REFRESH_RATE_OVERRIDE = "pref_common_refresh_rate_override"; // public static final String PREF_COMMON_FONT_SIZE_TEXT = "pref_common_font_size_text"; // public static final String PREF_COMMON_FONT_SIZE_TEXT_DEFAULT = "20"; // public static final String PREF_COMMON_FONT_SIZE_SOURCE = "pref_common_font_size_source"; // public static final String PREF_COMMON_FONT_SIZE_SOURCE_DEFAULT = "18"; // // public static final String PREF_QUOTES = "quotes"; // public static final String PREF_QUOTES_TEXT = "pref_quotes_text"; // public static final String PREF_QUOTES_SOURCE = "pref_quotes_source"; // public static final String PREF_QUOTES_LAST_UPDATED = "pref_quotes_last_updated"; // // public static final String PREF_ABOUT_CREDITS = "pref_about_credits"; // public static final String PREF_ABOUT_GITHUB = "pref_about_github"; // public static final String PREF_ABOUT_VERSION = "pref_about_version"; // // private PrefKeys() { } // }
import android.app.job.JobInfo; import android.app.job.JobScheduler; import android.content.ComponentName; import android.content.Context; import android.content.SharedPreferences; import android.net.ConnectivityManager; import android.net.NetworkInfo; import com.crossbowffs.quotelock.app.QuoteDownloaderService; import com.crossbowffs.quotelock.consts.PrefKeys;
package com.crossbowffs.quotelock.utils; public class JobUtils { private static final String TAG = JobUtils.class.getSimpleName(); public static final int JOB_ID = 0; public static boolean shouldRefreshQuote(Context context) {
// Path: src/com/crossbowffs/quotelock/app/QuoteDownloaderService.java // public class QuoteDownloaderService extends JobService { // private static final String TAG = QuoteDownloaderService.class.getSimpleName(); // // private class ServiceQuoteDownloaderTask extends QuoteDownloaderTask { // private final JobParameters mJobParameters; // // private ServiceQuoteDownloaderTask(JobParameters parameters) { // super(QuoteDownloaderService.this); // mJobParameters = parameters; // } // // @Override // protected void onPostExecute(QuoteData quote) { // super.onPostExecute(quote); // // We must back-off the job upon failure instead of creating // // a new one; otherwise, the update time compensation algorithm // // will schedule the next update immediately after this one. // jobFinished(mJobParameters, quote == null); // if (quote != null) { // JobUtils.createQuoteDownloadJob(mContext, true); // } // mUpdaterTask = null; // } // // @Override // protected void onCancelled(QuoteData quote) { // super.onCancelled(quote); // // No need to call #jobFinished, since #onStopJob will // // handle the back-off for us. // // jobFinished(mJobParameters, true); // mUpdaterTask = null; // } // } // // private QuoteDownloaderTask mUpdaterTask; // // @Override // public boolean onStartJob(JobParameters params) { // Xlog.d(TAG, "Quote downloader job started"); // // if (params.getJobId() != JobUtils.JOB_ID) { // Xlog.e(TAG, "Job ID mismatch, ignoring"); // return false; // } // // if (!JobUtils.shouldRefreshQuote(this)) { // Xlog.d(TAG, "Should not refresh quote now, ignoring"); // return false; // } // // mUpdaterTask = new ServiceQuoteDownloaderTask(params); // mUpdaterTask.execute(); // return true; // } // // @Override // public boolean onStopJob(JobParameters params) { // QuoteDownloaderTask task = mUpdaterTask; // if (task != null) { // // If the job already finished, we have either already // // rescheduled or backed-off the task, so we do not submit // // a new reschedule attempt from this method. If the job was // // not canceled however, we need this method to reschedule // // the job for us, so we return true. // boolean canceled = task.cancel(true); // if (canceled) { // Xlog.e(TAG, "Aborted download job"); // return true; // } else { // Xlog.e(TAG, "Attempted to abort completed download job"); // return false; // } // } else { // // Since the task is null, we either aborted the job in #onStartJob // // (so we shouldn't reschedule) or the job already finished // // (so rescheduling has already been taken care of). // // Apparently, this always happens when we create a new job, so we can // // ignore this warning. // Xlog.w(TAG, "Attempted to abort job, but updater task is null"); // return false; // } // } // } // // Path: src/com/crossbowffs/quotelock/consts/PrefKeys.java // public final class PrefKeys { // public static final String PREF_COMMON = "common"; // public static final String PREF_COMMON_REFRESH_RATE = "pref_common_refresh_rate"; // public static final String PREF_COMMON_REFRESH_RATE_DEFAULT = "900"; // public static final String PREF_COMMON_UNMETERED_ONLY = "pref_common_unmetered_only"; // public static final boolean PREF_COMMON_UNMETERED_ONLY_DEFAULT = false; // public static final String PREF_COMMON_QUOTE_MODULE = "pref_common_quote_module"; // public static final String PREF_COMMON_QUOTE_MODULE_DEFAULT = VnaasQuoteModule.class.getName(); // public static final String PREF_COMMON_MODULE_PREFERENCES = "pref_module_preferences"; // public static final String PREF_COMMON_REQUIRES_INTERNET = "pref_common_requires_internet"; // public static final String PREF_COMMON_REFRESH_RATE_OVERRIDE = "pref_common_refresh_rate_override"; // public static final String PREF_COMMON_FONT_SIZE_TEXT = "pref_common_font_size_text"; // public static final String PREF_COMMON_FONT_SIZE_TEXT_DEFAULT = "20"; // public static final String PREF_COMMON_FONT_SIZE_SOURCE = "pref_common_font_size_source"; // public static final String PREF_COMMON_FONT_SIZE_SOURCE_DEFAULT = "18"; // // public static final String PREF_QUOTES = "quotes"; // public static final String PREF_QUOTES_TEXT = "pref_quotes_text"; // public static final String PREF_QUOTES_SOURCE = "pref_quotes_source"; // public static final String PREF_QUOTES_LAST_UPDATED = "pref_quotes_last_updated"; // // public static final String PREF_ABOUT_CREDITS = "pref_about_credits"; // public static final String PREF_ABOUT_GITHUB = "pref_about_github"; // public static final String PREF_ABOUT_VERSION = "pref_about_version"; // // private PrefKeys() { } // } // Path: src/com/crossbowffs/quotelock/utils/JobUtils.java import android.app.job.JobInfo; import android.app.job.JobScheduler; import android.content.ComponentName; import android.content.Context; import android.content.SharedPreferences; import android.net.ConnectivityManager; import android.net.NetworkInfo; import com.crossbowffs.quotelock.app.QuoteDownloaderService; import com.crossbowffs.quotelock.consts.PrefKeys; package com.crossbowffs.quotelock.utils; public class JobUtils { private static final String TAG = JobUtils.class.getSimpleName(); public static final int JOB_ID = 0; public static boolean shouldRefreshQuote(Context context) {
SharedPreferences preferences = context.getSharedPreferences(PrefKeys.PREF_COMMON, Context.MODE_PRIVATE);
apsun/QuoteLock
src/com/crossbowffs/quotelock/modules/vnaas/api/VnaasCharacterQueryParams.java
// Path: src/com/crossbowffs/quotelock/modules/vnaas/model/VnaasNovel.java // public class VnaasNovel { // private final long mId; // private final String mName; // private final VnaasCharacter[] mCharacters; // // public VnaasNovel(long id, String name, VnaasCharacter[] characters) { // mId = id; // mName = name; // mCharacters = characters; // } // // public long getId() { // return mId; // } // // public String getName() { // return mName; // } // // public VnaasCharacter[] getCharacters() { // return mCharacters; // } // }
import com.crossbowffs.quotelock.modules.vnaas.model.VnaasNovel;
package com.crossbowffs.quotelock.modules.vnaas.api; public class VnaasCharacterQueryParams extends QueryParams { private static final String KEY_NOVEL_ID = "novel_id"; private static final String KEY_NOVEL_NAME = "name"; public VnaasCharacterQueryParams setNovel(long novelId) { setParam(KEY_NOVEL_ID, novelId); return this; }
// Path: src/com/crossbowffs/quotelock/modules/vnaas/model/VnaasNovel.java // public class VnaasNovel { // private final long mId; // private final String mName; // private final VnaasCharacter[] mCharacters; // // public VnaasNovel(long id, String name, VnaasCharacter[] characters) { // mId = id; // mName = name; // mCharacters = characters; // } // // public long getId() { // return mId; // } // // public String getName() { // return mName; // } // // public VnaasCharacter[] getCharacters() { // return mCharacters; // } // } // Path: src/com/crossbowffs/quotelock/modules/vnaas/api/VnaasCharacterQueryParams.java import com.crossbowffs.quotelock.modules.vnaas.model.VnaasNovel; package com.crossbowffs.quotelock.modules.vnaas.api; public class VnaasCharacterQueryParams extends QueryParams { private static final String KEY_NOVEL_ID = "novel_id"; private static final String KEY_NOVEL_NAME = "name"; public VnaasCharacterQueryParams setNovel(long novelId) { setParam(KEY_NOVEL_ID, novelId); return this; }
public VnaasCharacterQueryParams setNovel(VnaasNovel novel) {
apsun/QuoteLock
src/com/crossbowffs/quotelock/xposed/XposedUtilsHook.java
// Path: src/com/crossbowffs/quotelock/utils/Xlog.java // public final class Xlog { // private static final String LOG_TAG = BuildConfig.LOG_TAG; // private static final int LOG_LEVEL = BuildConfig.LOG_LEVEL; // private static final boolean LOG_TO_XPOSED = BuildConfig.LOG_TO_XPOSED; // // private Xlog() { } // // private static void log(int priority, String tag, String message, Object... args) { // if (priority < LOG_LEVEL) { // return; // } // // message = String.format(message, args); // if (args.length > 0 && args[args.length - 1] instanceof Throwable) { // Throwable throwable = (Throwable)args[args.length - 1]; // String stacktraceStr = Log.getStackTraceString(throwable); // message = message + '\n' + stacktraceStr; // } // // Log.println(priority, LOG_TAG, tag + ": " + message); // if (LOG_TO_XPOSED) { // Log.println(priority, "Xposed", LOG_TAG + ": " + tag + ": " + message); // } // } // // public static void v(String tag, String message, Object... args) { // log(Log.VERBOSE, tag, message, args); // } // // public static void d(String tag, String message, Object... args) { // log(Log.DEBUG, tag, message, args); // } // // public static void i(String tag, String message, Object... args) { // log(Log.INFO, tag, message, args); // } // // public static void w(String tag, String message, Object... args) { // log(Log.WARN, tag, message, args); // } // // public static void e(String tag, String message, Object... args) { // log(Log.ERROR, tag, message, args); // } // } // // Path: src/com/crossbowffs/quotelock/utils/XposedUtils.java // public final class XposedUtils { // private static final int MODULE_VERSION = BuildConfig.MODULE_VERSION; // private static final String XPOSED_PACKAGE = "de.robv.android.xposed.installer"; // private static final String XPOSED_ACTION = XPOSED_PACKAGE + ".OPEN_SECTION"; // private static final String XPOSED_EXTRA_SECTION = "section"; // public static final String XPOSED_SECTION_MODULES = "modules"; // public static final String XPOSED_SECTION_INSTALL = "install"; // // private XposedUtils() { } // // public static boolean isModuleEnabled() { // return getModuleVersion() >= 0; // } // // public static boolean isModuleUpdated() { // return MODULE_VERSION != getModuleVersion(); // } // // private static int getModuleVersion() { // // This method is hooked by the module to return the // // value of BuildConfig.MODULE_VERSION, as seen from the // // module side. // return -1; // } // // public static boolean isXposedInstalled(Context context) { // PackageManager packageManager = context.getPackageManager(); // try { // packageManager.getPackageInfo(XPOSED_PACKAGE, 0); // return true; // } catch (PackageManager.NameNotFoundException e) { // return false; // } // } // // public static boolean startXposedActivity(Context context, String section) { // Intent intent = new Intent(XPOSED_ACTION); // intent.putExtra(XPOSED_EXTRA_SECTION, section); // try { // context.startActivity(intent); // return true; // } catch (ActivityNotFoundException e) { // return false; // } // } // }
import com.crossbowffs.quotelock.BuildConfig; import com.crossbowffs.quotelock.utils.Xlog; import com.crossbowffs.quotelock.utils.XposedUtils; import de.robv.android.xposed.IXposedHookLoadPackage; import de.robv.android.xposed.XC_MethodReplacement; import de.robv.android.xposed.XposedHelpers; import de.robv.android.xposed.callbacks.XC_LoadPackage;
package com.crossbowffs.quotelock.xposed; public class XposedUtilsHook implements IXposedHookLoadPackage { private static final String TAG = XposedUtilsHook.class.getSimpleName(); private static final String QUOTELOCK_PACKAGE = BuildConfig.APPLICATION_ID; private static final int MODULE_VERSION = BuildConfig.MODULE_VERSION; private static void hookXposedUtils(XC_LoadPackage.LoadPackageParam lpparam) {
// Path: src/com/crossbowffs/quotelock/utils/Xlog.java // public final class Xlog { // private static final String LOG_TAG = BuildConfig.LOG_TAG; // private static final int LOG_LEVEL = BuildConfig.LOG_LEVEL; // private static final boolean LOG_TO_XPOSED = BuildConfig.LOG_TO_XPOSED; // // private Xlog() { } // // private static void log(int priority, String tag, String message, Object... args) { // if (priority < LOG_LEVEL) { // return; // } // // message = String.format(message, args); // if (args.length > 0 && args[args.length - 1] instanceof Throwable) { // Throwable throwable = (Throwable)args[args.length - 1]; // String stacktraceStr = Log.getStackTraceString(throwable); // message = message + '\n' + stacktraceStr; // } // // Log.println(priority, LOG_TAG, tag + ": " + message); // if (LOG_TO_XPOSED) { // Log.println(priority, "Xposed", LOG_TAG + ": " + tag + ": " + message); // } // } // // public static void v(String tag, String message, Object... args) { // log(Log.VERBOSE, tag, message, args); // } // // public static void d(String tag, String message, Object... args) { // log(Log.DEBUG, tag, message, args); // } // // public static void i(String tag, String message, Object... args) { // log(Log.INFO, tag, message, args); // } // // public static void w(String tag, String message, Object... args) { // log(Log.WARN, tag, message, args); // } // // public static void e(String tag, String message, Object... args) { // log(Log.ERROR, tag, message, args); // } // } // // Path: src/com/crossbowffs/quotelock/utils/XposedUtils.java // public final class XposedUtils { // private static final int MODULE_VERSION = BuildConfig.MODULE_VERSION; // private static final String XPOSED_PACKAGE = "de.robv.android.xposed.installer"; // private static final String XPOSED_ACTION = XPOSED_PACKAGE + ".OPEN_SECTION"; // private static final String XPOSED_EXTRA_SECTION = "section"; // public static final String XPOSED_SECTION_MODULES = "modules"; // public static final String XPOSED_SECTION_INSTALL = "install"; // // private XposedUtils() { } // // public static boolean isModuleEnabled() { // return getModuleVersion() >= 0; // } // // public static boolean isModuleUpdated() { // return MODULE_VERSION != getModuleVersion(); // } // // private static int getModuleVersion() { // // This method is hooked by the module to return the // // value of BuildConfig.MODULE_VERSION, as seen from the // // module side. // return -1; // } // // public static boolean isXposedInstalled(Context context) { // PackageManager packageManager = context.getPackageManager(); // try { // packageManager.getPackageInfo(XPOSED_PACKAGE, 0); // return true; // } catch (PackageManager.NameNotFoundException e) { // return false; // } // } // // public static boolean startXposedActivity(Context context, String section) { // Intent intent = new Intent(XPOSED_ACTION); // intent.putExtra(XPOSED_EXTRA_SECTION, section); // try { // context.startActivity(intent); // return true; // } catch (ActivityNotFoundException e) { // return false; // } // } // } // Path: src/com/crossbowffs/quotelock/xposed/XposedUtilsHook.java import com.crossbowffs.quotelock.BuildConfig; import com.crossbowffs.quotelock.utils.Xlog; import com.crossbowffs.quotelock.utils.XposedUtils; import de.robv.android.xposed.IXposedHookLoadPackage; import de.robv.android.xposed.XC_MethodReplacement; import de.robv.android.xposed.XposedHelpers; import de.robv.android.xposed.callbacks.XC_LoadPackage; package com.crossbowffs.quotelock.xposed; public class XposedUtilsHook implements IXposedHookLoadPackage { private static final String TAG = XposedUtilsHook.class.getSimpleName(); private static final String QUOTELOCK_PACKAGE = BuildConfig.APPLICATION_ID; private static final int MODULE_VERSION = BuildConfig.MODULE_VERSION; private static void hookXposedUtils(XC_LoadPackage.LoadPackageParam lpparam) {
String className = XposedUtils.class.getName();
apsun/QuoteLock
src/com/crossbowffs/quotelock/xposed/XposedUtilsHook.java
// Path: src/com/crossbowffs/quotelock/utils/Xlog.java // public final class Xlog { // private static final String LOG_TAG = BuildConfig.LOG_TAG; // private static final int LOG_LEVEL = BuildConfig.LOG_LEVEL; // private static final boolean LOG_TO_XPOSED = BuildConfig.LOG_TO_XPOSED; // // private Xlog() { } // // private static void log(int priority, String tag, String message, Object... args) { // if (priority < LOG_LEVEL) { // return; // } // // message = String.format(message, args); // if (args.length > 0 && args[args.length - 1] instanceof Throwable) { // Throwable throwable = (Throwable)args[args.length - 1]; // String stacktraceStr = Log.getStackTraceString(throwable); // message = message + '\n' + stacktraceStr; // } // // Log.println(priority, LOG_TAG, tag + ": " + message); // if (LOG_TO_XPOSED) { // Log.println(priority, "Xposed", LOG_TAG + ": " + tag + ": " + message); // } // } // // public static void v(String tag, String message, Object... args) { // log(Log.VERBOSE, tag, message, args); // } // // public static void d(String tag, String message, Object... args) { // log(Log.DEBUG, tag, message, args); // } // // public static void i(String tag, String message, Object... args) { // log(Log.INFO, tag, message, args); // } // // public static void w(String tag, String message, Object... args) { // log(Log.WARN, tag, message, args); // } // // public static void e(String tag, String message, Object... args) { // log(Log.ERROR, tag, message, args); // } // } // // Path: src/com/crossbowffs/quotelock/utils/XposedUtils.java // public final class XposedUtils { // private static final int MODULE_VERSION = BuildConfig.MODULE_VERSION; // private static final String XPOSED_PACKAGE = "de.robv.android.xposed.installer"; // private static final String XPOSED_ACTION = XPOSED_PACKAGE + ".OPEN_SECTION"; // private static final String XPOSED_EXTRA_SECTION = "section"; // public static final String XPOSED_SECTION_MODULES = "modules"; // public static final String XPOSED_SECTION_INSTALL = "install"; // // private XposedUtils() { } // // public static boolean isModuleEnabled() { // return getModuleVersion() >= 0; // } // // public static boolean isModuleUpdated() { // return MODULE_VERSION != getModuleVersion(); // } // // private static int getModuleVersion() { // // This method is hooked by the module to return the // // value of BuildConfig.MODULE_VERSION, as seen from the // // module side. // return -1; // } // // public static boolean isXposedInstalled(Context context) { // PackageManager packageManager = context.getPackageManager(); // try { // packageManager.getPackageInfo(XPOSED_PACKAGE, 0); // return true; // } catch (PackageManager.NameNotFoundException e) { // return false; // } // } // // public static boolean startXposedActivity(Context context, String section) { // Intent intent = new Intent(XPOSED_ACTION); // intent.putExtra(XPOSED_EXTRA_SECTION, section); // try { // context.startActivity(intent); // return true; // } catch (ActivityNotFoundException e) { // return false; // } // } // }
import com.crossbowffs.quotelock.BuildConfig; import com.crossbowffs.quotelock.utils.Xlog; import com.crossbowffs.quotelock.utils.XposedUtils; import de.robv.android.xposed.IXposedHookLoadPackage; import de.robv.android.xposed.XC_MethodReplacement; import de.robv.android.xposed.XposedHelpers; import de.robv.android.xposed.callbacks.XC_LoadPackage;
package com.crossbowffs.quotelock.xposed; public class XposedUtilsHook implements IXposedHookLoadPackage { private static final String TAG = XposedUtilsHook.class.getSimpleName(); private static final String QUOTELOCK_PACKAGE = BuildConfig.APPLICATION_ID; private static final int MODULE_VERSION = BuildConfig.MODULE_VERSION; private static void hookXposedUtils(XC_LoadPackage.LoadPackageParam lpparam) { String className = XposedUtils.class.getName();
// Path: src/com/crossbowffs/quotelock/utils/Xlog.java // public final class Xlog { // private static final String LOG_TAG = BuildConfig.LOG_TAG; // private static final int LOG_LEVEL = BuildConfig.LOG_LEVEL; // private static final boolean LOG_TO_XPOSED = BuildConfig.LOG_TO_XPOSED; // // private Xlog() { } // // private static void log(int priority, String tag, String message, Object... args) { // if (priority < LOG_LEVEL) { // return; // } // // message = String.format(message, args); // if (args.length > 0 && args[args.length - 1] instanceof Throwable) { // Throwable throwable = (Throwable)args[args.length - 1]; // String stacktraceStr = Log.getStackTraceString(throwable); // message = message + '\n' + stacktraceStr; // } // // Log.println(priority, LOG_TAG, tag + ": " + message); // if (LOG_TO_XPOSED) { // Log.println(priority, "Xposed", LOG_TAG + ": " + tag + ": " + message); // } // } // // public static void v(String tag, String message, Object... args) { // log(Log.VERBOSE, tag, message, args); // } // // public static void d(String tag, String message, Object... args) { // log(Log.DEBUG, tag, message, args); // } // // public static void i(String tag, String message, Object... args) { // log(Log.INFO, tag, message, args); // } // // public static void w(String tag, String message, Object... args) { // log(Log.WARN, tag, message, args); // } // // public static void e(String tag, String message, Object... args) { // log(Log.ERROR, tag, message, args); // } // } // // Path: src/com/crossbowffs/quotelock/utils/XposedUtils.java // public final class XposedUtils { // private static final int MODULE_VERSION = BuildConfig.MODULE_VERSION; // private static final String XPOSED_PACKAGE = "de.robv.android.xposed.installer"; // private static final String XPOSED_ACTION = XPOSED_PACKAGE + ".OPEN_SECTION"; // private static final String XPOSED_EXTRA_SECTION = "section"; // public static final String XPOSED_SECTION_MODULES = "modules"; // public static final String XPOSED_SECTION_INSTALL = "install"; // // private XposedUtils() { } // // public static boolean isModuleEnabled() { // return getModuleVersion() >= 0; // } // // public static boolean isModuleUpdated() { // return MODULE_VERSION != getModuleVersion(); // } // // private static int getModuleVersion() { // // This method is hooked by the module to return the // // value of BuildConfig.MODULE_VERSION, as seen from the // // module side. // return -1; // } // // public static boolean isXposedInstalled(Context context) { // PackageManager packageManager = context.getPackageManager(); // try { // packageManager.getPackageInfo(XPOSED_PACKAGE, 0); // return true; // } catch (PackageManager.NameNotFoundException e) { // return false; // } // } // // public static boolean startXposedActivity(Context context, String section) { // Intent intent = new Intent(XPOSED_ACTION); // intent.putExtra(XPOSED_EXTRA_SECTION, section); // try { // context.startActivity(intent); // return true; // } catch (ActivityNotFoundException e) { // return false; // } // } // } // Path: src/com/crossbowffs/quotelock/xposed/XposedUtilsHook.java import com.crossbowffs.quotelock.BuildConfig; import com.crossbowffs.quotelock.utils.Xlog; import com.crossbowffs.quotelock.utils.XposedUtils; import de.robv.android.xposed.IXposedHookLoadPackage; import de.robv.android.xposed.XC_MethodReplacement; import de.robv.android.xposed.XposedHelpers; import de.robv.android.xposed.callbacks.XC_LoadPackage; package com.crossbowffs.quotelock.xposed; public class XposedUtilsHook implements IXposedHookLoadPackage { private static final String TAG = XposedUtilsHook.class.getSimpleName(); private static final String QUOTELOCK_PACKAGE = BuildConfig.APPLICATION_ID; private static final int MODULE_VERSION = BuildConfig.MODULE_VERSION; private static void hookXposedUtils(XC_LoadPackage.LoadPackageParam lpparam) { String className = XposedUtils.class.getName();
Xlog.i(TAG, "Hooking Xposed module status checker");
apsun/QuoteLock
src/com/crossbowffs/quotelock/modules/vnaas/api/VnaasQuoteQueryParams.java
// Path: src/com/crossbowffs/quotelock/modules/vnaas/model/VnaasCharacter.java // public class VnaasCharacter { // private final long mId; // private final String mName; // private final VnaasNovel[] mNovels; // // public VnaasCharacter(long id, String name, VnaasNovel[] novels) { // mId = id; // mName = name; // mNovels = novels; // } // // public long getId() { // return mId; // } // // public String getName() { // return mName; // } // // public VnaasNovel[] getNovels() { // return mNovels; // } // } // // Path: src/com/crossbowffs/quotelock/modules/vnaas/model/VnaasNovel.java // public class VnaasNovel { // private final long mId; // private final String mName; // private final VnaasCharacter[] mCharacters; // // public VnaasNovel(long id, String name, VnaasCharacter[] characters) { // mId = id; // mName = name; // mCharacters = characters; // } // // public long getId() { // return mId; // } // // public String getName() { // return mName; // } // // public VnaasCharacter[] getCharacters() { // return mCharacters; // } // }
import com.crossbowffs.quotelock.modules.vnaas.model.VnaasCharacter; import com.crossbowffs.quotelock.modules.vnaas.model.VnaasNovel;
package com.crossbowffs.quotelock.modules.vnaas.api; public class VnaasQuoteQueryParams extends QueryParams { public VnaasQuoteQueryParams setCharacters(long... characterIds) { setParam("character_id", characterIds); return this; }
// Path: src/com/crossbowffs/quotelock/modules/vnaas/model/VnaasCharacter.java // public class VnaasCharacter { // private final long mId; // private final String mName; // private final VnaasNovel[] mNovels; // // public VnaasCharacter(long id, String name, VnaasNovel[] novels) { // mId = id; // mName = name; // mNovels = novels; // } // // public long getId() { // return mId; // } // // public String getName() { // return mName; // } // // public VnaasNovel[] getNovels() { // return mNovels; // } // } // // Path: src/com/crossbowffs/quotelock/modules/vnaas/model/VnaasNovel.java // public class VnaasNovel { // private final long mId; // private final String mName; // private final VnaasCharacter[] mCharacters; // // public VnaasNovel(long id, String name, VnaasCharacter[] characters) { // mId = id; // mName = name; // mCharacters = characters; // } // // public long getId() { // return mId; // } // // public String getName() { // return mName; // } // // public VnaasCharacter[] getCharacters() { // return mCharacters; // } // } // Path: src/com/crossbowffs/quotelock/modules/vnaas/api/VnaasQuoteQueryParams.java import com.crossbowffs.quotelock.modules.vnaas.model.VnaasCharacter; import com.crossbowffs.quotelock.modules.vnaas.model.VnaasNovel; package com.crossbowffs.quotelock.modules.vnaas.api; public class VnaasQuoteQueryParams extends QueryParams { public VnaasQuoteQueryParams setCharacters(long... characterIds) { setParam("character_id", characterIds); return this; }
public VnaasQuoteQueryParams setCharacters(VnaasCharacter... characters) {
apsun/QuoteLock
src/com/crossbowffs/quotelock/modules/vnaas/api/VnaasQuoteQueryParams.java
// Path: src/com/crossbowffs/quotelock/modules/vnaas/model/VnaasCharacter.java // public class VnaasCharacter { // private final long mId; // private final String mName; // private final VnaasNovel[] mNovels; // // public VnaasCharacter(long id, String name, VnaasNovel[] novels) { // mId = id; // mName = name; // mNovels = novels; // } // // public long getId() { // return mId; // } // // public String getName() { // return mName; // } // // public VnaasNovel[] getNovels() { // return mNovels; // } // } // // Path: src/com/crossbowffs/quotelock/modules/vnaas/model/VnaasNovel.java // public class VnaasNovel { // private final long mId; // private final String mName; // private final VnaasCharacter[] mCharacters; // // public VnaasNovel(long id, String name, VnaasCharacter[] characters) { // mId = id; // mName = name; // mCharacters = characters; // } // // public long getId() { // return mId; // } // // public String getName() { // return mName; // } // // public VnaasCharacter[] getCharacters() { // return mCharacters; // } // }
import com.crossbowffs.quotelock.modules.vnaas.model.VnaasCharacter; import com.crossbowffs.quotelock.modules.vnaas.model.VnaasNovel;
package com.crossbowffs.quotelock.modules.vnaas.api; public class VnaasQuoteQueryParams extends QueryParams { public VnaasQuoteQueryParams setCharacters(long... characterIds) { setParam("character_id", characterIds); return this; } public VnaasQuoteQueryParams setCharacters(VnaasCharacter... characters) { long[] ids = new long[characters.length]; for (int i = 0; i < ids.length; ++i) { ids[i] = characters[i].getId(); } return setCharacters(ids); } public VnaasQuoteQueryParams setNovels(long... novelIds) { setParam("novel_id", novelIds); return this; }
// Path: src/com/crossbowffs/quotelock/modules/vnaas/model/VnaasCharacter.java // public class VnaasCharacter { // private final long mId; // private final String mName; // private final VnaasNovel[] mNovels; // // public VnaasCharacter(long id, String name, VnaasNovel[] novels) { // mId = id; // mName = name; // mNovels = novels; // } // // public long getId() { // return mId; // } // // public String getName() { // return mName; // } // // public VnaasNovel[] getNovels() { // return mNovels; // } // } // // Path: src/com/crossbowffs/quotelock/modules/vnaas/model/VnaasNovel.java // public class VnaasNovel { // private final long mId; // private final String mName; // private final VnaasCharacter[] mCharacters; // // public VnaasNovel(long id, String name, VnaasCharacter[] characters) { // mId = id; // mName = name; // mCharacters = characters; // } // // public long getId() { // return mId; // } // // public String getName() { // return mName; // } // // public VnaasCharacter[] getCharacters() { // return mCharacters; // } // } // Path: src/com/crossbowffs/quotelock/modules/vnaas/api/VnaasQuoteQueryParams.java import com.crossbowffs.quotelock.modules.vnaas.model.VnaasCharacter; import com.crossbowffs.quotelock.modules.vnaas.model.VnaasNovel; package com.crossbowffs.quotelock.modules.vnaas.api; public class VnaasQuoteQueryParams extends QueryParams { public VnaasQuoteQueryParams setCharacters(long... characterIds) { setParam("character_id", characterIds); return this; } public VnaasQuoteQueryParams setCharacters(VnaasCharacter... characters) { long[] ids = new long[characters.length]; for (int i = 0; i < ids.length; ++i) { ids[i] = characters[i].getId(); } return setCharacters(ids); } public VnaasQuoteQueryParams setNovels(long... novelIds) { setParam("novel_id", novelIds); return this; }
public VnaasQuoteQueryParams setNovels(VnaasNovel... novels) {
apsun/QuoteLock
src/com/crossbowffs/quotelock/modules/vnaas/api/VnaasApiManager.java
// Path: src/com/crossbowffs/quotelock/modules/vnaas/model/VnaasCharacter.java // public class VnaasCharacter { // private final long mId; // private final String mName; // private final VnaasNovel[] mNovels; // // public VnaasCharacter(long id, String name, VnaasNovel[] novels) { // mId = id; // mName = name; // mNovels = novels; // } // // public long getId() { // return mId; // } // // public String getName() { // return mName; // } // // public VnaasNovel[] getNovels() { // return mNovels; // } // } // // Path: src/com/crossbowffs/quotelock/modules/vnaas/model/VnaasNovel.java // public class VnaasNovel { // private final long mId; // private final String mName; // private final VnaasCharacter[] mCharacters; // // public VnaasNovel(long id, String name, VnaasCharacter[] characters) { // mId = id; // mName = name; // mCharacters = characters; // } // // public long getId() { // return mId; // } // // public String getName() { // return mName; // } // // public VnaasCharacter[] getCharacters() { // return mCharacters; // } // } // // Path: src/com/crossbowffs/quotelock/modules/vnaas/model/VnaasQuote.java // public class VnaasQuote { // private final String mText; // private final VnaasCharacter mCharacter; // private final VnaasNovel mNovel; // // public VnaasQuote(String text, VnaasCharacter character, VnaasNovel novel) { // mText = text; // mCharacter = character; // mNovel = novel; // } // // public String getText() { // return mText; // } // // public VnaasCharacter getCharacter() { // return mCharacter; // } // // public VnaasNovel getNovel() { // return mNovel; // } // } // // Path: src/com/crossbowffs/quotelock/utils/IOUtils.java // public class IOUtils { // public static String streamToString(InputStream inputStream, String encoding, int bufferSize) throws IOException { // char[] buffer = new char[bufferSize]; // StringBuilder sb = new StringBuilder(); // try (InputStreamReader reader = new InputStreamReader(inputStream, encoding)) { // while (true) { // int count = reader.read(buffer, 0, bufferSize); // if (count < 0) break; // sb.append(buffer, 0, count); // } // } // return sb.toString(); // } // // public static String streamToString(InputStream inputStream) throws IOException { // return streamToString(inputStream, "UTF-8", 2048); // } // // public static String downloadString(String urlString) throws IOException { // URL url = new URL(urlString); // String ua = String.format("QuoteLock/%s (+%s)", BuildConfig.VERSION_NAME, Urls.GITHUB_QUOTELOCK); // HttpURLConnection connection = (HttpURLConnection)url.openConnection(); // try { // connection.setRequestProperty("User-Agent", ua); // int responseCode = connection.getResponseCode(); // if (responseCode == 200) { // return streamToString(connection.getInputStream()); // } else { // throw new IOException("Server returned non-200 status code: " + responseCode); // } // } finally { // connection.disconnect(); // } // } // }
import com.crossbowffs.quotelock.modules.vnaas.model.VnaasCharacter; import com.crossbowffs.quotelock.modules.vnaas.model.VnaasNovel; import com.crossbowffs.quotelock.modules.vnaas.model.VnaasQuote; import com.crossbowffs.quotelock.utils.IOUtils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException;
package com.crossbowffs.quotelock.modules.vnaas.api; public class VnaasApiManager { private static final String NOVELS_URL = "/novels"; private static final String CHARACTERS_URL = "/characters"; private static final String RANDOM_QUOTE_URL = "/random_quote"; private final String mBaseUrl; public VnaasApiManager(String baseUrl) { mBaseUrl = baseUrl; }
// Path: src/com/crossbowffs/quotelock/modules/vnaas/model/VnaasCharacter.java // public class VnaasCharacter { // private final long mId; // private final String mName; // private final VnaasNovel[] mNovels; // // public VnaasCharacter(long id, String name, VnaasNovel[] novels) { // mId = id; // mName = name; // mNovels = novels; // } // // public long getId() { // return mId; // } // // public String getName() { // return mName; // } // // public VnaasNovel[] getNovels() { // return mNovels; // } // } // // Path: src/com/crossbowffs/quotelock/modules/vnaas/model/VnaasNovel.java // public class VnaasNovel { // private final long mId; // private final String mName; // private final VnaasCharacter[] mCharacters; // // public VnaasNovel(long id, String name, VnaasCharacter[] characters) { // mId = id; // mName = name; // mCharacters = characters; // } // // public long getId() { // return mId; // } // // public String getName() { // return mName; // } // // public VnaasCharacter[] getCharacters() { // return mCharacters; // } // } // // Path: src/com/crossbowffs/quotelock/modules/vnaas/model/VnaasQuote.java // public class VnaasQuote { // private final String mText; // private final VnaasCharacter mCharacter; // private final VnaasNovel mNovel; // // public VnaasQuote(String text, VnaasCharacter character, VnaasNovel novel) { // mText = text; // mCharacter = character; // mNovel = novel; // } // // public String getText() { // return mText; // } // // public VnaasCharacter getCharacter() { // return mCharacter; // } // // public VnaasNovel getNovel() { // return mNovel; // } // } // // Path: src/com/crossbowffs/quotelock/utils/IOUtils.java // public class IOUtils { // public static String streamToString(InputStream inputStream, String encoding, int bufferSize) throws IOException { // char[] buffer = new char[bufferSize]; // StringBuilder sb = new StringBuilder(); // try (InputStreamReader reader = new InputStreamReader(inputStream, encoding)) { // while (true) { // int count = reader.read(buffer, 0, bufferSize); // if (count < 0) break; // sb.append(buffer, 0, count); // } // } // return sb.toString(); // } // // public static String streamToString(InputStream inputStream) throws IOException { // return streamToString(inputStream, "UTF-8", 2048); // } // // public static String downloadString(String urlString) throws IOException { // URL url = new URL(urlString); // String ua = String.format("QuoteLock/%s (+%s)", BuildConfig.VERSION_NAME, Urls.GITHUB_QUOTELOCK); // HttpURLConnection connection = (HttpURLConnection)url.openConnection(); // try { // connection.setRequestProperty("User-Agent", ua); // int responseCode = connection.getResponseCode(); // if (responseCode == 200) { // return streamToString(connection.getInputStream()); // } else { // throw new IOException("Server returned non-200 status code: " + responseCode); // } // } finally { // connection.disconnect(); // } // } // } // Path: src/com/crossbowffs/quotelock/modules/vnaas/api/VnaasApiManager.java import com.crossbowffs.quotelock.modules.vnaas.model.VnaasCharacter; import com.crossbowffs.quotelock.modules.vnaas.model.VnaasNovel; import com.crossbowffs.quotelock.modules.vnaas.model.VnaasQuote; import com.crossbowffs.quotelock.utils.IOUtils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; package com.crossbowffs.quotelock.modules.vnaas.api; public class VnaasApiManager { private static final String NOVELS_URL = "/novels"; private static final String CHARACTERS_URL = "/characters"; private static final String RANDOM_QUOTE_URL = "/random_quote"; private final String mBaseUrl; public VnaasApiManager(String baseUrl) { mBaseUrl = baseUrl; }
public VnaasNovel[] getNovels(VnaasNovelQueryParams params) throws IOException {
apsun/QuoteLock
src/com/crossbowffs/quotelock/modules/vnaas/api/VnaasApiManager.java
// Path: src/com/crossbowffs/quotelock/modules/vnaas/model/VnaasCharacter.java // public class VnaasCharacter { // private final long mId; // private final String mName; // private final VnaasNovel[] mNovels; // // public VnaasCharacter(long id, String name, VnaasNovel[] novels) { // mId = id; // mName = name; // mNovels = novels; // } // // public long getId() { // return mId; // } // // public String getName() { // return mName; // } // // public VnaasNovel[] getNovels() { // return mNovels; // } // } // // Path: src/com/crossbowffs/quotelock/modules/vnaas/model/VnaasNovel.java // public class VnaasNovel { // private final long mId; // private final String mName; // private final VnaasCharacter[] mCharacters; // // public VnaasNovel(long id, String name, VnaasCharacter[] characters) { // mId = id; // mName = name; // mCharacters = characters; // } // // public long getId() { // return mId; // } // // public String getName() { // return mName; // } // // public VnaasCharacter[] getCharacters() { // return mCharacters; // } // } // // Path: src/com/crossbowffs/quotelock/modules/vnaas/model/VnaasQuote.java // public class VnaasQuote { // private final String mText; // private final VnaasCharacter mCharacter; // private final VnaasNovel mNovel; // // public VnaasQuote(String text, VnaasCharacter character, VnaasNovel novel) { // mText = text; // mCharacter = character; // mNovel = novel; // } // // public String getText() { // return mText; // } // // public VnaasCharacter getCharacter() { // return mCharacter; // } // // public VnaasNovel getNovel() { // return mNovel; // } // } // // Path: src/com/crossbowffs/quotelock/utils/IOUtils.java // public class IOUtils { // public static String streamToString(InputStream inputStream, String encoding, int bufferSize) throws IOException { // char[] buffer = new char[bufferSize]; // StringBuilder sb = new StringBuilder(); // try (InputStreamReader reader = new InputStreamReader(inputStream, encoding)) { // while (true) { // int count = reader.read(buffer, 0, bufferSize); // if (count < 0) break; // sb.append(buffer, 0, count); // } // } // return sb.toString(); // } // // public static String streamToString(InputStream inputStream) throws IOException { // return streamToString(inputStream, "UTF-8", 2048); // } // // public static String downloadString(String urlString) throws IOException { // URL url = new URL(urlString); // String ua = String.format("QuoteLock/%s (+%s)", BuildConfig.VERSION_NAME, Urls.GITHUB_QUOTELOCK); // HttpURLConnection connection = (HttpURLConnection)url.openConnection(); // try { // connection.setRequestProperty("User-Agent", ua); // int responseCode = connection.getResponseCode(); // if (responseCode == 200) { // return streamToString(connection.getInputStream()); // } else { // throw new IOException("Server returned non-200 status code: " + responseCode); // } // } finally { // connection.disconnect(); // } // } // }
import com.crossbowffs.quotelock.modules.vnaas.model.VnaasCharacter; import com.crossbowffs.quotelock.modules.vnaas.model.VnaasNovel; import com.crossbowffs.quotelock.modules.vnaas.model.VnaasQuote; import com.crossbowffs.quotelock.utils.IOUtils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException;
package com.crossbowffs.quotelock.modules.vnaas.api; public class VnaasApiManager { private static final String NOVELS_URL = "/novels"; private static final String CHARACTERS_URL = "/characters"; private static final String RANDOM_QUOTE_URL = "/random_quote"; private final String mBaseUrl; public VnaasApiManager(String baseUrl) { mBaseUrl = baseUrl; } public VnaasNovel[] getNovels(VnaasNovelQueryParams params) throws IOException { String url = params.buildUrl(mBaseUrl + NOVELS_URL); JSONArray json = fetchJsonArray(url); try { return jsonArrayToNovels(json); } catch (JSONException e) { throw new IOException(e); } } public VnaasNovel getNovel(long novelId) throws IOException { String url = mBaseUrl + NOVELS_URL + "/" + novelId; JSONObject json = fetchJsonObject(url); try { return jsonToNovel(json); } catch (JSONException e) { throw new IOException(e); } }
// Path: src/com/crossbowffs/quotelock/modules/vnaas/model/VnaasCharacter.java // public class VnaasCharacter { // private final long mId; // private final String mName; // private final VnaasNovel[] mNovels; // // public VnaasCharacter(long id, String name, VnaasNovel[] novels) { // mId = id; // mName = name; // mNovels = novels; // } // // public long getId() { // return mId; // } // // public String getName() { // return mName; // } // // public VnaasNovel[] getNovels() { // return mNovels; // } // } // // Path: src/com/crossbowffs/quotelock/modules/vnaas/model/VnaasNovel.java // public class VnaasNovel { // private final long mId; // private final String mName; // private final VnaasCharacter[] mCharacters; // // public VnaasNovel(long id, String name, VnaasCharacter[] characters) { // mId = id; // mName = name; // mCharacters = characters; // } // // public long getId() { // return mId; // } // // public String getName() { // return mName; // } // // public VnaasCharacter[] getCharacters() { // return mCharacters; // } // } // // Path: src/com/crossbowffs/quotelock/modules/vnaas/model/VnaasQuote.java // public class VnaasQuote { // private final String mText; // private final VnaasCharacter mCharacter; // private final VnaasNovel mNovel; // // public VnaasQuote(String text, VnaasCharacter character, VnaasNovel novel) { // mText = text; // mCharacter = character; // mNovel = novel; // } // // public String getText() { // return mText; // } // // public VnaasCharacter getCharacter() { // return mCharacter; // } // // public VnaasNovel getNovel() { // return mNovel; // } // } // // Path: src/com/crossbowffs/quotelock/utils/IOUtils.java // public class IOUtils { // public static String streamToString(InputStream inputStream, String encoding, int bufferSize) throws IOException { // char[] buffer = new char[bufferSize]; // StringBuilder sb = new StringBuilder(); // try (InputStreamReader reader = new InputStreamReader(inputStream, encoding)) { // while (true) { // int count = reader.read(buffer, 0, bufferSize); // if (count < 0) break; // sb.append(buffer, 0, count); // } // } // return sb.toString(); // } // // public static String streamToString(InputStream inputStream) throws IOException { // return streamToString(inputStream, "UTF-8", 2048); // } // // public static String downloadString(String urlString) throws IOException { // URL url = new URL(urlString); // String ua = String.format("QuoteLock/%s (+%s)", BuildConfig.VERSION_NAME, Urls.GITHUB_QUOTELOCK); // HttpURLConnection connection = (HttpURLConnection)url.openConnection(); // try { // connection.setRequestProperty("User-Agent", ua); // int responseCode = connection.getResponseCode(); // if (responseCode == 200) { // return streamToString(connection.getInputStream()); // } else { // throw new IOException("Server returned non-200 status code: " + responseCode); // } // } finally { // connection.disconnect(); // } // } // } // Path: src/com/crossbowffs/quotelock/modules/vnaas/api/VnaasApiManager.java import com.crossbowffs.quotelock.modules.vnaas.model.VnaasCharacter; import com.crossbowffs.quotelock.modules.vnaas.model.VnaasNovel; import com.crossbowffs.quotelock.modules.vnaas.model.VnaasQuote; import com.crossbowffs.quotelock.utils.IOUtils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; package com.crossbowffs.quotelock.modules.vnaas.api; public class VnaasApiManager { private static final String NOVELS_URL = "/novels"; private static final String CHARACTERS_URL = "/characters"; private static final String RANDOM_QUOTE_URL = "/random_quote"; private final String mBaseUrl; public VnaasApiManager(String baseUrl) { mBaseUrl = baseUrl; } public VnaasNovel[] getNovels(VnaasNovelQueryParams params) throws IOException { String url = params.buildUrl(mBaseUrl + NOVELS_URL); JSONArray json = fetchJsonArray(url); try { return jsonArrayToNovels(json); } catch (JSONException e) { throw new IOException(e); } } public VnaasNovel getNovel(long novelId) throws IOException { String url = mBaseUrl + NOVELS_URL + "/" + novelId; JSONObject json = fetchJsonObject(url); try { return jsonToNovel(json); } catch (JSONException e) { throw new IOException(e); } }
public VnaasCharacter[] getCharacters(VnaasCharacterQueryParams params) throws IOException {
apsun/QuoteLock
src/com/crossbowffs/quotelock/modules/vnaas/api/VnaasApiManager.java
// Path: src/com/crossbowffs/quotelock/modules/vnaas/model/VnaasCharacter.java // public class VnaasCharacter { // private final long mId; // private final String mName; // private final VnaasNovel[] mNovels; // // public VnaasCharacter(long id, String name, VnaasNovel[] novels) { // mId = id; // mName = name; // mNovels = novels; // } // // public long getId() { // return mId; // } // // public String getName() { // return mName; // } // // public VnaasNovel[] getNovels() { // return mNovels; // } // } // // Path: src/com/crossbowffs/quotelock/modules/vnaas/model/VnaasNovel.java // public class VnaasNovel { // private final long mId; // private final String mName; // private final VnaasCharacter[] mCharacters; // // public VnaasNovel(long id, String name, VnaasCharacter[] characters) { // mId = id; // mName = name; // mCharacters = characters; // } // // public long getId() { // return mId; // } // // public String getName() { // return mName; // } // // public VnaasCharacter[] getCharacters() { // return mCharacters; // } // } // // Path: src/com/crossbowffs/quotelock/modules/vnaas/model/VnaasQuote.java // public class VnaasQuote { // private final String mText; // private final VnaasCharacter mCharacter; // private final VnaasNovel mNovel; // // public VnaasQuote(String text, VnaasCharacter character, VnaasNovel novel) { // mText = text; // mCharacter = character; // mNovel = novel; // } // // public String getText() { // return mText; // } // // public VnaasCharacter getCharacter() { // return mCharacter; // } // // public VnaasNovel getNovel() { // return mNovel; // } // } // // Path: src/com/crossbowffs/quotelock/utils/IOUtils.java // public class IOUtils { // public static String streamToString(InputStream inputStream, String encoding, int bufferSize) throws IOException { // char[] buffer = new char[bufferSize]; // StringBuilder sb = new StringBuilder(); // try (InputStreamReader reader = new InputStreamReader(inputStream, encoding)) { // while (true) { // int count = reader.read(buffer, 0, bufferSize); // if (count < 0) break; // sb.append(buffer, 0, count); // } // } // return sb.toString(); // } // // public static String streamToString(InputStream inputStream) throws IOException { // return streamToString(inputStream, "UTF-8", 2048); // } // // public static String downloadString(String urlString) throws IOException { // URL url = new URL(urlString); // String ua = String.format("QuoteLock/%s (+%s)", BuildConfig.VERSION_NAME, Urls.GITHUB_QUOTELOCK); // HttpURLConnection connection = (HttpURLConnection)url.openConnection(); // try { // connection.setRequestProperty("User-Agent", ua); // int responseCode = connection.getResponseCode(); // if (responseCode == 200) { // return streamToString(connection.getInputStream()); // } else { // throw new IOException("Server returned non-200 status code: " + responseCode); // } // } finally { // connection.disconnect(); // } // } // }
import com.crossbowffs.quotelock.modules.vnaas.model.VnaasCharacter; import com.crossbowffs.quotelock.modules.vnaas.model.VnaasNovel; import com.crossbowffs.quotelock.modules.vnaas.model.VnaasQuote; import com.crossbowffs.quotelock.utils.IOUtils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException;
public VnaasNovel getNovel(long novelId) throws IOException { String url = mBaseUrl + NOVELS_URL + "/" + novelId; JSONObject json = fetchJsonObject(url); try { return jsonToNovel(json); } catch (JSONException e) { throw new IOException(e); } } public VnaasCharacter[] getCharacters(VnaasCharacterQueryParams params) throws IOException { String url = params.buildUrl(mBaseUrl + CHARACTERS_URL); JSONArray json = fetchJsonArray(url); try { return jsonArrayToCharacters(json); } catch (JSONException e) { throw new IOException(e); } } public VnaasCharacter getCharacter(long characterId) throws IOException { String url = mBaseUrl + CHARACTERS_URL + "/" + characterId; JSONObject json = fetchJsonObject(url); try { return jsonToCharacter(json); } catch (JSONException e) { throw new IOException(e); } }
// Path: src/com/crossbowffs/quotelock/modules/vnaas/model/VnaasCharacter.java // public class VnaasCharacter { // private final long mId; // private final String mName; // private final VnaasNovel[] mNovels; // // public VnaasCharacter(long id, String name, VnaasNovel[] novels) { // mId = id; // mName = name; // mNovels = novels; // } // // public long getId() { // return mId; // } // // public String getName() { // return mName; // } // // public VnaasNovel[] getNovels() { // return mNovels; // } // } // // Path: src/com/crossbowffs/quotelock/modules/vnaas/model/VnaasNovel.java // public class VnaasNovel { // private final long mId; // private final String mName; // private final VnaasCharacter[] mCharacters; // // public VnaasNovel(long id, String name, VnaasCharacter[] characters) { // mId = id; // mName = name; // mCharacters = characters; // } // // public long getId() { // return mId; // } // // public String getName() { // return mName; // } // // public VnaasCharacter[] getCharacters() { // return mCharacters; // } // } // // Path: src/com/crossbowffs/quotelock/modules/vnaas/model/VnaasQuote.java // public class VnaasQuote { // private final String mText; // private final VnaasCharacter mCharacter; // private final VnaasNovel mNovel; // // public VnaasQuote(String text, VnaasCharacter character, VnaasNovel novel) { // mText = text; // mCharacter = character; // mNovel = novel; // } // // public String getText() { // return mText; // } // // public VnaasCharacter getCharacter() { // return mCharacter; // } // // public VnaasNovel getNovel() { // return mNovel; // } // } // // Path: src/com/crossbowffs/quotelock/utils/IOUtils.java // public class IOUtils { // public static String streamToString(InputStream inputStream, String encoding, int bufferSize) throws IOException { // char[] buffer = new char[bufferSize]; // StringBuilder sb = new StringBuilder(); // try (InputStreamReader reader = new InputStreamReader(inputStream, encoding)) { // while (true) { // int count = reader.read(buffer, 0, bufferSize); // if (count < 0) break; // sb.append(buffer, 0, count); // } // } // return sb.toString(); // } // // public static String streamToString(InputStream inputStream) throws IOException { // return streamToString(inputStream, "UTF-8", 2048); // } // // public static String downloadString(String urlString) throws IOException { // URL url = new URL(urlString); // String ua = String.format("QuoteLock/%s (+%s)", BuildConfig.VERSION_NAME, Urls.GITHUB_QUOTELOCK); // HttpURLConnection connection = (HttpURLConnection)url.openConnection(); // try { // connection.setRequestProperty("User-Agent", ua); // int responseCode = connection.getResponseCode(); // if (responseCode == 200) { // return streamToString(connection.getInputStream()); // } else { // throw new IOException("Server returned non-200 status code: " + responseCode); // } // } finally { // connection.disconnect(); // } // } // } // Path: src/com/crossbowffs/quotelock/modules/vnaas/api/VnaasApiManager.java import com.crossbowffs.quotelock.modules.vnaas.model.VnaasCharacter; import com.crossbowffs.quotelock.modules.vnaas.model.VnaasNovel; import com.crossbowffs.quotelock.modules.vnaas.model.VnaasQuote; import com.crossbowffs.quotelock.utils.IOUtils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; public VnaasNovel getNovel(long novelId) throws IOException { String url = mBaseUrl + NOVELS_URL + "/" + novelId; JSONObject json = fetchJsonObject(url); try { return jsonToNovel(json); } catch (JSONException e) { throw new IOException(e); } } public VnaasCharacter[] getCharacters(VnaasCharacterQueryParams params) throws IOException { String url = params.buildUrl(mBaseUrl + CHARACTERS_URL); JSONArray json = fetchJsonArray(url); try { return jsonArrayToCharacters(json); } catch (JSONException e) { throw new IOException(e); } } public VnaasCharacter getCharacter(long characterId) throws IOException { String url = mBaseUrl + CHARACTERS_URL + "/" + characterId; JSONObject json = fetchJsonObject(url); try { return jsonToCharacter(json); } catch (JSONException e) { throw new IOException(e); } }
public VnaasQuote getRandomQuote(VnaasQuoteQueryParams params) throws IOException {
apsun/QuoteLock
src/com/crossbowffs/quotelock/modules/vnaas/api/VnaasApiManager.java
// Path: src/com/crossbowffs/quotelock/modules/vnaas/model/VnaasCharacter.java // public class VnaasCharacter { // private final long mId; // private final String mName; // private final VnaasNovel[] mNovels; // // public VnaasCharacter(long id, String name, VnaasNovel[] novels) { // mId = id; // mName = name; // mNovels = novels; // } // // public long getId() { // return mId; // } // // public String getName() { // return mName; // } // // public VnaasNovel[] getNovels() { // return mNovels; // } // } // // Path: src/com/crossbowffs/quotelock/modules/vnaas/model/VnaasNovel.java // public class VnaasNovel { // private final long mId; // private final String mName; // private final VnaasCharacter[] mCharacters; // // public VnaasNovel(long id, String name, VnaasCharacter[] characters) { // mId = id; // mName = name; // mCharacters = characters; // } // // public long getId() { // return mId; // } // // public String getName() { // return mName; // } // // public VnaasCharacter[] getCharacters() { // return mCharacters; // } // } // // Path: src/com/crossbowffs/quotelock/modules/vnaas/model/VnaasQuote.java // public class VnaasQuote { // private final String mText; // private final VnaasCharacter mCharacter; // private final VnaasNovel mNovel; // // public VnaasQuote(String text, VnaasCharacter character, VnaasNovel novel) { // mText = text; // mCharacter = character; // mNovel = novel; // } // // public String getText() { // return mText; // } // // public VnaasCharacter getCharacter() { // return mCharacter; // } // // public VnaasNovel getNovel() { // return mNovel; // } // } // // Path: src/com/crossbowffs/quotelock/utils/IOUtils.java // public class IOUtils { // public static String streamToString(InputStream inputStream, String encoding, int bufferSize) throws IOException { // char[] buffer = new char[bufferSize]; // StringBuilder sb = new StringBuilder(); // try (InputStreamReader reader = new InputStreamReader(inputStream, encoding)) { // while (true) { // int count = reader.read(buffer, 0, bufferSize); // if (count < 0) break; // sb.append(buffer, 0, count); // } // } // return sb.toString(); // } // // public static String streamToString(InputStream inputStream) throws IOException { // return streamToString(inputStream, "UTF-8", 2048); // } // // public static String downloadString(String urlString) throws IOException { // URL url = new URL(urlString); // String ua = String.format("QuoteLock/%s (+%s)", BuildConfig.VERSION_NAME, Urls.GITHUB_QUOTELOCK); // HttpURLConnection connection = (HttpURLConnection)url.openConnection(); // try { // connection.setRequestProperty("User-Agent", ua); // int responseCode = connection.getResponseCode(); // if (responseCode == 200) { // return streamToString(connection.getInputStream()); // } else { // throw new IOException("Server returned non-200 status code: " + responseCode); // } // } finally { // connection.disconnect(); // } // } // }
import com.crossbowffs.quotelock.modules.vnaas.model.VnaasCharacter; import com.crossbowffs.quotelock.modules.vnaas.model.VnaasNovel; import com.crossbowffs.quotelock.modules.vnaas.model.VnaasQuote; import com.crossbowffs.quotelock.utils.IOUtils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException;
String url = params.buildUrl(mBaseUrl + CHARACTERS_URL); JSONArray json = fetchJsonArray(url); try { return jsonArrayToCharacters(json); } catch (JSONException e) { throw new IOException(e); } } public VnaasCharacter getCharacter(long characterId) throws IOException { String url = mBaseUrl + CHARACTERS_URL + "/" + characterId; JSONObject json = fetchJsonObject(url); try { return jsonToCharacter(json); } catch (JSONException e) { throw new IOException(e); } } public VnaasQuote getRandomQuote(VnaasQuoteQueryParams params) throws IOException { String url = params.buildUrl(mBaseUrl + RANDOM_QUOTE_URL); JSONObject json = fetchJsonObject(url); try { return jsonToQuote(json); } catch (JSONException e) { throw new IOException(e); } } private JSONObject fetchJsonObject(String urlString) throws IOException {
// Path: src/com/crossbowffs/quotelock/modules/vnaas/model/VnaasCharacter.java // public class VnaasCharacter { // private final long mId; // private final String mName; // private final VnaasNovel[] mNovels; // // public VnaasCharacter(long id, String name, VnaasNovel[] novels) { // mId = id; // mName = name; // mNovels = novels; // } // // public long getId() { // return mId; // } // // public String getName() { // return mName; // } // // public VnaasNovel[] getNovels() { // return mNovels; // } // } // // Path: src/com/crossbowffs/quotelock/modules/vnaas/model/VnaasNovel.java // public class VnaasNovel { // private final long mId; // private final String mName; // private final VnaasCharacter[] mCharacters; // // public VnaasNovel(long id, String name, VnaasCharacter[] characters) { // mId = id; // mName = name; // mCharacters = characters; // } // // public long getId() { // return mId; // } // // public String getName() { // return mName; // } // // public VnaasCharacter[] getCharacters() { // return mCharacters; // } // } // // Path: src/com/crossbowffs/quotelock/modules/vnaas/model/VnaasQuote.java // public class VnaasQuote { // private final String mText; // private final VnaasCharacter mCharacter; // private final VnaasNovel mNovel; // // public VnaasQuote(String text, VnaasCharacter character, VnaasNovel novel) { // mText = text; // mCharacter = character; // mNovel = novel; // } // // public String getText() { // return mText; // } // // public VnaasCharacter getCharacter() { // return mCharacter; // } // // public VnaasNovel getNovel() { // return mNovel; // } // } // // Path: src/com/crossbowffs/quotelock/utils/IOUtils.java // public class IOUtils { // public static String streamToString(InputStream inputStream, String encoding, int bufferSize) throws IOException { // char[] buffer = new char[bufferSize]; // StringBuilder sb = new StringBuilder(); // try (InputStreamReader reader = new InputStreamReader(inputStream, encoding)) { // while (true) { // int count = reader.read(buffer, 0, bufferSize); // if (count < 0) break; // sb.append(buffer, 0, count); // } // } // return sb.toString(); // } // // public static String streamToString(InputStream inputStream) throws IOException { // return streamToString(inputStream, "UTF-8", 2048); // } // // public static String downloadString(String urlString) throws IOException { // URL url = new URL(urlString); // String ua = String.format("QuoteLock/%s (+%s)", BuildConfig.VERSION_NAME, Urls.GITHUB_QUOTELOCK); // HttpURLConnection connection = (HttpURLConnection)url.openConnection(); // try { // connection.setRequestProperty("User-Agent", ua); // int responseCode = connection.getResponseCode(); // if (responseCode == 200) { // return streamToString(connection.getInputStream()); // } else { // throw new IOException("Server returned non-200 status code: " + responseCode); // } // } finally { // connection.disconnect(); // } // } // } // Path: src/com/crossbowffs/quotelock/modules/vnaas/api/VnaasApiManager.java import com.crossbowffs.quotelock.modules.vnaas.model.VnaasCharacter; import com.crossbowffs.quotelock.modules.vnaas.model.VnaasNovel; import com.crossbowffs.quotelock.modules.vnaas.model.VnaasQuote; import com.crossbowffs.quotelock.utils.IOUtils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; String url = params.buildUrl(mBaseUrl + CHARACTERS_URL); JSONArray json = fetchJsonArray(url); try { return jsonArrayToCharacters(json); } catch (JSONException e) { throw new IOException(e); } } public VnaasCharacter getCharacter(long characterId) throws IOException { String url = mBaseUrl + CHARACTERS_URL + "/" + characterId; JSONObject json = fetchJsonObject(url); try { return jsonToCharacter(json); } catch (JSONException e) { throw new IOException(e); } } public VnaasQuote getRandomQuote(VnaasQuoteQueryParams params) throws IOException { String url = params.buildUrl(mBaseUrl + RANDOM_QUOTE_URL); JSONObject json = fetchJsonObject(url); try { return jsonToQuote(json); } catch (JSONException e) { throw new IOException(e); } } private JSONObject fetchJsonObject(String urlString) throws IOException {
String jsonString = IOUtils.downloadString(urlString);
apsun/QuoteLock
src/com/crossbowffs/quotelock/modules/custom/app/CustomQuoteConfigActivity.java
// Path: src/com/crossbowffs/quotelock/api/QuoteData.java // public class QuoteData { // private final String mQuoteText; // private final String mQuoteSource; // // /** // * Creates a new quote data object. The parameters may be {@code null}, // * in which case they are replaced with an empty string. // * // * @param quoteText The first line (text) of the quote. // * @param quoteSource The second line (author) of the quote. // */ // public QuoteData(String quoteText, String quoteSource) { // mQuoteText = quoteText; // mQuoteSource = quoteSource; // } // // /** // * Gets the first line of the quote. Will not be {@code null}. // */ // public String getQuoteText() { // String text = mQuoteText; // if (text == null) { // text = ""; // } // return text; // } // // /** // * Gets the second line of the quote. Will not be {@code null}. // */ // public String getQuoteSource() { // String source = mQuoteSource; // if (source == null) { // source = ""; // } // return source; // } // } // // Path: src/com/crossbowffs/quotelock/modules/custom/provider/CustomQuoteContract.java // public class CustomQuoteContract { // public static final String AUTHORITY = BuildConfig.APPLICATION_ID + ".modules.custom.provider"; // public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY); // // public static class Quotes implements BaseColumns { // public static final String TABLE = "quotes"; // public static final Uri CONTENT_URI = Uri.withAppendedPath(CustomQuoteContract.CONTENT_URI, TABLE); // public static final String CONTENT_TYPE = ContentResolver.CURSOR_DIR_BASE_TYPE + "/vnd.crossbowffs.quote"; // public static final String CONTENT_ITEM_TYPE = ContentResolver.CURSOR_ITEM_BASE_TYPE + "/vnd.crossbowffs.quote"; // // public static final String TEXT = "text"; // public static final String SOURCE = "source"; // public static final String[] ALL = { // _ID, // TEXT, // SOURCE // }; // } // }
import android.app.AlertDialog; import android.app.ListActivity; import android.app.LoaderManager; import android.content.*; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.text.Editable; import android.text.TextUtils; import android.text.TextWatcher; import android.view.*; import android.widget.*; import com.crossbowffs.quotelock.R; import com.crossbowffs.quotelock.api.QuoteData; import com.crossbowffs.quotelock.modules.custom.provider.CustomQuoteContract;
package com.crossbowffs.quotelock.modules.custom.app; public class CustomQuoteConfigActivity extends ListActivity implements LoaderManager.LoaderCallbacks<Cursor> { private SimpleCursorAdapter mAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
// Path: src/com/crossbowffs/quotelock/api/QuoteData.java // public class QuoteData { // private final String mQuoteText; // private final String mQuoteSource; // // /** // * Creates a new quote data object. The parameters may be {@code null}, // * in which case they are replaced with an empty string. // * // * @param quoteText The first line (text) of the quote. // * @param quoteSource The second line (author) of the quote. // */ // public QuoteData(String quoteText, String quoteSource) { // mQuoteText = quoteText; // mQuoteSource = quoteSource; // } // // /** // * Gets the first line of the quote. Will not be {@code null}. // */ // public String getQuoteText() { // String text = mQuoteText; // if (text == null) { // text = ""; // } // return text; // } // // /** // * Gets the second line of the quote. Will not be {@code null}. // */ // public String getQuoteSource() { // String source = mQuoteSource; // if (source == null) { // source = ""; // } // return source; // } // } // // Path: src/com/crossbowffs/quotelock/modules/custom/provider/CustomQuoteContract.java // public class CustomQuoteContract { // public static final String AUTHORITY = BuildConfig.APPLICATION_ID + ".modules.custom.provider"; // public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY); // // public static class Quotes implements BaseColumns { // public static final String TABLE = "quotes"; // public static final Uri CONTENT_URI = Uri.withAppendedPath(CustomQuoteContract.CONTENT_URI, TABLE); // public static final String CONTENT_TYPE = ContentResolver.CURSOR_DIR_BASE_TYPE + "/vnd.crossbowffs.quote"; // public static final String CONTENT_ITEM_TYPE = ContentResolver.CURSOR_ITEM_BASE_TYPE + "/vnd.crossbowffs.quote"; // // public static final String TEXT = "text"; // public static final String SOURCE = "source"; // public static final String[] ALL = { // _ID, // TEXT, // SOURCE // }; // } // } // Path: src/com/crossbowffs/quotelock/modules/custom/app/CustomQuoteConfigActivity.java import android.app.AlertDialog; import android.app.ListActivity; import android.app.LoaderManager; import android.content.*; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.text.Editable; import android.text.TextUtils; import android.text.TextWatcher; import android.view.*; import android.widget.*; import com.crossbowffs.quotelock.R; import com.crossbowffs.quotelock.api.QuoteData; import com.crossbowffs.quotelock.modules.custom.provider.CustomQuoteContract; package com.crossbowffs.quotelock.modules.custom.app; public class CustomQuoteConfigActivity extends ListActivity implements LoaderManager.LoaderCallbacks<Cursor> { private SimpleCursorAdapter mAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
String[] from = {CustomQuoteContract.Quotes.TEXT, CustomQuoteContract.Quotes.SOURCE};
apsun/QuoteLock
src/com/crossbowffs/quotelock/modules/custom/app/CustomQuoteConfigActivity.java
// Path: src/com/crossbowffs/quotelock/api/QuoteData.java // public class QuoteData { // private final String mQuoteText; // private final String mQuoteSource; // // /** // * Creates a new quote data object. The parameters may be {@code null}, // * in which case they are replaced with an empty string. // * // * @param quoteText The first line (text) of the quote. // * @param quoteSource The second line (author) of the quote. // */ // public QuoteData(String quoteText, String quoteSource) { // mQuoteText = quoteText; // mQuoteSource = quoteSource; // } // // /** // * Gets the first line of the quote. Will not be {@code null}. // */ // public String getQuoteText() { // String text = mQuoteText; // if (text == null) { // text = ""; // } // return text; // } // // /** // * Gets the second line of the quote. Will not be {@code null}. // */ // public String getQuoteSource() { // String source = mQuoteSource; // if (source == null) { // source = ""; // } // return source; // } // } // // Path: src/com/crossbowffs/quotelock/modules/custom/provider/CustomQuoteContract.java // public class CustomQuoteContract { // public static final String AUTHORITY = BuildConfig.APPLICATION_ID + ".modules.custom.provider"; // public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY); // // public static class Quotes implements BaseColumns { // public static final String TABLE = "quotes"; // public static final Uri CONTENT_URI = Uri.withAppendedPath(CustomQuoteContract.CONTENT_URI, TABLE); // public static final String CONTENT_TYPE = ContentResolver.CURSOR_DIR_BASE_TYPE + "/vnd.crossbowffs.quote"; // public static final String CONTENT_ITEM_TYPE = ContentResolver.CURSOR_ITEM_BASE_TYPE + "/vnd.crossbowffs.quote"; // // public static final String TEXT = "text"; // public static final String SOURCE = "source"; // public static final String[] ALL = { // _ID, // TEXT, // SOURCE // }; // } // }
import android.app.AlertDialog; import android.app.ListActivity; import android.app.LoaderManager; import android.content.*; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.text.Editable; import android.text.TextUtils; import android.text.TextWatcher; import android.view.*; import android.widget.*; import com.crossbowffs.quotelock.R; import com.crossbowffs.quotelock.api.QuoteData; import com.crossbowffs.quotelock.modules.custom.provider.CustomQuoteContract;
switch (item.getItemId()) { case R.id.edit_quote: showEditQuoteDialog(rowId); return true; case R.id.delete_quote: deleteQuote(rowId); return true; default: return super.onContextItemSelected(item); } } @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { return new CursorLoader(this, CustomQuoteContract.Quotes.CONTENT_URI, CustomQuoteContract.Quotes.ALL, null, null, null); } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { mAdapter.changeCursor(data); } @Override public void onLoaderReset(Loader<Cursor> loader) { mAdapter.changeCursor(null); }
// Path: src/com/crossbowffs/quotelock/api/QuoteData.java // public class QuoteData { // private final String mQuoteText; // private final String mQuoteSource; // // /** // * Creates a new quote data object. The parameters may be {@code null}, // * in which case they are replaced with an empty string. // * // * @param quoteText The first line (text) of the quote. // * @param quoteSource The second line (author) of the quote. // */ // public QuoteData(String quoteText, String quoteSource) { // mQuoteText = quoteText; // mQuoteSource = quoteSource; // } // // /** // * Gets the first line of the quote. Will not be {@code null}. // */ // public String getQuoteText() { // String text = mQuoteText; // if (text == null) { // text = ""; // } // return text; // } // // /** // * Gets the second line of the quote. Will not be {@code null}. // */ // public String getQuoteSource() { // String source = mQuoteSource; // if (source == null) { // source = ""; // } // return source; // } // } // // Path: src/com/crossbowffs/quotelock/modules/custom/provider/CustomQuoteContract.java // public class CustomQuoteContract { // public static final String AUTHORITY = BuildConfig.APPLICATION_ID + ".modules.custom.provider"; // public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY); // // public static class Quotes implements BaseColumns { // public static final String TABLE = "quotes"; // public static final Uri CONTENT_URI = Uri.withAppendedPath(CustomQuoteContract.CONTENT_URI, TABLE); // public static final String CONTENT_TYPE = ContentResolver.CURSOR_DIR_BASE_TYPE + "/vnd.crossbowffs.quote"; // public static final String CONTENT_ITEM_TYPE = ContentResolver.CURSOR_ITEM_BASE_TYPE + "/vnd.crossbowffs.quote"; // // public static final String TEXT = "text"; // public static final String SOURCE = "source"; // public static final String[] ALL = { // _ID, // TEXT, // SOURCE // }; // } // } // Path: src/com/crossbowffs/quotelock/modules/custom/app/CustomQuoteConfigActivity.java import android.app.AlertDialog; import android.app.ListActivity; import android.app.LoaderManager; import android.content.*; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.text.Editable; import android.text.TextUtils; import android.text.TextWatcher; import android.view.*; import android.widget.*; import com.crossbowffs.quotelock.R; import com.crossbowffs.quotelock.api.QuoteData; import com.crossbowffs.quotelock.modules.custom.provider.CustomQuoteContract; switch (item.getItemId()) { case R.id.edit_quote: showEditQuoteDialog(rowId); return true; case R.id.delete_quote: deleteQuote(rowId); return true; default: return super.onContextItemSelected(item); } } @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { return new CursorLoader(this, CustomQuoteContract.Quotes.CONTENT_URI, CustomQuoteContract.Quotes.ALL, null, null, null); } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { mAdapter.changeCursor(data); } @Override public void onLoaderReset(Loader<Cursor> loader) { mAdapter.changeCursor(null); }
private QuoteData queryQuote(long rowId) {
apsun/QuoteLock
src/com/crossbowffs/quotelock/xposed/LockscreenHook.java
// Path: src/com/crossbowffs/quotelock/consts/PrefKeys.java // public final class PrefKeys { // public static final String PREF_COMMON = "common"; // public static final String PREF_COMMON_REFRESH_RATE = "pref_common_refresh_rate"; // public static final String PREF_COMMON_REFRESH_RATE_DEFAULT = "900"; // public static final String PREF_COMMON_UNMETERED_ONLY = "pref_common_unmetered_only"; // public static final boolean PREF_COMMON_UNMETERED_ONLY_DEFAULT = false; // public static final String PREF_COMMON_QUOTE_MODULE = "pref_common_quote_module"; // public static final String PREF_COMMON_QUOTE_MODULE_DEFAULT = VnaasQuoteModule.class.getName(); // public static final String PREF_COMMON_MODULE_PREFERENCES = "pref_module_preferences"; // public static final String PREF_COMMON_REQUIRES_INTERNET = "pref_common_requires_internet"; // public static final String PREF_COMMON_REFRESH_RATE_OVERRIDE = "pref_common_refresh_rate_override"; // public static final String PREF_COMMON_FONT_SIZE_TEXT = "pref_common_font_size_text"; // public static final String PREF_COMMON_FONT_SIZE_TEXT_DEFAULT = "20"; // public static final String PREF_COMMON_FONT_SIZE_SOURCE = "pref_common_font_size_source"; // public static final String PREF_COMMON_FONT_SIZE_SOURCE_DEFAULT = "18"; // // public static final String PREF_QUOTES = "quotes"; // public static final String PREF_QUOTES_TEXT = "pref_quotes_text"; // public static final String PREF_QUOTES_SOURCE = "pref_quotes_source"; // public static final String PREF_QUOTES_LAST_UPDATED = "pref_quotes_last_updated"; // // public static final String PREF_ABOUT_CREDITS = "pref_about_credits"; // public static final String PREF_ABOUT_GITHUB = "pref_about_github"; // public static final String PREF_ABOUT_VERSION = "pref_about_version"; // // private PrefKeys() { } // } // // Path: src/com/crossbowffs/quotelock/provider/PreferenceProvider.java // public class PreferenceProvider extends RemotePreferenceProvider { // public static final String AUTHORITY = BuildConfig.APPLICATION_ID + ".preferences"; // // public PreferenceProvider() { // super(AUTHORITY, new String[] {PrefKeys.PREF_COMMON, PrefKeys.PREF_QUOTES}); // } // // @Override // protected boolean checkAccess(String prefName, String prefKey, boolean write) { // return !write; // } // } // // Path: src/com/crossbowffs/quotelock/utils/Xlog.java // public final class Xlog { // private static final String LOG_TAG = BuildConfig.LOG_TAG; // private static final int LOG_LEVEL = BuildConfig.LOG_LEVEL; // private static final boolean LOG_TO_XPOSED = BuildConfig.LOG_TO_XPOSED; // // private Xlog() { } // // private static void log(int priority, String tag, String message, Object... args) { // if (priority < LOG_LEVEL) { // return; // } // // message = String.format(message, args); // if (args.length > 0 && args[args.length - 1] instanceof Throwable) { // Throwable throwable = (Throwable)args[args.length - 1]; // String stacktraceStr = Log.getStackTraceString(throwable); // message = message + '\n' + stacktraceStr; // } // // Log.println(priority, LOG_TAG, tag + ": " + message); // if (LOG_TO_XPOSED) { // Log.println(priority, "Xposed", LOG_TAG + ": " + tag + ": " + message); // } // } // // public static void v(String tag, String message, Object... args) { // log(Log.VERBOSE, tag, message, args); // } // // public static void d(String tag, String message, Object... args) { // log(Log.DEBUG, tag, message, args); // } // // public static void i(String tag, String message, Object... args) { // log(Log.INFO, tag, message, args); // } // // public static void w(String tag, String message, Object... args) { // log(Log.WARN, tag, message, args); // } // // public static void e(String tag, String message, Object... args) { // log(Log.ERROR, tag, message, args); // } // }
import android.content.Context; import android.content.SharedPreferences; import android.content.res.Resources; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.widget.GridLayout; import android.widget.TextView; import com.crossbowffs.quotelock.consts.PrefKeys; import com.crossbowffs.quotelock.provider.PreferenceProvider; import com.crossbowffs.quotelock.utils.Xlog; import com.crossbowffs.remotepreferences.RemotePreferences; import de.robv.android.xposed.*; import de.robv.android.xposed.callbacks.XC_InitPackageResources; import de.robv.android.xposed.callbacks.XC_LoadPackage; import org.xmlpull.v1.XmlPullParser;
package com.crossbowffs.quotelock.xposed; public class LockscreenHook implements IXposedHookZygoteInit, IXposedHookInitPackageResources, IXposedHookLoadPackage, SharedPreferences.OnSharedPreferenceChangeListener { private static final String TAG = LockscreenHook.class.getSimpleName(); private static final String RES_LAYOUT_QUOTE_LAYOUT = "quote_layout"; private static final String RES_STRING_OPEN_APP_1 = "open_quotelock_app_line1"; private static final String RES_STRING_OPEN_APP_2 = "open_quotelock_app_line2"; private static final String RES_ID_QUOTE_TEXTVIEW = "quote_textview"; private static final String RES_ID_SOURCE_TEXTVIEW = "source_textview"; private static String sModulePath; private static XSafeModuleResources sModuleRes; private TextView mQuoteTextView; private TextView mSourceTextView; private RemotePreferences mCommonPrefs; private RemotePreferences mQuotePrefs; private void refreshQuote() {
// Path: src/com/crossbowffs/quotelock/consts/PrefKeys.java // public final class PrefKeys { // public static final String PREF_COMMON = "common"; // public static final String PREF_COMMON_REFRESH_RATE = "pref_common_refresh_rate"; // public static final String PREF_COMMON_REFRESH_RATE_DEFAULT = "900"; // public static final String PREF_COMMON_UNMETERED_ONLY = "pref_common_unmetered_only"; // public static final boolean PREF_COMMON_UNMETERED_ONLY_DEFAULT = false; // public static final String PREF_COMMON_QUOTE_MODULE = "pref_common_quote_module"; // public static final String PREF_COMMON_QUOTE_MODULE_DEFAULT = VnaasQuoteModule.class.getName(); // public static final String PREF_COMMON_MODULE_PREFERENCES = "pref_module_preferences"; // public static final String PREF_COMMON_REQUIRES_INTERNET = "pref_common_requires_internet"; // public static final String PREF_COMMON_REFRESH_RATE_OVERRIDE = "pref_common_refresh_rate_override"; // public static final String PREF_COMMON_FONT_SIZE_TEXT = "pref_common_font_size_text"; // public static final String PREF_COMMON_FONT_SIZE_TEXT_DEFAULT = "20"; // public static final String PREF_COMMON_FONT_SIZE_SOURCE = "pref_common_font_size_source"; // public static final String PREF_COMMON_FONT_SIZE_SOURCE_DEFAULT = "18"; // // public static final String PREF_QUOTES = "quotes"; // public static final String PREF_QUOTES_TEXT = "pref_quotes_text"; // public static final String PREF_QUOTES_SOURCE = "pref_quotes_source"; // public static final String PREF_QUOTES_LAST_UPDATED = "pref_quotes_last_updated"; // // public static final String PREF_ABOUT_CREDITS = "pref_about_credits"; // public static final String PREF_ABOUT_GITHUB = "pref_about_github"; // public static final String PREF_ABOUT_VERSION = "pref_about_version"; // // private PrefKeys() { } // } // // Path: src/com/crossbowffs/quotelock/provider/PreferenceProvider.java // public class PreferenceProvider extends RemotePreferenceProvider { // public static final String AUTHORITY = BuildConfig.APPLICATION_ID + ".preferences"; // // public PreferenceProvider() { // super(AUTHORITY, new String[] {PrefKeys.PREF_COMMON, PrefKeys.PREF_QUOTES}); // } // // @Override // protected boolean checkAccess(String prefName, String prefKey, boolean write) { // return !write; // } // } // // Path: src/com/crossbowffs/quotelock/utils/Xlog.java // public final class Xlog { // private static final String LOG_TAG = BuildConfig.LOG_TAG; // private static final int LOG_LEVEL = BuildConfig.LOG_LEVEL; // private static final boolean LOG_TO_XPOSED = BuildConfig.LOG_TO_XPOSED; // // private Xlog() { } // // private static void log(int priority, String tag, String message, Object... args) { // if (priority < LOG_LEVEL) { // return; // } // // message = String.format(message, args); // if (args.length > 0 && args[args.length - 1] instanceof Throwable) { // Throwable throwable = (Throwable)args[args.length - 1]; // String stacktraceStr = Log.getStackTraceString(throwable); // message = message + '\n' + stacktraceStr; // } // // Log.println(priority, LOG_TAG, tag + ": " + message); // if (LOG_TO_XPOSED) { // Log.println(priority, "Xposed", LOG_TAG + ": " + tag + ": " + message); // } // } // // public static void v(String tag, String message, Object... args) { // log(Log.VERBOSE, tag, message, args); // } // // public static void d(String tag, String message, Object... args) { // log(Log.DEBUG, tag, message, args); // } // // public static void i(String tag, String message, Object... args) { // log(Log.INFO, tag, message, args); // } // // public static void w(String tag, String message, Object... args) { // log(Log.WARN, tag, message, args); // } // // public static void e(String tag, String message, Object... args) { // log(Log.ERROR, tag, message, args); // } // } // Path: src/com/crossbowffs/quotelock/xposed/LockscreenHook.java import android.content.Context; import android.content.SharedPreferences; import android.content.res.Resources; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.widget.GridLayout; import android.widget.TextView; import com.crossbowffs.quotelock.consts.PrefKeys; import com.crossbowffs.quotelock.provider.PreferenceProvider; import com.crossbowffs.quotelock.utils.Xlog; import com.crossbowffs.remotepreferences.RemotePreferences; import de.robv.android.xposed.*; import de.robv.android.xposed.callbacks.XC_InitPackageResources; import de.robv.android.xposed.callbacks.XC_LoadPackage; import org.xmlpull.v1.XmlPullParser; package com.crossbowffs.quotelock.xposed; public class LockscreenHook implements IXposedHookZygoteInit, IXposedHookInitPackageResources, IXposedHookLoadPackage, SharedPreferences.OnSharedPreferenceChangeListener { private static final String TAG = LockscreenHook.class.getSimpleName(); private static final String RES_LAYOUT_QUOTE_LAYOUT = "quote_layout"; private static final String RES_STRING_OPEN_APP_1 = "open_quotelock_app_line1"; private static final String RES_STRING_OPEN_APP_2 = "open_quotelock_app_line2"; private static final String RES_ID_QUOTE_TEXTVIEW = "quote_textview"; private static final String RES_ID_SOURCE_TEXTVIEW = "source_textview"; private static String sModulePath; private static XSafeModuleResources sModuleRes; private TextView mQuoteTextView; private TextView mSourceTextView; private RemotePreferences mCommonPrefs; private RemotePreferences mQuotePrefs; private void refreshQuote() {
Xlog.d(TAG, "Quote changed, updating lockscreen layout");
apsun/QuoteLock
src/com/crossbowffs/quotelock/xposed/LockscreenHook.java
// Path: src/com/crossbowffs/quotelock/consts/PrefKeys.java // public final class PrefKeys { // public static final String PREF_COMMON = "common"; // public static final String PREF_COMMON_REFRESH_RATE = "pref_common_refresh_rate"; // public static final String PREF_COMMON_REFRESH_RATE_DEFAULT = "900"; // public static final String PREF_COMMON_UNMETERED_ONLY = "pref_common_unmetered_only"; // public static final boolean PREF_COMMON_UNMETERED_ONLY_DEFAULT = false; // public static final String PREF_COMMON_QUOTE_MODULE = "pref_common_quote_module"; // public static final String PREF_COMMON_QUOTE_MODULE_DEFAULT = VnaasQuoteModule.class.getName(); // public static final String PREF_COMMON_MODULE_PREFERENCES = "pref_module_preferences"; // public static final String PREF_COMMON_REQUIRES_INTERNET = "pref_common_requires_internet"; // public static final String PREF_COMMON_REFRESH_RATE_OVERRIDE = "pref_common_refresh_rate_override"; // public static final String PREF_COMMON_FONT_SIZE_TEXT = "pref_common_font_size_text"; // public static final String PREF_COMMON_FONT_SIZE_TEXT_DEFAULT = "20"; // public static final String PREF_COMMON_FONT_SIZE_SOURCE = "pref_common_font_size_source"; // public static final String PREF_COMMON_FONT_SIZE_SOURCE_DEFAULT = "18"; // // public static final String PREF_QUOTES = "quotes"; // public static final String PREF_QUOTES_TEXT = "pref_quotes_text"; // public static final String PREF_QUOTES_SOURCE = "pref_quotes_source"; // public static final String PREF_QUOTES_LAST_UPDATED = "pref_quotes_last_updated"; // // public static final String PREF_ABOUT_CREDITS = "pref_about_credits"; // public static final String PREF_ABOUT_GITHUB = "pref_about_github"; // public static final String PREF_ABOUT_VERSION = "pref_about_version"; // // private PrefKeys() { } // } // // Path: src/com/crossbowffs/quotelock/provider/PreferenceProvider.java // public class PreferenceProvider extends RemotePreferenceProvider { // public static final String AUTHORITY = BuildConfig.APPLICATION_ID + ".preferences"; // // public PreferenceProvider() { // super(AUTHORITY, new String[] {PrefKeys.PREF_COMMON, PrefKeys.PREF_QUOTES}); // } // // @Override // protected boolean checkAccess(String prefName, String prefKey, boolean write) { // return !write; // } // } // // Path: src/com/crossbowffs/quotelock/utils/Xlog.java // public final class Xlog { // private static final String LOG_TAG = BuildConfig.LOG_TAG; // private static final int LOG_LEVEL = BuildConfig.LOG_LEVEL; // private static final boolean LOG_TO_XPOSED = BuildConfig.LOG_TO_XPOSED; // // private Xlog() { } // // private static void log(int priority, String tag, String message, Object... args) { // if (priority < LOG_LEVEL) { // return; // } // // message = String.format(message, args); // if (args.length > 0 && args[args.length - 1] instanceof Throwable) { // Throwable throwable = (Throwable)args[args.length - 1]; // String stacktraceStr = Log.getStackTraceString(throwable); // message = message + '\n' + stacktraceStr; // } // // Log.println(priority, LOG_TAG, tag + ": " + message); // if (LOG_TO_XPOSED) { // Log.println(priority, "Xposed", LOG_TAG + ": " + tag + ": " + message); // } // } // // public static void v(String tag, String message, Object... args) { // log(Log.VERBOSE, tag, message, args); // } // // public static void d(String tag, String message, Object... args) { // log(Log.DEBUG, tag, message, args); // } // // public static void i(String tag, String message, Object... args) { // log(Log.INFO, tag, message, args); // } // // public static void w(String tag, String message, Object... args) { // log(Log.WARN, tag, message, args); // } // // public static void e(String tag, String message, Object... args) { // log(Log.ERROR, tag, message, args); // } // }
import android.content.Context; import android.content.SharedPreferences; import android.content.res.Resources; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.widget.GridLayout; import android.widget.TextView; import com.crossbowffs.quotelock.consts.PrefKeys; import com.crossbowffs.quotelock.provider.PreferenceProvider; import com.crossbowffs.quotelock.utils.Xlog; import com.crossbowffs.remotepreferences.RemotePreferences; import de.robv.android.xposed.*; import de.robv.android.xposed.callbacks.XC_InitPackageResources; import de.robv.android.xposed.callbacks.XC_LoadPackage; import org.xmlpull.v1.XmlPullParser;
package com.crossbowffs.quotelock.xposed; public class LockscreenHook implements IXposedHookZygoteInit, IXposedHookInitPackageResources, IXposedHookLoadPackage, SharedPreferences.OnSharedPreferenceChangeListener { private static final String TAG = LockscreenHook.class.getSimpleName(); private static final String RES_LAYOUT_QUOTE_LAYOUT = "quote_layout"; private static final String RES_STRING_OPEN_APP_1 = "open_quotelock_app_line1"; private static final String RES_STRING_OPEN_APP_2 = "open_quotelock_app_line2"; private static final String RES_ID_QUOTE_TEXTVIEW = "quote_textview"; private static final String RES_ID_SOURCE_TEXTVIEW = "source_textview"; private static String sModulePath; private static XSafeModuleResources sModuleRes; private TextView mQuoteTextView; private TextView mSourceTextView; private RemotePreferences mCommonPrefs; private RemotePreferences mQuotePrefs; private void refreshQuote() { Xlog.d(TAG, "Quote changed, updating lockscreen layout"); // Update quote text
// Path: src/com/crossbowffs/quotelock/consts/PrefKeys.java // public final class PrefKeys { // public static final String PREF_COMMON = "common"; // public static final String PREF_COMMON_REFRESH_RATE = "pref_common_refresh_rate"; // public static final String PREF_COMMON_REFRESH_RATE_DEFAULT = "900"; // public static final String PREF_COMMON_UNMETERED_ONLY = "pref_common_unmetered_only"; // public static final boolean PREF_COMMON_UNMETERED_ONLY_DEFAULT = false; // public static final String PREF_COMMON_QUOTE_MODULE = "pref_common_quote_module"; // public static final String PREF_COMMON_QUOTE_MODULE_DEFAULT = VnaasQuoteModule.class.getName(); // public static final String PREF_COMMON_MODULE_PREFERENCES = "pref_module_preferences"; // public static final String PREF_COMMON_REQUIRES_INTERNET = "pref_common_requires_internet"; // public static final String PREF_COMMON_REFRESH_RATE_OVERRIDE = "pref_common_refresh_rate_override"; // public static final String PREF_COMMON_FONT_SIZE_TEXT = "pref_common_font_size_text"; // public static final String PREF_COMMON_FONT_SIZE_TEXT_DEFAULT = "20"; // public static final String PREF_COMMON_FONT_SIZE_SOURCE = "pref_common_font_size_source"; // public static final String PREF_COMMON_FONT_SIZE_SOURCE_DEFAULT = "18"; // // public static final String PREF_QUOTES = "quotes"; // public static final String PREF_QUOTES_TEXT = "pref_quotes_text"; // public static final String PREF_QUOTES_SOURCE = "pref_quotes_source"; // public static final String PREF_QUOTES_LAST_UPDATED = "pref_quotes_last_updated"; // // public static final String PREF_ABOUT_CREDITS = "pref_about_credits"; // public static final String PREF_ABOUT_GITHUB = "pref_about_github"; // public static final String PREF_ABOUT_VERSION = "pref_about_version"; // // private PrefKeys() { } // } // // Path: src/com/crossbowffs/quotelock/provider/PreferenceProvider.java // public class PreferenceProvider extends RemotePreferenceProvider { // public static final String AUTHORITY = BuildConfig.APPLICATION_ID + ".preferences"; // // public PreferenceProvider() { // super(AUTHORITY, new String[] {PrefKeys.PREF_COMMON, PrefKeys.PREF_QUOTES}); // } // // @Override // protected boolean checkAccess(String prefName, String prefKey, boolean write) { // return !write; // } // } // // Path: src/com/crossbowffs/quotelock/utils/Xlog.java // public final class Xlog { // private static final String LOG_TAG = BuildConfig.LOG_TAG; // private static final int LOG_LEVEL = BuildConfig.LOG_LEVEL; // private static final boolean LOG_TO_XPOSED = BuildConfig.LOG_TO_XPOSED; // // private Xlog() { } // // private static void log(int priority, String tag, String message, Object... args) { // if (priority < LOG_LEVEL) { // return; // } // // message = String.format(message, args); // if (args.length > 0 && args[args.length - 1] instanceof Throwable) { // Throwable throwable = (Throwable)args[args.length - 1]; // String stacktraceStr = Log.getStackTraceString(throwable); // message = message + '\n' + stacktraceStr; // } // // Log.println(priority, LOG_TAG, tag + ": " + message); // if (LOG_TO_XPOSED) { // Log.println(priority, "Xposed", LOG_TAG + ": " + tag + ": " + message); // } // } // // public static void v(String tag, String message, Object... args) { // log(Log.VERBOSE, tag, message, args); // } // // public static void d(String tag, String message, Object... args) { // log(Log.DEBUG, tag, message, args); // } // // public static void i(String tag, String message, Object... args) { // log(Log.INFO, tag, message, args); // } // // public static void w(String tag, String message, Object... args) { // log(Log.WARN, tag, message, args); // } // // public static void e(String tag, String message, Object... args) { // log(Log.ERROR, tag, message, args); // } // } // Path: src/com/crossbowffs/quotelock/xposed/LockscreenHook.java import android.content.Context; import android.content.SharedPreferences; import android.content.res.Resources; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.widget.GridLayout; import android.widget.TextView; import com.crossbowffs.quotelock.consts.PrefKeys; import com.crossbowffs.quotelock.provider.PreferenceProvider; import com.crossbowffs.quotelock.utils.Xlog; import com.crossbowffs.remotepreferences.RemotePreferences; import de.robv.android.xposed.*; import de.robv.android.xposed.callbacks.XC_InitPackageResources; import de.robv.android.xposed.callbacks.XC_LoadPackage; import org.xmlpull.v1.XmlPullParser; package com.crossbowffs.quotelock.xposed; public class LockscreenHook implements IXposedHookZygoteInit, IXposedHookInitPackageResources, IXposedHookLoadPackage, SharedPreferences.OnSharedPreferenceChangeListener { private static final String TAG = LockscreenHook.class.getSimpleName(); private static final String RES_LAYOUT_QUOTE_LAYOUT = "quote_layout"; private static final String RES_STRING_OPEN_APP_1 = "open_quotelock_app_line1"; private static final String RES_STRING_OPEN_APP_2 = "open_quotelock_app_line2"; private static final String RES_ID_QUOTE_TEXTVIEW = "quote_textview"; private static final String RES_ID_SOURCE_TEXTVIEW = "source_textview"; private static String sModulePath; private static XSafeModuleResources sModuleRes; private TextView mQuoteTextView; private TextView mSourceTextView; private RemotePreferences mCommonPrefs; private RemotePreferences mQuotePrefs; private void refreshQuote() { Xlog.d(TAG, "Quote changed, updating lockscreen layout"); // Update quote text
String text = mQuotePrefs.getString(PrefKeys.PREF_QUOTES_TEXT, null);
apsun/QuoteLock
src/com/crossbowffs/quotelock/provider/PreferenceProvider.java
// Path: src/com/crossbowffs/quotelock/consts/PrefKeys.java // public final class PrefKeys { // public static final String PREF_COMMON = "common"; // public static final String PREF_COMMON_REFRESH_RATE = "pref_common_refresh_rate"; // public static final String PREF_COMMON_REFRESH_RATE_DEFAULT = "900"; // public static final String PREF_COMMON_UNMETERED_ONLY = "pref_common_unmetered_only"; // public static final boolean PREF_COMMON_UNMETERED_ONLY_DEFAULT = false; // public static final String PREF_COMMON_QUOTE_MODULE = "pref_common_quote_module"; // public static final String PREF_COMMON_QUOTE_MODULE_DEFAULT = VnaasQuoteModule.class.getName(); // public static final String PREF_COMMON_MODULE_PREFERENCES = "pref_module_preferences"; // public static final String PREF_COMMON_REQUIRES_INTERNET = "pref_common_requires_internet"; // public static final String PREF_COMMON_REFRESH_RATE_OVERRIDE = "pref_common_refresh_rate_override"; // public static final String PREF_COMMON_FONT_SIZE_TEXT = "pref_common_font_size_text"; // public static final String PREF_COMMON_FONT_SIZE_TEXT_DEFAULT = "20"; // public static final String PREF_COMMON_FONT_SIZE_SOURCE = "pref_common_font_size_source"; // public static final String PREF_COMMON_FONT_SIZE_SOURCE_DEFAULT = "18"; // // public static final String PREF_QUOTES = "quotes"; // public static final String PREF_QUOTES_TEXT = "pref_quotes_text"; // public static final String PREF_QUOTES_SOURCE = "pref_quotes_source"; // public static final String PREF_QUOTES_LAST_UPDATED = "pref_quotes_last_updated"; // // public static final String PREF_ABOUT_CREDITS = "pref_about_credits"; // public static final String PREF_ABOUT_GITHUB = "pref_about_github"; // public static final String PREF_ABOUT_VERSION = "pref_about_version"; // // private PrefKeys() { } // }
import com.crossbowffs.quotelock.BuildConfig; import com.crossbowffs.quotelock.consts.PrefKeys; import com.crossbowffs.remotepreferences.RemotePreferenceProvider;
package com.crossbowffs.quotelock.provider; public class PreferenceProvider extends RemotePreferenceProvider { public static final String AUTHORITY = BuildConfig.APPLICATION_ID + ".preferences"; public PreferenceProvider() {
// Path: src/com/crossbowffs/quotelock/consts/PrefKeys.java // public final class PrefKeys { // public static final String PREF_COMMON = "common"; // public static final String PREF_COMMON_REFRESH_RATE = "pref_common_refresh_rate"; // public static final String PREF_COMMON_REFRESH_RATE_DEFAULT = "900"; // public static final String PREF_COMMON_UNMETERED_ONLY = "pref_common_unmetered_only"; // public static final boolean PREF_COMMON_UNMETERED_ONLY_DEFAULT = false; // public static final String PREF_COMMON_QUOTE_MODULE = "pref_common_quote_module"; // public static final String PREF_COMMON_QUOTE_MODULE_DEFAULT = VnaasQuoteModule.class.getName(); // public static final String PREF_COMMON_MODULE_PREFERENCES = "pref_module_preferences"; // public static final String PREF_COMMON_REQUIRES_INTERNET = "pref_common_requires_internet"; // public static final String PREF_COMMON_REFRESH_RATE_OVERRIDE = "pref_common_refresh_rate_override"; // public static final String PREF_COMMON_FONT_SIZE_TEXT = "pref_common_font_size_text"; // public static final String PREF_COMMON_FONT_SIZE_TEXT_DEFAULT = "20"; // public static final String PREF_COMMON_FONT_SIZE_SOURCE = "pref_common_font_size_source"; // public static final String PREF_COMMON_FONT_SIZE_SOURCE_DEFAULT = "18"; // // public static final String PREF_QUOTES = "quotes"; // public static final String PREF_QUOTES_TEXT = "pref_quotes_text"; // public static final String PREF_QUOTES_SOURCE = "pref_quotes_source"; // public static final String PREF_QUOTES_LAST_UPDATED = "pref_quotes_last_updated"; // // public static final String PREF_ABOUT_CREDITS = "pref_about_credits"; // public static final String PREF_ABOUT_GITHUB = "pref_about_github"; // public static final String PREF_ABOUT_VERSION = "pref_about_version"; // // private PrefKeys() { } // } // Path: src/com/crossbowffs/quotelock/provider/PreferenceProvider.java import com.crossbowffs.quotelock.BuildConfig; import com.crossbowffs.quotelock.consts.PrefKeys; import com.crossbowffs.remotepreferences.RemotePreferenceProvider; package com.crossbowffs.quotelock.provider; public class PreferenceProvider extends RemotePreferenceProvider { public static final String AUTHORITY = BuildConfig.APPLICATION_ID + ".preferences"; public PreferenceProvider() {
super(AUTHORITY, new String[] {PrefKeys.PREF_COMMON, PrefKeys.PREF_QUOTES});
apsun/QuoteLock
src/com/crossbowffs/quotelock/consts/PrefKeys.java
// Path: src/com/crossbowffs/quotelock/modules/vnaas/VnaasQuoteModule.java // public class VnaasQuoteModule implements QuoteModule { // @Override // public String getDisplayName(Context context) { // return context.getString(R.string.module_vnaas_name); // } // // @Override // public ComponentName getConfigActivity(Context context) { // return null; // } // // @Override // public int getMinimumRefreshInterval(Context context) { // return 0; // } // // @Override // public boolean requiresInternetConnectivity(Context context) { // return true; // } // // @Override // public QuoteData getQuote(Context context) throws IOException { // VnaasQuoteQueryParams query = new VnaasQuoteQueryParams(); // SharedPreferences preferences = context.getSharedPreferences(VnaasPrefKeys.PREF_VNAAS, Context.MODE_PRIVATE); // // String novelIdsStr = preferences.getString(VnaasPrefKeys.PREF_VNAAS_ENABLED_NOVELS, null); // if (novelIdsStr != null) { // query.setNovels(splitLongString(novelIdsStr)); // } // // String characterIdsStr = preferences.getString(VnaasPrefKeys.PREF_VNAAS_ENABLED_CHARACTERS, null); // if (characterIdsStr != null) { // query.setCharacters(splitLongString(characterIdsStr)); // } // // String contains = preferences.getString(VnaasPrefKeys.PREF_VNAAS_QUOTE_CONTAINS, null); // if (contains != null) { // query.setContains(contains); // } // // String apiUrl = preferences.getString(VnaasPrefKeys.PREF_VNAAS_API_URL, VnaasPrefKeys.PREF_VNAAS_API_URL_DEFAULT); // VnaasApiManager apiManager = new VnaasApiManager(apiUrl); // VnaasQuote quote = apiManager.getRandomQuote(query); // String quoteText = quote.getText().replaceAll("\\[(.+?)\\|(.+?)\\]", "$2"); // String charName = quote.getCharacter().getName(); // String novelName = quote.getNovel().getName(); // String sourceFormat = preferences.getString(VnaasPrefKeys.PREF_VNAAS_SOURCE_FORMAT, VnaasPrefKeys.PREF_VNAAS_SOURCE_FORMAT_DEFAULT); // String quoteSource = String.format(sourceFormat, charName, novelName); // return new QuoteData(quoteText, quoteSource); // } // // private long[] splitLongString(String str) { // String[] strSplit = str.split(","); // long[] longs = new long[strSplit.length]; // for (int i = 0; i < longs.length; ++i) { // longs[i] = Long.parseLong(strSplit[i]); // } // return longs; // } // }
import com.crossbowffs.quotelock.modules.vnaas.VnaasQuoteModule;
package com.crossbowffs.quotelock.consts; public final class PrefKeys { public static final String PREF_COMMON = "common"; public static final String PREF_COMMON_REFRESH_RATE = "pref_common_refresh_rate"; public static final String PREF_COMMON_REFRESH_RATE_DEFAULT = "900"; public static final String PREF_COMMON_UNMETERED_ONLY = "pref_common_unmetered_only"; public static final boolean PREF_COMMON_UNMETERED_ONLY_DEFAULT = false; public static final String PREF_COMMON_QUOTE_MODULE = "pref_common_quote_module";
// Path: src/com/crossbowffs/quotelock/modules/vnaas/VnaasQuoteModule.java // public class VnaasQuoteModule implements QuoteModule { // @Override // public String getDisplayName(Context context) { // return context.getString(R.string.module_vnaas_name); // } // // @Override // public ComponentName getConfigActivity(Context context) { // return null; // } // // @Override // public int getMinimumRefreshInterval(Context context) { // return 0; // } // // @Override // public boolean requiresInternetConnectivity(Context context) { // return true; // } // // @Override // public QuoteData getQuote(Context context) throws IOException { // VnaasQuoteQueryParams query = new VnaasQuoteQueryParams(); // SharedPreferences preferences = context.getSharedPreferences(VnaasPrefKeys.PREF_VNAAS, Context.MODE_PRIVATE); // // String novelIdsStr = preferences.getString(VnaasPrefKeys.PREF_VNAAS_ENABLED_NOVELS, null); // if (novelIdsStr != null) { // query.setNovels(splitLongString(novelIdsStr)); // } // // String characterIdsStr = preferences.getString(VnaasPrefKeys.PREF_VNAAS_ENABLED_CHARACTERS, null); // if (characterIdsStr != null) { // query.setCharacters(splitLongString(characterIdsStr)); // } // // String contains = preferences.getString(VnaasPrefKeys.PREF_VNAAS_QUOTE_CONTAINS, null); // if (contains != null) { // query.setContains(contains); // } // // String apiUrl = preferences.getString(VnaasPrefKeys.PREF_VNAAS_API_URL, VnaasPrefKeys.PREF_VNAAS_API_URL_DEFAULT); // VnaasApiManager apiManager = new VnaasApiManager(apiUrl); // VnaasQuote quote = apiManager.getRandomQuote(query); // String quoteText = quote.getText().replaceAll("\\[(.+?)\\|(.+?)\\]", "$2"); // String charName = quote.getCharacter().getName(); // String novelName = quote.getNovel().getName(); // String sourceFormat = preferences.getString(VnaasPrefKeys.PREF_VNAAS_SOURCE_FORMAT, VnaasPrefKeys.PREF_VNAAS_SOURCE_FORMAT_DEFAULT); // String quoteSource = String.format(sourceFormat, charName, novelName); // return new QuoteData(quoteText, quoteSource); // } // // private long[] splitLongString(String str) { // String[] strSplit = str.split(","); // long[] longs = new long[strSplit.length]; // for (int i = 0; i < longs.length; ++i) { // longs[i] = Long.parseLong(strSplit[i]); // } // return longs; // } // } // Path: src/com/crossbowffs/quotelock/consts/PrefKeys.java import com.crossbowffs.quotelock.modules.vnaas.VnaasQuoteModule; package com.crossbowffs.quotelock.consts; public final class PrefKeys { public static final String PREF_COMMON = "common"; public static final String PREF_COMMON_REFRESH_RATE = "pref_common_refresh_rate"; public static final String PREF_COMMON_REFRESH_RATE_DEFAULT = "900"; public static final String PREF_COMMON_UNMETERED_ONLY = "pref_common_unmetered_only"; public static final boolean PREF_COMMON_UNMETERED_ONLY_DEFAULT = false; public static final String PREF_COMMON_QUOTE_MODULE = "pref_common_quote_module";
public static final String PREF_COMMON_QUOTE_MODULE_DEFAULT = VnaasQuoteModule.class.getName();
apsun/QuoteLock
src/com/crossbowffs/quotelock/modules/brainyquote/app/BrainyQuoteConfigActivity.java
// Path: src/com/crossbowffs/quotelock/modules/brainyquote/consts/BrainyQuotePrefKeys.java // public static final String PREF_BRAINY = "brainy"; // // Path: src/com/crossbowffs/quotelock/modules/brainyquote/consts/BrainyQuotePrefKeys.java // public static final String PREF_BRAINY_TYPE_STRING = "pref_quotes_brainy_type_string"; // // Path: src/com/crossbowffs/quotelock/modules/brainyquote/consts/BrainyQuotePrefKeys.java // public static final String PREF_BRAINY_TYPE_INT = "pref_quotes_brainy_type_int";
import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; import android.os.Bundle; import android.widget.RadioButton; import android.widget.RadioGroup; import com.crossbowffs.quotelock.R; import static com.crossbowffs.quotelock.modules.brainyquote.consts.BrainyQuotePrefKeys.PREF_BRAINY; import static com.crossbowffs.quotelock.modules.brainyquote.consts.BrainyQuotePrefKeys.PREF_BRAINY_TYPE_STRING; import static com.crossbowffs.quotelock.modules.brainyquote.consts.BrainyQuotePrefKeys.PREF_BRAINY_TYPE_INT;
package com.crossbowffs.quotelock.modules.brainyquote.app; public class BrainyQuoteConfigActivity extends Activity implements RadioGroup.OnCheckedChangeListener { private SharedPreferences mBrainyquotePreferences; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
// Path: src/com/crossbowffs/quotelock/modules/brainyquote/consts/BrainyQuotePrefKeys.java // public static final String PREF_BRAINY = "brainy"; // // Path: src/com/crossbowffs/quotelock/modules/brainyquote/consts/BrainyQuotePrefKeys.java // public static final String PREF_BRAINY_TYPE_STRING = "pref_quotes_brainy_type_string"; // // Path: src/com/crossbowffs/quotelock/modules/brainyquote/consts/BrainyQuotePrefKeys.java // public static final String PREF_BRAINY_TYPE_INT = "pref_quotes_brainy_type_int"; // Path: src/com/crossbowffs/quotelock/modules/brainyquote/app/BrainyQuoteConfigActivity.java import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; import android.os.Bundle; import android.widget.RadioButton; import android.widget.RadioGroup; import com.crossbowffs.quotelock.R; import static com.crossbowffs.quotelock.modules.brainyquote.consts.BrainyQuotePrefKeys.PREF_BRAINY; import static com.crossbowffs.quotelock.modules.brainyquote.consts.BrainyQuotePrefKeys.PREF_BRAINY_TYPE_STRING; import static com.crossbowffs.quotelock.modules.brainyquote.consts.BrainyQuotePrefKeys.PREF_BRAINY_TYPE_INT; package com.crossbowffs.quotelock.modules.brainyquote.app; public class BrainyQuoteConfigActivity extends Activity implements RadioGroup.OnCheckedChangeListener { private SharedPreferences mBrainyquotePreferences; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
mBrainyquotePreferences = getSharedPreferences(PREF_BRAINY, Context.MODE_PRIVATE);
apsun/QuoteLock
src/com/crossbowffs/quotelock/modules/brainyquote/app/BrainyQuoteConfigActivity.java
// Path: src/com/crossbowffs/quotelock/modules/brainyquote/consts/BrainyQuotePrefKeys.java // public static final String PREF_BRAINY = "brainy"; // // Path: src/com/crossbowffs/quotelock/modules/brainyquote/consts/BrainyQuotePrefKeys.java // public static final String PREF_BRAINY_TYPE_STRING = "pref_quotes_brainy_type_string"; // // Path: src/com/crossbowffs/quotelock/modules/brainyquote/consts/BrainyQuotePrefKeys.java // public static final String PREF_BRAINY_TYPE_INT = "pref_quotes_brainy_type_int";
import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; import android.os.Bundle; import android.widget.RadioButton; import android.widget.RadioGroup; import com.crossbowffs.quotelock.R; import static com.crossbowffs.quotelock.modules.brainyquote.consts.BrainyQuotePrefKeys.PREF_BRAINY; import static com.crossbowffs.quotelock.modules.brainyquote.consts.BrainyQuotePrefKeys.PREF_BRAINY_TYPE_STRING; import static com.crossbowffs.quotelock.modules.brainyquote.consts.BrainyQuotePrefKeys.PREF_BRAINY_TYPE_INT;
package com.crossbowffs.quotelock.modules.brainyquote.app; public class BrainyQuoteConfigActivity extends Activity implements RadioGroup.OnCheckedChangeListener { private SharedPreferences mBrainyquotePreferences; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mBrainyquotePreferences = getSharedPreferences(PREF_BRAINY, Context.MODE_PRIVATE); setContentView(R.layout.radio_brainy_quote); RadioGroup radioGroup = (RadioGroup)findViewById(R.id.module_brainy_activity_radiogroup);
// Path: src/com/crossbowffs/quotelock/modules/brainyquote/consts/BrainyQuotePrefKeys.java // public static final String PREF_BRAINY = "brainy"; // // Path: src/com/crossbowffs/quotelock/modules/brainyquote/consts/BrainyQuotePrefKeys.java // public static final String PREF_BRAINY_TYPE_STRING = "pref_quotes_brainy_type_string"; // // Path: src/com/crossbowffs/quotelock/modules/brainyquote/consts/BrainyQuotePrefKeys.java // public static final String PREF_BRAINY_TYPE_INT = "pref_quotes_brainy_type_int"; // Path: src/com/crossbowffs/quotelock/modules/brainyquote/app/BrainyQuoteConfigActivity.java import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; import android.os.Bundle; import android.widget.RadioButton; import android.widget.RadioGroup; import com.crossbowffs.quotelock.R; import static com.crossbowffs.quotelock.modules.brainyquote.consts.BrainyQuotePrefKeys.PREF_BRAINY; import static com.crossbowffs.quotelock.modules.brainyquote.consts.BrainyQuotePrefKeys.PREF_BRAINY_TYPE_STRING; import static com.crossbowffs.quotelock.modules.brainyquote.consts.BrainyQuotePrefKeys.PREF_BRAINY_TYPE_INT; package com.crossbowffs.quotelock.modules.brainyquote.app; public class BrainyQuoteConfigActivity extends Activity implements RadioGroup.OnCheckedChangeListener { private SharedPreferences mBrainyquotePreferences; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mBrainyquotePreferences = getSharedPreferences(PREF_BRAINY, Context.MODE_PRIVATE); setContentView(R.layout.radio_brainy_quote); RadioGroup radioGroup = (RadioGroup)findViewById(R.id.module_brainy_activity_radiogroup);
int queryValueIndex = mBrainyquotePreferences.getInt(PREF_BRAINY_TYPE_INT, 0);
apsun/QuoteLock
src/com/crossbowffs/quotelock/modules/brainyquote/app/BrainyQuoteConfigActivity.java
// Path: src/com/crossbowffs/quotelock/modules/brainyquote/consts/BrainyQuotePrefKeys.java // public static final String PREF_BRAINY = "brainy"; // // Path: src/com/crossbowffs/quotelock/modules/brainyquote/consts/BrainyQuotePrefKeys.java // public static final String PREF_BRAINY_TYPE_STRING = "pref_quotes_brainy_type_string"; // // Path: src/com/crossbowffs/quotelock/modules/brainyquote/consts/BrainyQuotePrefKeys.java // public static final String PREF_BRAINY_TYPE_INT = "pref_quotes_brainy_type_int";
import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; import android.os.Bundle; import android.widget.RadioButton; import android.widget.RadioGroup; import com.crossbowffs.quotelock.R; import static com.crossbowffs.quotelock.modules.brainyquote.consts.BrainyQuotePrefKeys.PREF_BRAINY; import static com.crossbowffs.quotelock.modules.brainyquote.consts.BrainyQuotePrefKeys.PREF_BRAINY_TYPE_STRING; import static com.crossbowffs.quotelock.modules.brainyquote.consts.BrainyQuotePrefKeys.PREF_BRAINY_TYPE_INT;
package com.crossbowffs.quotelock.modules.brainyquote.app; public class BrainyQuoteConfigActivity extends Activity implements RadioGroup.OnCheckedChangeListener { private SharedPreferences mBrainyquotePreferences; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mBrainyquotePreferences = getSharedPreferences(PREF_BRAINY, Context.MODE_PRIVATE); setContentView(R.layout.radio_brainy_quote); RadioGroup radioGroup = (RadioGroup)findViewById(R.id.module_brainy_activity_radiogroup); int queryValueIndex = mBrainyquotePreferences.getInt(PREF_BRAINY_TYPE_INT, 0); RadioButton button = (RadioButton)radioGroup.getChildAt(queryValueIndex); button.setChecked(true); radioGroup.setOnCheckedChangeListener(this); } @Override public void onCheckedChanged(RadioGroup group, int checkedId) { String[] queryValueArray = getResources().getStringArray(R.array.brainy_quote_type_values); int queryValueIndex = group.indexOfChild(findViewById(checkedId)); String queryValue = queryValueArray[queryValueIndex]; mBrainyquotePreferences.edit() .putInt(PREF_BRAINY_TYPE_INT, queryValueIndex)
// Path: src/com/crossbowffs/quotelock/modules/brainyquote/consts/BrainyQuotePrefKeys.java // public static final String PREF_BRAINY = "brainy"; // // Path: src/com/crossbowffs/quotelock/modules/brainyquote/consts/BrainyQuotePrefKeys.java // public static final String PREF_BRAINY_TYPE_STRING = "pref_quotes_brainy_type_string"; // // Path: src/com/crossbowffs/quotelock/modules/brainyquote/consts/BrainyQuotePrefKeys.java // public static final String PREF_BRAINY_TYPE_INT = "pref_quotes_brainy_type_int"; // Path: src/com/crossbowffs/quotelock/modules/brainyquote/app/BrainyQuoteConfigActivity.java import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; import android.os.Bundle; import android.widget.RadioButton; import android.widget.RadioGroup; import com.crossbowffs.quotelock.R; import static com.crossbowffs.quotelock.modules.brainyquote.consts.BrainyQuotePrefKeys.PREF_BRAINY; import static com.crossbowffs.quotelock.modules.brainyquote.consts.BrainyQuotePrefKeys.PREF_BRAINY_TYPE_STRING; import static com.crossbowffs.quotelock.modules.brainyquote.consts.BrainyQuotePrefKeys.PREF_BRAINY_TYPE_INT; package com.crossbowffs.quotelock.modules.brainyquote.app; public class BrainyQuoteConfigActivity extends Activity implements RadioGroup.OnCheckedChangeListener { private SharedPreferences mBrainyquotePreferences; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mBrainyquotePreferences = getSharedPreferences(PREF_BRAINY, Context.MODE_PRIVATE); setContentView(R.layout.radio_brainy_quote); RadioGroup radioGroup = (RadioGroup)findViewById(R.id.module_brainy_activity_radiogroup); int queryValueIndex = mBrainyquotePreferences.getInt(PREF_BRAINY_TYPE_INT, 0); RadioButton button = (RadioButton)radioGroup.getChildAt(queryValueIndex); button.setChecked(true); radioGroup.setOnCheckedChangeListener(this); } @Override public void onCheckedChanged(RadioGroup group, int checkedId) { String[] queryValueArray = getResources().getStringArray(R.array.brainy_quote_type_values); int queryValueIndex = group.indexOfChild(findViewById(checkedId)); String queryValue = queryValueArray[queryValueIndex]; mBrainyquotePreferences.edit() .putInt(PREF_BRAINY_TYPE_INT, queryValueIndex)
.putString(PREF_BRAINY_TYPE_STRING, queryValue)
apsun/QuoteLock
src/com/crossbowffs/quotelock/modules/hitokoto/app/HitkotoConfigActivity.java
// Path: src/com/crossbowffs/quotelock/modules/hitokoto/consts/HitokotoPrefKeys.java // public static final String PREF_HITOKOTO = "hitoko"; // // Path: src/com/crossbowffs/quotelock/modules/hitokoto/consts/HitokotoPrefKeys.java // public static final String PREF_HITOKOTO_TYPE_INT = "pref_quotes_hitoko_type_int"; // // Path: src/com/crossbowffs/quotelock/modules/hitokoto/consts/HitokotoPrefKeys.java // public static final String PREF_HITOKOTO_TYPE_STRING = "pref_quotes_hitoko_type_string";
import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; import android.os.Bundle; import android.widget.RadioButton; import android.widget.RadioGroup; import com.crossbowffs.quotelock.R; import static com.crossbowffs.quotelock.modules.hitokoto.consts.HitokotoPrefKeys.PREF_HITOKOTO; import static com.crossbowffs.quotelock.modules.hitokoto.consts.HitokotoPrefKeys.PREF_HITOKOTO_TYPE_INT; import static com.crossbowffs.quotelock.modules.hitokoto.consts.HitokotoPrefKeys.PREF_HITOKOTO_TYPE_STRING;
package com.crossbowffs.quotelock.modules.hitokoto.app; public class HitkotoConfigActivity extends Activity implements RadioGroup.OnCheckedChangeListener { private SharedPreferences mHitokotoPreferences; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
// Path: src/com/crossbowffs/quotelock/modules/hitokoto/consts/HitokotoPrefKeys.java // public static final String PREF_HITOKOTO = "hitoko"; // // Path: src/com/crossbowffs/quotelock/modules/hitokoto/consts/HitokotoPrefKeys.java // public static final String PREF_HITOKOTO_TYPE_INT = "pref_quotes_hitoko_type_int"; // // Path: src/com/crossbowffs/quotelock/modules/hitokoto/consts/HitokotoPrefKeys.java // public static final String PREF_HITOKOTO_TYPE_STRING = "pref_quotes_hitoko_type_string"; // Path: src/com/crossbowffs/quotelock/modules/hitokoto/app/HitkotoConfigActivity.java import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; import android.os.Bundle; import android.widget.RadioButton; import android.widget.RadioGroup; import com.crossbowffs.quotelock.R; import static com.crossbowffs.quotelock.modules.hitokoto.consts.HitokotoPrefKeys.PREF_HITOKOTO; import static com.crossbowffs.quotelock.modules.hitokoto.consts.HitokotoPrefKeys.PREF_HITOKOTO_TYPE_INT; import static com.crossbowffs.quotelock.modules.hitokoto.consts.HitokotoPrefKeys.PREF_HITOKOTO_TYPE_STRING; package com.crossbowffs.quotelock.modules.hitokoto.app; public class HitkotoConfigActivity extends Activity implements RadioGroup.OnCheckedChangeListener { private SharedPreferences mHitokotoPreferences; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
mHitokotoPreferences = getSharedPreferences(PREF_HITOKOTO, Context.MODE_PRIVATE);
apsun/QuoteLock
src/com/crossbowffs/quotelock/modules/hitokoto/app/HitkotoConfigActivity.java
// Path: src/com/crossbowffs/quotelock/modules/hitokoto/consts/HitokotoPrefKeys.java // public static final String PREF_HITOKOTO = "hitoko"; // // Path: src/com/crossbowffs/quotelock/modules/hitokoto/consts/HitokotoPrefKeys.java // public static final String PREF_HITOKOTO_TYPE_INT = "pref_quotes_hitoko_type_int"; // // Path: src/com/crossbowffs/quotelock/modules/hitokoto/consts/HitokotoPrefKeys.java // public static final String PREF_HITOKOTO_TYPE_STRING = "pref_quotes_hitoko_type_string";
import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; import android.os.Bundle; import android.widget.RadioButton; import android.widget.RadioGroup; import com.crossbowffs.quotelock.R; import static com.crossbowffs.quotelock.modules.hitokoto.consts.HitokotoPrefKeys.PREF_HITOKOTO; import static com.crossbowffs.quotelock.modules.hitokoto.consts.HitokotoPrefKeys.PREF_HITOKOTO_TYPE_INT; import static com.crossbowffs.quotelock.modules.hitokoto.consts.HitokotoPrefKeys.PREF_HITOKOTO_TYPE_STRING;
package com.crossbowffs.quotelock.modules.hitokoto.app; public class HitkotoConfigActivity extends Activity implements RadioGroup.OnCheckedChangeListener { private SharedPreferences mHitokotoPreferences; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mHitokotoPreferences = getSharedPreferences(PREF_HITOKOTO, Context.MODE_PRIVATE); setContentView(R.layout.radio_hitokoto_quote); RadioGroup radioGroup = (RadioGroup)findViewById(R.id.module_hitokoto_activity_radiogroup);
// Path: src/com/crossbowffs/quotelock/modules/hitokoto/consts/HitokotoPrefKeys.java // public static final String PREF_HITOKOTO = "hitoko"; // // Path: src/com/crossbowffs/quotelock/modules/hitokoto/consts/HitokotoPrefKeys.java // public static final String PREF_HITOKOTO_TYPE_INT = "pref_quotes_hitoko_type_int"; // // Path: src/com/crossbowffs/quotelock/modules/hitokoto/consts/HitokotoPrefKeys.java // public static final String PREF_HITOKOTO_TYPE_STRING = "pref_quotes_hitoko_type_string"; // Path: src/com/crossbowffs/quotelock/modules/hitokoto/app/HitkotoConfigActivity.java import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; import android.os.Bundle; import android.widget.RadioButton; import android.widget.RadioGroup; import com.crossbowffs.quotelock.R; import static com.crossbowffs.quotelock.modules.hitokoto.consts.HitokotoPrefKeys.PREF_HITOKOTO; import static com.crossbowffs.quotelock.modules.hitokoto.consts.HitokotoPrefKeys.PREF_HITOKOTO_TYPE_INT; import static com.crossbowffs.quotelock.modules.hitokoto.consts.HitokotoPrefKeys.PREF_HITOKOTO_TYPE_STRING; package com.crossbowffs.quotelock.modules.hitokoto.app; public class HitkotoConfigActivity extends Activity implements RadioGroup.OnCheckedChangeListener { private SharedPreferences mHitokotoPreferences; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mHitokotoPreferences = getSharedPreferences(PREF_HITOKOTO, Context.MODE_PRIVATE); setContentView(R.layout.radio_hitokoto_quote); RadioGroup radioGroup = (RadioGroup)findViewById(R.id.module_hitokoto_activity_radiogroup);
int queryValueIndex = mHitokotoPreferences.getInt(PREF_HITOKOTO_TYPE_INT, 0);
apsun/QuoteLock
src/com/crossbowffs/quotelock/modules/hitokoto/app/HitkotoConfigActivity.java
// Path: src/com/crossbowffs/quotelock/modules/hitokoto/consts/HitokotoPrefKeys.java // public static final String PREF_HITOKOTO = "hitoko"; // // Path: src/com/crossbowffs/quotelock/modules/hitokoto/consts/HitokotoPrefKeys.java // public static final String PREF_HITOKOTO_TYPE_INT = "pref_quotes_hitoko_type_int"; // // Path: src/com/crossbowffs/quotelock/modules/hitokoto/consts/HitokotoPrefKeys.java // public static final String PREF_HITOKOTO_TYPE_STRING = "pref_quotes_hitoko_type_string";
import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; import android.os.Bundle; import android.widget.RadioButton; import android.widget.RadioGroup; import com.crossbowffs.quotelock.R; import static com.crossbowffs.quotelock.modules.hitokoto.consts.HitokotoPrefKeys.PREF_HITOKOTO; import static com.crossbowffs.quotelock.modules.hitokoto.consts.HitokotoPrefKeys.PREF_HITOKOTO_TYPE_INT; import static com.crossbowffs.quotelock.modules.hitokoto.consts.HitokotoPrefKeys.PREF_HITOKOTO_TYPE_STRING;
package com.crossbowffs.quotelock.modules.hitokoto.app; public class HitkotoConfigActivity extends Activity implements RadioGroup.OnCheckedChangeListener { private SharedPreferences mHitokotoPreferences; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mHitokotoPreferences = getSharedPreferences(PREF_HITOKOTO, Context.MODE_PRIVATE); setContentView(R.layout.radio_hitokoto_quote); RadioGroup radioGroup = (RadioGroup)findViewById(R.id.module_hitokoto_activity_radiogroup); int queryValueIndex = mHitokotoPreferences.getInt(PREF_HITOKOTO_TYPE_INT, 0); RadioButton button = (RadioButton)radioGroup.getChildAt(queryValueIndex); button.setChecked(true); radioGroup.setOnCheckedChangeListener(this); } @Override public void onCheckedChanged(RadioGroup group, int checkedId) { String[] queryValueArray = getResources().getStringArray(R.array.hitokoto_type_values); int queryValueIndex = group.indexOfChild(findViewById(checkedId)); String queryValue = queryValueArray[queryValueIndex]; mHitokotoPreferences.edit() .putInt(PREF_HITOKOTO_TYPE_INT, queryValueIndex)
// Path: src/com/crossbowffs/quotelock/modules/hitokoto/consts/HitokotoPrefKeys.java // public static final String PREF_HITOKOTO = "hitoko"; // // Path: src/com/crossbowffs/quotelock/modules/hitokoto/consts/HitokotoPrefKeys.java // public static final String PREF_HITOKOTO_TYPE_INT = "pref_quotes_hitoko_type_int"; // // Path: src/com/crossbowffs/quotelock/modules/hitokoto/consts/HitokotoPrefKeys.java // public static final String PREF_HITOKOTO_TYPE_STRING = "pref_quotes_hitoko_type_string"; // Path: src/com/crossbowffs/quotelock/modules/hitokoto/app/HitkotoConfigActivity.java import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; import android.os.Bundle; import android.widget.RadioButton; import android.widget.RadioGroup; import com.crossbowffs.quotelock.R; import static com.crossbowffs.quotelock.modules.hitokoto.consts.HitokotoPrefKeys.PREF_HITOKOTO; import static com.crossbowffs.quotelock.modules.hitokoto.consts.HitokotoPrefKeys.PREF_HITOKOTO_TYPE_INT; import static com.crossbowffs.quotelock.modules.hitokoto.consts.HitokotoPrefKeys.PREF_HITOKOTO_TYPE_STRING; package com.crossbowffs.quotelock.modules.hitokoto.app; public class HitkotoConfigActivity extends Activity implements RadioGroup.OnCheckedChangeListener { private SharedPreferences mHitokotoPreferences; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mHitokotoPreferences = getSharedPreferences(PREF_HITOKOTO, Context.MODE_PRIVATE); setContentView(R.layout.radio_hitokoto_quote); RadioGroup radioGroup = (RadioGroup)findViewById(R.id.module_hitokoto_activity_radiogroup); int queryValueIndex = mHitokotoPreferences.getInt(PREF_HITOKOTO_TYPE_INT, 0); RadioButton button = (RadioButton)radioGroup.getChildAt(queryValueIndex); button.setChecked(true); radioGroup.setOnCheckedChangeListener(this); } @Override public void onCheckedChanged(RadioGroup group, int checkedId) { String[] queryValueArray = getResources().getStringArray(R.array.hitokoto_type_values); int queryValueIndex = group.indexOfChild(findViewById(checkedId)); String queryValue = queryValueArray[queryValueIndex]; mHitokotoPreferences.edit() .putInt(PREF_HITOKOTO_TYPE_INT, queryValueIndex)
.putString(PREF_HITOKOTO_TYPE_STRING, queryValue)
apsun/QuoteLock
src/com/crossbowffs/quotelock/modules/natune/NatuneQuoteModule.java
// Path: src/com/crossbowffs/quotelock/api/QuoteData.java // public class QuoteData { // private final String mQuoteText; // private final String mQuoteSource; // // /** // * Creates a new quote data object. The parameters may be {@code null}, // * in which case they are replaced with an empty string. // * // * @param quoteText The first line (text) of the quote. // * @param quoteSource The second line (author) of the quote. // */ // public QuoteData(String quoteText, String quoteSource) { // mQuoteText = quoteText; // mQuoteSource = quoteSource; // } // // /** // * Gets the first line of the quote. Will not be {@code null}. // */ // public String getQuoteText() { // String text = mQuoteText; // if (text == null) { // text = ""; // } // return text; // } // // /** // * Gets the second line of the quote. Will not be {@code null}. // */ // public String getQuoteSource() { // String source = mQuoteSource; // if (source == null) { // source = ""; // } // return source; // } // } // // Path: src/com/crossbowffs/quotelock/api/QuoteModule.java // public interface QuoteModule { // /** // * Gets the user-friendly name of the quote provider that this module uses. // * Must not return {@code null}. // */ // String getDisplayName(Context context); // // /** // * Gets a {@link ComponentName} representing the configuration // * {@link android.app.Activity} for this module. // * Returns {@code null} if there is no configuration activity. // */ // ComponentName getConfigActivity(Context context); // // /** // * Returns a minimum refresh interval (in seconds) for the quote source. // * If there is no minimum refresh interval, returns 0. If the quote should // * never automatically be refreshed, returns {@link Integer#MAX_VALUE}. // */ // int getMinimumRefreshInterval(Context context); // // /** // * Whether the provider needs to download data from the internet. // * Returns {@code false} for providers which store data locally on the // * device. // */ // boolean requiresInternetConnectivity(Context context); // // /** // * Gets a new quote from the quote provider. This method is executed on a // * background thread, so you should not need to use any async calls. // * May return {@code null} or throw an exception in the case of an error. // */ // QuoteData getQuote(Context context) throws Exception; // } // // Path: src/com/crossbowffs/quotelock/utils/IOUtils.java // public class IOUtils { // public static String streamToString(InputStream inputStream, String encoding, int bufferSize) throws IOException { // char[] buffer = new char[bufferSize]; // StringBuilder sb = new StringBuilder(); // try (InputStreamReader reader = new InputStreamReader(inputStream, encoding)) { // while (true) { // int count = reader.read(buffer, 0, bufferSize); // if (count < 0) break; // sb.append(buffer, 0, count); // } // } // return sb.toString(); // } // // public static String streamToString(InputStream inputStream) throws IOException { // return streamToString(inputStream, "UTF-8", 2048); // } // // public static String downloadString(String urlString) throws IOException { // URL url = new URL(urlString); // String ua = String.format("QuoteLock/%s (+%s)", BuildConfig.VERSION_NAME, Urls.GITHUB_QUOTELOCK); // HttpURLConnection connection = (HttpURLConnection)url.openConnection(); // try { // connection.setRequestProperty("User-Agent", ua); // int responseCode = connection.getResponseCode(); // if (responseCode == 200) { // return streamToString(connection.getInputStream()); // } else { // throw new IOException("Server returned non-200 status code: " + responseCode); // } // } finally { // connection.disconnect(); // } // } // }
import android.content.ComponentName; import android.content.Context; import com.crossbowffs.quotelock.R; import com.crossbowffs.quotelock.api.QuoteData; import com.crossbowffs.quotelock.api.QuoteModule; import com.crossbowffs.quotelock.utils.IOUtils; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element;
package com.crossbowffs.quotelock.modules.natune; public class NatuneQuoteModule implements QuoteModule { @Override public String getDisplayName(Context context) { return context.getString(R.string.module_natune_name); } @Override public ComponentName getConfigActivity(Context context) { return null; } @Override public int getMinimumRefreshInterval(Context context) { return 0; } @Override public boolean requiresInternetConnectivity(Context context) { return true; } @Override
// Path: src/com/crossbowffs/quotelock/api/QuoteData.java // public class QuoteData { // private final String mQuoteText; // private final String mQuoteSource; // // /** // * Creates a new quote data object. The parameters may be {@code null}, // * in which case they are replaced with an empty string. // * // * @param quoteText The first line (text) of the quote. // * @param quoteSource The second line (author) of the quote. // */ // public QuoteData(String quoteText, String quoteSource) { // mQuoteText = quoteText; // mQuoteSource = quoteSource; // } // // /** // * Gets the first line of the quote. Will not be {@code null}. // */ // public String getQuoteText() { // String text = mQuoteText; // if (text == null) { // text = ""; // } // return text; // } // // /** // * Gets the second line of the quote. Will not be {@code null}. // */ // public String getQuoteSource() { // String source = mQuoteSource; // if (source == null) { // source = ""; // } // return source; // } // } // // Path: src/com/crossbowffs/quotelock/api/QuoteModule.java // public interface QuoteModule { // /** // * Gets the user-friendly name of the quote provider that this module uses. // * Must not return {@code null}. // */ // String getDisplayName(Context context); // // /** // * Gets a {@link ComponentName} representing the configuration // * {@link android.app.Activity} for this module. // * Returns {@code null} if there is no configuration activity. // */ // ComponentName getConfigActivity(Context context); // // /** // * Returns a minimum refresh interval (in seconds) for the quote source. // * If there is no minimum refresh interval, returns 0. If the quote should // * never automatically be refreshed, returns {@link Integer#MAX_VALUE}. // */ // int getMinimumRefreshInterval(Context context); // // /** // * Whether the provider needs to download data from the internet. // * Returns {@code false} for providers which store data locally on the // * device. // */ // boolean requiresInternetConnectivity(Context context); // // /** // * Gets a new quote from the quote provider. This method is executed on a // * background thread, so you should not need to use any async calls. // * May return {@code null} or throw an exception in the case of an error. // */ // QuoteData getQuote(Context context) throws Exception; // } // // Path: src/com/crossbowffs/quotelock/utils/IOUtils.java // public class IOUtils { // public static String streamToString(InputStream inputStream, String encoding, int bufferSize) throws IOException { // char[] buffer = new char[bufferSize]; // StringBuilder sb = new StringBuilder(); // try (InputStreamReader reader = new InputStreamReader(inputStream, encoding)) { // while (true) { // int count = reader.read(buffer, 0, bufferSize); // if (count < 0) break; // sb.append(buffer, 0, count); // } // } // return sb.toString(); // } // // public static String streamToString(InputStream inputStream) throws IOException { // return streamToString(inputStream, "UTF-8", 2048); // } // // public static String downloadString(String urlString) throws IOException { // URL url = new URL(urlString); // String ua = String.format("QuoteLock/%s (+%s)", BuildConfig.VERSION_NAME, Urls.GITHUB_QUOTELOCK); // HttpURLConnection connection = (HttpURLConnection)url.openConnection(); // try { // connection.setRequestProperty("User-Agent", ua); // int responseCode = connection.getResponseCode(); // if (responseCode == 200) { // return streamToString(connection.getInputStream()); // } else { // throw new IOException("Server returned non-200 status code: " + responseCode); // } // } finally { // connection.disconnect(); // } // } // } // Path: src/com/crossbowffs/quotelock/modules/natune/NatuneQuoteModule.java import android.content.ComponentName; import android.content.Context; import com.crossbowffs.quotelock.R; import com.crossbowffs.quotelock.api.QuoteData; import com.crossbowffs.quotelock.api.QuoteModule; import com.crossbowffs.quotelock.utils.IOUtils; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; package com.crossbowffs.quotelock.modules.natune; public class NatuneQuoteModule implements QuoteModule { @Override public String getDisplayName(Context context) { return context.getString(R.string.module_natune_name); } @Override public ComponentName getConfigActivity(Context context) { return null; } @Override public int getMinimumRefreshInterval(Context context) { return 0; } @Override public boolean requiresInternetConnectivity(Context context) { return true; } @Override
public QuoteData getQuote(Context context) throws Exception {
apsun/QuoteLock
src/com/crossbowffs/quotelock/modules/natune/NatuneQuoteModule.java
// Path: src/com/crossbowffs/quotelock/api/QuoteData.java // public class QuoteData { // private final String mQuoteText; // private final String mQuoteSource; // // /** // * Creates a new quote data object. The parameters may be {@code null}, // * in which case they are replaced with an empty string. // * // * @param quoteText The first line (text) of the quote. // * @param quoteSource The second line (author) of the quote. // */ // public QuoteData(String quoteText, String quoteSource) { // mQuoteText = quoteText; // mQuoteSource = quoteSource; // } // // /** // * Gets the first line of the quote. Will not be {@code null}. // */ // public String getQuoteText() { // String text = mQuoteText; // if (text == null) { // text = ""; // } // return text; // } // // /** // * Gets the second line of the quote. Will not be {@code null}. // */ // public String getQuoteSource() { // String source = mQuoteSource; // if (source == null) { // source = ""; // } // return source; // } // } // // Path: src/com/crossbowffs/quotelock/api/QuoteModule.java // public interface QuoteModule { // /** // * Gets the user-friendly name of the quote provider that this module uses. // * Must not return {@code null}. // */ // String getDisplayName(Context context); // // /** // * Gets a {@link ComponentName} representing the configuration // * {@link android.app.Activity} for this module. // * Returns {@code null} if there is no configuration activity. // */ // ComponentName getConfigActivity(Context context); // // /** // * Returns a minimum refresh interval (in seconds) for the quote source. // * If there is no minimum refresh interval, returns 0. If the quote should // * never automatically be refreshed, returns {@link Integer#MAX_VALUE}. // */ // int getMinimumRefreshInterval(Context context); // // /** // * Whether the provider needs to download data from the internet. // * Returns {@code false} for providers which store data locally on the // * device. // */ // boolean requiresInternetConnectivity(Context context); // // /** // * Gets a new quote from the quote provider. This method is executed on a // * background thread, so you should not need to use any async calls. // * May return {@code null} or throw an exception in the case of an error. // */ // QuoteData getQuote(Context context) throws Exception; // } // // Path: src/com/crossbowffs/quotelock/utils/IOUtils.java // public class IOUtils { // public static String streamToString(InputStream inputStream, String encoding, int bufferSize) throws IOException { // char[] buffer = new char[bufferSize]; // StringBuilder sb = new StringBuilder(); // try (InputStreamReader reader = new InputStreamReader(inputStream, encoding)) { // while (true) { // int count = reader.read(buffer, 0, bufferSize); // if (count < 0) break; // sb.append(buffer, 0, count); // } // } // return sb.toString(); // } // // public static String streamToString(InputStream inputStream) throws IOException { // return streamToString(inputStream, "UTF-8", 2048); // } // // public static String downloadString(String urlString) throws IOException { // URL url = new URL(urlString); // String ua = String.format("QuoteLock/%s (+%s)", BuildConfig.VERSION_NAME, Urls.GITHUB_QUOTELOCK); // HttpURLConnection connection = (HttpURLConnection)url.openConnection(); // try { // connection.setRequestProperty("User-Agent", ua); // int responseCode = connection.getResponseCode(); // if (responseCode == 200) { // return streamToString(connection.getInputStream()); // } else { // throw new IOException("Server returned non-200 status code: " + responseCode); // } // } finally { // connection.disconnect(); // } // } // }
import android.content.ComponentName; import android.content.Context; import com.crossbowffs.quotelock.R; import com.crossbowffs.quotelock.api.QuoteData; import com.crossbowffs.quotelock.api.QuoteModule; import com.crossbowffs.quotelock.utils.IOUtils; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element;
package com.crossbowffs.quotelock.modules.natune; public class NatuneQuoteModule implements QuoteModule { @Override public String getDisplayName(Context context) { return context.getString(R.string.module_natune_name); } @Override public ComponentName getConfigActivity(Context context) { return null; } @Override public int getMinimumRefreshInterval(Context context) { return 0; } @Override public boolean requiresInternetConnectivity(Context context) { return true; } @Override public QuoteData getQuote(Context context) throws Exception {
// Path: src/com/crossbowffs/quotelock/api/QuoteData.java // public class QuoteData { // private final String mQuoteText; // private final String mQuoteSource; // // /** // * Creates a new quote data object. The parameters may be {@code null}, // * in which case they are replaced with an empty string. // * // * @param quoteText The first line (text) of the quote. // * @param quoteSource The second line (author) of the quote. // */ // public QuoteData(String quoteText, String quoteSource) { // mQuoteText = quoteText; // mQuoteSource = quoteSource; // } // // /** // * Gets the first line of the quote. Will not be {@code null}. // */ // public String getQuoteText() { // String text = mQuoteText; // if (text == null) { // text = ""; // } // return text; // } // // /** // * Gets the second line of the quote. Will not be {@code null}. // */ // public String getQuoteSource() { // String source = mQuoteSource; // if (source == null) { // source = ""; // } // return source; // } // } // // Path: src/com/crossbowffs/quotelock/api/QuoteModule.java // public interface QuoteModule { // /** // * Gets the user-friendly name of the quote provider that this module uses. // * Must not return {@code null}. // */ // String getDisplayName(Context context); // // /** // * Gets a {@link ComponentName} representing the configuration // * {@link android.app.Activity} for this module. // * Returns {@code null} if there is no configuration activity. // */ // ComponentName getConfigActivity(Context context); // // /** // * Returns a minimum refresh interval (in seconds) for the quote source. // * If there is no minimum refresh interval, returns 0. If the quote should // * never automatically be refreshed, returns {@link Integer#MAX_VALUE}. // */ // int getMinimumRefreshInterval(Context context); // // /** // * Whether the provider needs to download data from the internet. // * Returns {@code false} for providers which store data locally on the // * device. // */ // boolean requiresInternetConnectivity(Context context); // // /** // * Gets a new quote from the quote provider. This method is executed on a // * background thread, so you should not need to use any async calls. // * May return {@code null} or throw an exception in the case of an error. // */ // QuoteData getQuote(Context context) throws Exception; // } // // Path: src/com/crossbowffs/quotelock/utils/IOUtils.java // public class IOUtils { // public static String streamToString(InputStream inputStream, String encoding, int bufferSize) throws IOException { // char[] buffer = new char[bufferSize]; // StringBuilder sb = new StringBuilder(); // try (InputStreamReader reader = new InputStreamReader(inputStream, encoding)) { // while (true) { // int count = reader.read(buffer, 0, bufferSize); // if (count < 0) break; // sb.append(buffer, 0, count); // } // } // return sb.toString(); // } // // public static String streamToString(InputStream inputStream) throws IOException { // return streamToString(inputStream, "UTF-8", 2048); // } // // public static String downloadString(String urlString) throws IOException { // URL url = new URL(urlString); // String ua = String.format("QuoteLock/%s (+%s)", BuildConfig.VERSION_NAME, Urls.GITHUB_QUOTELOCK); // HttpURLConnection connection = (HttpURLConnection)url.openConnection(); // try { // connection.setRequestProperty("User-Agent", ua); // int responseCode = connection.getResponseCode(); // if (responseCode == 200) { // return streamToString(connection.getInputStream()); // } else { // throw new IOException("Server returned non-200 status code: " + responseCode); // } // } finally { // connection.disconnect(); // } // } // } // Path: src/com/crossbowffs/quotelock/modules/natune/NatuneQuoteModule.java import android.content.ComponentName; import android.content.Context; import com.crossbowffs.quotelock.R; import com.crossbowffs.quotelock.api.QuoteData; import com.crossbowffs.quotelock.api.QuoteModule; import com.crossbowffs.quotelock.utils.IOUtils; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; package com.crossbowffs.quotelock.modules.natune; public class NatuneQuoteModule implements QuoteModule { @Override public String getDisplayName(Context context) { return context.getString(R.string.module_natune_name); } @Override public ComponentName getConfigActivity(Context context) { return null; } @Override public int getMinimumRefreshInterval(Context context) { return 0; } @Override public boolean requiresInternetConnectivity(Context context) { return true; } @Override public QuoteData getQuote(Context context) throws Exception {
String html = IOUtils.downloadString("https://natune.net/zitate/Zufalls5");
apsun/QuoteLock
src/com/crossbowffs/quotelock/modules/vnaas/api/VnaasNovelQueryParams.java
// Path: src/com/crossbowffs/quotelock/modules/vnaas/model/VnaasCharacter.java // public class VnaasCharacter { // private final long mId; // private final String mName; // private final VnaasNovel[] mNovels; // // public VnaasCharacter(long id, String name, VnaasNovel[] novels) { // mId = id; // mName = name; // mNovels = novels; // } // // public long getId() { // return mId; // } // // public String getName() { // return mName; // } // // public VnaasNovel[] getNovels() { // return mNovels; // } // }
import com.crossbowffs.quotelock.modules.vnaas.model.VnaasCharacter;
package com.crossbowffs.quotelock.modules.vnaas.api; public class VnaasNovelQueryParams extends QueryParams { public VnaasNovelQueryParams setCharacter(long characterId) { setParam("character_id", characterId); return this; }
// Path: src/com/crossbowffs/quotelock/modules/vnaas/model/VnaasCharacter.java // public class VnaasCharacter { // private final long mId; // private final String mName; // private final VnaasNovel[] mNovels; // // public VnaasCharacter(long id, String name, VnaasNovel[] novels) { // mId = id; // mName = name; // mNovels = novels; // } // // public long getId() { // return mId; // } // // public String getName() { // return mName; // } // // public VnaasNovel[] getNovels() { // return mNovels; // } // } // Path: src/com/crossbowffs/quotelock/modules/vnaas/api/VnaasNovelQueryParams.java import com.crossbowffs.quotelock.modules.vnaas.model.VnaasCharacter; package com.crossbowffs.quotelock.modules.vnaas.api; public class VnaasNovelQueryParams extends QueryParams { public VnaasNovelQueryParams setCharacter(long characterId) { setParam("character_id", characterId); return this; }
public VnaasNovelQueryParams setCharacter(VnaasCharacter character) {
jaxio/jpa-query-by-example
src/test/java/demo/Address.java
// Path: src/main/java/com/jaxio/jpa/querybyexample/Identifiable.java // public interface Identifiable<PK extends Serializable> { // // /** // * @return the primary key // */ // PK getId(); // // /** // * Sets the primary key // * // * @param id primary key // */ // void setId(PK id); // // /** // * Helper method to know whether the primary key is set or not. // * // * @return true if the primary key is set, false otherwise // */ // boolean isIdSet(); // }
import com.google.common.base.MoreObjects; import com.jaxio.jpa.querybyexample.Identifiable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.persistence.*; import java.io.Serializable;
/* * Source code generated by Celerio, a Jaxio product. * Documentation: http://www.jaxio.com/documentation/celerio/ * Follow us on twitter: @jaxiosoft * Need commercial support ? Contact us: [email protected] * Template pack-backend-jpa:src/main/java/domain/Entity.e.vm.java * Template is part of Open Source Project: https://github.com/jaxio/pack-backend-jpa */ package demo; @Entity @Table(name = "ADDRESS")
// Path: src/main/java/com/jaxio/jpa/querybyexample/Identifiable.java // public interface Identifiable<PK extends Serializable> { // // /** // * @return the primary key // */ // PK getId(); // // /** // * Sets the primary key // * // * @param id primary key // */ // void setId(PK id); // // /** // * Helper method to know whether the primary key is set or not. // * // * @return true if the primary key is set, false otherwise // */ // boolean isIdSet(); // } // Path: src/test/java/demo/Address.java import com.google.common.base.MoreObjects; import com.jaxio.jpa.querybyexample.Identifiable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.persistence.*; import java.io.Serializable; /* * Source code generated by Celerio, a Jaxio product. * Documentation: http://www.jaxio.com/documentation/celerio/ * Follow us on twitter: @jaxiosoft * Need commercial support ? Contact us: [email protected] * Template pack-backend-jpa:src/main/java/domain/Entity.e.vm.java * Template is part of Open Source Project: https://github.com/jaxio/pack-backend-jpa */ package demo; @Entity @Table(name = "ADDRESS")
public class Address implements Identifiable<Integer>, Serializable {
jaxio/jpa-query-by-example
src/test/java/demo/IdentifiableHashBuilder.java
// Path: src/main/java/com/jaxio/jpa/querybyexample/Identifiable.java // public interface Identifiable<PK extends Serializable> { // // /** // * @return the primary key // */ // PK getId(); // // /** // * Sets the primary key // * // * @param id primary key // */ // void setId(PK id); // // /** // * Helper method to know whether the primary key is set or not. // * // * @return true if the primary key is set, false otherwise // */ // boolean isIdSet(); // }
import com.jaxio.jpa.querybyexample.Identifiable; import org.slf4j.Logger; import java.io.Serializable;
/* * Source code generated by Celerio, a Jaxio product. * Documentation: http://www.jaxio.com/documentation/celerio/ * Follow us on twitter: @jaxiosoft * Need commercial support ? Contact us: [email protected] * Template pack-backend-jpa:src/main/java/domain/support/IdentifiableHashBuilder.p.vm.java * Template is part of Open Source Project: https://github.com/jaxio/pack-backend-jpa */ package demo; /** * The first time the {@link #hash(Logger, Identifiable)} is called, we check if the primary key is present or not. * <ul> * <li>If yes: we use it to get the hash</li> * <li>If no: we use a VMID during the entire life of this instance even if later on this instance is assigned a primary key.</li> * </ul> */ public class IdentifiableHashBuilder implements Serializable { private static final long serialVersionUID = 1L; private Object technicalId;
// Path: src/main/java/com/jaxio/jpa/querybyexample/Identifiable.java // public interface Identifiable<PK extends Serializable> { // // /** // * @return the primary key // */ // PK getId(); // // /** // * Sets the primary key // * // * @param id primary key // */ // void setId(PK id); // // /** // * Helper method to know whether the primary key is set or not. // * // * @return true if the primary key is set, false otherwise // */ // boolean isIdSet(); // } // Path: src/test/java/demo/IdentifiableHashBuilder.java import com.jaxio.jpa.querybyexample.Identifiable; import org.slf4j.Logger; import java.io.Serializable; /* * Source code generated by Celerio, a Jaxio product. * Documentation: http://www.jaxio.com/documentation/celerio/ * Follow us on twitter: @jaxiosoft * Need commercial support ? Contact us: [email protected] * Template pack-backend-jpa:src/main/java/domain/support/IdentifiableHashBuilder.p.vm.java * Template is part of Open Source Project: https://github.com/jaxio/pack-backend-jpa */ package demo; /** * The first time the {@link #hash(Logger, Identifiable)} is called, we check if the primary key is present or not. * <ul> * <li>If yes: we use it to get the hash</li> * <li>If no: we use a VMID during the entire life of this instance even if later on this instance is assigned a primary key.</li> * </ul> */ public class IdentifiableHashBuilder implements Serializable { private static final long serialVersionUID = 1L; private Object technicalId;
public int hash(Logger log, Identifiable<?> identifiable) {
jaxio/jpa-query-by-example
src/test/java/demo/Account.java
// Path: src/main/java/com/jaxio/jpa/querybyexample/Identifiable.java // public interface Identifiable<PK extends Serializable> { // // /** // * @return the primary key // */ // PK getId(); // // /** // * Sets the primary key // * // * @param id primary key // */ // void setId(PK id); // // /** // * Helper method to know whether the primary key is set or not. // * // * @return true if the primary key is set, false otherwise // */ // boolean isIdSet(); // }
import com.google.common.base.MoreObjects; import com.google.common.base.Objects; import com.jaxio.jpa.querybyexample.Identifiable; import org.hibernate.annotations.GenericGenerator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.persistence.*; import javax.persistence.criteria.CriteriaBuilder; import java.io.Serializable; import java.util.Date; import static javax.persistence.CascadeType.MERGE; import static javax.persistence.CascadeType.PERSIST; import static javax.persistence.FetchType.LAZY; import static javax.persistence.TemporalType.TIMESTAMP;
/* * Source code generated by Celerio, a Jaxio product. * Documentation: http://www.jaxio.com/documentation/celerio/ * Follow us on twitter: @jaxiosoft * Need commercial support ? Contact us: [email protected] * Template pack-backend-jpa:src/main/java/domain/Entity.e.vm.java * Template is part of Open Source Project: https://github.com/jaxio/pack-backend-jpa */ package demo; @Entity @Table(name = "ACCOUNT")
// Path: src/main/java/com/jaxio/jpa/querybyexample/Identifiable.java // public interface Identifiable<PK extends Serializable> { // // /** // * @return the primary key // */ // PK getId(); // // /** // * Sets the primary key // * // * @param id primary key // */ // void setId(PK id); // // /** // * Helper method to know whether the primary key is set or not. // * // * @return true if the primary key is set, false otherwise // */ // boolean isIdSet(); // } // Path: src/test/java/demo/Account.java import com.google.common.base.MoreObjects; import com.google.common.base.Objects; import com.jaxio.jpa.querybyexample.Identifiable; import org.hibernate.annotations.GenericGenerator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.persistence.*; import javax.persistence.criteria.CriteriaBuilder; import java.io.Serializable; import java.util.Date; import static javax.persistence.CascadeType.MERGE; import static javax.persistence.CascadeType.PERSIST; import static javax.persistence.FetchType.LAZY; import static javax.persistence.TemporalType.TIMESTAMP; /* * Source code generated by Celerio, a Jaxio product. * Documentation: http://www.jaxio.com/documentation/celerio/ * Follow us on twitter: @jaxiosoft * Need commercial support ? Contact us: [email protected] * Template pack-backend-jpa:src/main/java/domain/Entity.e.vm.java * Template is part of Open Source Project: https://github.com/jaxio/pack-backend-jpa */ package demo; @Entity @Table(name = "ACCOUNT")
public class Account implements Identifiable<Integer>, Serializable {
jaxio/jpa-query-by-example
src/main/java/com/jaxio/jpa/querybyexample/SearchParameters.java
// Path: src/main/java/com/jaxio/jpa/querybyexample/PropertySelector.java // public static <E, F> PropertySelector<E, F> newPropertySelector(Attribute<?, ?>... fields) { // return new PropertySelector<E, F>(checkNotNull(fields)); // }
import static com.jaxio.jpa.querybyexample.PropertySelector.newPropertySelector; import static org.apache.commons.lang.StringUtils.isNotBlank; import com.google.common.base.Function; import org.apache.commons.lang.builder.ToStringBuilder; import javax.persistence.metamodel.Attribute; import javax.persistence.metamodel.SingularAttribute; import java.io.Serializable; import java.util.List; import java.util.Map; import java.util.Set; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.collect.Lists.newArrayList; import static com.google.common.collect.Lists.transform; import static com.google.common.collect.Maps.newHashMap; import static com.google.common.collect.Sets.newHashSet;
} public <D extends Comparable<? super D>> SearchParameters range(D from, D to, Attribute<?, ?>... attributes) { return range(new Range<D, D>(from, to, attributes)); } // ----------------------------------- // Search by property selector support // ----------------------------------- public List<PropertySelector<?, ?>> getProperties() { return properties; } public void addProperty(PropertySelector<?, ?> propertySelector) { properties.add(checkNotNull(propertySelector)); } public boolean hasProperties() { return !properties.isEmpty(); } public SearchParameters property(PropertySelector<?, ?>... propertySelectors) { for (PropertySelector<?, ?> propertySelector : checkNotNull(propertySelectors)) { addProperty(propertySelector); } return this; } public <F> SearchParameters property(Attribute<?, ?> fields, F... selected) {
// Path: src/main/java/com/jaxio/jpa/querybyexample/PropertySelector.java // public static <E, F> PropertySelector<E, F> newPropertySelector(Attribute<?, ?>... fields) { // return new PropertySelector<E, F>(checkNotNull(fields)); // } // Path: src/main/java/com/jaxio/jpa/querybyexample/SearchParameters.java import static com.jaxio.jpa.querybyexample.PropertySelector.newPropertySelector; import static org.apache.commons.lang.StringUtils.isNotBlank; import com.google.common.base.Function; import org.apache.commons.lang.builder.ToStringBuilder; import javax.persistence.metamodel.Attribute; import javax.persistence.metamodel.SingularAttribute; import java.io.Serializable; import java.util.List; import java.util.Map; import java.util.Set; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.collect.Lists.newArrayList; import static com.google.common.collect.Lists.transform; import static com.google.common.collect.Maps.newHashMap; import static com.google.common.collect.Sets.newHashSet; } public <D extends Comparable<? super D>> SearchParameters range(D from, D to, Attribute<?, ?>... attributes) { return range(new Range<D, D>(from, to, attributes)); } // ----------------------------------- // Search by property selector support // ----------------------------------- public List<PropertySelector<?, ?>> getProperties() { return properties; } public void addProperty(PropertySelector<?, ?> propertySelector) { properties.add(checkNotNull(propertySelector)); } public boolean hasProperties() { return !properties.isEmpty(); } public SearchParameters property(PropertySelector<?, ?>... propertySelectors) { for (PropertySelector<?, ?> propertySelector : checkNotNull(propertySelectors)) { addProperty(propertySelector); } return this; } public <F> SearchParameters property(Attribute<?, ?> fields, F... selected) {
return property(newPropertySelector(fields).selected(selected));
CD4017BE/ThermokineticEngineering
src/java/cd4017be/kineng/capability/StructureLocations.java
// Path: src/java/cd4017be/kineng/Main.java // @Mod(modid = Main.ID, useMetadata = true) // public class Main { // // public static final String ID = "kineng"; // // @Instance(ID) // public static Main instance; // // public static Logger LOG; // // @SidedProxy(clientSide = "cd4017be." + ID + ".ClientProxy", serverSide = "cd4017be." + ID + ".CommonProxy") // public static CommonProxy proxy; // // public Main() { // RecipeScriptContext.scriptRegistry.add(new Version("kinetic", "/assets/" + ID + "/config/recipes.rcp")); // } // // @Mod.EventHandler // public void preInit(FMLPreInitializationEvent event) { // LOG = event.getModLog(); // proxy.preInit(); // StructureLocations.register(); // RecipeScriptContext.instance.run("kinetic.PRE_INIT"); // } // // @Mod.EventHandler // public void load(FMLInitializationEvent event) { // Objects.init(); // proxy.init(new ConfigConstants(RecipeScriptContext.instance.modules.get("kinetic"))); // } // // @Mod.EventHandler // public void postInit(FMLPostInitializationEvent event) { // Ticking.init(); // } // // @Mod.EventHandler // public void onShutdown(FMLServerStoppingEvent event) { // Ticking.clear(); // } // // }
import java.util.*; import cd4017be.kineng.Main; import net.minecraft.nbt.*; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.EnumFacing; import net.minecraft.util.ResourceLocation; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import net.minecraft.world.chunk.Chunk; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.common.capabilities.*; import net.minecraftforge.common.util.INBTSerializable; import net.minecraftforge.event.AttachCapabilitiesEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
package cd4017be.kineng.capability; /** * @author CD4017BE */ public class StructureLocations implements ICapabilityProvider, INBTSerializable<NBTBase> { @CapabilityInject(StructureLocations.class) public static final Capability<StructureLocations> MULTIBLOCKS = null; public static void register() {} static { CapabilityManager.INSTANCE.register( StructureLocations.class, new BasicStorage<StructureLocations>(), StructureLocations::new ); MinecraftForge.EVENT_BUS.register(StructureLocations.class); } @SubscribeEvent public static void attachCapabilities(AttachCapabilitiesEvent<Chunk> event) {
// Path: src/java/cd4017be/kineng/Main.java // @Mod(modid = Main.ID, useMetadata = true) // public class Main { // // public static final String ID = "kineng"; // // @Instance(ID) // public static Main instance; // // public static Logger LOG; // // @SidedProxy(clientSide = "cd4017be." + ID + ".ClientProxy", serverSide = "cd4017be." + ID + ".CommonProxy") // public static CommonProxy proxy; // // public Main() { // RecipeScriptContext.scriptRegistry.add(new Version("kinetic", "/assets/" + ID + "/config/recipes.rcp")); // } // // @Mod.EventHandler // public void preInit(FMLPreInitializationEvent event) { // LOG = event.getModLog(); // proxy.preInit(); // StructureLocations.register(); // RecipeScriptContext.instance.run("kinetic.PRE_INIT"); // } // // @Mod.EventHandler // public void load(FMLInitializationEvent event) { // Objects.init(); // proxy.init(new ConfigConstants(RecipeScriptContext.instance.modules.get("kinetic"))); // } // // @Mod.EventHandler // public void postInit(FMLPostInitializationEvent event) { // Ticking.init(); // } // // @Mod.EventHandler // public void onShutdown(FMLServerStoppingEvent event) { // Ticking.clear(); // } // // } // Path: src/java/cd4017be/kineng/capability/StructureLocations.java import java.util.*; import cd4017be.kineng.Main; import net.minecraft.nbt.*; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.EnumFacing; import net.minecraft.util.ResourceLocation; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import net.minecraft.world.chunk.Chunk; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.common.capabilities.*; import net.minecraftforge.common.util.INBTSerializable; import net.minecraftforge.event.AttachCapabilitiesEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; package cd4017be.kineng.capability; /** * @author CD4017BE */ public class StructureLocations implements ICapabilityProvider, INBTSerializable<NBTBase> { @CapabilityInject(StructureLocations.class) public static final Capability<StructureLocations> MULTIBLOCKS = null; public static void register() {} static { CapabilityManager.INSTANCE.register( StructureLocations.class, new BasicStorage<StructureLocations>(), StructureLocations::new ); MinecraftForge.EVENT_BUS.register(StructureLocations.class); } @SubscribeEvent public static void attachCapabilities(AttachCapabilitiesEvent<Chunk> event) {
event.addCapability(new ResourceLocation(Main.ID, "mbs"), new StructureLocations());
CD4017BE/ThermokineticEngineering
src/java/cd4017be/kineng/jeiPlugin/KineticCategory.java
// Path: src/java/cd4017be/kineng/Main.java // @Mod(modid = Main.ID, useMetadata = true) // public class Main { // // public static final String ID = "kineng"; // // @Instance(ID) // public static Main instance; // // public static Logger LOG; // // @SidedProxy(clientSide = "cd4017be." + ID + ".ClientProxy", serverSide = "cd4017be." + ID + ".CommonProxy") // public static CommonProxy proxy; // // public Main() { // RecipeScriptContext.scriptRegistry.add(new Version("kinetic", "/assets/" + ID + "/config/recipes.rcp")); // } // // @Mod.EventHandler // public void preInit(FMLPreInitializationEvent event) { // LOG = event.getModLog(); // proxy.preInit(); // StructureLocations.register(); // RecipeScriptContext.instance.run("kinetic.PRE_INIT"); // } // // @Mod.EventHandler // public void load(FMLInitializationEvent event) { // Objects.init(); // proxy.init(new ConfigConstants(RecipeScriptContext.instance.modules.get("kinetic"))); // } // // @Mod.EventHandler // public void postInit(FMLPostInitializationEvent event) { // Ticking.init(); // } // // @Mod.EventHandler // public void onShutdown(FMLServerStoppingEvent event) { // Ticking.clear(); // } // // } // // Path: src/java/cd4017be/kineng/recipe/ProcessingRecipes.java // public class ProcessingRecipes implements IRecipeHandler { // // public final HashMap<ItemKey, KineticRecipe> recipes = new HashMap<>(); // public final String name; // // public ProcessingRecipes(int type, String name) { // this.name = name; // type >>= 8; // if (type >= recipeList.length) // recipeList = Arrays.copyOf(recipeList, recipeList.length << 1); // recipeList[type] = this; // } // // public KineticRecipe get(ItemStack ing) { // KineticRecipe rcp = recipes.get(new ItemKey(ing)); // if (rcp == null && ing.getHasSubtypes()) // rcp = recipes.get(new ItemKey(new ItemStack(ing.getItem(), 1, OreDictionary.WILDCARD_VALUE))); // return rcp; // } // // public void add(KineticRecipe rcp) { // recipes.put(new ItemKey(rcp.io[0]), rcp); // } // // @Override // public void addRecipe(Parameters param) { // Object[] out = param.getArrayOrAll(4); // KineticRecipe rcp = new KineticRecipe(param.getNumber(3), param.getNumber(2), new ItemStack[out.length + 1]); // System.arraycopy(out, 0, rcp.io, 1, out.length); // Object o; // if (param.param[1] instanceof OreDictStack) // o = ((OreDictStack)param.param[1]).getItems(); // else o = param.get(1); // for (Object e : o instanceof Object[] ? (Object[])o : new Object[] {o}) // if (e instanceof ItemStack && !((ItemStack)e).isEmpty()) { // if (rcp.io[0] == null) rcp.io[0] = (ItemStack)e; // recipes.put(new ItemKey((ItemStack)e), rcp); // } // } // // public String jeiName() { // return Main.ID + ":" + name; // } // // public static ProcessingRecipes[] recipeList = new ProcessingRecipes[16]; // public static final ProcessingRecipes SAWMILL = new ProcessingRecipes(T_SAWBLADE, "sawmill"); // public static final ProcessingRecipes GRINDER = new ProcessingRecipes(T_GRINDER, "grinder"); // public static final ProcessingRecipes LATHE = new ProcessingRecipes(T_ANGULAR, "lathe"); // public static final ProcessingRecipes PRESS = new ProcessingRecipes(T_BELT, "press"); // public static IntConsumer JEI_SHOW_RECIPES; // public static final ResourceLocation GUI_TEX = new ResourceLocation(Main.ID, "textures/gui/processing.png"); // // public static ProcessingRecipes getRecipeList(int mode) { // mode >>>= 8; // return mode < recipeList.length ? recipeList[mode] : null; // } // // }
import cd4017be.kineng.Main; import cd4017be.kineng.recipe.ProcessingRecipes; import cd4017be.lib.util.TooltipUtil; import mezz.jei.api.IGuiHelper; import mezz.jei.api.gui.*; import mezz.jei.api.ingredients.IIngredients; import mezz.jei.api.recipe.IRecipeCategory; import net.minecraft.client.Minecraft;
package cd4017be.kineng.jeiPlugin; /** * @author CD4017BE * */ public class KineticCategory implements IRecipeCategory<KineticRecipeW> { public final String uid; final IDrawable icon; final String title; public KineticCategory(IGuiHelper guiHelper, String uid, int type) { this.uid = uid;
// Path: src/java/cd4017be/kineng/Main.java // @Mod(modid = Main.ID, useMetadata = true) // public class Main { // // public static final String ID = "kineng"; // // @Instance(ID) // public static Main instance; // // public static Logger LOG; // // @SidedProxy(clientSide = "cd4017be." + ID + ".ClientProxy", serverSide = "cd4017be." + ID + ".CommonProxy") // public static CommonProxy proxy; // // public Main() { // RecipeScriptContext.scriptRegistry.add(new Version("kinetic", "/assets/" + ID + "/config/recipes.rcp")); // } // // @Mod.EventHandler // public void preInit(FMLPreInitializationEvent event) { // LOG = event.getModLog(); // proxy.preInit(); // StructureLocations.register(); // RecipeScriptContext.instance.run("kinetic.PRE_INIT"); // } // // @Mod.EventHandler // public void load(FMLInitializationEvent event) { // Objects.init(); // proxy.init(new ConfigConstants(RecipeScriptContext.instance.modules.get("kinetic"))); // } // // @Mod.EventHandler // public void postInit(FMLPostInitializationEvent event) { // Ticking.init(); // } // // @Mod.EventHandler // public void onShutdown(FMLServerStoppingEvent event) { // Ticking.clear(); // } // // } // // Path: src/java/cd4017be/kineng/recipe/ProcessingRecipes.java // public class ProcessingRecipes implements IRecipeHandler { // // public final HashMap<ItemKey, KineticRecipe> recipes = new HashMap<>(); // public final String name; // // public ProcessingRecipes(int type, String name) { // this.name = name; // type >>= 8; // if (type >= recipeList.length) // recipeList = Arrays.copyOf(recipeList, recipeList.length << 1); // recipeList[type] = this; // } // // public KineticRecipe get(ItemStack ing) { // KineticRecipe rcp = recipes.get(new ItemKey(ing)); // if (rcp == null && ing.getHasSubtypes()) // rcp = recipes.get(new ItemKey(new ItemStack(ing.getItem(), 1, OreDictionary.WILDCARD_VALUE))); // return rcp; // } // // public void add(KineticRecipe rcp) { // recipes.put(new ItemKey(rcp.io[0]), rcp); // } // // @Override // public void addRecipe(Parameters param) { // Object[] out = param.getArrayOrAll(4); // KineticRecipe rcp = new KineticRecipe(param.getNumber(3), param.getNumber(2), new ItemStack[out.length + 1]); // System.arraycopy(out, 0, rcp.io, 1, out.length); // Object o; // if (param.param[1] instanceof OreDictStack) // o = ((OreDictStack)param.param[1]).getItems(); // else o = param.get(1); // for (Object e : o instanceof Object[] ? (Object[])o : new Object[] {o}) // if (e instanceof ItemStack && !((ItemStack)e).isEmpty()) { // if (rcp.io[0] == null) rcp.io[0] = (ItemStack)e; // recipes.put(new ItemKey((ItemStack)e), rcp); // } // } // // public String jeiName() { // return Main.ID + ":" + name; // } // // public static ProcessingRecipes[] recipeList = new ProcessingRecipes[16]; // public static final ProcessingRecipes SAWMILL = new ProcessingRecipes(T_SAWBLADE, "sawmill"); // public static final ProcessingRecipes GRINDER = new ProcessingRecipes(T_GRINDER, "grinder"); // public static final ProcessingRecipes LATHE = new ProcessingRecipes(T_ANGULAR, "lathe"); // public static final ProcessingRecipes PRESS = new ProcessingRecipes(T_BELT, "press"); // public static IntConsumer JEI_SHOW_RECIPES; // public static final ResourceLocation GUI_TEX = new ResourceLocation(Main.ID, "textures/gui/processing.png"); // // public static ProcessingRecipes getRecipeList(int mode) { // mode >>>= 8; // return mode < recipeList.length ? recipeList[mode] : null; // } // // } // Path: src/java/cd4017be/kineng/jeiPlugin/KineticCategory.java import cd4017be.kineng.Main; import cd4017be.kineng.recipe.ProcessingRecipes; import cd4017be.lib.util.TooltipUtil; import mezz.jei.api.IGuiHelper; import mezz.jei.api.gui.*; import mezz.jei.api.ingredients.IIngredients; import mezz.jei.api.recipe.IRecipeCategory; import net.minecraft.client.Minecraft; package cd4017be.kineng.jeiPlugin; /** * @author CD4017BE * */ public class KineticCategory implements IRecipeCategory<KineticRecipeW> { public final String uid; final IDrawable icon; final String title; public KineticCategory(IGuiHelper guiHelper, String uid, int type) { this.uid = uid;
this.icon = guiHelper.createDrawable(ProcessingRecipes.GUI_TEX, 208, type * 16, 16, 16);