answer
stringlengths 17
10.2M
|
|---|
package edu.iastate.cs.design.spec.post;
import edu.iastate.cs.design.spec.common.Specification;
import edu.iastate.cs.design.spec.persistenceResource.FactoryStartup;
import edu.iastate.cs.design.spec.stackexchange.request.IStackExchangeRequester;
import edu.iastate.cs.design.spec.stackexchange.request.QuestionAddRequestData;
import edu.iastate.cs.design.spec.stackexchange.request.StackExchangeRequester;
import javax.persistence.EntityManager;
import java.util.Arrays;
import java.util.List;
/**
* This class contains the main method for the part of the system that will
* find specifications in the database that need to be verified and will post
* them as questions on StackOverflow.
*/
public class Post {
private IPendingSpecificationDao pendingSpecificationDao;
private IStackExchangeRequester stackExchangeRequester;
public Post(IPendingSpecificationDao pendingSpecificationDao, IStackExchangeRequester stackExchangeRequester) {
this.pendingSpecificationDao = pendingSpecificationDao;
this.stackExchangeRequester = stackExchangeRequester;
}
public void run() {
Specification pendingSpecification = pendingSpecificationDao.removeNextPendingSpecification();
QuestionAddRequestData requestData = createQuestionAddRequestData(pendingSpecification);
stackExchangeRequester.postQuestion(requestData);
}
private QuestionAddRequestData createQuestionAddRequestData(Specification pendingSpecification) {
String title = createQuestionTitle(pendingSpecification);
String body = createQuestionBody(pendingSpecification);
List<String> tags = createQuestionTags(pendingSpecification);
String key = getStackExchangeKey();
String accessToken = getStackExchangeAccessToken();
return new QuestionAddRequestData(title, body, tags, key, accessToken);
}
private String getStackExchangeAccessToken() {
// TODO implement this correctly
return "access_token";
}
private String getStackExchangeKey() {
// TODO implement this correctly
return "key";
}
private List<String> createQuestionTags(Specification pendingSpecification) {
return Arrays.asList("JML", "Java", pendingSpecification.getClassName());
}
private String createQuestionTitle(Specification pendingSpecification) {
return "What should the JML specification be for the " + pendingSpecification.getMethodName() + "() method?";
}
private String createQuestionBody(Specification pendingSpecification) {
StringBuilder postBody = new StringBuilder();
postBody.append("What would be the proper JML specification for the <code>");
postBody.append(pendingSpecification.getMethodName());
postBody.append("()</code> method in the <code>");
postBody.append(pendingSpecification.getFullPackageName());
postBody.append(" package.");
postBody.append(pendingSpecification.getClassName());
postBody.append("</code>\n");
postBody.append("What I have for this method so far is: \n <code>");
for (String precondition : pendingSpecification.getPreconditions()) {
postBody.append(precondition);
postBody.append('\n');
}
for (String postcondition : pendingSpecification.getPostconditions()) {
postBody.append(postcondition);
postBody.append('\n');
}
postBody.append("public ");
postBody.append(pendingSpecification.getReturnType());
postBody.append(' ');
postBody.append(pendingSpecification.getMethodName());
postBody.append("(");
List<String> params = pendingSpecification.getFormalParameters();
for (int i = 0; i < params.size(); ++i) {
postBody.append(params.get(i));
if (i != params.size() - 1) {
postBody.append(", ");
}
}
postBody.append(")</code>");
// TODO we probably want to use method bodies here
return postBody.toString();
}
// Entry point
public static void main(String[] args) {
EntityManager entityManager = FactoryStartup.getAnEntityManager();
PendingSpecificationDao pendingSpecificationDao = new PendingSpecificationDao(entityManager);
StackExchangeRequester stackExchangeRequester = new StackExchangeRequester();
Post program = new Post(pendingSpecificationDao, stackExchangeRequester);
program.run();
}
}
|
package archimulator.util.akka;
import akka.actor.*;
import archimulator.util.DateHelper;
import org.apache.commons.lang.time.StopWatch;
import org.jfree.data.statistics.Statistics;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class ActorBasedSimulationHelper {
public static void main(String[] args) {
execute();
}
private static long execute() {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
ActorSystem system = ActorSystem.create("experiment");
ActorRef processor = system.actorOf(new Props(new UntypedActorFactory() {
public UntypedActor create() {
return new Processor(2, 2);
}
}), "processor");
processor.tell(new SimulationConfig("mst", 1000000000L));
system.awaitTermination();
stopWatch.stop();
System.out.println(stopWatch.getTime());
return stopWatch.getTime();
}
private static class SimulationConfig implements Serializable {
private String workload;
private long maxCycles;
public SimulationConfig(String workload, long maxCycles) {
this.workload = workload;
this.maxCycles = maxCycles;
}
}
private static class ExecuteOneCycle implements Serializable {
private long currentCycle;
public ExecuteOneCycle(long currentCycle) {
this.currentCycle = currentCycle;
}
}
private static class OneCycleExecuted implements Serializable {
}
public static class Core extends UntypedActor {
public void onReceive(Object o) throws Exception {
if (o instanceof ExecuteOneCycle) {
ExecuteOneCycle executeOneCycle = (ExecuteOneCycle) o;
// System.out.printf("[%s %s: %d] Execute one cycle.\n", DateHelper.toString(new Date()), getSelf().path().name(), executeOneCycle.currentCycle);
getSender().tell(new OneCycleExecuted(), getSelf());
} else {
unhandled(o);
}
}
}
private static class Processor extends UntypedActor {
private int numCores;
private int numThreadsPerCore;
private List<ActorRef> cores;
private long currentCycle = 0;
private long maxCycles = 0;
private int numPendings = 0;
public Processor(int numCores, int numThreadsPerCore) {
this.numCores = numCores;
this.numThreadsPerCore = numThreadsPerCore;
this.cores = new ArrayList<ActorRef>();
for (int i = 0; i < numCores; i++) {
for (int j = 0; j < numThreadsPerCore; j++) {
this.cores.add(
this.getContext().actorOf(new Props(new UntypedActorFactory() {
public UntypedActor create() {
return new Core();
}
}), "core_" + i + "_" + j));
}
}
}
public void onReceive(Object o) throws Exception {
if (o instanceof SimulationConfig) {
SimulationConfig simulationConfig = (SimulationConfig) o;
maxCycles = simulationConfig.maxCycles;
executeOneCycle(currentCycle);
} else if (o instanceof OneCycleExecuted) {
OneCycleExecuted oneCycleExecuted = (OneCycleExecuted) o;
numPendings
if (numPendings == 0) {
// System.out.printf("[%s %s: %d] Execute one cycle.\n", DateHelper.toString(new Date()), getSelf().path().name(), currentCycle);
if(currentCycle % 1000000 == 0) {
System.out.printf("[%s %s: %d] Execute one cycle.\n", DateHelper.toString(new Date()), getSelf().path().name(), currentCycle);
}
currentCycle++;
if (currentCycle < maxCycles) {
executeOneCycle(currentCycle);
} else {
System.out.println("Simulation stopped.");
getContext().system().shutdown();
}
}
} else {
unhandled(o);
}
}
private void executeOneCycle(long currentCycle) {
numPendings = this.cores.size();
for (ActorRef core : cores) {
core.tell(new ExecuteOneCycle(currentCycle), getSelf());
}
}
}
}
|
package at.dru.ratemonitor.service.impl;
import at.dru.ratemonitor.data.ConversionRate;
import at.dru.ratemonitor.service.IHtmlParser;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.annotation.Nonnull;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
@Component
public class DefaultHtmlParser implements IHtmlParser {
private static final SimpleDateFormat DATE_FORMAT_RATE = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss");
private static final String URL = "https:
@Value("${application.timeOut}")
private int timeOut;
@Value("${application.userAgent}")
private String userAgent;
@Nonnull
@Override
public List<ConversionRate> getConversionRates() {
try {
return loadRatesFromURL();
} catch (IOException | ParseException e) {
throw new RuntimeException("Cannot parse rates", e);
}
}
@Nonnull
private List<ConversionRate> loadRatesFromURL() throws IOException, ParseException {
Document doc = Jsoup.connect(URL)
.timeout(timeOut)
.userAgent(userAgent)
.get();
ConversionRate cr = new ConversionRate();
String changedDatePart = Optional.ofNullable(doc.select("body > div > div > p:nth-child(1)"))
.map(Elements::text)
.map(text -> text.replace("Datum: ", "").trim())
.orElseThrow(() -> new IllegalStateException("Cannot select changed date"));
String changedTimePart = Optional.ofNullable(doc.select("body > div > div > p:nth-child(2)"))
.map(Elements::text)
.map(text -> text.replace("Zeit: ", "").trim())
.orElseThrow(() -> new IllegalStateException("Cannot select changed time"));
String changedDate = changedDatePart + " " + changedTimePart;
String country = Optional.ofNullable(doc.select("body > div > div > table > tbody > tr:nth-child(6) > td:nth-child(1)"))
.map(Elements::text)
.orElseThrow(() -> new IllegalStateException("Cannot select country"));
double buyRate = Optional.ofNullable(doc.select("body > div > div > table > tbody > tr:nth-child(6) > td:nth-child(3)"))
.map(Elements::text)
.map(Double::valueOf)
.orElseThrow(() -> new IllegalStateException("Cannot select buy rate"));
double sellRate = Optional.ofNullable(doc.select("body > div > div > table > tbody > tr:nth-child(6) > td:nth-child(4)"))
.map(Elements::text)
.map(Double::valueOf)
.orElseThrow(() -> new IllegalStateException("Cannot select selll rate"));
cr.setFromCurrency("CHF");
cr.setCountry(country);
cr.setToCurrency("EUR");
cr.setBuyRate(buyRate);
cr.setSellRate(sellRate);
cr.setChangedDate(changedDate);
cr.setParsedDate(DATE_FORMAT_RATE.parse(changedDate));
return Collections.singletonList(cr);
}
}
|
package org.exist.xquery;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;
import org.exist.storage.DBBroker;
import org.exist.xmldb.DatabaseInstanceManager;
import org.exist.xmldb.EXistResource;
import org.xmldb.api.DatabaseManager;
import org.xmldb.api.base.Collection;
import org.xmldb.api.base.CompiledExpression;
import org.xmldb.api.base.Database;
import org.xmldb.api.base.ResourceSet;
import org.xmldb.api.base.XMLDBException;
import org.xmldb.api.modules.BinaryResource;
import org.xmldb.api.modules.CollectionManagementService;
import org.xmldb.api.modules.XQueryService;
import org.junit.*;
import static org.junit.Assert.*;
/**
* @author wolf
*
*/
public class StoredModuleTest {
private final static Logger LOG = Logger.getLogger(StoredModuleTest.class);
private final static String URI = "xmldb:exist://" + DBBroker.ROOT_COLLECTION;
// private final static String DRIVER = "org.exist.xmldb.DatabaseImpl";
private final static String MODULE =
"module namespace itg-modules = \"http://localhost:80/itg/xquery\";\n" +
"declare variable $itg-modules:colls as xs:string+ external;\n" +
"declare variable $itg-modules:coll as xs:string external;\n" +
"declare variable $itg-modules:ordinal as xs:integer external;\n" +
"declare function itg-modules:check-coll() as xs:boolean {\n" +
" if (fn:empty($itg-modules:coll)) then fn:false()\n" +
" else fn:true()\n" +
"};";
private static Collection rootCollection = null;
private static CollectionManagementService cmService = null;
private static XQueryService xqService = null;
private static Database database = null;
@BeforeClass
public static void first() {
LOG.info("Starting...");
try {
BasicConfigurator.configure();
Class<?> cl = Class.forName("org.exist.xmldb.DatabaseImpl");
database = (Database) cl.newInstance();
database.setProperty("create-database", "true");
DatabaseManager.registerDatabase(database);
rootCollection = DatabaseManager.getCollection(URI, "admin", "");
xqService = (XQueryService) rootCollection.getService("XQueryService", "1.0");
cmService = (CollectionManagementService) rootCollection.getService("CollectionManagementService", "1.0");
} catch (Exception ex) {
LOG.error(ex);
}
}
@AfterClass
public static void tearDown() throws XMLDBException {
LOG.info("Shutting down");
DatabaseManager.deregisterDatabase(database);
DatabaseInstanceManager dim =
(DatabaseInstanceManager) rootCollection.getService("DatabaseInstanceManager", "1.0");
dim.shutdown();
}
private Collection createCollection(String collectionName) throws XMLDBException {
LOG.info("Create collection " + collectionName);
Collection collection = rootCollection.getChildCollection(collectionName);
if (collection == null) {
//cmService.removeCollection(collectionName);
cmService.createCollection(collectionName);
}
collection = DatabaseManager.getCollection(URI + "/" + collectionName, "admin", "");
assertNotNull(collection);
return collection;
}
private void writeModule(Collection collection, String modulename, String module) throws XMLDBException {
LOG.info("Create module " + modulename);
BinaryResource res = (BinaryResource) collection.createResource(modulename, "BinaryResource");
((EXistResource) res).setMimeType("application/xquery");
res.setContent(module.getBytes());
collection.storeResource(res);
collection.close();
}
private ResourceSet executeQuery(String query) throws XMLDBException {
CompiledExpression compiledQuery = xqService.compile(query);
ResourceSet result = xqService.execute(compiledQuery);
return result;
}
@Test
public void testDB() {
assertNotNull(database);
assertNotNull(rootCollection);
assertNotNull(xqService);
assertNotNull(cmService);
}
@Test
public void testQuery() throws Exception {
Collection c = createCollection("test");
writeModule(c, "test.xqm", MODULE);
String query = "import module namespace itg-modules = \"http://localhost:80/itg/xquery\" at " +
"\"xmldb:exist://" + DBBroker.ROOT_COLLECTION + "/test/test.xqm\"; itg-modules:check-coll()";
String cols[] = {"one", "two", "three"};
xqService.setNamespace("itg-modules", "http://localhost:80/itg/xquery");
CompiledExpression compiledQuery = xqService.compile(query);
for (int i = 0; i < cols.length; i++) {
xqService.declareVariable("itg-modules:coll", cols[i]);
ResourceSet result = xqService.execute(compiledQuery);
System.out.println("Result: " + result.getResource(0).getContent());
}
}
@Test
public void testModule1() throws Exception {
String collectionName = "module1";
String module = "module namespace mod1 = 'urn:module1';" +
"declare function mod1:showMe() as xs:string {" +
"'hi from module 1'" +
"};";
String query = "import module namespace mod1 = 'urn:module1' " +
"at 'xmldb:exist:/" + collectionName + "/module1.xqm'; " +
"mod1:showMe()";
Collection c = createCollection(collectionName);
writeModule(c, "module1.xqm", module);
ResourceSet rs = executeQuery(query);
String r = (String) rs.getResource(0).getContent();
assertEquals("hi from module 1", r);
}
private static final String module2 = "module namespace mod2 = 'urn:module2'; " +
"import module namespace mod3 = 'urn:module3' " +
"at 'module3/module3.xqm'; " +
"declare function mod2:showMe() as xs:string {" +
" mod3:showMe() " +
"};";
private static final String module2b = "module namespace mod2 = 'urn:module2'; " +
"import module namespace mod3 = 'urn:module3' " +
"at 'module3.xqm'; " +
"declare function mod2:showMe() as xs:string {" +
" mod3:showMe() " +
"};";
private static final String module3a = "module namespace mod3 = 'urn:module3';" +
"declare function mod3:showMe() as xs:string {" +
"'hi from module 3a'" +
"};";
private static final String module3b = "module namespace mod3 = 'urn:module3';" +
"import module namespace mod4 = 'urn:module4' " +
"at '../module2/module4.xqm'; " +
"declare function mod3:showMe() as xs:string {" +
"mod4:showMe()" +
"};";
private static final String module4 = "module namespace mod4 = 'urn:module4';" +
"declare function mod4:showMe() as xs:string {" +
"'hi from module 4'" +
"};";
@Test(expected=XMLDBException.class)
public void testModule23_missingRelativeContext() throws XMLDBException {
String collection2Name = "module2";
String collection3Name = "module2/module3";
String query = "import module namespace mod2 = 'urn:module2' " +
"at 'module2/module2.xqm'; " +
"mod2:showMe()";
Collection c2 = createCollection(collection2Name);
writeModule(c2, "module2.xqm", module2);
Collection c3 = createCollection(collection3Name);
writeModule(c3, "module3.xqm", module3a);
ResourceSet rs = executeQuery(query);
String r = (String) rs.getResource(0).getContent();
assertEquals("hi from module 3a", r);
}
@Test
public void testRelativeImportDb() throws Exception {
String collection2Name = "module2";
String collection3Name = "module2/module3";
String query = "import module namespace mod2 = 'urn:module2' " +
"at 'xmldb:exist:/" + collection2Name + "/module2.xqm'; " +
"mod2:showMe()";
Collection c2 = createCollection(collection2Name);
writeModule(c2, "module2.xqm", module2);
writeModule(c2, "module3.xqm", module3b);
writeModule(c2, "module4.xqm", module4);
Collection c3 = createCollection(collection3Name);
writeModule(c3, "module3.xqm", module3a);
// test relative module import in subfolder
try {
ResourceSet rs = executeQuery(query);
String r = (String) rs.getResource(0).getContent();
assertEquals("hi from module 3a", r);
} catch (XMLDBException ex) {
fail(ex.getMessage());
LOG.error(ex);
}
// test relative module import in same folder, and using ".."
writeModule(c2, "module2.xqm", module2b);
try {
ResourceSet rs = executeQuery(query);
String r = (String) rs.getResource(0).getContent();
assertEquals("hi from module 4", r);
} catch (XMLDBException ex) {
fail(ex.getMessage());
LOG.error(ex);
}
}
@Test
public void testRelativeImportFile() throws Exception {
String collection2Name = "module2";
String collection3Name = "module2/module3";
String query = "import module namespace mod2 = 'urn:module2' " +
"at '/test/temp/" + collection2Name + "/module2.xqm'; " +
"mod2:showMe()";
String c2 = "test/temp/" + collection2Name;
writeFile(c2 + "/module2.xqm", module2);
writeFile(c2 + "/module3.xqm", module3b);
writeFile(c2 + "/module4.xqm", module4);
String c3 = "test/temp/" + collection3Name;
writeFile(c3 + "/module3.xqm", module3a);
// test relative module import in subfolder
try {
ResourceSet rs = executeQuery(query);
String r = (String) rs.getResource(0).getContent();
assertEquals("hi from module 3a", r);
} catch (XMLDBException ex) {
fail(ex.getMessage());
LOG.error(ex);
}
// test relative module import in same folder, and using ".."
writeFile(c2 + "/module2.xqm", module2b);
try {
ResourceSet rs = executeQuery(query);
String r = (String) rs.getResource(0).getContent();
assertEquals("hi from module 4", r);
} catch (XMLDBException ex) {
fail(ex.getMessage());
LOG.error(ex);
}
}
@Test
public void testCircularImports() throws XMLDBException {
final String index_module =
"import module namespace module1 = \"http://test/module1\" at \"xmldb:exist:///db/testCircular/module1.xqy\";" +
"module1:func()";
final String module1_module =
"module namespace module1 = \"http://test/module1\";" +
"import module namespace processor = \"http://test/processor\" at \"processor.xqy\";" +
"declare function module1:func()" +
"{" +
" processor:execute()" +
"};" +
"declare function module1:hello($name as xs:string)" +
"{" +
" <hello>{$name}</hello>" +
"};";
final String processor_module =
"module namespace processor = \"http://test/processor\";" +
"import module namespace impl = \"http://test/processor/impl/exist-db\" at \"impl.xqy\";" +
"declare function processor:execute()" +
"{" +
" impl:execute()" +
"};";
final String impl_module =
"module namespace impl = \"http://test/processor/impl/exist-db\";" +
"import module namespace controller = \"http://test/controller\" at \"controller.xqy\";" +
"declare function impl:execute()" +
"{" +
" controller:index()" +
"};";
final String controller_module =
"module namespace controller = \"http://test/controller\";" +
"import module namespace module1 = \"http://test/module1\" at \"module1.xqy\";" +
"declare function controller:index() as item()*" +
"{" +
" module1:hello(\"world\")" +
"};";
Collection testHome = createCollection("testCircular");
//writeModule(testHome, "index.xqy", index_module);
writeModule(testHome, "module1.xqy", module1_module);
writeModule(testHome, "processor.xqy", processor_module);
writeModule(testHome, "impl.xqy", impl_module);
writeModule(testHome, "controller.xqy", controller_module);
CompiledExpression query = xqService.compile(index_module);
ResourceSet execute = xqService.execute(query);
}
private void writeFile(String path, String module) throws IOException {
path = path.replace("/", File.separator);
File f = new File (path);
File dir = f.getParentFile();
assertTrue (dir.exists() || dir.mkdirs());
assertTrue (dir.canWrite());
assertTrue (f.createNewFile() || f.canWrite());
PrintWriter writer = new PrintWriter (new FileOutputStream(f));
writer.print(module);
writer.close();
}
}
|
package at.medunigraz.imi.abbres.resolver;
import java.util.NavigableSet;
import java.util.TreeSet;
import at.medunigraz.imi.abbres.model.Abbreviation;
import at.medunigraz.imi.abbres.model.NGramMapFactory;
import at.medunigraz.imi.abbres.model.mapper.Mapper;
import at.medunigraz.imi.abbres.model.mapper.SingleMapper;
import at.medunigraz.imi.abbres.model.matcher.LeftBigramMatcher;
import at.medunigraz.imi.abbres.model.matcher.Matcher;
import at.medunigraz.imi.abbres.model.matcher.RightBigramMatcher;
import at.medunigraz.imi.abbres.model.matcher.UnigramMatcher;
import at.medunigraz.imi.abbres.model.policy.FuzzyPolicy;
import at.medunigraz.imi.abbres.model.policy.Policy;
import at.medunigraz.imi.abbres.model.policy.StrictPolicy;
import at.medunigraz.imi.abbres.model.reducer.FuzzyBigramWithFallbackReducer;
public class DefaultResolver implements Resolver {
public DefaultResolver() {
NGramMapFactory.warm();
}
@Override
public String resolve(Abbreviation abbreviation) {
Matcher unigram = new UnigramMatcher(abbreviation);
Matcher leftBigram = new LeftBigramMatcher(abbreviation);
Matcher rightBigram = new RightBigramMatcher(abbreviation);
Policy strict = new StrictPolicy();
Mapper strictUnigram = new SingleMapper(unigram, strict);
Mapper strictLeftBigram = new SingleMapper(leftBigram, strict);
Mapper strictRightBigram = new SingleMapper(rightBigram, strict);
Policy fuzzy = new FuzzyPolicy();
Mapper fuzzyUnigram = new SingleMapper(unigram, fuzzy);
Mapper fuzzyLeftBigram = new SingleMapper(leftBigram, fuzzy);
Mapper fuzzyRightBigram = new SingleMapper(rightBigram, fuzzy);
NavigableSet<Mapper> set = new TreeSet<>();
set.add(strictUnigram);
set.add(strictLeftBigram);
set.add(strictRightBigram);
set.add(fuzzyUnigram);
set.add(fuzzyLeftBigram);
set.add(fuzzyRightBigram);
return new FuzzyBigramWithFallbackReducer().reduce(set);
}
}
|
package au.org.ands.vocabs.toolkit.utils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.invoke.MethodHandles;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;
import org.glassfish.jersey.uri.UriComponent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import au.org.ands.vocabs.toolkit.db.TasksUtils;
import au.org.ands.vocabs.toolkit.db.model.Task;
import au.org.ands.vocabs.toolkit.db.model.Versions;
import au.org.ands.vocabs.toolkit.db.model.Vocabularies;
import au.org.ands.vocabs.toolkit.tasks.TaskInfo;
/** Utility methods for working with files. */
public final class ToolkitFileUtils {
/** Logger for this class. */
private static Logger logger;
/** Private contructor for utility class. */
private ToolkitFileUtils() {
}
static {
logger = LoggerFactory.getLogger(
MethodHandles.lookup().lookupClass());
}
/** Require the existence of a directory. Create it, if it
* does not already exist.
* @param dir The full pathname of the required directory.
*/
public static void requireDirectory(final String dir) {
File oDir = new File(dir);
if (!oDir.exists()) {
oDir.mkdirs();
}
}
/** Save data to a file.
* @param dirName The full directory name
* @param fileName The base name of the file to create
* @param format The format to use; a key in
* ToolkitConfig.FORMAT_TO_FILEEXT_MAP.
* @param data The data to be written
* @return The complete, full path to the file.
*/
public static String saveFile(final String dirName, final String fileName,
final String format, final String data) {
String fileExtension =
ToolkitConfig.FORMAT_TO_FILEEXT_MAP.get(format.toLowerCase());
String filePath = dirName
+ File.separator + fileName + fileExtension;
FileWriter writer = null;
try {
requireDirectory(dirName);
File oFile = new File(filePath);
writer = new FileWriter(oFile);
writer.write(data);
writer.close();
} catch (IOException e) {
return "Exception: " + e.toString();
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
return "Exception: " + e.toString();
}
}
}
return filePath;
}
/** Construct a TaskInfo object based on a task id.
* @param taskId The task's task id
* @return The TaskInfo object
*/
public static TaskInfo getTaskInfo(final int taskId) {
Task task = TasksUtils.getTaskById(taskId);
if (task == null) {
logger.error("getTaskInfo: getTaskById returned null; task id:"
+ taskId);
return null;
}
Vocabularies vocab = TasksUtils.getVocabularyById(
task.getVocabularyId());
if (vocab == null) {
logger.error("getTaskInfo: getVocabularyById returned null; "
+ "task id:"
+ taskId + "; vocab id:" + task.getVocabularyId());
return null;
}
Versions version = TasksUtils.getVersionById(task.getVersionId());
if (version == null) {
logger.error("getTaskInfo: getVersionById returned null; "
+ "task id:"
+ taskId + "; version id:" + task.getVersionId());
return null;
}
TaskInfo taskInfo = new TaskInfo(task, vocab, version);
if (version.getVocabId() != task.getVocabularyId()) {
logger.error("getTaskInfo: version's vocab id does not match"
+ " task's version id; "
+ "task id:"
+ taskId + "; version id:" + task.getVersionId());
return null;
}
if (vocab.getSlug() == null || vocab.getSlug().trim().isEmpty()) {
logger.error("getTaskInfo: vocab's slug is empty; "
+ "task id:"
+ taskId + "; vocab id:" + task.getVocabularyId());
return null;
}
if (vocab.getOwner() == null || vocab.getOwner().trim().isEmpty()) {
logger.error("getTaskInfo: vocab's owner is empty; "
+ "task id:"
+ taskId + "; vocab id:" + task.getVocabularyId());
return null;
}
if (version.getTitle() == null || version.getTitle().trim().isEmpty()) {
logger.error("getTaskInfo: version's title is empty; "
+ "task id:"
+ taskId + "; version id:" + task.getVersionId());
return null;
}
return taskInfo;
}
/** Get the full path of the directory used to store all
* the files referred to by the task.
* @param taskInfo The TaskInfo object representing the task.
* @param extraPath An optional additional path component to be added
* at the end. If not required, pass in null or an empty string.
* @return The full path of the directory used to store the
* vocabulary data.
*/
public static String getTaskOutputPath(final TaskInfo taskInfo,
final String extraPath) {
Path path = Paths.get(ToolkitConfig.DATA_FILES_PATH)
.resolve(makeSlug(taskInfo.getVocabulary().getOwner()))
.resolve(makeSlug(taskInfo.getVocabulary().getSlug()))
.resolve(makeSlug(taskInfo.getVersion().getTitle()));
if (extraPath != null && (!extraPath.isEmpty())) {
path = path.resolve(extraPath);
}
return path.toString();
}
/** Get the full path of the directory used to store all
* harvested data referred to by the task.
* @param taskInfo The TaskInfo object representing the task.
* at the end. If not required, pass in null or an empty string.
* @return The full path of the directory used to store the
* vocabulary data.
*/
public static String getTaskHarvestOutputPath(final TaskInfo taskInfo) {
return getTaskOutputPath(taskInfo, ToolkitConfig.HARVEST_DATA_PATH);
}
/** Get the full path of the temporary directory used to store all
* harvested data for metadata extraction for a PoolParty vocabulary.
* @param projectId The PoolParty projectId.
* @return The full path of the directory used to store the
* vocabulary data.
*/
public static String getMetadataOutputPath(final String projectId) {
Path path = Paths.get(ToolkitConfig.METADATA_TEMP_FILES_PATH)
.resolve(makeSlug(projectId));
return path.toString();
}
/** Get the full path of the backup directory used to store all
* backup data for a project.
* @param projectId The project ID. For now, this will be a PoolParty
* project ID.
* @return The full path of the directory used to store the
* vocabulary data.
*/
public static String getBackupPath(final String projectId) {
Path path = Paths.get(ToolkitConfig.BACKUP_FILES_PATH)
.resolve(makeSlug(projectId));
return path.toString();
}
public static String makeSlug(final String aString) {
return UriComponent.encode(aString.
replaceAll("\\s", "-").
replaceAll("/", "-").
toLowerCase(),
UriComponent.Type.PATH_SEGMENT).
replaceAll("%", "-");
}
/**
* Get the Sesame repository ID for a vocabulary's version
* referred to by the task.
*
* @param taskInfo
* The TaskInfo object representing the task.
* @return The repository id for the vocabulary with this version.
*/
public static String getTaskRepositoryId(final TaskInfo taskInfo) {
return makeSlug(taskInfo.getVocabulary().getOwner())
+ "_"
+ makeSlug(taskInfo.getVocabulary().getSlug())
+ "_"
+ makeSlug(taskInfo.getVersion().getTitle());
}
/**
* Get the SISSVoc repository ID for a vocabulary's version
* referred to by the task. It neither begins nor ends with a slash.
*
* @param taskInfo
* The TaskInfo object representing the task.
* @return The repository id for the vocabulary with this version.
*/
public static String getSISSVocRepositoryPath(final TaskInfo taskInfo) {
return makeSlug(taskInfo.getVocabulary().getOwner())
+ "/"
+ makeSlug(taskInfo.getVocabulary().getSlug())
+ "/"
+ makeSlug(taskInfo.getVersion().getTitle());
}
/** Size of buffer to use when writing to a ZIP archive. */
private static final int BUFFER_SIZE = 4096;
/** Add a file to a ZIP archive.
* @param zos The ZipOutputStream representing the ZIP archive.
* @param file The File which is to be added to the ZIP archive.
* @return True if adding succeeded.
* @throws IOException Any exception when reading/writing data.
*/
private static boolean zipFile(final ZipOutputStream zos, final File file)
throws IOException {
if (!file.canRead()) {
logger.error("zipFile can not read " + file.getCanonicalPath());
return false;
}
zos.putNextEntry(new ZipEntry(file.getName()));
FileInputStream fis = new FileInputStream(file);
byte[] buffer = new byte[BUFFER_SIZE];
int byteCount = 0;
while ((byteCount = fis.read(buffer)) != -1) {
zos.write(buffer, 0, byteCount);
}
fis.close();
zos.closeEntry();
return true;
}
/** Compress the files in the backup folder for a project.
* @param projectId The project ID
* @throws IOException Any exception when reading/writing data.
*/
public static void compressBackupFolder(final String projectId)
throws IOException {
String backupPath = getBackupPath(projectId);
if (!Files.isDirectory(Paths.get(backupPath))) {
// No such directory, so nothing to do.
return;
}
String projectSlug = makeSlug(projectId);
// The name of the ZIP file that does/will contain all
// backups for this project.
Path zipFilePath = Paths.get(backupPath).resolve(projectSlug + ".zip");
// A temporary ZIP file. Any existing content in the zipFilePath
// will be copied into this, followed by any other files in
// the directory that have not yet been added.
Path tempZipFilePath = Paths.get(backupPath).resolve("temp" + ".zip");
File tempZipFile = tempZipFilePath.toFile();
if (!tempZipFile.exists()) {
tempZipFile.createNewFile();
}
ZipOutputStream tempZipOut = new ZipOutputStream(
new FileOutputStream(tempZipFile));
File existingZipFile = zipFilePath.toFile();
if (existingZipFile.exists()) {
ZipFile zipIn = new ZipFile(existingZipFile);
Enumeration<? extends ZipEntry> entries = zipIn.entries();
while (entries.hasMoreElements()) {
ZipEntry e = entries.nextElement();
System.out.println("copy: " + e.getName());
tempZipOut.putNextEntry(e);
if (!e.isDirectory()) {
copy(zipIn.getInputStream(e), tempZipOut);
}
tempZipOut.closeEntry();
}
zipIn.close();
}
File dir = new File(backupPath);
File[] files = dir.listFiles();
for (File source : files) {
if (!source.getName().toLowerCase().endsWith(".zip")) {
logger.debug("Compressing and deleting file "
+ source.toString());
if (zipFile(tempZipOut, source)) {
source.delete();
}
}
}
tempZipOut.flush();
tempZipOut.close();
tempZipFile.renameTo(existingZipFile);
}
/** Size of buffer to use for copying files. */
private static final int COPY_BUFFER_SIZE = 4096 * 1024;
/** Copy the contents of an InputStream into an OutputStream.
* @param input The content to be copied.
* @param output The destination of the content being copied.
* @throws IOException Any IOException during read/write.
*/
public static void copy(final InputStream input,
final OutputStream output) throws IOException {
int bytesRead;
byte[] buffer = new byte[COPY_BUFFER_SIZE];
while ((bytesRead = input.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
}
}
}
|
package com.anuragkapur.ada1;
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.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
/**
* Compute SCCs
*
* @author anuragkapur
*/
public class StronglyConnectedComponents {
private static int noOfNodes = 875714;
private static Set<Integer> vertices = new HashSet<Integer>();
private static Map<Integer,List<Integer>> edges = new HashMap<Integer, List<Integer>>();
private static Map<Integer,List<Integer>> reverseEdges = new HashMap<Integer, List<Integer>>();
private static int finishTime = -1;
private static int[] nodes = new int[noOfNodes + 1];
private static int[] nodesSortedByFinishTime = new int[noOfNodes];
private static int sccSize = 0;
private static List<Integer> sccSizes = new ArrayList<Integer>();
/**
* Computes the Graph DS consisting of Set of vertices and Map of egdes
*
* @param line
*/
private static void computeVerticesAndEdges(String line) {
StringTokenizer tokenizer = new StringTokenizer(line," ");
Integer vertex1 = new Integer(tokenizer.nextToken());
Integer vertex2 = new Integer(tokenizer.nextToken());
vertices.add(vertex1);
vertices.add(vertex2);
List<Integer> nodesOfEdge = null;
// populate edges
nodesOfEdge = edges.get(vertex1);
if(nodesOfEdge != null) {
nodesOfEdge.add(vertex2);
}else {
nodesOfEdge = new ArrayList<Integer>();
nodesOfEdge.add(vertex2);
edges.put(vertex1, nodesOfEdge);
}
// populate reverse edges
nodesOfEdge = null;
nodesOfEdge = reverseEdges.get(vertex2);
if(nodesOfEdge != null) {
nodesOfEdge.add(vertex1);
}else {
nodesOfEdge = new ArrayList<Integer>();
nodesOfEdge.add(vertex1);
reverseEdges.put(vertex2, nodesOfEdge);
}
}
/**
* DFS on G-reverse
*
* @param startNode
*/
private static void dfsGRev(Integer startNode) {
// mark node i as explored
nodes[startNode.intValue()] = 1;
// find edges with start node as tail and another node as head in G-rev
List<Integer> heads = reverseEdges.get(startNode);
if(heads != null) {
Iterator<Integer> headsIterator = heads.iterator();
while(headsIterator.hasNext()) {
Integer head = (Integer)headsIterator.next();
// ignore self loops
if(head.intValue() == startNode.intValue()) {
continue;
}
if(nodes[head.intValue()] == 0) {
// node not already explored
dfsGRev(head);
}
}
}
finishTime ++;
nodesSortedByFinishTime[finishTime] = startNode.intValue();
}
/**
* Compute finishing times on G-Rev
*/
private static void computeFinishingTimesOnGRev() {
// iterate over all vertices and compute DFS on G-rev
for(int i=0; i<noOfNodes; i++) {
if(nodes[i+1] == 0) {
// node is unexplored
dfsGRev(new Integer(i+1));
}
}
}
/**
* DFS on G
*
* @param startNode
*/
private static void dfs(Integer startNode) {
// increment SCC size
sccSize ++;
// mark node i as explored
nodes[startNode.intValue()] = 1;
// find edges with start node as tail and another node as head in G
List<Integer> heads = edges.get(startNode);
if(heads != null) {
Iterator<Integer> headsIterator = heads.iterator();
while(headsIterator.hasNext()) {
Integer head = (Integer)headsIterator.next();
// ignore self loops
if(head.intValue() == startNode.intValue()) {
continue;
}
if(nodes[head.intValue()] == 0) {
// node not already explored
dfs(head);
}
}
}
}
/**
* Compute Strongly connected components on G
*/
private static void computeSCCs() {
// reset all nodes to unexplored
for (int i = 0; i < nodes.length; i++) {
nodes[i] = 0;
}
// iterate over all vertices and compute DFS
for (int i = nodesSortedByFinishTime.length-1; i >= 0; i
if(nodes[nodesSortedByFinishTime[i]] == 0) {
// node is unexplored
sccSize = 0;
dfs(new Integer(nodesSortedByFinishTime[i]));
//System.out.println("sccSize :: " + sccSize);
sccSizes.add(new Integer(sccSize));
}
}
int sccs[] = new int[sccSizes.size()];
for (int i = 0; i < sccs.length; i++) {
sccs[i] = sccSizes.get(i).intValue();
}
// sort them
Arrays.sort(sccs);
for (int i = 0; i < 5; i++) {
if(sccs.length - 1 - i >= 0) {
System.out.println(sccs[sccs.length - 1 - i]);
}
}
}
/**
* @param args
*/
public static void main(String[] args) {
File file = new File("src/com/anuragkapur/ada1/scc.txt");
String line = null;
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(file));
while((line = br.readLine()) != null) {
computeVerticesAndEdges(line);
}
System.out.println("Input parsing and graph construction complete");
computeFinishingTimesOnGRev();
System.out.println("DFS round 1 complete");
computeSCCs();
System.out.println("DFS round 2 complete");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
|
package com.bodastage.e4.clock.ui.views;
import java.net.URL;
import java.time.ZoneId;
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import org.eclipse.e4.ui.di.Focus;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.resource.FontRegistry;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.resource.ImageRegistry;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.jface.resource.LocalResourceManager;
import org.eclipse.jface.resource.ResourceManager;
import org.eclipse.jface.viewers.DelegatingStyledCellLabelProvider;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.ISharedImages;
import com.bodastage.e4.clock.ui.internal.TimeZoneComparator;
import com.bodastage.e4.clock.ui.internal.TimeZoneContentProvider;
import com.bodastage.e4.clock.ui.internal.TimeZoneLabelProvider;
import com.bodastage.e4.clock.ui.internal.TimeZoneViewerComparator;
import com.bodastage.e4.clock.ui.internal.TimeZoneViewerFilter;
public class TimeZoneTreeView {
private TreeViewer treeViewer;
@Inject
private ISharedImages images;
@PostConstruct
public void create(Composite parent) {
ResourceManager rm = JFaceResources.getResources();
LocalResourceManager lrm = new LocalResourceManager(rm, parent);
ImageRegistry ir = new ImageRegistry(lrm);
URL sample = getClass().getResource("/icons/sample.gif");
ir.put("sample", ImageDescriptor.createFromURL(sample));
FontRegistry fr = JFaceResources.getFontRegistry();
treeViewer = new TreeViewer(parent, SWT.H_SCROLL | SWT.V_SCROLL | SWT.MULTI);
treeViewer.setLabelProvider(new DelegatingStyledCellLabelProvider(new TimeZoneLabelProvider(images, ir, fr)));
treeViewer.setContentProvider(new TimeZoneContentProvider());
treeViewer.setInput(new Object[] { TimeZoneComparator.getTimeZones() });
// Reverse sorting
treeViewer.setData("REVERSE", Boolean.TRUE);
treeViewer.setComparator(new TimeZoneViewerComparator());
// Filtering
treeViewer.setFilters(new ViewerFilter[] { new TimeZoneViewerFilter("GMT") });
// Expand tree automatically
treeViewer.setExpandPreCheckFilters(true);
treeViewer.addDoubleClickListener(event -> {
Viewer viewer = event.getViewer();
Shell shell = viewer.getControl().getShell();
ISelection sel = viewer.getSelection();
Object selectedValue;
if (!(sel instanceof IStructuredSelection) || sel.isEmpty()) {
selectedValue = null;
} else {
selectedValue = ((IStructuredSelection) sel).getFirstElement();
}
if (selectedValue instanceof ZoneId) {
ZoneId timeZone = (ZoneId) selectedValue;
MessageDialog.openInformation(shell, timeZone.getId(), timeZone.toString());
}
});
}
@Focus
public void focus() {
treeViewer.getControl().setFocus();
}
}
|
package br.com.dbsoft.ui.component.group;
import java.io.IOException;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;
import javax.faces.render.FacesRenderer;
import br.com.dbsoft.ui.component.DBSRenderer;
import br.com.dbsoft.ui.core.DBSFaces;
import br.com.dbsoft.ui.core.DBSFaces.CSS;
@FacesRenderer(componentFamily=DBSFaces.FAMILY, rendererType=DBSGroup.RENDERER_TYPE)
public class DBSGroupRenderer extends DBSRenderer {
@Override
public void decode(FacesContext pContext, UIComponent pComponent) {
}
@Override
public boolean getRendersChildren() {
return true; //True=Chama o encodeChildren abaixo e interrompe a busca por filho pela rotina renderChildren
}
@Override
public void encodeChildren(FacesContext pContext, UIComponent pComponent) throws IOException {
// if (pComponent.getChildren().size()!=0){
}
@Override
public void encodeBegin(FacesContext pContext, UIComponent pComponent)
throws IOException {
if (!pComponent.isRendered()){return;}
DBSGroup xGroup = (DBSGroup) pComponent;
ResponseWriter xWriter = pContext.getResponseWriter();
String xClass = CSS.GROUP.MAIN;
if (xGroup.getStyleClass()!=null){
xClass = xClass + " " + xGroup.getStyleClass();
}
String xClientId = xGroup.getClientId(pContext);
xWriter.startElement("div", xGroup);
DBSFaces.setAttribute(xWriter, "id", xClientId);
DBSFaces.setAttribute(xWriter, "name", xClientId);
if (xClass!=""){
DBSFaces.setAttribute(xWriter, "class", xClass);
}
DBSFaces.setAttribute(xWriter, "style", xGroup.getStyle());
xWriter.startElement("div", xGroup);
DBSFaces.setAttribute(xWriter, "class", CSS.MODIFIER.CONTAINER);
xWriter.startElement("div", xGroup);
DBSFaces.setAttribute(xWriter, "class", CSS.MODIFIER.HEADER);
xWriter.startElement("div", xGroup);
xWriter.startElement("div", xGroup);
DBSFaces.setAttribute(xWriter, "class", CSS.THEME.INPUT_LABEL + CSS.NOT_SELECTABLE);
if (!xGroup.getLabel().equals("")){
xWriter.write(xGroup.getLabel() + ":");
}
xWriter.endElement("div");
xWriter.endElement("div");
xWriter.startElement("div", xGroup);
DBSFaces.setAttribute(xWriter, "class", "-line");
xWriter.startElement("span", xGroup);
xWriter.endElement("span");
xWriter.endElement("div");
xWriter.endElement("div");
xWriter.startElement("div", xGroup);
if (xGroup.getFloatLeft()){
DBSFaces.setAttribute(xWriter, "class", CSS.MODIFIER.CONTENT + "-floatleft");
}else{
DBSFaces.setAttribute(xWriter, "class", CSS.MODIFIER.CONTENT);
}
DBSFaces.renderChildren(pContext, xGroup);
}
@Override
public void encodeEnd(FacesContext pContext, UIComponent pComponent) throws IOException{
if (!pComponent.isRendered()){return;}
ResponseWriter xWriter = pContext.getResponseWriter();
xWriter.endElement("div");
xWriter.endElement("div");
xWriter.endElement("div");
}
}
|
package cloud.cluster.sim.clustersimulator;
import cloud.cluster.sim.clustersimulator.dto.*;
import cloud.cluster.sim.utilities.SimSettingsExtractor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* Implements operations on the Cluster.
*/
@Component
public class ClusterManager {
private long rpsForOneVm;
private ClusterExtRep clusterExtRep;
private Cluster cluster;
private int currentResourceIndex = 0;
private static final Logger logger = LoggerFactory.getLogger(ClusterManager.class);
private List<AllocationState> allocationEvolution = new ArrayList<AllocationState>();
@Autowired
private CostComputer costComputer;
/**
* Read ClusterExtRep configuration date from Json file.
*/
public ClusterManager() {
this.rpsForOneVm = SimSettingsExtractor.getSimulationSettings().getRpsForVm();
ClassLoader classLoader = getClass().getClassLoader();
String path = classLoader.getResource("clusterConfiguration.json").getFile();
ObjectMapper mapper = new ObjectMapper();
try {
clusterExtRep = mapper.readValue(new File(path), ClusterExtRep.class);
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
clusterExtRepToCluster(clusterExtRep);
}
/**
* Convert external representaiton of cluster into internal representation.
*
* @param clusterExtRep representation of cluster in the clusterConfiguration file.
*/
private void clusterExtRepToCluster(ClusterExtRep clusterExtRep) {
List<Vm> vmList = new ArrayList<Vm>();
clusterExtRep.getTgGroup().stream().forEach(tcGroup -> {
TreatmentCategory tc = new TreatmentCategory(tcGroup.getName(), tcGroup.getSla(), tcGroup.getCost());
for (int i = 0; i < tcGroup.getVmNumber(); i++) {
vmList.add(new Vm(tc));
}
});
cluster = new Cluster(vmList);
}
/**
* Return the Cluster used by the ClusterManager.
*
* @return Cluster used by the ClusterManager.
*/
Cluster getCluster() {
return cluster;
}
public long getRpsForOneVm() {
return rpsForOneVm;
}
/**
* Compute the maximum RPS supported by the Cluster managed by the ClusterManager.
*
* @return maximum number of request that can be fulfilled by the Cluster in one second.
*/
public long computeCumulativeRpsForCluster() {
return cluster.getVms().size() * rpsForOneVm;
}
/**
* Get the number of VMs in the cluster.
*
* @return Vm number in the cluster.
*/
public int getClusterSize() {
return cluster.getVms().size();
}
/**
* Allows iteration through cluster elements in a circular list fashion while allowing removal of cluster VMs.
*
* @return
*/
public Vm nextVm() {
if (currentResourceIndex >= getClusterSize()) {
currentResourceIndex = 0;
}
if (getClusterSize() <= 0) {
return null;
}
else {
return cluster.getVms().get(currentResourceIndex++);
}
}
/**
* Remove VMs from cluster.
*
* @param id of the VM that should be removed.
*/
public void removeVm(int id) {
if (cluster.getVms().size() <= 1) {
return;
}
if (id < currentResourceIndex) {
currentResourceIndex
}
costComputer.addCostForShutDown(cluster.getVms().get(id));
cluster.getVms().remove(id);
compressAllocationEvolution(Reason.SUBTRACT);
}
public void failVm(int id) {
if (id < currentResourceIndex) {
currentResourceIndex
}
cluster.getVms().remove(id);
compressAllocationEvolution(Reason.FAIL);
}
/**
* Add Vms to the cluster, always before the index , in order to allocate tasks to these Vms first.
*
* @param vm new VM that needs to be added to the cluster.
*/
public void addVm(Vm vm) {
if (currentResourceIndex >= cluster.getVms().size()) {
cluster.getVms().add(vm);
}
else {
cluster.getVms().add(currentResourceIndex + 1, vm);
}
compressAllocationEvolution(Reason.ADD);
}
/**
* Compress traces for allocations and deallocations that happen at the same time.
*
* @param reason
*/
private void compressAllocationEvolution(Reason reason) {
if (allocationEvolution.size() > 0) {
AllocationState latAllocationState = allocationEvolution.get(allocationEvolution.size() - 1);
if(Math.abs(latAllocationState.getTime() - Time.timeMillis) < 0.00000001) {
latAllocationState.setVmNumber(
(reason == Reason.ADD) ?
latAllocationState.getVmNumber() + 1 :
latAllocationState.getVmNumber() - 1);
return;
}
}
allocationEvolution.add(new AllocationState(Time.timeMillis,
(reason == Reason.ADD) ? +1: -1,
reason));
}
/**
* Traces for VM allocation evolution.
*
* @return a list with evolution traces.
*/
public List<AllocationState> getAllocationEvolution() {
return allocationEvolution;
}
public CostComputer getCostComputer() {
return costComputer;
}
}
|
package com.akiban.server.expression.std;
import com.akiban.qp.operator.QueryContext;
import com.akiban.server.error.InvalidParameterValueException;
import com.akiban.server.error.WrongExpressionArityException;
import com.akiban.server.expression.Expression;
import com.akiban.server.expression.ExpressionComposer;
import com.akiban.server.expression.ExpressionEvaluation;
import com.akiban.server.expression.ExpressionType;
import com.akiban.server.expression.TypesList;
import com.akiban.server.service.functions.Scalar;
import com.akiban.server.types.AkType;
import com.akiban.server.types.NullValueSource;
import com.akiban.server.types.ValueSource;
import com.akiban.server.types.extract.Extractors;
import com.akiban.sql.StandardException;
import org.joda.time.DateTimeZone;
import org.joda.time.IllegalFieldValueException;
public class ToDaysExpression extends AbstractUnaryExpression
{
@Scalar("to_days")
public static final ExpressionComposer COMPOSER = new UnaryComposer()
{
@Override
protected Expression compose(Expression argument)
{
return new ToDaysExpression(argument);
}
@Override
public ExpressionType composeType(TypesList argumentTypes) throws StandardException
{
if (argumentTypes.size() != 1)
throw new WrongExpressionArityException(1, argumentTypes.size());
argumentTypes.setType(0, AkType.DATE);
return ExpressionTypes.LONG;
}
};
private static class InnerEvaluation extends AbstractUnaryExpressionEvaluation
{
private static final long BEGINNING = Extractors.getLongExtractor(AkType.DATE).stdLongToUnix(33, DateTimeZone.UTC);
private static final long FACTOR = 3600L * 1000 * 24;
public InnerEvaluation (ExpressionEvaluation eval)
{
super(eval);
}
@Override
public ValueSource eval()
{
ValueSource date = operand();
if (date.isNull())
return NullValueSource.only();
try
{
valueHolder().putLong((Extractors.getLongExtractor(AkType.DATE).stdLongToUnix(date.getDate(), DateTimeZone.UTC)
- BEGINNING) / FACTOR);
return valueHolder();
}
catch ( IllegalFieldValueException e) // zero dates
{
QueryContext qc = queryContext();
if (qc != null)
qc.warnClient(new InvalidParameterValueException(e.getMessage()));
return NullValueSource.only();
}
}
}
ToDaysExpression (Expression arg)
{
super(AkType.LONG, arg);
}
@Override
protected String name()
{
return "TO_DAYS";
}
@Override
public ExpressionEvaluation evaluation()
{
return new InnerEvaluation(operandEvaluation());
}
}
|
package com.itmill.toolkit.terminal.gwt.client.ui;
import java.util.Set;
import com.google.gwt.dom.client.DivElement;
import com.google.gwt.dom.client.Document;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.Widget;
import com.itmill.toolkit.terminal.gwt.client.ApplicationConnection;
import com.itmill.toolkit.terminal.gwt.client.BrowserInfo;
import com.itmill.toolkit.terminal.gwt.client.Container;
import com.itmill.toolkit.terminal.gwt.client.Paintable;
import com.itmill.toolkit.terminal.gwt.client.RenderInformation;
import com.itmill.toolkit.terminal.gwt.client.RenderSpace;
import com.itmill.toolkit.terminal.gwt.client.UIDL;
import com.itmill.toolkit.terminal.gwt.client.Util;
public class IPanel extends SimplePanel implements Container {
public static final String CLASSNAME = "i-panel";
ApplicationConnection client;
String id;
private final Element captionNode = DOM.createDiv();
private final Element captionText = DOM.createSpan();
private Icon icon;
private final Element bottomDecoration = DOM.createDiv();
private final Element contentNode = DOM.createDiv();
private Element errorIndicatorElement;
private String height;
private Paintable layout;
ShortcutActionHandler shortcutHandler;
private String width = "";
private Element geckoCaptionMeter;
private int scrollTop;
private int scrollLeft;
private RenderInformation renderInformation = new RenderInformation();
private int borderPaddingHorizontal = -1;
private int borderPaddingVertical = -1;
private int captionPaddingHorizontal = -1;
private int captionMarginLeft = -1;
private boolean rendering;
private int contentMarginLeft = -1;
public IPanel() {
super();
DivElement captionWrap = Document.get().createDivElement();
captionWrap.appendChild(captionNode);
captionNode.appendChild(captionText);
captionWrap.setClassName(CLASSNAME + "-captionwrap");
captionNode.setClassName(CLASSNAME + "-caption");
contentNode.setClassName(CLASSNAME + "-content");
bottomDecoration.setClassName(CLASSNAME + "-deco");
getElement().appendChild(captionWrap);
getElement().appendChild(contentNode);
getElement().appendChild(bottomDecoration);
setStyleName(CLASSNAME);
DOM.sinkEvents(getElement(), Event.ONKEYDOWN);
DOM.sinkEvents(contentNode, Event.ONSCROLL);
contentNode.getStyle().setProperty("position", "relative");
getElement().getStyle().setProperty("overflow", "hidden");
}
@Override
protected Element getContainerElement() {
return contentNode;
}
private void setCaption(String text) {
DOM.setInnerHTML(captionText, text);
}
public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
rendering = true;
if (!uidl.hasAttribute("cached")) {
// Handle caption displaying and style names, prior generics.
// Affects size
// calculations
// Restore default stylenames
contentNode.setClassName(CLASSNAME + "-content");
bottomDecoration.setClassName(CLASSNAME + "-deco");
captionNode.setClassName(CLASSNAME + "-caption");
boolean hasCaption = false;
if (uidl.hasAttribute("caption")
&& !uidl.getStringAttribute("caption").equals("")) {
setCaption(uidl.getStringAttribute("caption"));
hasCaption = true;
} else {
setCaption("");
captionNode.setClassName(CLASSNAME + "-nocaption");
}
// Add proper stylenames for all elements. This way we can prevent
// unwanted CSS selector inheritance.
if (uidl.hasAttribute("style")) {
final String[] styles = uidl.getStringAttribute("style").split(
" ");
final String captionBaseClass = CLASSNAME
+ (hasCaption ? "-caption" : "-nocaption");
final String contentBaseClass = CLASSNAME + "-content";
final String decoBaseClass = CLASSNAME + "-deco";
String captionClass = captionBaseClass;
String contentClass = contentBaseClass;
String decoClass = decoBaseClass;
for (int i = 0; i < styles.length; i++) {
captionClass += " " + captionBaseClass + "-" + styles[i];
contentClass += " " + contentBaseClass + "-" + styles[i];
decoClass += " " + decoBaseClass + "-" + styles[i];
}
captionNode.setClassName(captionClass);
contentNode.setClassName(contentClass);
bottomDecoration.setClassName(decoClass);
}
}
// Ensure correct implementation
if (client.updateComponent(this, uidl, false)) {
rendering = false;
return;
}
this.client = client;
id = uidl.getId();
setIconUri(uidl, client);
handleError(uidl);
// Render content
final UIDL layoutUidl = uidl.getChildUIDL(0);
final Paintable newLayout = client.getPaintable(layoutUidl);
if (newLayout != layout) {
if (layout != null) {
client.unregisterPaintable(layout);
}
setWidget((Widget) newLayout);
layout = newLayout;
}
layout.updateFromUIDL(layoutUidl, client);
runHacks(false);
// We may have actions attached to this panel
if (uidl.getChildCount() > 1) {
final int cnt = uidl.getChildCount();
for (int i = 1; i < cnt; i++) {
UIDL childUidl = uidl.getChildUIDL(i);
if (childUidl.getTag().equals("actions")) {
if (shortcutHandler == null) {
shortcutHandler = new ShortcutActionHandler(id, client);
}
shortcutHandler.updateActionMap(childUidl);
}
}
}
if (uidl.hasVariable("scrollTop")
&& uidl.getIntVariable("scrollTop") != scrollTop) {
scrollTop = uidl.getIntVariable("scrollTop");
DOM.setElementPropertyInt(contentNode, "scrollTop", scrollTop);
}
if (uidl.hasVariable("scrollLeft")
&& uidl.getIntVariable("scrollLeft") != scrollLeft) {
scrollLeft = uidl.getIntVariable("scrollLeft");
DOM.setElementPropertyInt(contentNode, "scrollLeft", scrollLeft);
}
rendering = false;
}
private void handleError(UIDL uidl) {
if (uidl.hasAttribute("error")) {
if (errorIndicatorElement == null) {
errorIndicatorElement = DOM.createDiv();
DOM.setElementProperty(errorIndicatorElement, "className",
"i-errorindicator");
DOM.sinkEvents(errorIndicatorElement, Event.MOUSEEVENTS);
sinkEvents(Event.MOUSEEVENTS);
}
DOM.insertBefore(captionNode, errorIndicatorElement, captionText);
} else if (errorIndicatorElement != null) {
DOM.removeChild(captionNode, errorIndicatorElement);
errorIndicatorElement = null;
}
}
private void setIconUri(UIDL uidl, ApplicationConnection client) {
final String iconUri = uidl.hasAttribute("icon") ? uidl
.getStringAttribute("icon") : null;
if (iconUri == null) {
if (icon != null) {
DOM.removeChild(captionNode, icon.getElement());
icon = null;
}
} else {
if (icon == null) {
icon = new Icon(client);
DOM.insertChild(captionNode, icon.getElement(), 0);
}
icon.setUri(iconUri);
}
}
public void runHacks(boolean runGeckoFix) {
if (BrowserInfo.get().isIE6() && width != null && !width.equals("")) {
/*
* IE6 requires overflow-hidden elements to have a width specified
* so we calculate the width of the content and caption nodes when
* no width has been specified.
*/
/*
* Fixes #1923 IPanel: Horizontal scrollbar does not appear in IE6
* with wide content
*/
/*
* Caption must be shrunk for parent measurements to return correct
* result in IE6
*/
DOM.setStyleAttribute(captionNode, "width", "1px");
int parentPadding = Util.measureHorizontalPaddingAndBorder(
getElement(), 0);
int parentWidthExcludingPadding = getElement().getOffsetWidth()
- parentPadding;
Util.setWidthExcludingPaddingAndBorder(captionNode,
parentWidthExcludingPadding - getCaptionMarginLeft(), 26,
false);
int contentMarginLeft = getContentMarginLeft();
Util.setWidthExcludingPaddingAndBorder(contentNode,
parentWidthExcludingPadding - contentMarginLeft, 2, false);
}
if ((BrowserInfo.get().isIE() || BrowserInfo.get().isFF2())
&& (width == null || width.equals(""))) {
/*
* IE and FF2 needs width to be specified for the root DIV so we
* calculate that from the sizes of the caption and layout
*/
int captionWidth = captionText.getOffsetWidth()
+ getCaptionMarginLeft() + getCaptionPaddingHorizontal();
int layoutWidth = ((Widget) layout).getOffsetWidth()
+ getContainerBorderWidth();
int width = layoutWidth;
if (captionWidth > width) {
width = captionWidth;
}
if (BrowserInfo.get().isIE7()) {
Util.setWidthExcludingPaddingAndBorder(captionNode, width
- getCaptionMarginLeft(), 26, false);
}
super.setWidth(width + "px");
}
if (runGeckoFix && BrowserInfo.get().isGecko()) {
// workaround for #1764
if (width == null || width.equals("")) {
if (geckoCaptionMeter == null) {
geckoCaptionMeter = DOM.createDiv();
DOM.appendChild(captionNode, geckoCaptionMeter);
}
int captionWidth = DOM.getElementPropertyInt(captionText,
"offsetWidth");
int availWidth = DOM.getElementPropertyInt(geckoCaptionMeter,
"offsetWidth");
if (captionWidth == availWidth) {
/*
* Caption width defines panel width -> Gecko based browsers
* somehow fails to float things right, without the
* "noncode" below
*/
setWidth(getOffsetWidth() + "px");
} else {
DOM.setStyleAttribute(captionNode, "width", "");
}
}
}
client.runDescendentsLayout(this);
Util.runWebkitOverflowAutoFix(contentNode);
}
@Override
public void onBrowserEvent(Event event) {
final Element target = DOM.eventGetTarget(event);
final int type = DOM.eventGetType(event);
if (type == Event.ONKEYDOWN && shortcutHandler != null) {
shortcutHandler.handleKeyboardEvent(event);
return;
}
if (type == Event.ONSCROLL) {
int newscrollTop = DOM.getElementPropertyInt(contentNode,
"scrollTop");
int newscrollLeft = DOM.getElementPropertyInt(contentNode,
"scrollLeft");
if (client != null
&& (newscrollLeft != scrollLeft || newscrollTop != scrollTop)) {
scrollLeft = newscrollLeft;
scrollTop = newscrollTop;
client.updateVariable(id, "scrollTop", scrollTop, false);
client.updateVariable(id, "scrollLeft", scrollLeft, false);
}
} else if (captionNode.isOrHasChild(target)) {
if (client != null) {
client.handleTooltipEvent(event, this);
}
}
}
@Override
public void setHeight(String height) {
this.height = height;
super.setHeight(height);
if (height != null && height != "") {
final int targetHeight = getOffsetHeight();
int containerHeight = targetHeight - captionNode.getOffsetHeight()
- bottomDecoration.getOffsetHeight()
- getContainerBorderHeight();
if (containerHeight < 0) {
containerHeight = 0;
}
DOM
.setStyleAttribute(contentNode, "height", containerHeight
+ "px");
} else {
DOM.setStyleAttribute(contentNode, "height", "");
}
if (!rendering) {
runHacks(true);
}
}
private int getCaptionMarginLeft() {
if (captionMarginLeft < 0) {
detectContainerBorders();
}
return captionMarginLeft;
}
private int getContentMarginLeft() {
if (contentMarginLeft < 0) {
detectContainerBorders();
}
return contentMarginLeft;
}
private int getCaptionPaddingHorizontal() {
if (captionPaddingHorizontal < 0) {
detectContainerBorders();
}
return captionPaddingHorizontal;
}
private int getContainerBorderHeight() {
if (borderPaddingVertical < 0) {
detectContainerBorders();
}
return borderPaddingVertical;
}
@Override
public void setWidth(String width) {
if (this.width.equals(width)) {
return;
}
this.width = width;
super.setWidth(width);
if (!rendering) {
runHacks(true);
if (height.equals("")) {
// Width change may affect height
Util.updateRelativeChildrenAndSendSizeUpdateEvent(client, this);
}
}
}
private int getContainerBorderWidth() {
if (borderPaddingHorizontal < 0) {
detectContainerBorders();
}
return borderPaddingHorizontal;
}
private void detectContainerBorders() {
DOM.setStyleAttribute(contentNode, "overflow", "hidden");
borderPaddingHorizontal = Util.measureHorizontalBorder(contentNode);
borderPaddingVertical = Util.measureVerticalBorder(contentNode);
DOM.setStyleAttribute(contentNode, "overflow", "auto");
captionPaddingHorizontal = Util.measureHorizontalPaddingAndBorder(
captionNode, 26);
captionMarginLeft = Util.measureMarginLeft(captionNode);
contentMarginLeft = Util.measureMarginLeft(contentNode);
}
public boolean hasChildComponent(Widget component) {
if (component != null && component == layout) {
return true;
} else {
return false;
}
}
public void replaceChildComponent(Widget oldComponent, Widget newComponent) {
// TODO This is untested as no layouts require this
if (oldComponent != layout) {
return;
}
setWidget(newComponent);
layout = (Paintable) newComponent;
}
public RenderSpace getAllocatedSpace(Widget child) {
int w = 0;
int h = 0;
if (width != null && !width.equals("")) {
w = getOffsetWidth() - getContainerBorderWidth();
if (w < 0) {
w = 0;
}
}
if (height != null && !height.equals("")) {
h = contentNode.getOffsetHeight() - getContainerBorderHeight();
if (h < 0) {
h = 0;
}
}
return new RenderSpace(w, h, true);
}
public boolean requestLayout(Set<Paintable> child) {
if (height != null && height != "" && width != null && width != "") {
/*
* If the height and width has been specified the child components
* cannot make the size of the layout change
*/
return true;
}
runHacks(false);
return !renderInformation.updateSize(getElement());
}
public void updateCaption(Paintable component, UIDL uidl) {
// NOP: layouts caption, errors etc not rendered in Panel
}
@Override
protected void onAttach() {
super.onAttach();
detectContainerBorders();
}
}
|
package com.alibaba.rocketmq.storm;
import com.alibaba.rocketmq.common.MixAll;
import org.apache.commons.lang.BooleanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.rocketmq.client.consumer.DefaultMQPullConsumer;
import com.alibaba.rocketmq.client.consumer.DefaultMQPushConsumer;
import com.alibaba.rocketmq.client.consumer.MQConsumer;
import com.alibaba.rocketmq.client.consumer.listener.MessageListener;
import com.alibaba.rocketmq.client.exception.MQClientException;
import com.alibaba.rocketmq.common.consumer.ConsumeFromWhere;
import com.alibaba.rocketmq.common.protocol.heartbeat.MessageModel;
import com.alibaba.rocketmq.storm.domain.RocketMQConfig;
import com.alibaba.rocketmq.storm.internal.tools.FastBeanUtils;
import com.google.common.collect.Sets;
/**
* @author Von Gosling
*/
public class MessageConsumerManager {
private static final Logger LOG = LoggerFactory
.getLogger(MessageConsumerManager.class);
private static DefaultMQPushConsumer pushConsumer;
private static DefaultMQPullConsumer pullConsumer;
MessageConsumerManager() {
}
public static MQConsumer getConsumerInstance(RocketMQConfig config, MessageListener listener,
Boolean isPushlet) throws MQClientException {
LOG.info("Begin to init consumer,instanceName->{},configuration->{}",
new Object[] { config.getInstanceName(), config });
LOG.info("
LOG.info("
if (BooleanUtils.isTrue(isPushlet)) {
pushConsumer = (DefaultMQPushConsumer) FastBeanUtils.copyProperties(config,
DefaultMQPushConsumer.class);
pushConsumer.setConsumerGroup(config.getGroupId());
pushConsumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_LAST_OFFSET);
pushConsumer.subscribe(config.getTopic(), config.getTopicTag());
pushConsumer.setMessageModel(MessageModel.CLUSTERING);
pushConsumer.registerMessageListener(listener);
//pushConsumer.setNamesrvAddr(null);
return pushConsumer;
} else {
pullConsumer = (DefaultMQPullConsumer) FastBeanUtils.copyProperties(config,
DefaultMQPullConsumer.class);
pullConsumer.setConsumerGroup(config.getGroupId());
pullConsumer.setMessageModel(MessageModel.CLUSTERING);
//pullConsumer.setRegisterTopics(Sets.newHashSet(config.getTopic()));
//pullConsumer.setNamesrvAddr(null);
return pullConsumer;
}
}
}
|
package com.jiahaoliuliu.android.myexpenses;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.MenuItem;
import com.jiahaoliuliu.android.myexpenses.model.Expense;
import com.jiahaoliuliu.android.myexpenses.util.Preferences;
import com.jiahaoliuliu.android.myexpenses.util.Preferences.BooleanId;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.support.v4.app.ActionBarDrawerToggle;
import android.app.Activity;
import android.content.Context;
import android.content.res.Configuration;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CheckedTextView;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.support.v4.view.GravityCompat;
import android.telephony.CellLocation;
import android.telephony.TelephonyManager;
import android.telephony.gsm.GsmCellLocation;
public class MainActivity extends SherlockFragmentActivity {
private static final String LOG_TAG = MainActivity.class.getSimpleName();
// Variables
private DrawerLayout mDrawerLayout;
private LinearLayout mDrawerLinearLayout;
private ActionBarDrawerToggle mDrawerToggle;
private TextView totalExpenseTV;
private ListView contentListView;
private Context context;
private Preferences preferences;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private Double totalQuantity;
// For the soft input
private InputMethodManager imm;
private TelephonyManager telephonyManager;
private List<Expense> expenseList;
// Layouts
// Drawer
private EditText addNewExpenseEditText;
private Button addNewExpenseButton;
private CheckBox addNewExpenseCheckBox;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.drawer_main);
// Get the title
mTitle = mDrawerTitle = getTitle();
context = this;
preferences = new Preferences(context);
imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
// Create the empty array
expenseList = new ArrayList<Expense>();
// Link the content
mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
mDrawerLinearLayout = (LinearLayout)findViewById(R.id.linearLayoutDrawer);
totalExpenseTV = (TextView)findViewById(R.id.totalExpenseQuantityTextView);
contentListView = (ListView)findViewById(R.id.contentListView);
View listHeaderView = getLayoutInflater().inflate(R.layout.list_header_layout, null);
totalExpenseTV = (TextView)listHeaderView.findViewById(R.id.totalExpenseQuantityTextView);
contentListView.addHeaderView(listHeaderView, null, false);
addNewExpenseEditText = (EditText)mDrawerLinearLayout.findViewById(R.id.addNewExpenseEditText);
addNewExpenseButton = (Button)mDrawerLinearLayout.findViewById(R.id.addNewExpenseButton);
addNewExpenseCheckBox = (CheckBox)mDrawerLinearLayout.findViewById(R.id.addNewExpenseButtonCheckBox);
// Set a custom shadow that overlays the main content when the drawer opens
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
//mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
// Enable ActionBar app icon to behave as action to toggle nav drawer
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// ActionBarDrawerToggle ties together the proper interactions
// between the sliding drawer and the action bar app icon
mDrawerToggle = new ActionBarDrawerToggle(
this,
mDrawerLayout,
R.drawable.ic_drawer,
R.string.drawer_open,
R.string.drawer_close) {
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
addNewExpenseEditText.clearFocus();
// Hide soft windows
imm.hideSoftInputFromWindow(addNewExpenseEditText.getWindowToken(), 0);
}
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
// Set the title on the action when drawer open
getSupportActionBar().setTitle(mDrawerTitle);
// Force the keyboard to show on EditText focus
// TODO: Show the soft keyboard after onResume
addNewExpenseEditText.requestFocus();
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
// If it is the first time that the application starts
if (!preferences.getBoolean(BooleanId.ALREADY_STARTED)) {
preferences.setBoolean(BooleanId.ALREADY_STARTED, true);
preferences.setBoolean(BooleanId.SHOWN_ADD_NEW_EXPENSE_AT_BEGINNING, true);
}
boolean showAddNewExpenseAtBeginning = preferences.getBoolean(BooleanId.SHOWN_ADD_NEW_EXPENSE_AT_BEGINNING);
if (showAddNewExpenseAtBeginning) {
mDrawerLayout.openDrawer(mDrawerLinearLayout);
addNewExpenseEditText.requestFocus();
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);
}
// Draw the layout
addNewExpenseCheckBox.setChecked(showAddNewExpenseAtBeginning);
totalExpenseTV.setText(String.valueOf(calculateTotalExpense()));
final ContentListAdapter contentListAdapter = new ContentListAdapter(context,
R.layout.date_row_layout,
expenseList);
contentListView.setAdapter(contentListAdapter);
// Layout logic
addNewExpenseButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// If the user has not entered any data
String quantityString = addNewExpenseEditText.getText().toString();
if (quantityString == null || quantityString.equals("")) {
Toast.makeText(
context,
getResources().getString(R.string.error_add_new_expense_empty),
Toast.LENGTH_LONG).show();
return;
}
Log.v(LOG_TAG, "Adding new quantity: " + quantityString);
Expense expense = new Expense();
expense.setDate(new Date());
expense.setLocation(getCellLocation());
expense.setQuantity(Double.valueOf(quantityString));
expenseList.add(expense);
// Update the layout of the main screen
totalExpenseTV.setText(String.valueOf(calculateTotalExpense()));
// Clear the edit text
addNewExpenseEditText.setText("");
contentListAdapter.notifyDataSetChanged();
Toast.makeText(
context,
getResources().getString(R.string.add_new_expense_correctly),
Toast.LENGTH_LONG
).show();
}
});
addNewExpenseCheckBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
preferences.setBoolean(BooleanId.SHOWN_ADD_NEW_EXPENSE_AT_BEGINNING, isChecked);
}
});
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
if (mDrawerLayout.isDrawerOpen(mDrawerLinearLayout)) {
mDrawerLayout.closeDrawer(mDrawerLinearLayout);
} else {
mDrawerLayout.openDrawer(mDrawerLinearLayout);
}
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggles
mDrawerToggle.onConfigurationChanged(newConfig);
}
@Override
public void setTitle(CharSequence title) {
mTitle = title;
getSupportActionBar().setTitle(mTitle);
}
private GsmCellLocation getCellLocation() {
if (telephonyManager.getPhoneType() == TelephonyManager.PHONE_TYPE_GSM) {
final GsmCellLocation location = (GsmCellLocation) telephonyManager.getCellLocation();
return location;
} else {
Log.e(LOG_TAG, "The phone type is not gsm");
return null;
}
}
private double calculateTotalExpense() {
double result = 0.0;
for (Expense expense: expenseList) {
result += expense.getQuantity();
}
return result;
}
private class ContentListAdapter extends ArrayAdapter<String> {
private Context context;
private List<Expense> expenseList;
private SimpleDateFormat format = new SimpleDateFormat("y-M-d HH:mm");
public ContentListAdapter(Context context, int resource, List<Expense> expenseList) {
super(context, resource);
this.context = context;
this.expenseList = expenseList;
}
@Override
public int getCount() {
return this.expenseList.size();
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.date_row_layout, parent, false);
TextView expenseDateTV = (TextView)rowView.findViewById(R.id.expenseDateTextView);
expenseDateTV.setText(format.format(expenseList.get(position).getDate()));
TextView expenseQuantityTV = (TextView)rowView.findViewById(R.id.expenseQuantityTextView);
expenseQuantityTV.setText(String.valueOf(expenseList.get(position).getQuantity()));
return rowView;
}
}
}
|
package traffic.model;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;
import org.jdom.JDOMException;
import org.junit.Test;
import traffic.graph.Graph;
import traffic.graph.GraphNode;
import traffic.strategy.LookaheadShortestPathVehicleStrategy;
import traffic.strategy.QuadraticSpeedStrategy;
/**
* @author Jochen Wuttke - wuttkej@gmail.com
*
*/
public class SimulationXMLReaderTest {
@Test (expected=FileNotFoundException.class)
public void testFileNotFound() throws JDOMException, IOException, ConfigurationException {
SimulationXMLReader.buildSimulator( new File("bad config") );
}
@Test
public void testStart() throws JDOMException, IOException, ConfigurationException {
List<Vehicle> cars = (List<Vehicle>)SimulationXMLReader.buildSimulator( new File("resources/test/config.xml" )).getAgents(Vehicle.class);
assertEquals(cars.get(0).getCurrentPosition().getID(), 0);
assertEquals(cars.get(1).getCurrentPosition().getID(), 4);
assertEquals(cars.get(2).getCurrentPosition().getID(), 3);
assertEquals(cars.get(3).getCurrentPosition().getID(), 8);
assertEquals(cars.get(4).getCurrentPosition().getID(), 3);
}
@Test
public void testVehicleNum() throws JDOMException, IOException, ConfigurationException {
List<Vehicle> cars = SimulationXMLReader.buildSimulator( new File("resources/test/config.xml" )).getAgents(Vehicle.class);
assertEquals(cars.get(0).getID(), 0);
assertEquals(cars.get(1).getID(), 1);
assertEquals(cars.get(2).getID(), 2);
assertEquals(cars.get(3).getID(), 3);
assertEquals(cars.get(4).getID(), 4);
}
@Test
public void invalidVehicleStrategyDefaultsCorrectly() throws JDOMException, IOException, ConfigurationException {
List<Vehicle> cars = SimulationXMLReader.buildSimulator( new File("resources/test/invalid-strategy.xml" )).getAgents(Vehicle.class);
assertEquals( LookaheadShortestPathVehicleStrategy.class, cars.get(1).getStrategy().getClass() );
}
@Test(expected=ConfigurationException.class)
public void invalidDefaultVehicleStrategyThrows() throws JDOMException, IOException, ConfigurationException {
List<Vehicle> cars = SimulationXMLReader.buildSimulator( new File("resources/test/illegal-default-car-strategy.xml" )).getAgents(Vehicle.class);
}
@Test(expected=ConfigurationException.class)
public void noVehicleThrows() throws JDOMException, IOException, ConfigurationException {
List<Vehicle> cars = SimulationXMLReader.buildSimulator( new File("resources/test/no-car.xml" )).getAgents(Vehicle.class);
fail( "This should throw a meaningful exception to be handled by main()" );
}
@Test(expected=ConfigurationException.class)
public void noVehiclesThrows() throws JDOMException, IOException, ConfigurationException {
List<Vehicle> cars = SimulationXMLReader.buildSimulator( new File("resources/test/no-cars.xml" )).getAgents(Vehicle.class);
fail( "This should throw a meaningful exception to be handled by main()" );
}
@Test
public void invalidStartEndIsIgnored() throws JDOMException, IOException, ConfigurationException {
List<Vehicle> cars = SimulationXMLReader.buildSimulator( new File("resources/test/invalid-start.xml" )).getAgents(Vehicle.class);
assertEquals( 3, cars.size() );
assertEquals( 0, cars.get(0).getID() );
assertEquals( 3, cars.get(1).getID() );
assertEquals( 4, cars.get(2).getID() );
}
@Test
public void testStrategies() throws FileNotFoundException, ConfigurationException {
TrafficSimulator sim = SimulationXMLReader.buildSimulator( new File("resources/test/config.xml" ) );
Graph g = sim.getGraph();
assertEquals(1, g.getNode(6).getCurrentDelay());
g.addVehicleAtNode(sim.getVehicle(0), 6);
g.addVehicleAtNode(sim.getVehicle(1), 6);
assertEquals(3, g.getNode(6).getCurrentDelay()); //Tests Quadratic Speed Strategy
assertEquals(1, g.getNode(1).getCurrentDelay());
g.addVehicleAtNode(sim.getVehicle(2), 1);
g.addVehicleAtNode(sim.getVehicle(3), 1);
assertEquals(3, g.getNode(1).getCurrentDelay() ); //Tests Linear Speed Strategy
}
@Test
public void testNeighbors() throws FileNotFoundException, ConfigurationException {
Graph g = SimulationXMLReader.buildSimulator( new File("resources/test/config.xml")).getGraph();
List<GraphNode> neighbors = g.getNodes().get(2).getNeighbors();
int first = neighbors.get(0).getID();
assertEquals(first, 4);
int second = neighbors.get(1).getID();
assertEquals(second, 7);
int third = neighbors.get(2).getID();
assertEquals(third, 9);
}
@Test
public void emptyNeighborListIsIgnored() throws FileNotFoundException, ConfigurationException {
Graph g = SimulationXMLReader.buildSimulator( new File("resources/test/unconnected-node.xml")).getGraph();
assertEquals( g.getNodes().size(), 9);
}
@Test(expected=ConfigurationException.class)
public void noNodesThrows() throws FileNotFoundException, ConfigurationException {
Graph g = SimulationXMLReader.buildSimulator(new File("resources/test/no-nodes.xml")).getGraph();
}
@Test(expected=ConfigurationException.class)
public void noGraphThrows() throws FileNotFoundException, ConfigurationException {
Graph g = SimulationXMLReader.buildSimulator( new File("resources/test/no-graph.xml" )).getGraph();
}
@Test
public void invalidNeighborIsIgnored() throws FileNotFoundException, ConfigurationException {
Graph g = SimulationXMLReader.buildSimulator( new File("resources/test/invalid-neighbor.xml")).getGraph();
List<GraphNode> neighbors = g.getNeighbors( 0 );
assertEquals(1, neighbors.size() );
assertEquals(4, neighbors.get(0).getID() );
neighbors = g.getNeighbors( 1 );
assertEquals(null, neighbors );
}
@Test
public void invalidSpeedStrategyDefaultsCorrectly() throws FileNotFoundException, ConfigurationException {
Graph g = SimulationXMLReader.buildSimulator( new File("resources/test/invalid-strategy2.xml")).getGraph();
assertEquals( QuadraticSpeedStrategy.class, g.getNodes().get(1).getSpeedStrategy().getClass() );
}
@Test
public void loadsAutoGeneratedConfig() throws FileNotFoundException, ConfigurationException {
Graph g = SimulationXMLReader.buildSimulator( new File("resources/test/auto-generated.xml")).getGraph();
//this passes when no unexpected exceptions are thrown
}
@Test
public void setsDelayCorrectly() throws FileNotFoundException, ConfigurationException {
Graph g = SimulationXMLReader.buildSimulator( new File("resources/test/config-weights.xml")).getGraph();
assertEquals( 7, g.getNodes().get(1).getDelay() );
}
@Test
public void setsDelayCorrectly2() throws FileNotFoundException, ConfigurationException {
Graph g = SimulationXMLReader.buildSimulator( new File("resources/test/shortest-path-test-weights.xml")).getGraph();
assertEquals( 4, g.getNodes().get(3).getDelay() );
}
@Test (expected=ConfigurationException.class)
public void invalidDelayDefaults() throws FileNotFoundException, ConfigurationException {
Graph g = SimulationXMLReader.buildSimulator( new File("resources/test/config-weights-invalid.xml")).getGraph();
}
@Test (expected=ConfigurationException.class)
public void negativeDelayDefaults() throws FileNotFoundException, ConfigurationException {
Graph g = SimulationXMLReader.buildSimulator( new File("resources/test/config-weights-invalid2.xml")).getGraph();
}
@Test
public void nodesHaveAllVehicles() throws FileNotFoundException, ConfigurationException {
Graph g = SimulationXMLReader.buildSimulator( new File("resources/test/shortest-path-test-weights.xml")).getGraph();
assertEquals( 3, g.getNode(2).numVehiclesAtNode() );
}
}
|
package com.googlecode.objectify.test;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import com.google.appengine.api.datastore.Cursor;
import com.google.appengine.api.datastore.QueryResultIterator;
import com.googlecode.objectify.Key;
import com.googlecode.objectify.cmd.Query;
import com.googlecode.objectify.test.entity.Trivial;
import com.googlecode.objectify.test.util.TestBase;
import com.googlecode.objectify.test.util.TestObjectify;
/**
* Tests of query cursors
*
* @author Jeff Schnitzer <jeff@infohazard.org>
*/
public class QueryCursorTests extends TestBase
{
@SuppressWarnings("unused")
private static Logger log = Logger.getLogger(QueryCursorTests.class.getName());
Trivial triv1;
Trivial triv2;
List<Key<Trivial>> keys;
@BeforeMethod
public void setUp()
{
super.setUp();
fact.register(Trivial.class);
this.triv1 = new Trivial("foo1", 1);
this.triv2 = new Trivial("foo2", 2);
List<Trivial> trivs = new ArrayList<Trivial>();
trivs.add(this.triv1);
trivs.add(this.triv2);
TestObjectify ofy = this.fact.begin();
Map<Key<Trivial>, Trivial> result = ofy.save().entities(trivs).now();
this.keys = new ArrayList<Key<Trivial>>(result.keySet());
}
@Test
public void testCursorEnd() throws Exception
{
TestObjectify ofy = this.fact.begin();
Query<Trivial> q = ofy.load().type(Trivial.class);
QueryResultIterator<Trivial> it = q.limit(1).iterator();
assert it.hasNext();
Trivial t1 = it.next();
assert t1.getId().equals(triv1.getId());
assert !it.hasNext();
Cursor cursor = it.getCursor();
assert cursor != null;
it = q.startAt(cursor).limit(1).iterator();
assert it.hasNext();
Trivial t2 = it.next();
assert t2.getId().equals(triv2.getId());
assert !it.hasNext();
// We should be at end
cursor = it.getCursor();
assert cursor != null;
it = q.startAt(cursor).iterator();
assert !it.hasNext();
// Try that again just to be sure
cursor = it.getCursor();
assert cursor != null;
it = q.startAt(cursor).iterator();
assert !it.hasNext();
}
@Test
public void testCursorOneFetchToEnd() throws Exception
{
TestObjectify ofy = this.fact.begin();
Query<Trivial> q = ofy.load().type(Trivial.class);
QueryResultIterator<Trivial> it = q.iterator();
it.next();
it.next();
assert !it.hasNext();
// We should be at end
Cursor cursor = it.getCursor();
assert cursor != null;
it = q.startAt(cursor).iterator();
assert !it.hasNext();
// Try that again just to be sure
cursor = it.getCursor();
assert cursor != null;
it = q.startAt(cursor).iterator();
assert !it.hasNext();
}
@Test
public void testLimitAndCursorUsingIterator() throws Exception {
// create 30 objects with someString=foo,
// then search for limit 20 (finding cursor at 15th position)
// then search for limit 20 using that cursor
// then use get() and see if we get the object at cursor
TestObjectify ofy = this.fact.begin();
for (int i = 0; i < 30; i++) {
ofy.put(new Trivial("foo", i));
}
Query<Trivial> q1 = ofy.load().type(Trivial.class).filter("someString", "foo").limit(20);
QueryResultIterator<Trivial> i1 = q1.iterator();
List<Trivial> l1 = new ArrayList<Trivial>();
Cursor cursor = null;
Trivial objectAfterCursor = null;
int count = 1;
while (i1.hasNext())
{
Trivial trivial = i1.next();
l1.add(trivial);
if (count == 15) {
cursor = i1.getCursor();
}
if (count == 16) {
objectAfterCursor = trivial;
}
count++;
}
assert l1.size() == 20;
Query<Trivial> q2 = ofy.load().type(Trivial.class).filter("someString =", "foo").limit(20).startAt(cursor);
QueryResultIterator<Trivial> i2 = q2.iterator();
List<Trivial> l2 = new ArrayList<Trivial>();
while (i2.hasNext())
{
Trivial trivial = i2.next();
l2.add(trivial);
}
assert l2.size() == 15;
Trivial gotten = q2.first().get();
assert gotten.getId().equals(objectAfterCursor.getId());
}
}
|
package com.michaldabski.filemanager.sqlite;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.Environment;
import com.michaldabski.filemanager.R;
import com.michaldabski.filemanager.favourites.FavouriteFolder;
import com.michaldabski.msqlite.MSQLiteOpenHelper;
import com.michaldabski.utils.FileUtils;
public class SQLiteHelper extends MSQLiteOpenHelper
{
private static final String DB_NAME = "file_manager.db";
private static final int DB_VERSION = 4;
private final Context context;
public SQLiteHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION,
new Class[] { FavouriteFolder.class });
this.context = context;
}
@Override
public void onCreate(SQLiteDatabase db)
{
super.onCreate(db);
List<FavouriteFolder> favouriteFolders = new ArrayList<FavouriteFolder>();
if (Environment.getExternalStorageDirectory().isDirectory())
{
favouriteFolders.add(new FavouriteFolder(Environment.getExternalStorageDirectory(), FileUtils.DISPLAY_NAME_SD_CARD));
if (Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).isDirectory())
favouriteFolders.add(new FavouriteFolder(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), getString(R.string.downloads)));
if (Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC).isDirectory())
favouriteFolders.add(new FavouriteFolder(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC), getString(R.string.music)));
if (Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).isDirectory())
favouriteFolders.add(new FavouriteFolder(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), getString(R.string.photos)));
}
else favouriteFolders.add(new FavouriteFolder(Environment.getExternalStoragePublicDirectory("/"), getString(R.string.root)));
for (FavouriteFolder favouriteFolder : favouriteFolders)
{
if (favouriteFolder.exists())
insert(db, favouriteFolder);
}
}
protected String getString(int res)
{
return context.getString(res);
}
}
|
package com.cidic.design.controller;
import java.io.File;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import com.cidic.design.DcController;
import com.cidic.design.exception.DCException;
import com.cidic.design.model.ResultModel;
import com.cidic.design.util.FileUtil;
@Controller
@RequestMapping(value="/file")
public class FileDisposeController extends DcController{
private static final String COMPRESS_FILE_DIR = File.separator + "WEB-INF"+ File.separator +"attachFile";
private static final String NEWS_IMAGE_FILE_DIR = File.separator + "WEB-INF"+ File.separator +"newsImageFile";
private static final String PRODUCTION_FILE_DIR = File.separator + "WEB-INF"+ File.separator +"productionFile";
private static final String OTHER_FILE_DIR = File.separator + "WEB-INF"+ File.separator +"others";
/**
*
* @param file
* @param fileType 1: 2: 3
* @param request
* @param response
* @return
*/
@RequestMapping(value = "/uploadMultiFile", method = RequestMethod.POST)
public @ResponseBody ResultModel uploadMultiFile(@RequestParam MultipartFile file, @RequestParam int fileType, HttpServletRequest request,
HttpServletResponse response) {
resultModel = new ResultModel();
if (file.isEmpty()) {
throw new DCException(500, "");
} else {
String path = "";
String fileFolderPrefix = "";
if (fileType == 1){
path = request.getSession().getServletContext().getRealPath(COMPRESS_FILE_DIR);
fileFolderPrefix = File.separator + "attachFile";
}
else if (fileType == 2){
path = request.getSession().getServletContext().getRealPath(NEWS_IMAGE_FILE_DIR);
fileFolderPrefix = File.separator + "newsImageFile";
}
else if (fileType == 3){
path = request.getSession().getServletContext().getRealPath(PRODUCTION_FILE_DIR);
fileFolderPrefix = File.separator + "productionFile";
}
else{
path = request.getSession().getServletContext().getRealPath(OTHER_FILE_DIR);
fileFolderPrefix = File.separator + "others";
}
String fileName = FileUtil.makeFileName()
+ file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
String realPath = FileUtil.makePath(fileName, path);
try {
FileUtils.copyInputStreamToFile(file.getInputStream(), new File(realPath, fileName));
resultModel.setObject(fileFolderPrefix + realPath.replace(path, "") + File.separator + fileName);
resultModel.setResultCode(200);
resultModel.setSuccess(true);
return resultModel;
} catch (IOException e) {
throw new DCException(500, "");
}
}
}
/**
*
* @param request
* @param response
* @param filePath
* @return
* @throws IOException
*/
@RequestMapping(value = "/downloadFile", method = RequestMethod.GET)
public ResponseEntity<byte[]> download(HttpServletRequest request, HttpServletResponse response,
@RequestParam(required = true) String filePath) throws IOException {
String path = request.getSession().getServletContext().getRealPath(COMPRESS_FILE_DIR);
File file = new File(path + filePath);
HttpHeaders headers = new HttpHeaders();
String fileName = new String(filePath.substring(filePath.lastIndexOf(".")).getBytes("UTF-8"), "iso-8859-1");
headers.setContentDispositionFormData("attachment", fileName);
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);
}
/**
*
* @param request
* @param response
* @param imgPath
* @param fileType 2: 3
* @return
* @throws IOException
*/
//@RequiresRoles(value ={"","",""})
@RequestMapping(value = "/image", method = RequestMethod.GET)
public ResponseEntity<byte[]> getImage(HttpServletRequest request, HttpServletResponse response,
@RequestParam String imgPath) throws IOException {
String path = request.getSession().getServletContext().getRealPath(File.separator + "WEB-INF");
File file = new File(path + imgPath);
HttpHeaders headers = new HttpHeaders();
String fileName = new String(imgPath.substring(imgPath.lastIndexOf(".")).getBytes("UTF-8"), "iso-8859-1");
headers.setContentDispositionFormData("attachment", fileName);
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);
}
}
|
package com.opencms.workplace;
import com.opencms.file.*;
import com.opencms.core.*;
import com.opencms.util.*;
import com.opencms.template.*;
import java.util.*;
import java.io.*;
import javax.servlet.http.*;
public class CmsAdminProjectResentFiles extends CmsWorkplaceDefault implements I_CmsConstants,I_CmsFileListUsers {
/**
* Checks if a resource should be added to the vector. If the check was true
* it adds the resource.
*
* @param resources The Vector with the resources to return.
* @param filter The filter to check the state.
* @param resource The resource to check and add.
*/
private void addResource(Vector resources, String filter, CmsResource resource) {
if("all".equals(filter)) {
// add in all cases
resources.addElement(resource);
}
else {
if(("new".equals(filter)) && (resource.getState() == C_STATE_NEW)) {
// add if resource is new
resources.addElement(resource);
}
else {
if(("changed".equals(filter)) && (resource.getState() == C_STATE_CHANGED)) {
// add if resource is changed
resources.addElement(resource);
}
else {
if(("deleted".equals(filter)) && (resource.getState() == C_STATE_DELETED)) {
// add if resource is deleted
resources.addElement(resource);
}
else {
if(("locked".equals(filter)) && (resource.isLocked())) {
// add if resource is locked
resources.addElement(resource);
}
}
}
}
}
}
/**
* Check if this resource should be displayed in the filelist.
* @param cms The CmsObject
* @param res The resource to be checked.
* @return True or false.
* @exception CmsException if something goes wrong.
*/
private boolean checkAccess(CmsObject cms, CmsResource res) throws CmsException {
boolean access = false;
int accessflags = res.getAccessFlags();
// First check if the user may have access by one of his groups.
boolean groupAccess = false;
Enumeration allGroups =
cms.getGroupsOfUser(cms.getRequestContext().currentUser().getName()).elements();
while((!groupAccess) && allGroups.hasMoreElements()) {
groupAccess = cms.readGroup(res).equals((CmsGroup)allGroups.nextElement());
}
if(((accessflags & C_ACCESS_PUBLIC_VISIBLE) > 0) || (cms.readOwner(res).equals(cms.getRequestContext().currentUser())
&& (accessflags & C_ACCESS_OWNER_VISIBLE) > 0) || (groupAccess && (accessflags & C_ACCESS_GROUP_VISIBLE) > 0)
|| (cms.getRequestContext().currentUser().getName().equals(C_USER_ADMIN))) {
access = true;
}
return access;
}
/**
* Gets the content of a defined section in a given template file and its subtemplates
* with the given parameters.
*
* @see getContent(CmsObject cms, String templateFile, String elementName, Hashtable parameters)
* @param cms CmsObject Object for accessing system resources.
* @param templateFile Filename of the template file.
* @param elementName Element name of this template in our parent template.
* @param parameters Hashtable with all template class parameters.
* @param templateSelector template section that should be processed.
*/
public byte[] getContent(CmsObject cms, String templateFile, String elementName,
Hashtable parameters, String templateSelector) throws CmsException {
// get the session
I_CmsSession session = cms.getRequestContext().getSession(true);
int currentProjectId = cms.getRequestContext().currentProject().getId();
// load the template file
CmsXmlWpTemplateFile xmlTemplateDocument = (CmsXmlWpTemplateFile)getOwnTemplateFile(cms,
templateFile, elementName, parameters, templateSelector);
String filter = (String)parameters.get("filter");
String action = (String)parameters.get("action");
xmlTemplateDocument.setData("onload", "");
if("restoreproject".equals(action)) {
// restore the old project..
Integer oldId = (Integer)session.getValue("oldProjectId");
if(oldId != null) {
cms.getRequestContext().setCurrentProject(oldId.intValue());
}
session.removeValue("oldProjectId");
// redirect to the needed headfile.
try {
cms.getRequestContext().getResponse().sendCmsRedirect(getConfigFile(cms).getWorkplaceActionPath()
+ "administration_head_5.html");
}
catch(IOException exc) {
throw new CmsException("Could not redirect to administration_head_5.html", exc);
}
//return "".getBytes();
return null;
}
if(filter == null) {
// this is the first time, this page is called
filter = "all";
if(session.getValue("oldProjectId") == null) {
int projectId = Integer.parseInt((String)parameters.get("projectid"));
session.putValue("oldProjectId", new Integer(cms.getRequestContext().currentProject().getId()));
// set this project temporarly
cms.getRequestContext().setCurrentProject(projectId);
// update the head-frame
xmlTemplateDocument.setData("onload",
"window.top.body.admin_head.location.href='administration_head_4.html';");
}
}
// store the chosen filter into the session
session.putValue("filter", filter);
// Finally start the processing
//return startProcessing(cms, xmlTemplateDocument, elementName, parameters, templateSelector);
// Finally start the processing
byte[] content = startProcessing(cms, xmlTemplateDocument, elementName,
parameters, templateSelector);
//set the current project back
//cms.getRequestContext().setCurrentProject(currentProjectId);
return content;
}
/**
* From interface <code>I_CmsFileListUsers</code>.
* <P>
* Fills all customized columns with the appropriate settings for the given file
* list entry. Any column filled by this method may be used in the customized template
* for the file list.
* @param cms Cms object for accessing system resources.
* @param filelist Template file containing the definitions for the file list together with
* the included customized defintions.
* @param res CmsResource Object of the current file list entry.
* @param lang Current language file.
* @exception CmsException if access to system resources failed.
* @see I_CmsFileListUsers
*/
public void getCustomizedColumnValues(CmsObject cms, CmsXmlWpTemplateFile filelistTemplate,
CmsResource res, CmsXmlLanguageFile lang) throws CmsException {
String name = res.getName();
String path = res.getPath();
String link = "
String servlets = ((HttpServletRequest)cms.getRequestContext().getRequest().getOriginalRequest()).getServletPath();
if(res.isFile() && (res.getState() != C_STATE_DELETED)) {
link = "javascript:openwinfull('" + servlets + res.getAbsolutePath()
+ "', 'preview', 0, 0);";
}
filelistTemplate.setData("LINK_VALUE", link);
filelistTemplate.setData("SHORTNAME_VALUE", name);
filelistTemplate.setData("PATH_VALUE", path);
}
/**
* From interface <code>I_CmsFileListUsers</code>.
* <P>
* Collects all folders and files that are displayed in the file list.
* @param cms The CmsObject.
* @return A vector of folder and file objects.
* @exception Throws CmsException if something goes wrong.
*/
public Vector getFiles(CmsObject cms) throws CmsException {
Vector resources = new Vector();
// get the session
I_CmsSession session = cms.getRequestContext().getSession(true);
String filter = (String)session.getValue("filter");
if(filter == null) {
filter = "all";
}
// get all ressources, that are changed in this project
getFiles(cms, C_ROOT, resources, filter);
return resources;
}
/**
* Get all changed files in a project.
*
* @param cms The cms object.
* @param folderName The name of the folder to start.
* @param resources A Vector to store the result into.
* @param filter The filter-value, to select the files.
*/
private void getFiles(CmsObject cms, String folderName, Vector resources, String filter)
throws CmsException {
CmsResource resource;
Vector resourcesToTest;
// get resources
resourcesToTest = cms.readFileHeaders(cms.getRequestContext().currentProject().getId());
//copy the values into the resources, if they where changed
for(int i = 0;i < resourcesToTest.size();i++) {
resource = (CmsResource)resourcesToTest.elementAt(i);
if(resource.getState() != C_STATE_UNCHANGED) {
addResource(resources, filter, resource);
}
}
}
/**
* Indicates if the results of this class are cacheable.
*
* @param cms CmsObject Object for accessing system resources
* @param templateFile Filename of the template file
* @param elementName Element name of this template in our parent template.
* @param parameters Hashtable with all template class parameters.
* @param templateSelector template section that should be processed.
* @return <EM>true</EM> if cacheable, <EM>false</EM> otherwise.
*/
public boolean isCacheable(CmsObject cms, String templateFile, String elementName,
Hashtable parameters, String templateSelector) {
return false;
}
/**
* From interface <code>I_CmsFileListUsers</code>.
* <P>
* Used to modify the bit pattern for hiding and showing columns in
* the file list.
* @param cms Cms object for accessing system resources.
* @param prefs Old bit pattern.
* @return New modified bit pattern.
* @see I_CmsFileListUsers
*/
public int modifyDisplayedColumns(CmsObject cms, int prefs) {
prefs = ((prefs & C_FILELIST_NAME) == 0) ? prefs : (prefs - C_FILELIST_NAME);
prefs = ((prefs & C_FILELIST_TITLE) == 0) ? prefs : (prefs - C_FILELIST_TITLE);
return prefs;
}
}
|
package com.cloudesire.azure.client.apiobjects;
import com.cloudesire.azure.client.apiobjects.enums.VirtualMachineSize;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
/**
* @author Manuel Mazzuola <manuel.mazzuola@liberologico.com>
*/
@XmlRootElement (name = "Deployment")
@XmlAccessorType (value = XmlAccessType.FIELD)
public class Deployment
{
@XmlElement (name = "Name")
private String name;
@XmlElement (name = "DeploymentSlot")
private String deploymentSlot = "Production";
@XmlElement (name = "PrivateID")
private String privateIp;
@XmlElement (name = "Status")
private String status;
@XmlElement (name = "Label")
private String label;
@XmlElement (name = "Url")
private String url;
@XmlElement (name = "RoleInstanceList")
private RoleInstanceList roleInstanceList = new RoleInstanceList();
@XmlElement (name = "RoleList")
private RoleList roleList = new RoleList();
@XmlElement (name = "VirtualNetworkName")
private String virtualNetworkName;
public String getName ()
{
return name;
}
public void setName ( String name )
{
this.name = name;
}
public String getDeploymentSlot ()
{
return deploymentSlot;
}
public void setDeploymentSlot ( String deploymentSlot )
{
this.deploymentSlot = deploymentSlot;
}
public String getLabel ()
{
return label;
}
public void setLabel ( String label )
{
this.label = label;
}
public RoleList getRoleList ()
{
return roleList;
}
public RoleInstanceList getRoleInstanceList ()
{
return roleInstanceList;
}
public void setRoleInstanceList ( RoleInstanceList roleInstanceList )
{
this.roleInstanceList = roleInstanceList;
}
public void setRoleList ( RoleList roleList )
{
this.roleList = roleList;
}
public String getVirtualNetworkName ()
{
return virtualNetworkName;
}
public void setVirtualNetworkName ( String virtualNetworkName )
{
this.virtualNetworkName = virtualNetworkName;
}
// Overwrite properties if used
public static class Builder
{
private String name;
private String label;
private String hostname;
private String username;
private String password;
private String sourceImage;
private String sourceImageLink;
private String dataImageLink;
private int minMemory;
private int minCpu;
private int minDisk;
public Builder ()
{
}
public Builder withName ( String name )
{
this.name = name;
return this;
}
public Builder withLabel ( String label )
{
this.label = label;
return this;
}
public Builder withHostname ( String hostname )
{
this.hostname = hostname;
return this;
}
public Builder withUsername ( String username )
{
this.username = username;
return this;
}
public Builder withPassword ( String password )
{
this.password = password;
return this;
}
public Builder withSourceImage ( String sourceImage )
{
this.sourceImage = sourceImage;
return this;
}
public Builder withSourceImageLink ( String sourceImageLink )
{
this.sourceImageLink = sourceImageLink;
return this;
}
public Builder withDataImageLink ( String dataImageLink )
{
this.dataImageLink = dataImageLink;
return this;
}
public Builder withMinCpu ( int minCpu )
{
this.minCpu = minCpu;
return this;
}
/**
* Specify the minimum amount of memory in MB
*
* @param minMemory
* @return Builder
*/
public Builder withMinMemory ( int minMemory )
{
this.minMemory = minMemory;
return this;
}
/**
* Specify the minimum amount of disk in GB
*
* @param minDisk
* @return Builder
*/
public Builder withMinDisk ( int minDisk )
{
this.minDisk = minDisk;
return this;
}
public Deployment build ()
{
return new Deployment(this);
}
}
public Deployment ()
{
}
public Deployment ( Builder builder )
{
RoleList roleList = this.roleList;
List<Role> roles = new ArrayList<>();
Role role = new Role();
ConfigurationSets configurationSets = role.getConfigurationSets();
List<ConfigurationSet> configurationList = new ArrayList<>();
ConfigurationSet set = new ConfigurationSet();
ConfigurationSet newtworkSet = new ConfigurationSet();
OSVirtualHardDisk osvh = role.getOsVirtualHardDisk();
DataVirtualHardDisks disks = role.getDataVirtualHardDisks();
List<DataVirtualHardDisk> disksList = new ArrayList<>();
DataVirtualHardDisk disk = new DataVirtualHardDisk();
InputEndpoints endpoints = new InputEndpoints();
InputEndpoint endpoint = new InputEndpoint();
List<InputEndpoint> listEndpoints = new ArrayList<>();
endpoint.setName("ssh");
endpoint.setLocalPort(22);
endpoint.setPort(22);
endpoint.setProtocol("TCP");
listEndpoints.add(endpoint);
endpoints.setEndpoints(listEndpoints);
newtworkSet.setConfigurationSetType("NetworkConfiguration");
newtworkSet.setConfigurationSetTypeAttribute("NetworkConfiguration");
newtworkSet.setInputEndpoints(endpoints);
set.setHostName(builder.hostname);
set.setUserName(builder.username);
set.setUserPassword(builder.password);
configurationList.add(set);
configurationList.add(newtworkSet);
configurationSets.setConfigurationSets(configurationList);
osvh.setSourceImageName(builder.sourceImage);
osvh.setMediaLink(builder.sourceImageLink);
role.setRoleName(UUID.randomUUID().toString());
role.setConfigurationSets(configurationSets);
role.setOsVirtualHardDisk(osvh);
disk.setLogicalDiskSizeInGB(builder.minDisk);
disk.setMediaLink(builder.dataImageLink);
disk.setDiskLabel(builder.label);
disksList.add(disk);
disks.setDataVirtualHardDisks(disksList);
role.setDataVirtualHardDisks(disks);
VirtualMachineSize size = VirtualMachineSize.ExtraSmall;
if (builder.minCpu >= 0) size = VirtualMachineSize.Small;
if (builder.minCpu >= 1) size = VirtualMachineSize.Medium;
if (builder.minCpu >= 2) size = VirtualMachineSize.Large;
if (builder.minCpu >= 4) size = VirtualMachineSize.ExtraLarge;
if (builder.minMemory >= 0 && size.getSize() < VirtualMachineSize.Small.getSize())
size = VirtualMachineSize.Small;
if (builder.minMemory >= 1792 && size.getSize() < VirtualMachineSize.Medium.getSize())
size = VirtualMachineSize.Medium;
if (builder.minMemory >= 3584 && size.getSize() < VirtualMachineSize.Large.getSize())
size = VirtualMachineSize.Large;
if (builder.minMemory >= 7168 && size.getSize() < VirtualMachineSize.ExtraLarge.getSize())
size = VirtualMachineSize.ExtraLarge;
if (builder.minCpu <= 1 && builder.minMemory < 1792) size = VirtualMachineSize.ExtraSmall;
role.setRoleSize(size.toString());
roles.add(role);
roleList.setRoles(roles);
this.setName(builder.name);
this.setLabel(builder.label);
}
@Override
public String toString ()
{
return "Name: " + name + " DeloymentSlot: "
+ deploymentSlot + " label: " + label + " RoleList: "
+ roleList + " RoleInstanceList: " + roleInstanceList + " VirtualNetworkName: " + virtualNetworkName;
}
}
|
package com.couchbase.lite.replicator;
import com.couchbase.lite.CouchbaseLiteException;
import com.couchbase.lite.Database;
import com.couchbase.lite.Misc;
import com.couchbase.lite.ReplicationFilter;
import com.couchbase.lite.RevisionList;
import com.couchbase.lite.SavedRevision;
import com.couchbase.lite.Status;
import com.couchbase.lite.auth.Authenticator;
import com.couchbase.lite.auth.AuthenticatorImpl;
import com.couchbase.lite.internal.InterfaceAudience;
import com.couchbase.lite.internal.RevisionInternal;
import com.couchbase.lite.support.BatchProcessor;
import com.couchbase.lite.support.Batcher;
import com.couchbase.lite.support.BlockingQueueListener;
import com.couchbase.lite.support.CustomFuture;
import com.couchbase.lite.support.CustomLinkedBlockingQueue;
import com.couchbase.lite.support.HttpClientFactory;
import com.couchbase.lite.support.RemoteRequestCompletionBlock;
import com.couchbase.lite.support.RemoteRequestRetry;
import com.couchbase.lite.util.CollectionUtils;
import com.couchbase.lite.util.Log;
import com.couchbase.lite.util.TextUtils;
import com.couchbase.lite.util.URIUtils;
import com.couchbase.lite.util.Utils;
import com.couchbase.org.apache.http.entity.mime.MultipartEntity;
import com.github.oxo42.stateless4j.StateMachine;
import com.github.oxo42.stateless4j.delegates.Action1;
import com.github.oxo42.stateless4j.transitions.Transition;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpResponseException;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.cookie.BasicClientCookie2;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Internal Replication object that does the heavy lifting
*
* @exclude
*/
@InterfaceAudience.Private
abstract class ReplicationInternal implements BlockingQueueListener {
// Change listeners can be called back synchronously or asynchronously.
protected enum ChangeListenerNotifyStyle {
SYNC, ASYNC
}
public static final String BY_CHANNEL_FILTER_NAME = "sync_gateway/bychannel";
public static final String CHANNELS_QUERY_PARAM = "channels";
public static final int EXECUTOR_THREAD_POOL_SIZE = 5;
private static int lastSessionID = 0;
public static int MAX_RETRIES = 10; // total number of attempts = 11 (1 initial + MAX_RETRIES)
public static int RETRY_DELAY_SECONDS = 60; // #define kRetryDelay 60.0 in CBL_Replicator.m
protected Replication parentReplication;
protected Database db;
protected URL remote;
protected HttpClientFactory clientFactory;
protected String lastSequence;
protected Authenticator authenticator;
protected String filterName;
protected Map<String, Object> filterParams;
protected List<String> documentIDs;
private String remoteUUID;
protected Map<String, Object> requestHeaders;
private String serverType;
protected Batcher<RevisionInternal> batcher;
protected static int PROCESSOR_DELAY = 500;
protected static int INBOX_CAPACITY = 100;
protected ScheduledExecutorService remoteRequestExecutor;
private Throwable error; // use private to make sure if error is set through setError()
private String remoteCheckpointDocID;
protected Map<String, Object> remoteCheckpoint;
protected AtomicInteger completedChangesCount;
protected AtomicInteger changesCount;
protected CollectionUtils.Functor<RevisionInternal, RevisionInternal> revisionBodyTransformationBlock;
protected String sessionID;
protected BlockingQueue<Future> pendingFutures;
private boolean lastSequenceChanged = false;
private boolean savingCheckpoint;
private boolean overdueForCheckpointSave;
// the code assumes this is a _single threaded_ work executor.
// if it's not, the behavior will be buggy. I don't see a way to assert this in the code.
protected ScheduledExecutorService workExecutor;
protected StateMachine<ReplicationState, ReplicationTrigger> stateMachine;
protected List<ChangeListener> changeListeners;
protected Replication.Lifecycle lifecycle;
protected ChangeListenerNotifyStyle changeListenerNotifyStyle;
private Future retryFuture = null; // future obj of retry task
private int retryCount = 0; // counter for retry.
/**
* Constructor
*/
ReplicationInternal(Database db, URL remote,
HttpClientFactory clientFactory,
ScheduledExecutorService workExecutor,
Replication.Lifecycle lifecycle,
Replication parentReplication) {
Utils.assertNotNull(lifecycle, "Must pass in a non-null lifecycle");
this.parentReplication = parentReplication;
this.db = db;
this.remote = remote;
this.clientFactory = clientFactory;
this.workExecutor = workExecutor;
this.lifecycle = lifecycle;
this.requestHeaders = new HashMap<String, Object>();
changeListeners = new CopyOnWriteArrayList<ChangeListener>();
// The reason that notifications are ASYNC is to make the public API call
// Replication.getStatus() work as expected. Because if this is set to SYNC,
// it causes the following issue:
// - Notification sent from state transition from INITIAL -> RUNNING.
// - Replication change listener called back during transition.
// - Replication change listener calls replication.status(), and gets INITIAL instead of RUNNING.
// - Replication change listener never notified when it goes into the RUNNING state.
// Workarounds to above problem:
// - By sending notifications ASYNC, by the time that the listener calls replication.status(),
// calling replication.getStatus() will return RUNNING.
// - Alternatively, change listeners could look at the passed transition rather than
// depending on calling replication.status(), and changeListenerNotifyStyle could be set to SYNC.
changeListenerNotifyStyle = ChangeListenerNotifyStyle.ASYNC;
pendingFutures = new CustomLinkedBlockingQueue<Future>(this);
initializeStateMachine();
this.retryCount = 0;
}
/**
* Trigger this replication to start (async)
*/
public void triggerStart() {
fireTrigger(ReplicationTrigger.START);
}
/**
* Trigger this replication to stop (async)
*/
public void triggerStopGraceful() {
fireTrigger(ReplicationTrigger.STOP_GRACEFUL);
}
/**
* Trigger this replication to go offline (async)
*/
public void triggerGoOffline() {
fireTrigger(ReplicationTrigger.GO_OFFLINE);
}
/**
* Trigger this replication to go online (async)
*/
public void triggerGoOnline() {
fireTrigger(ReplicationTrigger.GO_ONLINE);
}
/**
* Fire a trigger to the state machine
*/
protected void fireTrigger(final ReplicationTrigger trigger) {
Log.d(Log.TAG_SYNC, "[fireTrigger()] => " + trigger);
// All state machine triggers need to happen on the replicator thread
synchronized (workExecutor) {
if (!workExecutor.isShutdown()) {
workExecutor.submit(new Runnable() {
@Override
public void run() {
try {
Log.d(Log.TAG_SYNC, "firing trigger: %s", trigger);
stateMachine.fire(trigger);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
});
}
}
}
/**
* Trigger this replication to stop immediately -- assumes pending work has
* been drained, or that caller chooses to ignore any pending work.
*/
protected void triggerStopImmediate() {
fireTrigger(ReplicationTrigger.STOP_IMMEDIATE);
}
/**
* Start the replication process.
*/
protected void start() {
try {
if (!db.isOpen()) {
String msg = String.format("Db: %s is not open, abort replication", db);
parentReplication.setLastError(new Exception(msg));
fireTrigger(ReplicationTrigger.STOP_IMMEDIATE);
return;
}
db.addReplication(parentReplication);
db.addActiveReplication(parentReplication);
initSessionId();
// init batcher
initBatcher();
// init authorizer / authenticator
initAuthorizer();
initializeRequestWorkers();
// single-shot replication
if (!isContinuous()) {
goOnline();
}
// continuous mode
else {
if (isNetworkReachable())
goOnline();
else
triggerGoOffline();
startNetworkReachabilityManager();
}
} catch (Exception e) {
Log.e(Log.TAG_SYNC, "%s: Exception in start()", e, this);
}
}
private void initSessionId() {
this.sessionID = String.format("repl%03d", ++lastSessionID);
}
/**
* Take the replication offline
*/
protected void goOffline() {
// implemented by subclasses
}
/**
* Put the replication back online after being offline
*/
protected void goOnline() {
this.retryCount = 0;
checkSession();
}
public void databaseClosing() {
triggerStopGraceful();
}
/**
* Close all resources associated with this replicator.
*/
protected void close() {
// shutdown ScheduledExecutorService. Without shutdown, cause thread leak
if (remoteRequestExecutor != null && !remoteRequestExecutor.isShutdown()) {
// Note: Time to wait is set 60 sec because RemoteRequest's socket timeout is set 60 seconds.
Utils.shutdownAndAwaitTermination(remoteRequestExecutor,
Replication.DEFAULT_MAX_TIMEOUT_FOR_SHUTDOWN,
Replication.DEFAULT_MAX_TIMEOUT_FOR_SHUTDOWN);
}
}
protected void initAuthorizer() {
// TODO: add this back in .. See Replication constructor
}
protected void initBatcher() {
batcher = new Batcher<RevisionInternal>(workExecutor, INBOX_CAPACITY, PROCESSOR_DELAY, new BatchProcessor<RevisionInternal>() {
@Override
public void process(List<RevisionInternal> inbox) {
try {
Log.v(Log.TAG_SYNC, "*** %s: BEGIN processInbox (%d sequences)", this, inbox.size());
processInbox(new RevisionList(inbox));
Log.v(Log.TAG_SYNC, "*** %s: END processInbox (lastSequence=%s)", this, lastSequence);
} catch (Exception e) {
Log.e(Log.TAG_SYNC, "ERROR: processInbox failed: ", e);
throw new RuntimeException(e);
}
}
});
}
protected void startNetworkReachabilityManager() {
db.getManager().getContext().getNetworkReachabilityManager().addNetworkReachabilityListener(parentReplication);
}
protected void stopNetworkReachabilityManager() {
db.getManager().getContext().getNetworkReachabilityManager().removeNetworkReachabilityListener(parentReplication);
}
protected boolean isNetworkReachable() {
return db.getManager().getContext().getNetworkReachabilityManager().isOnline();
}
public abstract boolean shouldCreateTarget();
public abstract void setCreateTarget(boolean createTarget);
protected void initializeRequestWorkers() {
if (remoteRequestExecutor == null) {
int executorThreadPoolSize = db.getManager().getExecutorThreadPoolSize() <= 0 ?
EXECUTOR_THREAD_POOL_SIZE : db.getManager().getExecutorThreadPoolSize();
Log.v(Log.TAG_SYNC, "executorThreadPoolSize=" + executorThreadPoolSize);
remoteRequestExecutor = Executors.newScheduledThreadPool(executorThreadPoolSize, new ThreadFactory() {
private int counter = 0;
@Override
public Thread newThread(Runnable r) {
String threadName = "CBLRequestWorker";
try {
String replicationIdentifier = Utils.shortenString(remoteCheckpointDocID(), 5);
threadName = String.format("CBLRequestWorker-%s-%s", replicationIdentifier, counter++);
} catch (Exception e) {
Log.e(Log.TAG_SYNC, "Error creating thread name", e);
}
return new Thread(r, threadName);
}
});
}
}
@InterfaceAudience.Private
protected void checkSession() {
// REVIEW : This is not in line with the iOS implementation
if (getAuthenticator() != null && ((AuthenticatorImpl) getAuthenticator()).usesCookieBasedLogin()) {
checkSessionAtPath("/_session");
} else {
fetchRemoteCheckpointDoc();
}
}
@InterfaceAudience.Private
protected void checkSessionAtPath(final String sessionPath) {
Future future = sendAsyncRequest("GET", sessionPath, null, new RemoteRequestCompletionBlock() {
@Override
public void onCompletion(HttpResponse httpResponse, Object result, Throwable err) {
try {
if (err != null) {
// If not at /db/_session, try CouchDB location /_session
if (err instanceof HttpResponseException &&
((HttpResponseException) err).getStatusCode() == 404 &&
"/_session".equalsIgnoreCase(sessionPath)) {
checkSessionAtPath("_session");
return;
}
Log.e(Log.TAG_SYNC, this + ": Session check failed", err);
setError(err);
} else {
Map<String, Object> response = (Map<String, Object>) result;
Log.e(Log.TAG_SYNC, "%s checkSessionAtPath() response: %s", this, response);
Map<String, Object> userCtx = (Map<String, Object>) response.get("userCtx");
String username = (String) userCtx.get("name");
if (username != null && username.length() > 0) {
Log.d(Log.TAG_SYNC, "%s Active session, logged in as %s", this, username);
fetchRemoteCheckpointDoc();
} else {
Log.d(Log.TAG_SYNC, "%s No active session, going to login", this);
login();
}
}
} catch (Exception e) {
Log.e(Log.TAG_SYNC, "%s Exception in checkSessionAtPath()", this, e);
}
}
});
pendingFutures.add(future);
}
@InterfaceAudience.Private
protected void login() {
Map<String, String> loginParameters = ((AuthenticatorImpl) getAuthenticator()).loginParametersForSite(remote);
if (loginParameters == null) {
Log.d(Log.TAG_SYNC, "%s: %s has no login parameters, so skipping login", this, getAuthenticator());
fetchRemoteCheckpointDoc();
return;
}
final String loginPath = ((AuthenticatorImpl) getAuthenticator()).loginPathForSite(remote);
Log.d(Log.TAG_SYNC, "%s: Doing login with %s at %s", this, getAuthenticator().getClass(), loginPath);
Future future = sendAsyncRequest("POST", loginPath, loginParameters, new RemoteRequestCompletionBlock() {
@Override
public void onCompletion(HttpResponse httpResponse, Object result, Throwable e) {
if (e != null) {
Log.d(Log.TAG_SYNC, "%s: Login failed for path: %s", this, loginPath);
setError(e);
// TODO: double check this behavior against iOS implementation, especially
// TODO: with regards to behavior of a continuous replication.
// Note: was added in order that unit test testReplicatorErrorStatus() finished and passed.
// (before adding this, the replication would just end up in limbo and never finish)
triggerStopGraceful();
} else {
Log.v(Log.TAG_SYNC, "%s: Successfully logged in!", this);
fetchRemoteCheckpointDoc();
}
}
});
pendingFutures.add(future);
}
@InterfaceAudience.Private
protected void setError(Throwable throwable) {
// TODO - needs to port
//if (error.code == NSURLErrorCancelled && $equal(error.domain, NSURLErrorDomain))
// return;
if (throwable != this.error) {
Log.e(Log.TAG_SYNC, "%s: Progress: set error = %s", this, throwable);
parentReplication.setLastError(throwable);
this.error = throwable;
// if permanent error, stop immediately
if(Utils.isPermanentError(this.error) || !isContinuous()) {
triggerStopGraceful();
}
// iOS version sends notification from stop() method, but java version does not.
// following codes are always executed.
Replication.ChangeEvent changeEvent = new Replication.ChangeEvent(this);
changeEvent.setError(this.error);
notifyChangeListeners(changeEvent);
}
}
@InterfaceAudience.Private
protected void addToCompletedChangesCount(int delta) {
int previousVal = getCompletedChangesCount().getAndAdd(delta);
Log.v(Log.TAG_SYNC, "%s: Incrementing completedChangesCount count from %s by adding %d -> %d",
this, previousVal, delta, completedChangesCount.get());
Replication.ChangeEvent changeEvent = new Replication.ChangeEvent(this);
notifyChangeListeners(changeEvent);
}
@InterfaceAudience.Private
protected void addToChangesCount(int delta) {
int previousVal = getChangesCount().getAndAdd(delta);
if (getChangesCount().get() < 0) {
Log.w(Log.TAG_SYNC, "Changes count is negative, this could indicate an error");
}
Log.v(Log.TAG_SYNC, "%s: Incrementing changesCount count from %s by adding %d -> %d",
this, previousVal, delta, changesCount.get());
Replication.ChangeEvent changeEvent = new Replication.ChangeEvent(this);
notifyChangeListeners(changeEvent);
}
public AtomicInteger getCompletedChangesCount() {
if (completedChangesCount == null) {
completedChangesCount = new AtomicInteger(0);
}
return completedChangesCount;
}
public AtomicInteger getChangesCount() {
if (changesCount == null) {
changesCount = new AtomicInteger(0);
}
return changesCount;
}
/**
* @exclude
*/
@InterfaceAudience.Private
public CustomFuture sendAsyncRequest(String method, String relativePath, Object body,
RemoteRequestCompletionBlock onCompletion) {
return sendAsyncRequest(method, relativePath, body, false, onCompletion);
}
/**
* @exclude
*/
@InterfaceAudience.Private
public CustomFuture sendAsyncRequest(String method, String relativePath, Object body, boolean dontLog404,
RemoteRequestCompletionBlock onCompletion) {
try {
String urlStr = buildRelativeURLString(relativePath);
URL url = new URL(urlStr);
return sendAsyncRequest(method, url, body, dontLog404, onCompletion);
} catch (MalformedURLException e) {
Log.e(Log.TAG_SYNC, "Malformed URL for async request", e);
}
return null;
}
/**
* @exclude
*/
@InterfaceAudience.Private
public CustomFuture sendAsyncRequest(String method, URL url, Object body, boolean dontLog404,
final RemoteRequestCompletionBlock onCompletion) {
Log.d(Log.TAG_SYNC, "[sendAsyncRequest()] " + method + " => " + url);
RemoteRequestRetry request = new RemoteRequestRetry(
RemoteRequestRetry.RemoteRequestType.REMOTE_REQUEST,
remoteRequestExecutor,
workExecutor,
clientFactory,
method,
url,
body,
getLocalDatabase(),
getHeaders(),
onCompletion
);
request.setDontLog404(dontLog404);
request.setAuthenticator(getAuthenticator());
request.setOnPreCompletionCaller(new RemoteRequestCompletionBlock() {
@Override
public void onCompletion(HttpResponse httpResponse, Object result, Throwable e) {
if (serverType == null && httpResponse != null) {
Header serverHeader = httpResponse.getFirstHeader("Server");
if (serverHeader != null) {
String serverVersion = serverHeader.getValue();
Log.v(Log.TAG_SYNC, "serverVersion: %s", serverVersion);
serverType = serverVersion;
}
}
}
});
return request.submit(canSendCompressedRequests());
}
/**
* @exclude
*/
@InterfaceAudience.Private
public CustomFuture sendAsyncMultipartRequest(String method, String relativePath,
MultipartEntity multiPartEntity,
RemoteRequestCompletionBlock onCompletion) {
URL url = null;
try {
String urlStr = buildRelativeURLString(relativePath);
url = new URL(urlStr);
} catch (MalformedURLException e) {
throw new IllegalArgumentException(e);
}
RemoteRequestRetry request = new RemoteRequestRetry(
RemoteRequestRetry.RemoteRequestType.REMOTE_MULTIPART_REQUEST,
remoteRequestExecutor,
workExecutor,
clientFactory,
method,
url,
multiPartEntity,
getLocalDatabase(),
getHeaders(),
onCompletion
);
request.setAuthenticator(getAuthenticator());
return request.submit();
}
/**
* @exclude
*/
@InterfaceAudience.Private
public CustomFuture sendAsyncMultipartDownloaderRequest(String method, String relativePath,
Object body, Database db,
RemoteRequestCompletionBlock onCompletion) {
try {
String urlStr = buildRelativeURLString(relativePath);
URL url = new URL(urlStr);
RemoteRequestRetry request = new RemoteRequestRetry(
RemoteRequestRetry.RemoteRequestType.REMOTE_MULTIPART_DOWNLOADER_REQUEST,
remoteRequestExecutor,
workExecutor,
clientFactory,
method,
url,
body,
getLocalDatabase(),
getHeaders(),
onCompletion
);
request.setAuthenticator(getAuthenticator());
return request.submit();
} catch (MalformedURLException e) {
Log.e(Log.TAG_SYNC, "Malformed URL for async request", e);
}
return null;
}
/**
* Get the local database which is the source or target of this replication
*/
protected Database getLocalDatabase() {
return db;
}
protected void setLocalDatabase(Database db) {
this.db = db;
}
/**
* Extra HTTP headers to send in all requests to the remote server.
* Should map strings (header names) to strings.
*/
@InterfaceAudience.Public
public Map<String, Object> getHeaders() {
return requestHeaders;
}
/**
* Set Extra HTTP headers to be sent in all requests to the remote server.
*/
@InterfaceAudience.Public
public void setHeaders(Map<String, Object> requestHeadersParam) {
if (requestHeadersParam != null && !requestHeaders.equals(requestHeadersParam)) {
requestHeaders = requestHeadersParam;
}
}
/**
* in CBL_Replicator.m
* - (void) saveLastSequence
*
* @exclude
*/
@InterfaceAudience.Private
public void saveLastSequence() {
if (!lastSequenceChanged) {
return;
}
if (savingCheckpoint) {
// If a save is already in progress, don't do anything. (The completion block will trigger
// another save after the first one finishes.)
overdueForCheckpointSave = true;
return;
}
lastSequenceChanged = false;
overdueForCheckpointSave = false;
Log.d(Log.TAG_SYNC, "%s: saveLastSequence() called. lastSequence: %s remoteCheckpoint: %s",
this, lastSequence, remoteCheckpoint);
final Map<String, Object> body = new HashMap<String, Object>();
if (remoteCheckpoint != null) {
body.putAll(remoteCheckpoint);
}
body.put("lastSequence", lastSequence);
savingCheckpoint = true;
final String remoteCheckpointDocID = remoteCheckpointDocID();
if (remoteCheckpointDocID == null) {
Log.w(Log.TAG_SYNC, "%s: remoteCheckpointDocID is null, aborting saveLastSequence()", this);
return;
}
final String checkpointID = remoteCheckpointDocID;
Log.d(Log.TAG_SYNC, "%s: start put remote _local document. checkpointID: %s body: %s",
this, checkpointID, body);
Future future = sendAsyncRequest("PUT", "/_local/" + checkpointID, body, new RemoteRequestCompletionBlock() {
@Override
public void onCompletion(HttpResponse httpResponse, Object result, Throwable e) {
Log.d(Log.TAG_SYNC,
"%s: put remote _local document request finished. checkpointID: %s body: %s",
this, checkpointID, body);
try {
if (e != null) {
Log.w(Log.TAG_SYNC, "%s: Unable to save remote checkpoint", e, this);
// Failed to save checkpoint:
switch (Utils.getStatusFromError(e)) {
case Status.NOT_FOUND:
Log.i(Log.TAG_SYNC, "%s: could not save remote checkpoint: 404 NOT FOUND", this);
remoteCheckpoint = null; // doc deleted or db reset
overdueForCheckpointSave = true; // try saving again
break;
case Status.CONFLICT:
Log.i(Log.TAG_SYNC, "%s: could not save remote checkpoint: 409 CONFLICT", this);
refreshRemoteCheckpointDoc();
break;
default:
Log.i(Log.TAG_SYNC, "%s: could not save remote checkpoint: %s", this, e);
// TODO: On 401 or 403, and this is a pull, remember that remote
// TODo: is read-only & don't attempt to read its checkpoint next time.
break;
}
} else {
// Saved checkpoint:
Map<String, Object> response = (Map<String, Object>) result;
body.put("_rev", response.get("rev"));
remoteCheckpoint = body;
boolean isOpen = false;
try {
if (db != null) {
db.open();
isOpen = true;
}
} catch (CouchbaseLiteException ex) {
Log.w(Log.TAG_SYNC, "%s: Cannot open the database", ex, this);
}
if (isOpen) {
Log.d(Log.TAG_SYNC,
"%s: saved remote checkpoint, updating local checkpoint. RemoteCheckpoint: %s",
this, remoteCheckpoint);
setLastSequenceFromWorkExecutor(lastSequence, checkpointID);
} else {
Log.w(Log.TAG_SYNC, "%s: Database is null or closed, not calling db.setLastSequence() ", this);
}
}
} finally {
savingCheckpoint = false;
if (overdueForCheckpointSave) {
Log.i(Log.TAG_SYNC, "%s: overdueForCheckpointSave == true, calling saveLastSequence()", this);
overdueForCheckpointSave = false;
saveLastSequence();
}
}
}
});
pendingFutures.add(future);
}
protected void setLastSequenceFromWorkExecutor(final String lastSequence, final String checkpointId) {
// write access to database from workExecutor
workExecutor.submit(new Runnable() {
@Override
public void run() {
if(db != null && db.isOpen())
db.setLastSequence(lastSequence, checkpointId);
}
});
// no wait...
}
/**
* Variant of -fetchRemoveCheckpointDoc that's used while replication is running, to reload the
* checkpoint to get its current revision number, if there was an error saving it.
*/
@InterfaceAudience.Private
private void refreshRemoteCheckpointDoc() {
Log.i(Log.TAG_SYNC, "%s: Refreshing remote checkpoint to get its _rev...", this);
Future future = sendAsyncRequest("GET", "/_local/" + remoteCheckpointDocID(), null, new RemoteRequestCompletionBlock() {
@Override
public void onCompletion(HttpResponse httpResponse, Object result, Throwable e) {
if (db == null) {
Log.w(Log.TAG_SYNC, "%s: db == null while refreshing remote checkpoint. aborting", this);
return;
}
if (e != null && Utils.getStatusFromError(e) != Status.NOT_FOUND) {
Log.e(Log.TAG_SYNC, "%s: Error refreshing remote checkpoint", e, this);
} else {
Log.d(Log.TAG_SYNC, "%s: Refreshed remote checkpoint: %s", this, result);
remoteCheckpoint = (Map<String, Object>) result;
lastSequenceChanged = true;
saveLastSequence(); // try saving again
}
}
});
pendingFutures.add(future);
}
@InterfaceAudience.Private
protected String buildRelativeURLString(String relativePath) {
// the following code is a band-aid for a system problem in the codebase
// where it is appending "relative paths" that start with a slash, eg:
// which is not compatible with the way the java url concatonation works.
String remoteUrlString = remote.toExternalForm();
if (remoteUrlString.endsWith("/") && relativePath.startsWith("/")) {
remoteUrlString = remoteUrlString.substring(0, remoteUrlString.length() - 1);
}
if ("_session".equals(relativePath)) {
try {
URL remoteUrl = new URL(remoteUrlString);
String relativePathWithLeadingSlash = String.format("/%s", relativePath); // required on couchbase-lite-java
URL remoteUrlNoPath = new URL(remoteUrl.getProtocol(), remoteUrl.getHost(),
remoteUrl.getPort(), relativePathWithLeadingSlash);
remoteUrlString = remoteUrlNoPath.toExternalForm();
return remoteUrlString;
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
}
return remoteUrlString + relativePath;
}
/**
* @exclude
*/
@InterfaceAudience.Private
public void fetchRemoteCheckpointDoc() {
lastSequenceChanged = false;
String checkpointId = remoteCheckpointDocID();
final String localLastSequence = db.lastSequenceWithCheckpointId(checkpointId);
boolean dontLog404 = true;
Future future = sendAsyncRequest("GET", "/_local/" + checkpointId, null, dontLog404, new RemoteRequestCompletionBlock() {
@Override
public void onCompletion(HttpResponse httpResponse, Object result, Throwable e) {
if (e != null && !Utils.is404(e)) {
Log.w(Log.TAG_SYNC, "%s: error getting remote checkpoint", e, this);
setError(e);
} else {
if (e != null && Utils.is404(e)) {
Log.v(Log.TAG_SYNC, "%s: Remote checkpoint does not exist on server yet: %s",
this, remoteCheckpointDocID());
maybeCreateRemoteDB();
}
Map<String, Object> response = (Map<String, Object>) result;
remoteCheckpoint = response;
String remoteLastSequence = null;
if (response != null) {
remoteLastSequence = (String) response.get("lastSequence");
}
if (remoteLastSequence != null && remoteLastSequence.equals(localLastSequence)) {
lastSequence = localLastSequence;
Log.d(Log.TAG_SYNC, "%s: Replicating from lastSequence=%s", this, lastSequence);
} else {
Log.d(Log.TAG_SYNC, "%s: lastSequence mismatch: I had: %s, remote had: %s",
this, localLastSequence, remoteLastSequence);
}
beginReplicating();
}
}
});
pendingFutures.add(future);
}
protected abstract void maybeCreateRemoteDB();
/**
* This is the _local document ID stored on the remote server to keep track of state.
* Its ID is based on the local database ID (the private one, to make the result unguessable)
* and the remote database's URL.
*
* @exclude
*/
public String remoteCheckpointDocID() {
if (remoteCheckpointDocID != null) {
return remoteCheckpointDocID;
} else {
if (db == null) {
return null;
}
return remoteCheckpointDocID(db.privateUUID());
}
}
public String remoteCheckpointDocID(String localUUID) {
// canonicalization: make sure it produces the same checkpoint id regardless of
// ordering of filterparams / docids
Map<String, Object> filterParamsCanonical = null;
if (getFilterParams() != null) {
filterParamsCanonical = new TreeMap<String, Object>(getFilterParams());
}
List<String> docIdsSorted = null;
if (getDocIds() != null) {
docIdsSorted = new ArrayList<String>(getDocIds());
Collections.sort(docIdsSorted);
}
// use a treemap rather than a dictionary for purposes of canonicalization
Map<String, Object> spec = new TreeMap<String, Object>();
spec.put("localUUID", localUUID);
spec.put("push", !isPull());
spec.put("continuous", isContinuous());
if (getFilter() != null) {
spec.put("filter", getFilter());
}
if (filterParamsCanonical != null) {
spec.put("filterParams", filterParamsCanonical);
}
if (docIdsSorted != null) {
spec.put("docids", docIdsSorted);
}
if (remoteUUID != null) {
spec.put("remoteUUID", remoteUUID);
} else {
spec.put("remoteURL", remote.toExternalForm());
}
byte[] inputBytes = null;
try {
inputBytes = db.getManager().getObjectMapper().writeValueAsBytes(spec);
} catch (IOException e) {
throw new RuntimeException(e);
}
remoteCheckpointDocID = Misc.HexSHA1Digest(inputBytes);
return remoteCheckpointDocID;
}
/**
* For javadocs, see Replication
*/
public String getFilter() {
return filterName;
}
/**
* Set the filter to be used by this replication
*/
public void setFilter(String filterName) {
this.filterName = filterName;
}
/**
* Get replicator filter. If the replicator is a pull replicator,
* calling this method will return null.
*
* This is equivalent to CBL_ReplicatorSettings's compilePushFilterForDatabase:status:.
*/
public ReplicationFilter compilePushReplicationFilter() {
if (isPull())
return null;
if (filterName != null)
return db.getFilter(filterName);
else if (documentIDs != null && documentIDs.size() > 0) {
final List<String> docIDs = documentIDs;
return new ReplicationFilter() {
@Override
public boolean filter(SavedRevision revision, Map<String, Object> params) {
return docIDs.contains(revision.getDocument().getId());
}
};
}
return null;
}
/**
* Is this a pull replication? (Eg, it pulls data from Sync Gateway -> Device running CBL?)
*/
public abstract boolean isPull();
/**
* Gets the documents to specify as part of the replication.
*/
public List<String> getDocIds() {
return documentIDs;
}
/**
* Sets the documents to specify as part of the replication.
*/
public void setDocIds(List<String> docIds) {
documentIDs = docIds;
}
/**
* Should the replication operate continuously, copying changes as soon as the
* source database is modified? (Defaults to NO).
*/
public boolean isContinuous() {
return lifecycle == Replication.Lifecycle.CONTINUOUS;
}
/**
* For javadoc, see Replication
*/
public Map<String, Object> getFilterParams() {
return filterParams;
}
/**
* Set parameters to pass to the filter function.
*/
public void setFilterParams(Map<String, Object> filterParams) {
this.filterParams = filterParams;
}
/**
* Get the remoteUUID representing the remote server.
*/
public String getRemoteUUID() {
return remoteUUID;
}
/**
* Set the remoteUUID representing the remote server.
*/
public void setRemoteUUID(String remoteUUID) {
this.remoteUUID = remoteUUID;
}
abstract protected void processInbox(RevisionList inbox);
/**
* gzip
* <p/>
* in CBL_Replicator.m
* - (BOOL) canSendCompressedRequests
*/
public boolean canSendCompressedRequests() {
// https://github.com/couchbase/couchbase-lite-ios/issues/240#issuecomment-32506552
// gzip upload is only enabled when the server is Sync Gateway 0.92 or later
return serverIsSyncGatewayVersion("0.92");
}
/**
* After successfully authenticating and getting remote checkpoint,
* begin the work of transferring documents.
*/
abstract protected void beginReplicating();
/**
* Actual work of stopping the replication process.
*/
protected void stop() {
if (!isRunning())
return;
// clear batcher
batcher.clear();
// set non-continuous
setLifecycle(Replication.Lifecycle.ONESHOT);
// cancel if middle of retry
cancelRetryFuture();
// cancel all pending future tasks.
while (!pendingFutures.isEmpty()) {
Future future = pendingFutures.poll();
if (future != null && !future.isCancelled() && !future.isDone()) {
future.cancel(true);
}
}
}
/**
* Notify all change listeners of a ChangeEvent
*/
private void notifyChangeListeners(final Replication.ChangeEvent changeEvent) {
if (changeListenerNotifyStyle == ChangeListenerNotifyStyle.SYNC) {
for (ChangeListener changeListener : changeListeners) {
try {
changeListener.changed(changeEvent);
} catch (Exception e) {
e.printStackTrace();
Log.e(Log.TAG_SYNC, "Exception notifying replication listener: %s", e);
}
}
} else {
// ASYNC
synchronized (workExecutor) {
if (!workExecutor.isShutdown()) {
workExecutor.submit(new Runnable() {
@Override
public void run() {
try {
for (ChangeListener changeListener : changeListeners) {
changeListener.changed(changeEvent);
}
} catch (Exception e) {
Log.e(Log.TAG_SYNC, "Exception notifying replication listener: %s", e);
throw new RuntimeException(e);
}
}
});
}
}
}
}
/**
* Adds a change delegate that will be called whenever the Replication changes.
*/
@InterfaceAudience.Public
public void addChangeListener(ChangeListener changeListener) {
changeListeners.add(changeListener);
}
/**
* Initialize the state machine which defines the overall behavior of the replication
* object.
*/
protected void initializeStateMachine() {
stateMachine = new StateMachine<ReplicationState, ReplicationTrigger>(ReplicationState.INITIAL);
// hierarchy
stateMachine.configure(ReplicationState.IDLE).substateOf(ReplicationState.RUNNING);
stateMachine.configure(ReplicationState.OFFLINE).substateOf(ReplicationState.RUNNING);
// permitted transitions
stateMachine.configure(ReplicationState.INITIAL).permit(
ReplicationTrigger.START,
ReplicationState.RUNNING
);
stateMachine.configure(ReplicationState.IDLE).permit(
ReplicationTrigger.RESUME,
ReplicationState.RUNNING
);
stateMachine.configure(ReplicationState.RUNNING).permit(
ReplicationTrigger.WAITING_FOR_CHANGES,
ReplicationState.IDLE
);
stateMachine.configure(ReplicationState.RUNNING).permit(
ReplicationTrigger.STOP_IMMEDIATE,
ReplicationState.STOPPED
);
stateMachine.configure(ReplicationState.RUNNING).permit(
ReplicationTrigger.STOP_GRACEFUL,
ReplicationState.STOPPING
);
stateMachine.configure(ReplicationState.RUNNING).permit(
ReplicationTrigger.GO_OFFLINE,
ReplicationState.OFFLINE
);
stateMachine.configure(ReplicationState.OFFLINE).permit(
ReplicationTrigger.GO_ONLINE,
ReplicationState.RUNNING
);
stateMachine.configure(ReplicationState.STOPPING).permit(
ReplicationTrigger.STOP_IMMEDIATE,
ReplicationState.STOPPED
);
// ignored transitions
stateMachine.configure(ReplicationState.RUNNING).ignore(ReplicationTrigger.START);
stateMachine.configure(ReplicationState.STOPPING).ignore(ReplicationTrigger.STOP_GRACEFUL);
stateMachine.configure(ReplicationState.STOPPED).ignore(ReplicationTrigger.STOP_GRACEFUL);
stateMachine.configure(ReplicationState.STOPPED).ignore(ReplicationTrigger.STOP_IMMEDIATE);
stateMachine.configure(ReplicationState.STOPPING).ignore(ReplicationTrigger.WAITING_FOR_CHANGES);
stateMachine.configure(ReplicationState.STOPPED).ignore(ReplicationTrigger.WAITING_FOR_CHANGES);
stateMachine.configure(ReplicationState.OFFLINE).ignore(ReplicationTrigger.WAITING_FOR_CHANGES);
stateMachine.configure(ReplicationState.INITIAL).ignore(ReplicationTrigger.GO_OFFLINE);
stateMachine.configure(ReplicationState.STOPPING).ignore(ReplicationTrigger.GO_OFFLINE);
stateMachine.configure(ReplicationState.STOPPED).ignore(ReplicationTrigger.GO_OFFLINE);
stateMachine.configure(ReplicationState.OFFLINE).ignore(ReplicationTrigger.GO_OFFLINE);
stateMachine.configure(ReplicationState.INITIAL).ignore(ReplicationTrigger.GO_ONLINE);
stateMachine.configure(ReplicationState.RUNNING).ignore(ReplicationTrigger.GO_ONLINE);
stateMachine.configure(ReplicationState.STOPPING).ignore(ReplicationTrigger.GO_ONLINE);
stateMachine.configure(ReplicationState.STOPPED).ignore(ReplicationTrigger.GO_ONLINE);
stateMachine.configure(ReplicationState.IDLE).ignore(ReplicationTrigger.GO_ONLINE);
stateMachine.configure(ReplicationState.OFFLINE).ignore(ReplicationTrigger.RESUME);
stateMachine.configure(ReplicationState.INITIAL).ignore(ReplicationTrigger.RESUME);
stateMachine.configure(ReplicationState.RUNNING).ignore(ReplicationTrigger.RESUME);
stateMachine.configure(ReplicationState.STOPPING).ignore(ReplicationTrigger.RESUME);
stateMachine.configure(ReplicationState.STOPPED).ignore(ReplicationTrigger.RESUME);
// actions
stateMachine.configure(ReplicationState.RUNNING).onEntry(new Action1<Transition<ReplicationState, ReplicationTrigger>>() {
@Override
public void doIt(Transition<ReplicationState, ReplicationTrigger> transition) {
Log.v(Log.TAG_SYNC, "[onEntry()] " + transition.getSource() + " => " + transition.getDestination());
start();
notifyChangeListenersStateTransition(transition);
}
});
stateMachine.configure(ReplicationState.RUNNING).onExit(new Action1<Transition<ReplicationState, ReplicationTrigger>>() {
@Override
public void doIt(Transition<ReplicationState, ReplicationTrigger> transition) {
Log.v(Log.TAG_SYNC, "[onExit()] " + transition.getSource() + " => " + transition.getDestination());
}
});
stateMachine.configure(ReplicationState.IDLE).onEntry(new Action1<Transition<ReplicationState, ReplicationTrigger>>() {
@Override
public void doIt(Transition<ReplicationState, ReplicationTrigger> transition) {
Log.v(Log.TAG_SYNC, "[onEntry()] " + transition.getSource() + " => " + transition.getDestination());
retryReplicationIfError();
if (transition.getSource() == transition.getDestination()) {
// ignore IDLE to IDLE
return;
}
notifyChangeListenersStateTransition(transition);
// #352
// But, for Core Java, some of codes wait IDLE state. So this is reason to wait till
// state becomes IDLE.
if (Utils.isPermanentError(ReplicationInternal.this.error) && isContinuous()) {
Log.d(Log.TAG_SYNC, "IDLE: triggerStopGraceful() " + ReplicationInternal.this.error.toString());
triggerStopGraceful();
}
}
});
stateMachine.configure(ReplicationState.IDLE).onExit(new Action1<Transition<ReplicationState, ReplicationTrigger>>() {
@Override
public void doIt(Transition<ReplicationState, ReplicationTrigger> transition) {
Log.v(Log.TAG_SYNC, "[onExit()] " + transition.getSource() + " => " + transition.getDestination());
if (transition.getSource() == transition.getDestination()) {
// ignore IDLE to IDLE
return;
}
notifyChangeListenersStateTransition(transition);
}
});
stateMachine.configure(ReplicationState.OFFLINE).onEntry(new Action1<Transition<ReplicationState, ReplicationTrigger>>() {
@Override
public void doIt(Transition<ReplicationState, ReplicationTrigger> transition) {
Log.v(Log.TAG_SYNC, "[onEntry()] " + transition.getSource() + " => " + transition.getDestination());
goOffline();
notifyChangeListenersStateTransition(transition);
}
});
stateMachine.configure(ReplicationState.OFFLINE).onExit(new Action1<Transition<ReplicationState, ReplicationTrigger>>() {
@Override
public void doIt(Transition<ReplicationState, ReplicationTrigger> transition) {
Log.v(Log.TAG_SYNC, "[onExit()] " + transition.getSource() + " => " + transition.getDestination());
goOnline();
notifyChangeListenersStateTransition(transition);
}
});
stateMachine.configure(ReplicationState.STOPPING).onEntry(new Action1<Transition<ReplicationState, ReplicationTrigger>>() {
@Override
public void doIt(Transition<ReplicationState, ReplicationTrigger> transition) {
Log.v(Log.TAG_SYNC, "[onEntry()] " + transition.getSource() + " => " + transition.getDestination());
// NOTE: Based on StateMachine configuration, this should not happen.
// However, from Unit Test result, this could be happen.
// We should revisit StateMachine configuration and also its Thread-safe-ability
if (transition.getSource() == transition.getDestination()) {
// ignore STOPPING to STOPPING
return;
}
stop();
notifyChangeListenersStateTransition(transition);
}
});
stateMachine.configure(ReplicationState.STOPPED).onEntry(new Action1<Transition<ReplicationState, ReplicationTrigger>>() {
@Override
public void doIt(Transition<ReplicationState, ReplicationTrigger> transition) {
Log.v(Log.TAG_SYNC, "[onEntry()] " + transition.getSource() + " => " + transition.getDestination());
// NOTE: Based on StateMachine configuration, this should not happen.
// However, from Unit Test result, this could be happen.
// We should revisit StateMachine configuration and also its Thread-safe-ability
if (transition.getSource() == transition.getDestination()) {
// ignore STOPPED to STOPPED
return;
}
saveLastSequence(); // move from databaseClosing() method as databaseClosing() is not called
// stop network reachablity check
stopNetworkReachabilityManager();
// close any active resources associated with this replicator
close();
clearDbRef();
notifyChangeListenersStateTransition(transition);
}
});
}
private void logTransition(Transition<ReplicationState, ReplicationTrigger> transition) {
Log.d(Log.TAG_SYNC, "State transition: %s -> %s (via %s). this: %s", transition.getSource(), transition.getDestination(), transition.getTrigger(), this);
}
private void notifyChangeListenersStateTransition(Transition<ReplicationState, ReplicationTrigger> transition) {
logTransition(transition);
Replication.ChangeEvent changeEvent = new Replication.ChangeEvent(this);
ReplicationStateTransition replicationStateTransition = new ReplicationStateTransition(transition);
changeEvent.setTransition(replicationStateTransition);
notifyChangeListeners(changeEvent);
}
/**
* A delegate that can be used to listen for Replication changes.
*/
@InterfaceAudience.Public
public interface ChangeListener {
void changed(Replication.ChangeEvent event);
}
public Authenticator getAuthenticator() {
return authenticator;
}
public void setAuthenticator(Authenticator authenticator) {
this.authenticator = authenticator;
}
@InterfaceAudience.Private
protected boolean serverIsSyncGatewayVersion(String minVersion) {
return serverIsSyncGatewayVersion(serverType, minVersion);
}
@InterfaceAudience.Private
protected static boolean serverIsSyncGatewayVersion(String serverName, String minVersion) {
String prefix = "Couchbase Sync Gateway/";
if (serverName == null) {
return false;
} else {
if (serverName.startsWith(prefix)) {
String versionString = serverName.substring(prefix.length());
// NOTE: If version number is higher than 10.xx, this comprison does not work eg. "10.0" < "2.0"
return versionString.compareTo(minVersion) >= 0;
}
}
return false;
}
/**
* @exclude
*/
@InterfaceAudience.Private
public void addToInbox(RevisionInternal rev) {
Log.v(Log.TAG_SYNC, "%s: addToInbox() called, rev: %s. Thread: %s", this, rev, Thread.currentThread());
batcher.queueObject(rev);
}
/**
* Called after a continuous replication has gone idle, but it failed to transfer some revisions
* and so wants to try again in a minute. Can be overridden by subclasses.
* <p/>
* in CBL_Replicator.m
* - (void) retry
*/
protected void retry() {
Log.v(Log.TAG_SYNC, "[retry()]");
retryCount++;
this.error = null;
checkSession();
}
/**
* in CBL_Replicator.m
* - (void) retryIfReady
*/
protected void retryIfReady() {
Log.v(Log.TAG_SYNC, "[retryIfReady()] stateMachine => " + stateMachine.getState().toString());
// check if state is still IDLE (ONLINE), then retry now.
if (stateMachine.getState().equals(ReplicationState.IDLE)) {
Log.v(Log.TAG_SYNC, "%s RETRYING, to transfer missed revisions...", this);
cancelRetryFuture();
retry();
}
}
/**
* helper function to schedule retry future. no in iOS code.
*/
private void scheduleRetryFuture() {
long delay = RETRY_DELAY_SECONDS * (long) Math.pow((double) 2, (double) Math.min(retryCount, MAX_RETRIES));
Log.v(Log.TAG_SYNC, "%s: Failed to xfer; will retry in %d sec",
this, delay);
this.retryFuture = workExecutor.schedule(new Runnable() {
public void run() {
retryIfReady();
}
}, delay, TimeUnit.SECONDS);
}
/**
* helper function to cancel retry future. not in iOS code.
*/
private void cancelRetryFuture() {
if (retryFuture != null && !retryFuture.isDone()) {
retryFuture.cancel(true);
}
retryFuture = null;
}
/**
* Retry replication if previous attempt ends with error
*/
protected void retryReplicationIfError() {
// Make sure if state is IDLE, this method should be called when state becomes IDLE
if (!stateMachine.getState().equals(ReplicationState.IDLE)) {
return;
}
// IDLE_OK
if (this.error == null) {
retryCount = 0;
}
// IDLE_ERROR
else {
// not retry infinite times
if (retryCount < MAX_RETRIES) {
// mode should be continuous
if (isContinuous()) {
// 12/16/2014 - only retry if error is transient error 50x http error
// It may need to retry for any kind of errors
if (Utils.isTransientError(this.error)) {
cancelRetryFuture();
scheduleRetryFuture();
}
}
}
}
}
@InterfaceAudience.Private
protected void setServerType(String serverType) {
this.serverType = serverType;
}
public Replication.Lifecycle getLifecycle() {
return lifecycle;
}
public void setLifecycle(Replication.Lifecycle lifecycle) {
this.lifecycle = lifecycle;
}
private static int SAVE_LAST_SEQUENCE_DELAY = 5; // 5 sec;
/**
* in CBL_Replicator.m
* - (void) setLastSequence:(NSString*)lastSequence;
*
* @exclude
*/
@InterfaceAudience.Private
public void setLastSequence(String lastSequenceIn) {
if (lastSequenceIn != null && !lastSequenceIn.equals(lastSequence)) {
Log.v(Log.TAG_SYNC, "%s: Setting lastSequence to %s from(%s)", this, lastSequenceIn, lastSequence);
lastSequence = lastSequenceIn;
if (!lastSequenceChanged) {
lastSequenceChanged = true;
workExecutor.schedule(new Runnable() {
public void run() {
saveLastSequence();
}
}, SAVE_LAST_SEQUENCE_DELAY, TimeUnit.SECONDS);
}
}
}
protected RevisionInternal transformRevision(RevisionInternal rev) {
if (revisionBodyTransformationBlock != null) {
try {
final int generation = rev.getGeneration();
RevisionInternal xformed = revisionBodyTransformationBlock.invoke(rev);
if (xformed == null)
return null;
if (xformed != rev) {
final Map<String, Object> xformedProps = xformed.getProperties();
assert (xformed.getDocID().equals(rev.getDocID()));
assert (xformed.getRevID().equals(rev.getRevID()));
assert (xformedProps.get("_revisions").equals(rev.getProperties().get("_revisions")));
if (xformedProps.get("_attachments") != null) {
// Insert 'revpos' properties into any attachments added by the callback:
RevisionInternal mx = new RevisionInternal(xformedProps);
xformed = mx;
mx.mutateAttachments(new CollectionUtils.Functor<Map<String, Object>, Map<String, Object>>() {
public Map<String, Object> invoke(Map<String, Object> info) {
if (info.get("revpos") != null) {
return info;
}
if (info.get("data") == null) {
throw new IllegalStateException("Transformer added attachment without adding data");
}
Map<String, Object> nuInfo = new HashMap<String, Object>(info);
nuInfo.put("revpos", generation);
return nuInfo;
}
});
}
rev = xformed;
}
} catch (Exception e) {
Log.w(Log.TAG_SYNC, "%s: Exception transforming a revision of doc '%s", e, this, rev.getDocID());
}
}
return rev;
}
@InterfaceAudience.Private
protected static Status statusFromBulkDocsResponseItem(Map<String, Object> item) {
try {
if (!item.containsKey("error")) {
return new Status(Status.OK);
}
String errorStr = (String) item.get("error");
if (errorStr == null || errorStr.isEmpty()) {
return new Status(Status.OK);
}
// 'status' property is nonstandard; Couchbase Lite returns it, others don't.
Object objStatus = item.get("status");
if (objStatus instanceof Integer) {
int status = ((Integer) objStatus).intValue();
if (status >= 400) {
return new Status(status);
}
}
// If no 'status' present, interpret magic hardcoded CouchDB error strings:
if ("unauthorized".equalsIgnoreCase(errorStr)) {
return new Status(Status.UNAUTHORIZED);
} else if ("forbidden".equalsIgnoreCase(errorStr)) {
return new Status(Status.FORBIDDEN);
} else if ("conflict".equalsIgnoreCase(errorStr)) {
return new Status(Status.CONFLICT);
} else if ("missing".equalsIgnoreCase(errorStr)) {
return new Status(Status.NOT_FOUND);
} else if ("not_found".equalsIgnoreCase(errorStr)) {
return new Status(Status.NOT_FOUND);
} else {
return new Status(Status.UPSTREAM_ERROR);
}
} catch (Exception e) {
Log.e(Database.TAG, "Exception getting status from " + item, e);
}
return new Status(Status.OK);
}
private void clearDbRef() {
// NOTE: clearDbRef() is called from only from StateMachine with ReplicationState.STOPPED
// which is executed with WorkExecutor Thread
// TODO: there was some logic here that was NOT saving the checkpoint to
// TODO: the DB if: (savingCheckpoint && lastSequence != null && db != null)
try {
Log.v(Log.TAG_SYNC, "%s: clearDbRef() called", this);
if (!db.isOpen()) {
Log.w(Log.TAG_SYNC, "Not attempting to setLastSequence, db is closed");
} else {
db.setLastSequence(lastSequence, remoteCheckpointDocID());
}
Log.v(Log.TAG_SYNC, "%s: clearDbRef() setting db to null", this);
db = null;
} catch (Exception e) {
Log.e(Log.TAG_SYNC, "Exception in clearDbRef(): %s", e);
}
}
/**
* For java docs, see Replication.setCookie()
*/
public void setCookie(String name, String value, String path, long maxAge, boolean secure, boolean httpOnly) {
Date now = new Date();
Date expirationDate = new Date(now.getTime() + maxAge);
setCookie(name, value, path, expirationDate, secure, httpOnly);
}
/**
* For java docs, see Replication.setCookie()
*/
public void setCookie(String name, String value, String path, Date expirationDate, boolean secure, boolean httpOnly) {
if (remote == null) {
throw new IllegalStateException("Cannot setCookie since remote == null");
}
BasicClientCookie2 cookie = new BasicClientCookie2(name, value);
cookie.setDomain(remote.getHost());
if (path != null && path.length() > 0) {
cookie.setPath(path);
} else {
cookie.setPath(remote.getPath());
}
cookie.setExpiryDate(expirationDate);
cookie.setSecure(secure);
List<Cookie> cookies = Collections.singletonList((Cookie) cookie);
this.clientFactory.addCookies(cookies);
}
/**
* For java docs, see Replication.deleteCookie()
*/
public void deleteCookie(String name) {
this.clientFactory.deleteCookie(name);
}
protected HttpClientFactory getClientFactory() {
return clientFactory;
}
/**
* For javadocs, see Replication object
*/
public List<String> getChannels() {
if (filterParams == null || filterParams.isEmpty()) {
return new ArrayList<String>();
}
String params = (String) filterParams.get(CHANNELS_QUERY_PARAM);
if (!isPull() || getFilter() == null || !BY_CHANNEL_FILTER_NAME.equals(getFilter()) || params == null || params.isEmpty()) {
return new ArrayList<String>();
}
String[] paramsArray = params.split(",");
return new ArrayList<String>(Arrays.asList(paramsArray));
}
/**
* For javadocs, see Replication object
*/
public void setChannels(List<String> channels) {
if (channels != null && !channels.isEmpty()) {
if (!isPull()) {
Log.w(Log.TAG_SYNC, "filterChannels can only be set in pull replications");
return;
}
setFilter(BY_CHANNEL_FILTER_NAME);
Map<String, Object> filterParams = new HashMap<String, Object>();
filterParams.put(CHANNELS_QUERY_PARAM, TextUtils.join(",", channels));
setFilterParams(filterParams);
} else if (BY_CHANNEL_FILTER_NAME.equals(getFilter())) {
setFilter(null);
setFilterParams(null);
}
}
public String getSessionID() {
return sessionID;
}
public abstract void waitForPendingFutures();
@Override
public void changed(EventType type, Object o, BlockingQueue queue) {
if (type == EventType.PUT || type == EventType.ADD) {
if (!queue.isEmpty()) {
// trigger to RUNNING if state is IDLE
if (isContinuous())
fireTrigger(ReplicationTrigger.RESUME);
// run waitForPendingFutures.
new Thread(new Runnable() {
@Override
public void run() {
waitForPendingFutures();
}
}).start();
}
}
}
/**
* Encodes the given document id for use in an URI.
* <p/>
* Avoids encoding the slash in _design documents since it may cause a 301 redirect.
*/
protected static String encodeDocumentId(String docId) {
if (docId.startsWith("_design/")) {
// http://docs.couchdb.org/en/1.6.1/http-api.html#cap-/{db}/_design/{ddoc}
String designDocId = docId.substring("_design/".length());
return "_design/".concat(URIUtils.encode(designDocId));
} else {
return URIUtils.encode(docId);
}
}
protected boolean isRunning() {
return stateMachine.isInState(ReplicationState.RUNNING) ||
stateMachine.isInState(ReplicationState.IDLE) ||
stateMachine.isInState(ReplicationState.OFFLINE);
}
}
|
package com.uwflow.flow_android.fragment;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.astuetz.PagerSlidingTabStrip;
import com.facebook.*;
import com.facebook.model.GraphObject;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Target;
import com.uwflow.flow_android.MainFlowActivity;
import com.uwflow.flow_android.R;
import com.uwflow.flow_android.adapters.ProfilePagerAdapter;
import com.uwflow.flow_android.constant.Constants;
import com.uwflow.flow_android.db_object.*;
import com.uwflow.flow_android.loaders.*;
import com.uwflow.flow_android.network.FlowApiRequestCallbackAdapter;
import com.uwflow.flow_android.network.FlowApiRequests;
import org.json.JSONException;
import org.json.JSONObject;
public class ProfileFragment extends Fragment {
private String mProfileID;
private ProfilePagerAdapter mProfilePagerAdapter;
protected ImageView userImage;
protected TextView userName;
protected TextView userProgram;
protected ViewPager viewPager;
protected PagerSlidingTabStrip tabs;
private ImageView mCoverPhoto;
protected User user;
protected UserFriends userFriends;
protected Exams userExams;
protected UserCourseDetail userCourses;
protected ScheduleCourses userSchedule;
protected ProfileReceiver profileReceiver;
protected Bitmap userCover;
protected Target coverImageCallback;
protected Target imageCallback;
// only fetch data once
protected boolean fetchCompleted = false;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.profile_layout, container, false);
mProfileID = getArguments() != null ? getArguments().getString(Constants.PROFILE_ID_KEY) : null;
userImage = (ImageView) rootView.findViewById(R.id.user_image);
userName = (TextView) rootView.findViewById(R.id.user_name);
userProgram = (TextView) rootView.findViewById(R.id.user_program);
mCoverPhoto = (ImageView) rootView.findViewById(R.id.cover_photo);
viewPager = (ViewPager) rootView.findViewById(R.id.pager);
// Note: this is sorta cheating. We might need to decrease this number so that we don't run into memory issues.
viewPager.setOffscreenPageLimit(3);
if (mProfileID == null)
mProfilePagerAdapter = new ProfilePagerAdapter(getChildFragmentManager(), getArguments(), true);
else
mProfilePagerAdapter = new ProfilePagerAdapter(getChildFragmentManager(), getArguments(), false);
viewPager.setAdapter(mProfilePagerAdapter);
tabs = (PagerSlidingTabStrip) rootView.findViewById(R.id.pager_tabs);
tabs.setViewPager(viewPager);
// Set default tab to Schedule
if (mProfileID == null)
viewPager.setCurrentItem(Constants.PROFILE_SCHEDULE_PAGE_INDEX);
profileReceiver = new ProfileReceiver();
populateData();
LocalBroadcastManager.getInstance(this.getActivity().getApplicationContext()).registerReceiver(profileReceiver,
new IntentFilter(Constants.BroadcastActionId.UPDATE_PROFILE_USER));
if (!fetchCompleted) fetchProfileInfo();
return rootView;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
@Override
public void onDestroyView() {
// Unregister since the activity is not visible
LocalBroadcastManager.getInstance(this.getActivity().getApplicationContext()).unregisterReceiver(profileReceiver);
super.onDestroyView();
}
protected void fetchProfileInfo() {
fetchCompleted = true;
if (mProfileID == null) {
// Load logged-in users profile if an ID is unspecified.
initLoaders();
} else {
// fetch user profile data from network
initLoadFromNetwork(mProfileID);
}
}
private void fetchCoverPhoto(long fbid) {
if (userCover != null) {
mCoverPhoto.setImageBitmap(userCover);
} else {
Bundle params = new Bundle();
params.putString("fields", "cover");
new Request(
Session.getActiveSession(),
"/" + fbid,
params,
HttpMethod.GET,
new Request.Callback() {
public void onCompleted(Response response) {
GraphObject graphObject = response.getGraphObject();
FacebookRequestError error = response.getError();
if (graphObject != null) {
if (graphObject.getProperty("cover") != null) {
try {
JSONObject json = graphObject.getInnerJSONObject();
JSONObject coverObject =
new JSONObject((String) json.getString("cover"));
String url = coverObject.getString("source");
coverImageCallback = new Target() {
@Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom loadedFrom) {
Log.d("BITMAP", "LOADED COVER FROM: " + loadedFrom.toString());
userCover = bitmap;
mCoverPhoto.setImageBitmap(userCover);
}
@Override
public void onBitmapFailed(Drawable drawable) {
Log.d("BITMAP", "NOTLOADED");
}
@Override
public void onPrepareLoad(Drawable drawable) {
}
};
Picasso.with(getActivity().getApplicationContext()).load(url).into(coverImageCallback);
} catch (JSONException e) {
}
} else if (error != null) {
}
}
}
}
).executeAsync();
}
}
protected void initLoaders() {
final UserLoaderCallback userLoader = new UserLoaderCallback(getActivity().getApplicationContext(), this, ((MainFlowActivity) getActivity()).getHelper());
final UserFriendsLoaderCallback userFriendsLoader = new UserFriendsLoaderCallback(getActivity().getApplicationContext(), this, ((MainFlowActivity) getActivity()).getHelper());
final UserScheduleLoaderCallback userScheduleLoaderCallback = new UserScheduleLoaderCallback(getActivity().getApplicationContext(), this, ((MainFlowActivity) getActivity()).getHelper());
final UserExamsLoaderCallback userExamsLoaderCallback = new UserExamsLoaderCallback(getActivity().getApplicationContext(), this, ((MainFlowActivity) getActivity()).getHelper());
final UserCoursesLoaderCallback userCoursesLoaderCallback = new UserCoursesLoaderCallback(getActivity().getApplicationContext(), this, ((MainFlowActivity) getActivity()).getHelper());
getLoaderManager().initLoader(Constants.LoaderManagerId.PROFILE_LOADER_ID, null, userLoader);
getLoaderManager().initLoader(Constants.LoaderManagerId.PROFILE_FRIENDS_LOADER_ID, null, userFriendsLoader);
getLoaderManager().initLoader(Constants.LoaderManagerId.PROFILE_SCHEDULE_LOADER_ID, null, userScheduleLoaderCallback);
getLoaderManager().initLoader(Constants.LoaderManagerId.PROFILE_EXAMS_LOADER_ID, null, userExamsLoaderCallback);
getLoaderManager().initLoader(Constants.LoaderManagerId.PROFILE_COURSES_LOADER_ID, null, userCoursesLoaderCallback);
}
protected void initLoadFromNetwork(final String uid) {
if (uid == null)
return;
// Get user data
FlowApiRequests.getUser(
uid,
new FlowApiRequestCallbackAdapter() {
@Override
public void getUserCallback(User user) {
setUser(user);
}
});
FlowApiRequests.getUserSchedule(
uid,
new FlowApiRequestCallbackAdapter() {
@Override
public void getUserScheduleCallback(ScheduleCourses scheduleCourses) {
setUserSchedule(scheduleCourses);
}
});
FlowApiRequests.getUserExams(
uid,
new FlowApiRequestCallbackAdapter() {
@Override
public void getUserExamsCallback(Exams exams) {
setUserExams(exams);
}
});
FlowApiRequests.getUserCourses(
uid,
new FlowApiRequestCallbackAdapter() {
@Override
public void getUserCoursesCallback(UserCourseDetail userCourseDetail) {
setUserCourses(userCourseDetail);
}
});
// Get user exam data
FlowApiRequests.getUserExams(
uid,
new FlowApiRequestCallbackAdapter() {
@Override
public void getUserExamsCallback(Exams response) {
setUserExams(response);
}
});
}
protected void populateData() {
if (user != null) {
fetchCoverPhoto(user.getFbid());
imageCallback = new Target() {
@Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom loadedFrom) {
userImage.setImageBitmap(bitmap);
}
@Override
public void onBitmapFailed(Drawable drawable) {
}
@Override
public void onPrepareLoad(Drawable drawable) {
}
};
// Set profile picture
Picasso.with(getActivity()).load(user.getProfilePicUrls().getDefaultPic()).into(imageCallback);
userName.setText(user.getName());
userProgram.setText(user.getProgramName());
}
}
protected class ProfileReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
populateData();
}
}
// Getters and Setters for child fragment to pull data
public User getUser() {
return user;
}
public void setUser(User user) {
if (this.user == null) {
this.user = user;
fireUserBroadcast();
}
}
public UserFriends getUserFriends() {
return userFriends;
}
public void setUserFriends(UserFriends userFriends) {
if (this.userFriends == null) {
this.userFriends = userFriends;
fireUserFriendBroadcast();
}
}
public Exams getUserExams() {
return userExams;
}
public void setUserExams(Exams userExams) {
if (this.userExams == null) {
this.userExams = userExams;
fireUserExamBroadcast();
}
}
public UserCourseDetail getUserCourses() {
return userCourses;
}
public void setUserCourses(UserCourseDetail userCourses) {
if (this.userCourses == null) {
this.userCourses = userCourses;
fireUserCoursesBroadcast();
}
}
public ScheduleCourses getUserSchedule() {
return userSchedule;
}
public void setUserSchedule(ScheduleCourses userSchedule) {
if (this.userSchedule == null) {
this.userSchedule = userSchedule;
fireUserScheduleBroadcast();
}
}
protected void fireUserBroadcast() {
Intent intent = new Intent(Constants.BroadcastActionId.UPDATE_PROFILE_USER);
LocalBroadcastManager.getInstance(this.getActivity().getApplicationContext()).sendBroadcast(intent);
}
protected void fireUserFriendBroadcast() {
Intent intent = new Intent(Constants.BroadcastActionId.UPDATE_PROFILE_USER_FRIENDS);
LocalBroadcastManager.getInstance(this.getActivity().getApplicationContext()).sendBroadcast(intent);
}
protected void fireUserScheduleBroadcast() {
Intent intent = new Intent(Constants.BroadcastActionId.UPDATE_PROFILE_USER_SCHEDULE);
LocalBroadcastManager.getInstance(this.getActivity().getApplicationContext()).sendBroadcast(intent);
}
protected void fireUserExamBroadcast() {
Intent intent = new Intent(Constants.BroadcastActionId.UPDATE_PROFILE_USER_EXAMS);
LocalBroadcastManager.getInstance(this.getActivity().getApplicationContext()).sendBroadcast(intent);
}
protected void fireUserCoursesBroadcast() {
Intent intent = new Intent(Constants.BroadcastActionId.UPDATE_PROFILE_USER_COURSES);
LocalBroadcastManager.getInstance(this.getActivity().getApplicationContext()).sendBroadcast(intent);
}
}
|
package com.gamingmesh.jobs.hooks.McMMO;
import java.util.HashMap;
import org.bukkit.GameMode;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.inventory.ItemStack;
import com.gamingmesh.jobs.Jobs;
import com.gamingmesh.jobs.actions.ItemActionInfo;
import com.gamingmesh.jobs.container.ActionType;
import com.gamingmesh.jobs.container.JobsPlayer;
import com.gamingmesh.jobs.hooks.HookManager;
import com.gamingmesh.jobs.listeners.JobsPaymentListener;
import com.gmail.nossr50.events.skills.abilities.McMMOPlayerAbilityActivateEvent;
import com.gmail.nossr50.events.skills.abilities.McMMOPlayerAbilityDeactivateEvent;
import com.gmail.nossr50.events.skills.fishing.McMMOPlayerFishingTreasureEvent;
import com.gmail.nossr50.events.skills.repair.McMMOPlayerRepairCheckEvent;
public class McMMO2_X_listener implements Listener {
private Jobs plugin;
public McMMO2_X_listener(Jobs plugin) {
this.plugin = plugin;
}
@EventHandler
public void onFishingTreasure(McMMOPlayerFishingTreasureEvent event) {
// make sure plugin is enabled
if (!plugin.isEnabled())
return;
Player player = event.getPlayer();
//disabling plugin in world
if (!Jobs.getGCManager().canPerformActionInWorld(player.getWorld()))
return;
// check if in creative
if (!JobsPaymentListener.payIfCreative(player))
return;
if (!Jobs.getPermissionHandler().hasWorldPermission(player, player.getLocation().getWorld().getName()))
return;
// check if player is riding
if (Jobs.getGCManager().disablePaymentIfRiding && player.isInsideVehicle())
return;
if (!JobsPaymentListener.payForItemDurabilityLoss(player))
return;
if (event.getTreasure() == null)
return;
JobsPlayer jPlayer = Jobs.getPlayerManager().getJobsPlayer(player);
if (jPlayer == null)
return;
Jobs.action(jPlayer, new ItemActionInfo(event.getTreasure(), ActionType.FISH));
}
@EventHandler
public void OnItemrepair(McMMOPlayerRepairCheckEvent event) {
// make sure plugin is enabled
if (!plugin.isEnabled())
return;
Player player = event.getPlayer();
// disabling plugin in world
if (player == null || !Jobs.getGCManager().canPerformActionInWorld(player.getWorld()))
return;
ItemStack resultStack = event.getRepairedObject();
if (resultStack == null)
return;
if (!Jobs.getPermissionHandler().hasWorldPermission(player, player.getLocation().getWorld().getName()))
return;
// check if in creative
if (player.getGameMode().equals(GameMode.CREATIVE) && !player.hasPermission("jobs.paycreative") && !Jobs.getGCManager().payInCreative())
return;
JobsPlayer jPlayer = Jobs.getPlayerManager().getJobsPlayer(player);
if (jPlayer == null)
return;
Jobs.action(jPlayer, new ItemActionInfo(resultStack, ActionType.REPAIR));
}
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void OnAbilityOn(McMMOPlayerAbilityActivateEvent event) {
HashMap<String, Long> InfoMap = HookManager.getMcMMOManager().getMap().get(event.getPlayer().getUniqueId());
if (InfoMap == null) {
InfoMap = new HashMap<>();
HookManager.getMcMMOManager().getMap().put(event.getPlayer().getUniqueId(), InfoMap);
}
InfoMap.put(event.getAbility().toString().toLowerCase(), System.currentTimeMillis() + (60 * 1000));
}
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void OnAbilityOff(McMMOPlayerAbilityDeactivateEvent event) {
HashMap<String, Long> InfoMap = HookManager.getMcMMOManager().getMap().get(event.getPlayer().getUniqueId());
if (InfoMap != null) {
InfoMap.remove(event.getAbility().toString().toLowerCase());
if (InfoMap.isEmpty())
HookManager.getMcMMOManager().getMap().remove(event.getPlayer().getUniqueId());
}
}
}
|
package com.github.anastasia.zaitsewa.graphview;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.Pair;
import android.util.TypedValue;
import android.view.View;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Observable;
import java.util.Observer;
/**
* Class for drawing custom Graph
* (contains axis, axis labels, non-interactive points(Drawables) and levels)
*/
public class GraphView extends View implements Observer {
private static final String ZERO_LABEL = "0";
private static final int MARGIN_DP = 5;
private static final int DEFAULT_LABEL_PLACE_DP = 15;
private static final int DEFAULT_TEXT_SIZE_SP = 8;
private static final int DEFAULT_SPACING_BETWEEN_LABELS_DP = 20;
private static final int DEFAULT_AXIS_LABEL_MARGIN_DP = 2;
private static final int DEFAULT_LINE_COLOR = Color.BLACK;
private static final int DEFAULT_TEXT_COLOR = Color.DKGRAY;
private static final int DEFAULT_FILL_COLOR = 0x44000000;
private static final int DEFAULT_LEVEL_COLOR = 0x44888888;
private final List<Pair<Float, String>> labelsX = new ArrayList<Pair<Float, String>>();
private final List<Pair<Float, String>> labelsY = new ArrayList<Pair<Float, String>>();
private int lineColor;
private int textColor;
private int fillColor;
private int levelColor;
private float textSize;
private float spacingPXX;
private float spacingPXY;
private float labelPlacePX;
private boolean enableXAxis;
private boolean enableYAxis;
private boolean enableLabels;
private boolean enableFill;
private Paint linePaint;
private Paint textPaint;
private Paint fillPaint;
private Paint levelPaint;
private int width;
private int height;
private List<PointsProvider> providers = new ArrayList<PointsProvider>();
private List<Pair<Float, Float>> pointsPX = new ArrayList<Pair<Float, Float>>();
private List<Path> paths = new ArrayList<Path>();
private List<Path> fillPaths = new ArrayList<Path>();
private float pxProY;
private float pxProX;
private double maxY;
private double maxX;
private double minX;
private float textHeight = 0f;
private Drawable pointDrawable;
private float defaultAxisLabelMarginPX;
private float marginPX;
public GraphView(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray a = context.getTheme().obtainStyledAttributes(
attrs,
R.styleable.GraphView,
0, 0);
try {
enableXAxis = a.getBoolean(R.styleable.GraphView_graphView_enableXAxis, true);
enableYAxis = a.getBoolean(R.styleable.GraphView_graphView_enableYAxis, true);
enableLabels = a.getBoolean(R.styleable.GraphView_graphView_enableLabels, true);
enableFill = a.getBoolean(R.styleable.GraphView_graphView_enableFill, true);
lineColor = a.getColor(R.styleable.GraphView_graphView_lineColor, DEFAULT_LINE_COLOR);
textColor = a.getColor(R.styleable.GraphView_graphView_textColor, DEFAULT_TEXT_COLOR);
fillColor = a.getColor(R.styleable.GraphView_graphView_fillColor, DEFAULT_FILL_COLOR);
levelColor = a.getColor(R.styleable.GraphView_graphView_levelColor, DEFAULT_LEVEL_COLOR);
pointDrawable = a.getDrawable(R.styleable.GraphView_graphView_pointDrawable);
textSize = a.getDimension(R.styleable.GraphView_graphView_textSize,
TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
DEFAULT_TEXT_SIZE_SP,
getResources().getDisplayMetrics()
)
);
spacingPXX = a.getDimensionPixelOffset(
R.styleable.GraphView_graphView_spacingX,
(int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
DEFAULT_SPACING_BETWEEN_LABELS_DP,
getResources().getDisplayMetrics()
)
);
spacingPXY = a.getDimensionPixelOffset(
R.styleable.GraphView_graphView_spacingY,
(int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
DEFAULT_SPACING_BETWEEN_LABELS_DP,
getResources().getDisplayMetrics()
)
);
labelPlacePX = a.getDimensionPixelOffset(
R.styleable.GraphView_graphView_labelPlace,
(int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
DEFAULT_LABEL_PLACE_DP,
getResources().getDisplayMetrics()
)
);
} finally {
a.recycle();
}
init();
}
public GraphView(Context context) {
super(context);
enableXAxis = true;
enableYAxis = true;
enableLabels = true;
enableFill = true;
lineColor = DEFAULT_LINE_COLOR;
textColor = DEFAULT_TEXT_COLOR;
fillColor = DEFAULT_FILL_COLOR;
levelColor = DEFAULT_LEVEL_COLOR;
pointDrawable = getResources().getDrawable(R.drawable.point);
textSize = TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
DEFAULT_TEXT_SIZE_SP,
getResources().getDisplayMetrics()
);
spacingPXX = TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
DEFAULT_SPACING_BETWEEN_LABELS_DP,
getResources().getDisplayMetrics()
);
spacingPXY = TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
DEFAULT_SPACING_BETWEEN_LABELS_DP,
getResources().getDisplayMetrics()
);
labelPlacePX = TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
DEFAULT_LABEL_PLACE_DP,
getResources().getDisplayMetrics()
);
init();
}
private void init() {
linePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
linePaint.setStyle(Paint.Style.STROKE);
linePaint.setColor(lineColor);
fillPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
fillPaint.setStyle(Paint.Style.FILL);
fillPaint.setColor(fillColor);
levelPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
levelPaint.setStyle(Paint.Style.STROKE);
levelPaint.setColor(levelColor);
textPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
textPaint.setColor(textColor);
textPaint.setTextSize(textSize);
defaultAxisLabelMarginPX = TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
DEFAULT_AXIS_LABEL_MARGIN_DP,
getResources().getDisplayMetrics()
);
marginPX = TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
MARGIN_DP,
getResources().getDisplayMetrics()
);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (enableXAxis) {
//Drawing X-Axis
canvas.drawLine(
labelPlacePX, height - labelPlacePX - 1,
width - 1, height - labelPlacePX - 1,
linePaint
);
if (enableLabels) {
//Drawing Labels
textPaint.setTextAlign(Paint.Align.LEFT);
for (Pair<Float, String> labelX : labelsX) {
canvas.drawText(
labelX.second,
labelX.first,
height - labelPlacePX + textHeight + defaultAxisLabelMarginPX,
textPaint
);
}
}
}
if (enableYAxis) {
//Drawing Y-Axis
canvas.drawLine(
labelPlacePX, height - labelPlacePX - 1,
labelPlacePX, 0,
linePaint
);
if (enableLabels) {
textPaint.setTextAlign(Paint.Align.RIGHT);
for (Pair<Float, String> labelY : labelsY) {
//Drawing Y-Labels
canvas.drawText(
labelY.second,
labelPlacePX - defaultAxisLabelMarginPX,
labelY.first,
textPaint
);
//Draw Levels
float levelY = labelY.first - textHeight / 2;
canvas.drawLine(
labelPlacePX,
levelY,
width - 1,
levelY,
levelPaint
);
}
}
}
if (paths == null) {
return;
}
if (enableFill) {
//Drawing Fillings for Plot
for (Path fillPath : fillPaths) {
canvas.drawPath(fillPath, fillPaint);
}
}
//Drawing Plots
for (Path path : paths) {
canvas.drawPath(path, linePaint);
}
//Drawing Points
if (pointsPX == null) {
return;
}
//TODO:Add ability to set or reset points for each plot
if (pointDrawable != null) {
for (Pair<Float, Float> point : pointsPX) {
float x = point.first;
float y = point.second;
pointDrawable.setBounds(
(int) (x - pointDrawable.getIntrinsicWidth() / 2),
(int) (y - pointDrawable.getIntrinsicHeight() / 2),
(int) (x + pointDrawable.getIntrinsicWidth() / 2),
(int) (y + pointDrawable.getIntrinsicHeight() / 2)
);
pointDrawable.draw(canvas);
}
}
}
private void changePlot() {
pxProY = (height - marginPX - labelPlacePX) / (float) maxY;
pxProX = (width - labelPlacePX) / (float) (maxX - minX);
pointsPX.clear();
for (PointsProvider provider : providers) {
changePath(provider.getPoints());
}
changeLabels();
}
private void changePath(List<Point> points) {
paths.clear();
Path path = new Path();
float x = labelPlacePX;
float y = (float) (height - labelPlacePX - pxProY * points.get(0).getY());
path.moveTo(x, y);
pointsPX.add(new Pair<Float, Float>(x, y));
for (int i = 1; i < points.size(); i++) {
x = (float) (labelPlacePX + pxProX * (points.get(i).getX() - minX));
y = (float) (height - labelPlacePX - pxProY * points.get(i).getY());
path.lineTo(x, y);
pointsPX.add(new Pair<Float, Float>(x, y));
}
paths.add(path);
fillPaths.clear();
//TODO:ability to set or reset fill for every provider
if (enableFill) {
//Construct path for fill
Path pathFill = new Path(path);
pathFill.lineTo(
width - 1,
height - labelPlacePX - 1
);
pathFill.lineTo(
labelPlacePX,
height - labelPlacePX - 1
);
pathFill.close();
fillPaths.add(pathFill);
}
}
private void changeLabels() {
float lastLabelPX = labelPlacePX;
Rect rect = new Rect();
labelsX.clear();
labelsY.clear();
if (enableXAxis && enableLabels) {
//Part for X axis
double minScaleStepX = maxX;
int indexLeadProviderX = -1;
for (int i = 0; i < providers.size(); i++) {
double stepX = providers.get(i).getScaleStepX();
if (stepX < minScaleStepX) {
minScaleStepX = stepX;
indexLeadProviderX = i;
}
}
labelsX.clear();
for (double x = minX; x <= maxX; x += minScaleStepX) {
String labelX = providers.get(indexLeadProviderX).getLabelX(x);
textPaint.getTextBounds(labelX, 0, labelX.length(), rect);
float pxX = labelPlacePX + (float) (x - minX) * pxProX - rect.width() / 2;
if ((pxX - lastLabelPX >= spacingPXX) && (pxX + rect.width() <= width)) {
lastLabelPX = pxX + rect.width();
labelsX.add(new Pair<Float, String>(pxX, labelX));
}
}
textHeight = rect.height();
}
if (enableYAxis && enableLabels) {
//Part for Y axis
double minScaleStepY = maxY;
int indexLeadProviderY = -1;
for (int i = 0; i < providers.size(); i++) {
double stepY = providers.get(i).getScaleStepY();
if (stepY < minScaleStepY) {
minScaleStepY = stepY;
indexLeadProviderY = i;
}
}
labelsY.clear();
textPaint.getTextBounds(ZERO_LABEL, 0, ZERO_LABEL.length(), rect);
labelsY.add(new Pair<Float, String>(height - labelPlacePX + rect.height() / 2, ZERO_LABEL));
lastLabelPX = height - labelPlacePX - rect.height() / 2;
for (double y = 0; y <= maxY; y += minScaleStepY) {
String labelY = providers.get(indexLeadProviderY).getLabelY(y);
textPaint.getTextBounds(labelY, 0, labelY.length(), rect);
float pxY = height - labelPlacePX - pxProY * (float) y + rect.height() / 2;
if ((lastLabelPX - pxY >= spacingPXY) && (pxY - rect.height() >= 0)) {
lastLabelPX = pxY - rect.height();
labelsY.add(new Pair<Float, String>(pxY, labelY));
}
}
}
}
/**
* Recalculate data for GraphView to draw
*
* @param observable
* @param data
*/
@Override
public void update(Observable observable, Object data) {
if (providers.isEmpty()) {
clear();
return;
}
maxY = getMaxY();
maxX = getMaxX();
minX = getMinX();
changePlot();
invalidate();
}
private double getMaxY() {
Point.ComparatorY comparator = new Point.ComparatorY();
double maxY = Collections.max(providers.get(0).getPoints(), comparator).getY();
for (int i = 1; i < providers.size(); i++) {
double y = Collections.max(providers.get(i).getPoints(), comparator).getY();
if (maxY < y) {
maxY = y;
}
}
return maxY;
}
private double getMaxX() {
Point.ComparatorX comparator = new Point.ComparatorX();
double maxX = Collections.max(providers.get(0).getPoints(), comparator).getX();
for (int i = 1; i < providers.size(); i++) {
double x = Collections.max(providers.get(i).getPoints(), comparator).getX();
if (maxX < x) {
maxX = x;
}
}
return maxX;
}
private double getMinX() {
Point.ComparatorX comparator = new Point.ComparatorX();
double minX = Collections.min(providers.get(0).getPoints(), comparator).getX();
for (int i = 1; i < providers.size(); i++) {
double x = Collections.min(providers.get(i).getPoints(), comparator).getX();
if (minX > x) {
minX = x;
}
}
return minX;
}
private void clear() {
paths.clear();
fillPaths.clear();
labelsX.clear();
labelsY.clear();
invalidate();
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
width = w;
height = h;
if (providers.isEmpty()) {
return;
}
changePlot();
invalidate();
}
public void addPointsProvider(PointsProvider pointsProvider) {
providers.add(pointsProvider);
pointsProvider.addObserver(this);
invalidate();
}
public void setPointDrawable(Drawable pointDrawable) {
this.pointDrawable = pointDrawable;
invalidate();
}
public int getTextColor() {
return textColor;
}
public void setTextColor(int textColor) {
this.textColor = textColor;
invalidate();
}
/**
* @return the color of area below the plot
*/
public int getFillColor() {
return fillColor;
}
/**
* @param fillColor - the color of area below the plot
*/
public void setFillColor(int fillColor) {
this.fillColor = fillColor;
invalidate();
}
/**
* @return the color of lines that extends the Y-levels of labels
*/
public int getLevelColor() {
return levelColor;
}
/**
* @param levelColor - the color of lines that extends the Y-levels of labels
*/
public void setLevelColor(int levelColor) {
this.levelColor = levelColor;
invalidate();
}
public float getTextSize() {
return textSize;
}
public void setTextSize(float textSize) {
this.textSize = textSize;
invalidate();
}
/**
* @return the desirable spacing between X-axis labels
*/
public float getSpacingPXX() {
return spacingPXX;
}
/**
* @param spacingPXX - the desirable spacing between X-axis labels
*/
public void setSpacingPXX(float spacingPXX) {
this.spacingPXX = spacingPXX;
invalidate();
}
/**
* @return the desirable spacing in between Y-axis labels
*/
public float getSpacingPXY() {
return spacingPXY;
}
/**
* @param spacingPXY - the desirable spacing between Y-axis labels
*/
public void setSpacingPXY(float spacingPXY) {
this.spacingPXY = spacingPXY;
invalidate();
}
/**
* @return the space in pixels for locating Labels on Graph Axis
*/
public float getLabelPlacePX() {
return labelPlacePX;
}
/**
* @param labelPlacePX - the space in pixels for locating Labels on Graph Axis
*/
public void setLabelPlacePX(float labelPlacePX) {
this.labelPlacePX = labelPlacePX;
invalidate();
}
public int getLineColor() {
return lineColor;
}
public void setLineColor(int lineColor) {
this.lineColor = lineColor;
invalidate();
}
}
|
package org.jgroups.tests;
import org.jgroups.Global;
import org.jgroups.JChannel;
import org.jgroups.Message;
import org.jgroups.ReceiverAdapter;
import org.jgroups.stack.GossipRouter;
import org.jgroups.util.Promise;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
/**
* Test designed to make sure the TUNNEL doesn't lock the client and the GossipRouter
* under heavy load.
*
* @author Ovidiu Feodorov <ovidiu@feodorov.com>
* @version $Id: TUNNELDeadLockTest.java,v 1.19 2009/10/05 19:33:16 vlada Exp $
* @see TUNNELDeadLockTest#testStress
*/
@Test(groups={Global.STACK_INDEPENDENT, Global.GOSSIP_ROUTER},sequential=true)
public class TUNNELDeadLockTest extends ChannelTestBase {
private JChannel channel;
private Promise<Boolean> promise;
private int receivedCnt;
// the total number of the messages pumped down the channel
private int msgCount=20000;
// the message payload size (in bytes);
private int payloadSize=32;
// the time (in ms) the main thread waits for all the messages to arrive,
// before declaring the test failed.
private int mainTimeout=60000;
GossipRouter gossipRouter;
@BeforeMethod
void setUp() throws Exception {
promise=new Promise<Boolean>();
gossipRouter=new GossipRouter();
gossipRouter.start();
}
@AfterMethod(alwaysRun=true)
void tearDown() throws Exception {
// I prefer to close down the channel inside the test itself, for the
// reason that the channel might be brought in an uncloseable state by
// the test.
// TO_DO: no elegant way to stop the Router threads and clean-up
// resources. Use the Router administrative interface, when available.
channel.close();
promise.reset();
promise=null;
gossipRouter.stop();
System.out.println("Router stopped");
}
/**
* Pushes messages down the channel as fast as possible. Sometimes this
* manages to bring the channel and the Router into deadlock. On the
* machine I run it usually happens after 700 - 1000 messages and I
* suspect that this number it is related to the socket buffer size.
* (the comments are written when I didn't solve the bug yet). <br>
* <p/>
* The number of messages sent can be controlled with msgCount.
* The time (in ms) the main threads wait for the all messages to come can
* be controlled with mainTimeout. If this time passes and the test
* doesn't see all the messages, it declares itself failed.
*/
@Test
public void testStress() throws Exception {
channel=new JChannel("tunnel.xml");
channel.connect("agroup");
channel.setReceiver(new ReceiverAdapter() {
@Override
public void receive(Message msg) {
receivedCnt++;
if(receivedCnt % 2000 == 0)
System.out.println("-- received " + receivedCnt);
if(receivedCnt == msgCount) {
// let the main thread know I got all msgs
promise.setResult(Boolean.TRUE);
}
}
});
// stress send messages - the sender thread
new Thread(new Runnable() {
public void run() {
try {
for(int i=0; i < msgCount; i++) {
channel.send(null, null, new byte[payloadSize]);
if(i % 2000 == 0)
System.out.println("-- sent " + i);
}
}
catch(Exception e) {
System.err.println("Error sending data over ...");
e.printStackTrace();
}
}
}).start();
// wait for all the messages to come; if I don't see all of them in
// mainTimeout ms, I fail the test
Boolean result=promise.getResult(mainTimeout);
if(result == null) {
String msg=
"The channel has failed to send/receive " + msgCount + " messages " +
"possibly because of the channel deadlock or too short " +
"timeout (currently " + mainTimeout + " ms). " + receivedCnt +
" messages received so far.";
assert false : msg;
}
}
}
|
package com.bigndesign.light;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.Toast;
import com.auth0.android.Auth0;
import com.auth0.android.lock.AuthenticationCallback;
import com.auth0.android.lock.Lock;
import com.auth0.android.lock.LockCallback;
import com.auth0.android.lock.UsernameStyle;
import com.auth0.android.lock.utils.LockException;
import com.auth0.android.result.Credentials;
public class LoginActivity extends AppCompatActivity {
private Lock mLock;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Auth0 auth0 = new Auth0(getString(R.string.auth0_client_id), getString(R.string.auth0_domain));
mLock = Lock.newBuilder(auth0, mCallback)
.withUsernameStyle(UsernameStyle.USERNAME)
.closable(true)
// Add parameters to the Lock Builder
.build(this);
startActivity(mLock.newIntent(this));
}
@Override
protected void onDestroy() {
super.onDestroy();
// Your own Activity code
mLock.onDestroy(this);
mLock = null;
}
private final LockCallback mCallback = new AuthenticationCallback() {
@Override
public void onAuthentication(Credentials credentials) {
Toast.makeText(getApplicationContext(), "Log In - Success", Toast.LENGTH_SHORT).show();
Intent askIntent = new Intent(getApplicationContext(), AskActivity.class);
Bundle bundle = new Bundle();
bundle.putString("userId", credentials.getIdToken());
askIntent.putExtras(bundle);
startActivity(askIntent, bundle);
finish();
}
@Override
public void onCanceled() {
Toast.makeText(getApplicationContext(), "Log In - Cancelled", Toast.LENGTH_SHORT).show();
finish();
}
@Override
public void onError(LockException error) {
Toast.makeText(getApplicationContext(), "Log In - Error Occurred", Toast.LENGTH_SHORT).show();
}
};
}
|
package com.github.dylon.liblevenshtein.levenshtein;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.experimental.Accessors;
import lombok.experimental.FieldDefaults;
import com.github.dylon.liblevenshtein.levenshtein.factory.IElementFactory;
@Accessors(fluent=true)
@FieldDefaults(level=AccessLevel.PRIVATE)
public class State implements IState {
@Getter(onMethod=@_({@Override}))
int size = 0;
IElementFactory<int[]> factory;
int outerIndex = 0;
Element<int[]> outer = null;
int innerIndex = 0;
Element<int[]> inner = null;
Element<int[]> tail;
Element<int[]> head;
public State(final IElementFactory<int[]> factory) {
this.factory = factory;
this.tail = factory.build(null);
this.head = tail;
}
@Override
public void add(final int[] position) {
final Element<int[]> next = factory.build(position);
if (null == tail) {
tail = next;
}
else {
head.next(next);
}
head = next;
size += 1;
}
@Override
public int[] getOuter(final int index) {
if (index < 0 || index >= size) {
throw new ArrayIndexOutOfBoundsException(
"Expected 0 <= index < size, but received: " + index);
}
if (0 == index) {
outerIndex = 0;
outer = tail;
}
while (outerIndex > index) {
outerIndex -= 1;
outer = outer.prev();
}
while (outerIndex < index) {
outerIndex += 1;
outer = outer.next();
}
return outer.value();
}
@Override
public int[] getInner(final int index) {
if (index < 0 || index >= size) {
throw new ArrayIndexOutOfBoundsException(
"Expected 0 <= index < size, but received: " + index);
}
if (0 == index) {
innerIndex = 0;
inner = tail;
}
while (innerIndex > index) {
innerIndex -= 1;
inner = inner.prev();
}
while (innerIndex < index) {
innerIndex += 1;
inner = inner.next();
}
return inner.value();
}
@Override
public int[] removeInner() {
if (innerIndex >= size) {
throw new ArrayIndexOutOfBoundsException(
"No elements at index: " + innerIndex);
}
final Element<int[]> inner = this.inner;
this.inner = inner.next();
if (null != inner.prev()) {
inner.prev().next(inner.next());
}
if (null != inner.next()) {
inner.next().prev(inner.prev());
}
if (tail == inner) {
tail = null;
}
if (head == inner) {
head = head.prev();
}
final int[] position = inner.value();
factory.recycle(inner);
size -= 1;
return position;
}
@Override
public void clear() {
Element<int[]> head = this.head;
while (null != head && null != head.prev()) {
final Element<int[]> prev = head.prev();
prev.next(null);
factory.recycle(head);
head = prev;
}
if (null != head) {
factory.recycle(head);
}
this.size = 0;
this.outerIndex = 0;
this.outer = null;
this.innerIndex = 0;
this.inner = null;
this.head = null;
this.tail = null;
}
}
|
package com.github.fabioticconi.alone.systems;
import com.artemis.ComponentMapper;
import com.artemis.annotations.Wire;
import com.artemis.utils.IntBag;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.fabioticconi.alone.components.*;
import com.github.fabioticconi.alone.constants.WeaponType;
import net.mostlyoriginal.api.system.core.PassiveSystem;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
public class CraftSystem extends PassiveSystem
{
ComponentMapper<Inventory> mInventory;
ComponentMapper<Name> mName;
ComponentMapper<Equip> mEquip;
@Wire
ObjectMapper mapper;
HashMap<String, CraftItem> recipes;
@Override
protected void initialize()
{
try
{
loadRecipes();
} catch (final IOException e)
{
e.printStackTrace();
}
}
public List<String> getRecipeNames()
{
try
{
loadRecipes();
return new ArrayList<>(recipes.keySet());
} catch (final IOException e)
{
e.printStackTrace();
return List.of();
}
}
public HashMap<String, CraftItem> getRecipes()
{
try
{
loadRecipes();
} catch (final IOException e)
{
e.printStackTrace();
}
return recipes;
}
private void loadRecipes() throws IOException
{
final InputStream fileStream = new FileInputStream("data/crafting.yml");
recipes = mapper.readValue(fileStream, new TypeReference<HashMap<String, CraftItem>>()
{
});
for (final Map.Entry<String, CraftItem> entry : recipes.entrySet())
{
final CraftItem temp = entry.getValue();
temp.tag = entry.getKey();
for (final String tempSource : temp.source)
{
switch (tempSource)
{
case "stone":
case "branch":
case "vine":
case "trunk":
break;
default:
if (!recipes.keySet().contains(tempSource))
throw new RuntimeException("unknown item in source field: " + tempSource);
}
}
for (final String tempTool : temp.tools)
{
switch (tempTool)
{
case "stone":
case "branch":
case "vine":
case "trunk":
break;
default:
if (!recipes.keySet().contains(tempTool))
throw new RuntimeException("unknown item in tools field: " + tempTool);
}
}
// System.out.println(entry.getKey() + " | " + entry.getValue());
}
}
public boolean craftItem(final int entityId, final CraftItem itemRecipe)
{
final Inventory items = mInventory.get(entityId);
if (items == null)
return false;
final IntBag tempSources = new IntBag(itemRecipe.source.length);
final IntBag tempTools = new IntBag(itemRecipe.tools.length);
final int[] data = items.items.getData();
for (int i = 0, size = items.items.size(); i < size; i++)
{
final int itemId = data[i];
// we might only want an equipped weapon
if (!mName.has(itemId))
continue;
final Name name = mName.get(itemId);
int ii = 0;
while (ii < itemRecipe.source.length)
{
if (tempSources.get(ii) < 0 && name.tag.equals(itemRecipe.source[ii]))
{
tempSources.set(ii, itemId);
break; // item can be used only once
}
ii++;
}
// if ii == source.length, then it means that the previous loop completed
// without setting itemId as a "source". So it's OK to evaluate whether it
// can be used as a "tool".
ii = 0;
while (ii < itemRecipe.tools.length)
{
if (tempTools.get(ii) < 0 && name.tag.equals(itemRecipe.tools[ii]))
{
tempTools.set(ii, itemId);
break; // item can be used only once
}
ii++;
}
}
if (tempSources.size() < itemRecipe.source.length || tempTools.size() < itemRecipe.tools.length)
return false;
// TODO: here we should first create the object (using the internal fields.. we are still missing
// some, eg sprite, if is weapon, if is wearable..
// TODO: then we must destroy the items in the "source" array. Make sure to remove them from the map
// AND from the inventory too.
return true;
}
public static class CraftItem
{
public String name;
public String tag;
public String[] source;
public String[] tools;
public int n = 1;
// if I put this in a list of "components",
// then it's easier to instantiate them (since I know already they are
// Components, I can just add them to EntityEdit in a loop.
public boolean wearable;
public Weapon weapon;
public Sprite sprite;
@Override
public String toString()
{
return "CraftItem{" + "name='" + name + '\'' + ", tag='" + tag + '\'' + ", source=" +
Arrays.toString(source) + ", tools=" + Arrays.toString(tools) + ", n=" + n + '}';
}
}
}
|
package com.ejay.kingoftheroad;
import android.app.Fragment;
import android.location.Location;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
//package com.ejay.kingoftheroad;
public class MapFragment extends Fragment {
private final static String TAG = "MapActivity";
protected GoogleMap mMap;
private MapView mMapView;
private Location mLocation;
private GoogleApiClient mGoogleApiClient;
public class MapHandler implements OnMapReadyCallback {
@Override
public void onMapReady(GoogleMap map) {
Log.e(TAG, "Testing!");
mMap = map;
prepareMapIfReady();
}
}
class GoogleApiClientHandler implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
@Override
public void onConnected(Bundle bundle) {
mLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
prepareMapIfReady();
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Toast.makeText(getActivity(), "Failed to connect to Google Play Services", Toast.LENGTH_SHORT).show();
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.map_fragment, container, false);
mMapView = (MapView) rootView.findViewById(R.id.map);
mMapView.onCreate(savedInstanceState);
mMapView.getMapAsync(new MapHandler());
MapsInitializer.initialize(getActivity());
// Obtain an instance of Google API client.
mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
.addApi(LocationServices.API)
.addConnectionCallbacks(new GoogleApiClientHandler())
.addOnConnectionFailedListener(new GoogleApiClientHandler())
.build();
return rootView;
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// Inflate the menu; this adds items to the action bar if it is present.
inflater.inflate(R.menu.menu_map, menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
@Override
public void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
@Override
public void onPause() {
super.onPause();
mMapView.onPause();
}
@Override
public void onResume() {
super.onResume();
mMapView.onResume();
}
private void prepareMapIfReady() {
if (mLocation != null && mMap != null) {
mMap.setMyLocationEnabled(true);
mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
public void onMyLocationChange(Location arg0) {
mMap.clear();
mMap.addMarker(new MarkerOptions().position((new LatLng(arg0.getLatitude(), arg0.getLongitude()))).title("I am here!"));
}
});
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(mLocation.getLatitude(), mLocation.getLongitude()), 8
));
mMap.animateCamera(CameraUpdateFactory.zoomTo(17),1500,null);
}
}
}
|
package com.github.stefanliebenberg.html;
import com.github.stefanliebenberg.internal.IBuildOptions;
import com.github.stefanliebenberg.render.HtmlRenderer;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.io.File;
import java.util.List;
import java.util.Map;
public class HtmlBuildOptions implements IBuildOptions {
private File outputFile;
private List<File> javascriptFiles;
private List<File> stylesheetFiles;
private Boolean shouldBuildInline = false;
private Map<File, File> locationMap;
private String content;
private HtmlRenderer htmlRenderer;
@Nullable
public List<File> getJavascriptFiles() {
return javascriptFiles;
}
public void setJavascriptFiles(@Nullable final List<File> javascriptFiles) {
this.javascriptFiles = javascriptFiles;
}
@Nullable
public List<File> getStylesheetFiles() {
return stylesheetFiles;
}
public void setStylesheetFiles(@Nullable final List<File> stylesheetFiles) {
this.stylesheetFiles = stylesheetFiles;
}
@Nonnull
public Boolean getShouldBuildInline() {
return shouldBuildInline;
}
public void setShouldBuildInline(@Nonnull final Boolean shouldBuildInline) {
this.shouldBuildInline = shouldBuildInline;
}
@Nullable
public Map<File, File> getLocationMap() {
return locationMap;
}
public void setLocationMap(@Nullable final Map<File, File> locationMap) {
this.locationMap = locationMap;
}
@Nullable
public String getContent() {
return content;
}
public void setContent(@Nullable final String content) {
this.content = content;
}
@Nullable
public HtmlRenderer getHtmlRenderer() {
return htmlRenderer;
}
public void setHtmlRenderer(@Nullable final HtmlRenderer htmlRenderer) {
this.htmlRenderer = htmlRenderer;
}
@Nullable
public File getOutputFile() {
return outputFile;
}
public void setOutputFile(
@Nullable final File outputFile) {
this.outputFile = outputFile;
}
}
|
package com.example.phong.musicCaster;
import android.graphics.Bitmap;
public class Song {
private long songID;
private String songTitle;
private String songArtist;
private Bitmap albumArtwork = null;
public Song(long ID, String title, String artist, Bitmap artwork){
songID = ID;
songTitle = title;
songArtist = artist;
albumArtwork = artwork;
}
public long getSongID() {
return songID;
}
public String getSongTitle() {
return songTitle;
}
public String getSongArtist() {
return songArtist;
}
public Bitmap getArtWork(){return albumArtwork;}
}
|
package com.njackson.hrm;
import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;
import com.njackson.application.IInjectionContainer;
import com.njackson.application.modules.ForApplication;
import com.njackson.events.GPSServiceCommand.GPSStatus;
import com.njackson.events.base.BaseStatus;
import com.njackson.service.IServiceCommand;
import com.squareup.otto.Bus;
import com.squareup.otto.Subscribe;
import javax.inject.Inject;
import javax.inject.Named;
public class HrmServiceCommand implements IServiceCommand {
private final String TAG = "PB-HrmServiceCommand";
@Inject @ForApplication Context _applicationContext;
@Inject Bus _bus;
@Inject SharedPreferences _sharedPreferences;
@Inject IHrm _hrm;
IInjectionContainer _container;
private BaseStatus.Status _currentStatus= BaseStatus.Status.DISABLED;
@Override
public void execute(IInjectionContainer container) {
container.inject(this);
_bus.register(this);
_container = container;
}
@Override
public void dispose() {
_bus.unregister(this);
}
@Override
public BaseStatus.Status getStatus() {
return null;
}
@Subscribe
public void onGPSStatusEvent(GPSStatus event) {
switch(event.getStatus()) {
case STARTED:
if(_currentStatus != BaseStatus.Status.STARTED) {
start();
}
break;
case STOPPED:
if(_currentStatus != BaseStatus.Status.STOPPED) {
stop();
}
}
}
private void start() {
Log.d(TAG, "start");
_hrm.start(_sharedPreferences.getString("hrm_address", ""), _bus, _container);
_currentStatus = BaseStatus.Status.STARTED;
}
public void stop() {
Log.d(TAG, "stop");
_hrm.stop();
_currentStatus = BaseStatus.Status.STOPPED;
}
}
|
package com.litecoding.smali2java.renderer;
import java.util.List;
import com.litecoding.smali2java.entity.java.Renderable;
import com.litecoding.smali2java.entity.smali.Param;
import com.litecoding.smali2java.entity.smali.SmaliEntity;
import com.litecoding.smali2java.entity.smali.SmaliMethod;
public class MethodRenderer {
private static boolean isEgyptianBraces = false;
public static String renderObject(SmaliMethod smaliMethod) {
return render(smaliMethod);
}
public static String render(SmaliMethod smaliMethod) {
//TODO: improve the following
StringBuilder builder = new StringBuilder();
switch(smaliMethod.getFlagValue(SmaliEntity.MASK_ACCESSIBILITY)) {
case SmaliEntity.PUBLIC: {
builder.append("public ");
break;
}
case SmaliEntity.PROTECTED: {
builder.append("protected ");
break;
}
case SmaliEntity.PRIVATE: {
builder.append("private ");
break;
}
default: {
break;
}
}
if(smaliMethod.isFlagSet(SmaliEntity.STATIC)) {
builder.append("static ");
}
if(smaliMethod.isFlagSet(SmaliEntity.FINAL)) {
builder.append("final ");
}
if(smaliMethod.isFlagSet(SmaliEntity.ABSTRACT)) {
builder.append("abstract ");
}
if(smaliMethod.isConstructor())
builder.append(JavaRenderUtils.renderShortJavaClassName(smaliMethod.getName()));
else {
builder.append(JavaRenderUtils.renderShortComplexTypeDeclaration(smaliMethod.getReturnType()));
builder.append(" ");
builder.append(smaliMethod.getName());
}
builder.append(renderMethodProto(smaliMethod.getParams()));
if(smaliMethod.getSmaliClass().isFlagSet(SmaliEntity.INTERFACE) &&
smaliMethod.getCommands().size() == 0) {
builder.append(";\n");
} else {
if(!isEgyptianBraces)
builder.append("\n");
builder.append("{\n");
List<Renderable> javaEntities = JavaRenderer.generateJavaEntities(smaliMethod);
for(Renderable entity : javaEntities) {
builder.append(entity.render());
builder.append("\n");
}
builder.append("}\n\n");
}
return builder.toString();
}
private static String renderMethodProto(List<Param> params) {
StringBuilder builder = new StringBuilder();
builder.append("(");
for(int i = 0; i < params.size(); i++) {
if(i > 0)
builder.append(", ");
Param param = params.get(i);
if(param.getName() == null || param.getName().equals(""))
param.setName(generateParamName(i, param.getType()));
builder.append(JavaRenderUtils.renderShortComplexTypeDeclaration(param.getType()));
builder.append(" ");
builder.append(param.getName());
}
builder.append(")");
return builder.toString();
}
/**
* Generates a name for an anonymous parameter
* @param i parameter index
* @param type
* @return
*/
private static String generateParamName(int i, String type) {
String tmp = JavaRenderUtils.renderShortComplexTypeDeclaration(type).replaceAll("\\[\\]", "Arr");
StringBuilder builder = new StringBuilder();
builder.append("a");
builder.append(tmp.substring(0, 1).toUpperCase());
builder.append(tmp.substring(1));
builder.append(i);
return builder.toString();
}
// /**
// * Generates a name for anonymous parameter
// * @param i stack variable index
// * @param type
// * @return
// */
// private String generateVarName(int i, String type) {
// String tmp = JavaRenderUtils.renderShortComplexTypeDeclaration(type).replaceAll("\\[\\]", "Arr");
// StringBuilder builder = new StringBuilder();
// builder.append("v");
// builder.append(tmp.substring(0, 1).toUpperCase());
// builder.append(tmp.substring(1));
// builder.append(i);
// return builder.toString();
}
|
package com.samourai.sentinel.util;
import android.content.Context;
import com.samourai.sentinel.BuildConfig;
import com.samourai.sentinel.SamouraiSentinel;
import com.samourai.sentinel.tor.TorManager;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
public class WebUtil {
private static WebUtil instance = null;
private Context context = null;
private WebUtil(Context context) {
this.context = context;
}
public static WebUtil getInstance(Context ctx) {
if (instance == null) {
instance = new WebUtil(ctx);
}
return instance;
}
public static final String SAMOURAI_API = "https://api.samouraiwallet.com/";
public static final String SAMOURAI_API2 = "https://api.samouraiwallet.com/v2/";
public static final String SAMOURAI_API2_TESTNET = "https://api.samouraiwallet.com/test/v2/";
public static final String SAMOURAI_API2_TOR_DIST = "http://d2oagweysnavqgcfsfawqwql2rwxend7xxpriq676lzsmtfwbt75qbqd.onion/v2/";
public static final String SAMOURAI_API2_TESTNET_TOR_DIST = "http://d2oagweysnavqgcfsfawqwql2rwxend7xxpriq676lzsmtfwbt75qbqd.onion/test/v2/";
public static final String LBC_EXCHANGE_URL = "https://localbitcoins.com/bitcoinaverage/ticker-all-currencies/";
public static final String BFX_EXCHANGE_URL = "https://api.bitfinex.com/v1/pubticker/btcusd";
private static final int DefaultRequestRetry = 2;
private static final int DefaultRequestTimeout = 60000;
public String postURL(String URL, String urlParameters) throws Exception {
if ( PrefsUtil.getInstance(context).getValue(PrefsUtil.ENABLE_TOR, false)) {
return tor_postURL(URL,urlParameters);
}
final MediaType JSON
= MediaType.parse("application/json; charset=utf-8");
RequestBody body = RequestBody.create(JSON, urlParameters.toString());
OkHttpClient.Builder builder = new OkHttpClient.Builder();
if (BuildConfig.DEBUG) {
builder.addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY));
}
Request request = new Request.Builder()
.url(URL)
.post(body)
.build();
try (Response response = builder.build().newCall(request).execute()) {
if (response.body() == null) {
return "";
}
return response.body().string();
}
}
public String postURL(String URL, FormBody args) throws Exception {
if ( PrefsUtil.getInstance(context).getValue(PrefsUtil.ENABLE_TOR, false)) {
return tor_postURL(URL,args);
}
OkHttpClient.Builder builder = new OkHttpClient.Builder();
if (BuildConfig.DEBUG) {
builder.addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY));
}
Request request = new Request.Builder()
.url(URL)
.post(args)
.build();
try (Response response = builder.build().newCall(request).execute()) {
if (response.body() == null) {
return "";
}
return response.body().string();
}
}
public String getURL(String URL) throws Exception {
if ( PrefsUtil.getInstance(context).getValue(PrefsUtil.ENABLE_TOR, false)) {
return tor_getURL(URL);
}
OkHttpClient.Builder builder = new OkHttpClient.Builder()
.connectTimeout(90, TimeUnit.SECONDS)
.retryOnConnectionFailure(true)
.readTimeout(90, TimeUnit.SECONDS);
if (BuildConfig.DEBUG) {
builder.addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY));
}
Request request = new Request.Builder()
.url(URL)
.build();
try (Response response = builder.build().newCall(request).execute()) {
if (response.body() == null) {
return "";
}
return response.body().string();
}
}
private String tor_getURL(String URL) throws Exception {
OkHttpClient.Builder builder = new OkHttpClient.Builder()
.proxy(TorManager.getInstance(this.context).getProxy())
.connectTimeout(90, TimeUnit.SECONDS)
.readTimeout(90, TimeUnit.SECONDS);
if (BuildConfig.DEBUG) {
builder.addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY));
}
if (URL.contains("onion")) {
getHostNameVerifier(builder);
}
Request request = new Request.Builder()
.url(URL)
.build();
try (Response response = builder.build().newCall(request).execute()) {
if (response.body() == null) {
return "";
}
return response.body().string();
}
}
public String tor_postURL(String URL, String args) throws Exception {
final MediaType JSON
= MediaType.parse("application/json; charset=utf-8");
RequestBody body = RequestBody.create(JSON, args.toString());
OkHttpClient.Builder builder = new OkHttpClient.Builder()
.proxy(TorManager.getInstance(this.context).getProxy())
.connectTimeout(90, TimeUnit.SECONDS)
.readTimeout(90, TimeUnit.SECONDS);
if (URL.contains("onion")) {
getHostNameVerifier(builder);
}
if (BuildConfig.DEBUG) {
builder.addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY));
}
Request request = new Request.Builder()
.url(URL)
.post(body)
.build();
try (Response response = builder.build().newCall(request).execute()) {
if (response.body() == null) {
return "";
}
return response.body().string();
}
}
public String tor_postURL(String URL, FormBody args) throws Exception {
OkHttpClient.Builder builder = new OkHttpClient.Builder()
.proxy(TorManager.getInstance(this.context).getProxy());
if (URL.contains("onion")) {
getHostNameVerifier(builder);
}
if (BuildConfig.DEBUG) {
builder.addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY));
}
Request request = new Request.Builder()
.url(URL)
.post(args)
.build();
try (Response response = builder.build().newCall(request).execute()) {
if (response.body() == null) {
return "";
}
return response.body().string();
}
}
private void getHostNameVerifier(OkHttpClient.Builder
clientBuilder) throws
Exception {
LogUtil.info("DK", "getHostNameVerifier: ");
// Create a trust manager that does not validate certificate chains
final TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
@Override
public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) {
}
@Override
public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) {
}
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[]{};
}
}
};
// Install the all-trusting trust manager
final SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
// Create an ssl socket factory with our all-trusting manager
final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
clientBuilder.sslSocketFactory(sslSocketFactory, (X509TrustManager) trustAllCerts[0]);
clientBuilder.hostnameVerifier((hostname, session) -> true);
}
public static String getAPIUrl(Context context) {
if (TorManager.getInstance(context).isRequired()) {
return SamouraiSentinel.getInstance().isTestNet() ? SAMOURAI_API2_TESTNET_TOR_DIST : SAMOURAI_API2_TOR_DIST;
} else {
return SamouraiSentinel.getInstance().isTestNet() ? SAMOURAI_API2_TESTNET : SAMOURAI_API2;
}
}
}
|
package com.samourai.wallet.api;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import com.samourai.wallet.JSONRPC.JSONRPC;
import com.samourai.wallet.JSONRPC.TrustedNodeUtil;
import com.samourai.wallet.SamouraiWallet;
import com.samourai.wallet.bip47.BIP47Meta;
import com.samourai.wallet.bip47.BIP47Util;
import com.samourai.wallet.hd.HD_Address;
import com.samourai.wallet.hd.HD_Wallet;
import com.samourai.wallet.hd.HD_WalletFactory;
import com.samourai.wallet.segwit.BIP49Util;
import com.samourai.wallet.segwit.BIP84Util;
import com.samourai.wallet.segwit.SegwitAddress;
import com.samourai.wallet.segwit.bech32.Bech32Segwit;
import com.samourai.wallet.segwit.bech32.Bech32Util;
import com.samourai.wallet.send.BlockedUTXO;
import com.samourai.wallet.send.FeeUtil;
import com.samourai.wallet.send.MyTransactionOutPoint;
import com.samourai.wallet.send.RBFUtil;
import com.samourai.wallet.send.SuggestedFee;
import com.samourai.wallet.send.UTXO;
import com.samourai.wallet.send.UTXOFactory;
import com.samourai.wallet.util.AddressFactory;
import com.samourai.wallet.util.ConnectivityStatus;
import com.samourai.wallet.util.FormatsUtil;
import com.samourai.wallet.util.PrefsUtil;
import com.samourai.wallet.util.TorUtil;
import com.samourai.wallet.util.WebUtil;
import com.samourai.wallet.bip47.rpc.PaymentCode;
import com.samourai.wallet.bip47.rpc.PaymentAddress;
import com.samourai.wallet.R;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.bitcoinj.core.Address;
import org.bitcoinj.core.AddressFormatException;
import org.bitcoinj.core.ECKey;
import org.bitcoinj.core.Sha256Hash;
import org.bitcoinj.core.TransactionOutPoint;
import org.bitcoinj.crypto.MnemonicException;
import org.bitcoinj.params.MainNetParams;
import org.bitcoinj.params.TestNet3Params;
import org.bitcoinj.script.Script;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.bouncycastle.util.encoders.Hex;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.math.BigInteger;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
public class APIFactory {
private static long xpub_balance = 0L;
private static HashMap<String, Long> xpub_amounts = null;
private static HashMap<String,List<Tx>> xpub_txs = null;
private static HashMap<String,Integer> unspentAccounts = null;
private static HashMap<String,Integer> unspentBIP49 = null;
private static HashMap<String,Integer> unspentBIP84 = null;
private static HashMap<String,String> unspentPaths = null;
private static HashMap<String,UTXO> utxos = null;
private static HashMap<String, Long> bip47_amounts = null;
private static long latest_block_height = -1L;
private static String latest_block_hash = null;
private static APIFactory instance = null;
private static Context context = null;
private static AlertDialog alertDialog = null;
private APIFactory() { ; }
public static APIFactory getInstance(Context ctx) {
context = ctx;
if(instance == null) {
xpub_amounts = new HashMap<String, Long>();
xpub_txs = new HashMap<String,List<Tx>>();
xpub_balance = 0L;
bip47_amounts = new HashMap<String, Long>();
unspentPaths = new HashMap<String, String>();
unspentAccounts = new HashMap<String, Integer>();
unspentBIP49 = new HashMap<String, Integer>();
unspentBIP84 = new HashMap<String, Integer>();
utxos = new HashMap<String, UTXO>();
instance = new APIFactory();
}
return instance;
}
public synchronized void reset() {
xpub_balance = 0L;
xpub_amounts.clear();
bip47_amounts.clear();
xpub_txs.clear();
unspentPaths = new HashMap<String, String>();
unspentAccounts = new HashMap<String, Integer>();
unspentBIP49 = new HashMap<String, Integer>();
unspentBIP84 = new HashMap<String, Integer>();
utxos = new HashMap<String, UTXO>();
UTXOFactory.getInstance().clear();
}
private synchronized JSONObject getXPUB(String[] xpubs, boolean parse) {
String _url = SamouraiWallet.getInstance().isTestNet() ? WebUtil.SAMOURAI_API2_TESTNET : WebUtil.SAMOURAI_API2;
JSONObject jsonObject = null;
try {
String response = null;
if(!TorUtil.getInstance(context).statusFromBroadcast()) {
// use POST
StringBuilder args = new StringBuilder();
args.append("active=");
args.append(StringUtils.join(xpubs, URLEncoder.encode("|", "UTF-8")));
Log.i("APIFactory", "XPUB:" + args.toString());
response = WebUtil.getInstance(context).postURL(_url + "multiaddr?", args.toString());
Log.i("APIFactory", "XPUB response:" + response);
}
else {
HashMap<String,String> args = new HashMap<String,String>();
args.put("active", StringUtils.join(xpubs, "|"));
Log.i("APIFactory", "XPUB:" + args.toString());
response = WebUtil.getInstance(context).tor_postURL(_url + "multiaddr", args);
Log.i("APIFactory", "XPUB response:" + response);
}
try {
jsonObject = new JSONObject(response);
if(!parse) {
return jsonObject;
}
xpub_txs.put(xpubs[0], new ArrayList<Tx>());
parseXPUB(jsonObject);
xpub_amounts.put(HD_WalletFactory.getInstance(context).get().getAccount(0).xpubstr(), xpub_balance - BlockedUTXO.getInstance().getTotalValueBlocked());
}
catch(JSONException je) {
je.printStackTrace();
jsonObject = null;
}
}
catch(Exception e) {
jsonObject = null;
e.printStackTrace();
}
return jsonObject;
}
private synchronized JSONObject registerXPUB(String xpub, int purpose) {
String _url = SamouraiWallet.getInstance().isTestNet() ? WebUtil.SAMOURAI_API2_TESTNET : WebUtil.SAMOURAI_API2;
JSONObject jsonObject = null;
try {
String response = null;
if(!TorUtil.getInstance(context).statusFromBroadcast()) {
// use POST
StringBuilder args = new StringBuilder();
args.append("xpub=");
args.append(xpub);
args.append("&type=");
if(PrefsUtil.getInstance(context).getValue(PrefsUtil.IS_RESTORE, false) == true) {
args.append("restore");
}
else {
args.append("new");
}
if(purpose == 49) {
args.append("&segwit=");
args.append("bip49");
}
else if(purpose == 84) {
args.append("&segwit=");
args.append("bip84");
}
else {
;
}
Log.i("APIFactory", "XPUB:" + args.toString());
response = WebUtil.getInstance(context).postURL(_url + "xpub?", args.toString());
Log.i("APIFactory", "XPUB response:" + response);
}
else {
HashMap<String,String> args = new HashMap<String,String>();
args.put("xpub", xpub);
if(PrefsUtil.getInstance(context).getValue(PrefsUtil.IS_RESTORE, false) == true) {
args.put("type", "restore");
}
else {
args.put("type", "new");
}
if(purpose == 49) {
args.put("segwit", "bip49");
}
else if(purpose == 84) {
args.put("segwit", "bip84");
}
else {
;
}
Log.i("APIFactory", "XPUB:" + args.toString());
response = WebUtil.getInstance(context).tor_postURL(_url + "xpub", args);
Log.i("APIFactory", "XPUB response:" + response);
}
try {
jsonObject = new JSONObject(response);
Log.i("APIFactory", "XPUB response:" + jsonObject.toString());
if(jsonObject.has("status") && jsonObject.getString("status").equals("ok")) {
if(purpose == 49) {
PrefsUtil.getInstance(context).setValue(PrefsUtil.XPUB49REG, true);
PrefsUtil.getInstance(context).removeValue(PrefsUtil.IS_RESTORE);
}
else if(purpose == 84) {
PrefsUtil.getInstance(context).setValue(PrefsUtil.XPUB84REG, true);
PrefsUtil.getInstance(context).removeValue(PrefsUtil.IS_RESTORE);
}
else {
;
}
}
}
catch(JSONException je) {
je.printStackTrace();
jsonObject = null;
}
}
catch(Exception e) {
jsonObject = null;
e.printStackTrace();
}
return jsonObject;
}
private synchronized boolean parseXPUB(JSONObject jsonObject) throws JSONException {
if(jsonObject != null) {
if(jsonObject.has("wallet")) {
JSONObject walletObj = (JSONObject)jsonObject.get("wallet");
if(walletObj.has("final_balance")) {
xpub_balance = walletObj.getLong("final_balance");
Log.d("APIFactory", "xpub_balance:" + xpub_balance);
}
}
if(jsonObject.has("info")) {
JSONObject infoObj = (JSONObject)jsonObject.get("info");
if(infoObj.has("latest_block")) {
JSONObject blockObj = (JSONObject)infoObj.get("latest_block");
if(blockObj.has("height")) {
latest_block_height = blockObj.getLong("height");
}
if(blockObj.has("hash")) {
latest_block_hash = blockObj.getString("hash");
}
}
}
if(jsonObject.has("addresses")) {
JSONArray addressesArray = (JSONArray)jsonObject.get("addresses");
JSONObject addrObj = null;
for(int i = 0; i < addressesArray.length(); i++) {
addrObj = (JSONObject)addressesArray.get(i);
if(addrObj != null && addrObj.has("final_balance") && addrObj.has("address")) {
if(FormatsUtil.getInstance().isValidXpub((String)addrObj.get("address"))) {
xpub_amounts.put((String)addrObj.get("address"), addrObj.getLong("final_balance"));
if(addrObj.getString("address").equals(BIP84Util.getInstance(context).getWallet().getAccount(0).xpubstr())) {
AddressFactory.getInstance().setHighestBIP84ReceiveIdx(addrObj.has("account_index") ? addrObj.getInt("account_index") : 0);
AddressFactory.getInstance().setHighestBIP84ChangeIdx(addrObj.has("change_index") ? addrObj.getInt("change_index") : 0);
}
else if(addrObj.getString("address").equals(BIP49Util.getInstance(context).getWallet().getAccount(0).xpubstr())) {
AddressFactory.getInstance().setHighestBIP49ReceiveIdx(addrObj.has("account_index") ? addrObj.getInt("account_index") : 0);
AddressFactory.getInstance().setHighestBIP49ChangeIdx(addrObj.has("change_index") ? addrObj.getInt("change_index") : 0);
}
else if(AddressFactory.getInstance().xpub2account().get((String) addrObj.get("address")) != null) {
AddressFactory.getInstance().setHighestTxReceiveIdx(AddressFactory.getInstance().xpub2account().get((String) addrObj.get("address")), addrObj.has("account_index") ? addrObj.getInt("account_index") : 0);
AddressFactory.getInstance().setHighestTxChangeIdx(AddressFactory.getInstance().xpub2account().get((String)addrObj.get("address")), addrObj.has("change_index") ? addrObj.getInt("change_index") : 0);
}
else {
;
}
}
else {
long amount = 0L;
String addr = null;
addr = (String)addrObj.get("address");
amount = addrObj.getLong("final_balance");
String pcode = BIP47Meta.getInstance().getPCode4Addr(addr);
if(addr != null && addr.length() > 0 && pcode != null && pcode.length() > 0 && BIP47Meta.getInstance().getIdx4Addr(addr) != null) {
int idx = BIP47Meta.getInstance().getIdx4Addr(addr);
if(amount > 0L) {
BIP47Meta.getInstance().addUnspent(pcode, idx);
}
else {
BIP47Meta.getInstance().removeUnspent(pcode, Integer.valueOf(idx));
}
if(addr != null) {
bip47_amounts.put(addr, amount);
}
}
}
}
}
}
if(jsonObject.has("txs")) {
JSONArray txArray = (JSONArray)jsonObject.get("txs");
JSONObject txObj = null;
for(int i = 0; i < txArray.length(); i++) {
txObj = (JSONObject)txArray.get(i);
long height = 0L;
long amount = 0L;
long ts = 0L;
String hash = null;
String addr = null;
String _addr = null;
if(txObj.has("block_height")) {
height = txObj.getLong("block_height");
}
else {
height = -1L; // 0 confirmations
}
if(txObj.has("hash")) {
hash = (String)txObj.get("hash");
}
if(txObj.has("result")) {
amount = txObj.getLong("result");
}
if(txObj.has("time")) {
ts = txObj.getLong("time");
}
if(txObj.has("inputs")) {
JSONArray inputArray = (JSONArray)txObj.get("inputs");
JSONObject inputObj = null;
for(int j = 0; j < inputArray.length(); j++) {
inputObj = (JSONObject)inputArray.get(j);
if(inputObj.has("prev_out")) {
JSONObject prevOutObj = (JSONObject)inputObj.get("prev_out");
if(prevOutObj.has("xpub")) {
JSONObject xpubObj = (JSONObject)prevOutObj.get("xpub");
addr = (String)xpubObj.get("m");
}
else if(prevOutObj.has("addr") && BIP47Meta.getInstance().getPCode4Addr((String)prevOutObj.get("addr")) != null) {
_addr = (String)prevOutObj.get("addr");
}
else {
_addr = (String)prevOutObj.get("addr");
}
}
}
}
if(txObj.has("out")) {
JSONArray outArray = (JSONArray)txObj.get("out");
JSONObject outObj = null;
for(int j = 0; j < outArray.length(); j++) {
outObj = (JSONObject)outArray.get(j);
if(outObj.has("xpub")) {
JSONObject xpubObj = (JSONObject)outObj.get("xpub");
addr = (String)xpubObj.get("m");
}
else {
_addr = (String)outObj.get("addr");
}
}
}
if(addr != null || _addr != null) {
if(addr == null) {
addr = _addr;
}
Tx tx = new Tx(hash, addr, amount, ts, (latest_block_height > 0L && height > 0L) ? (latest_block_height - height) + 1 : 0);
if(BIP47Meta.getInstance().getPCode4Addr(addr) != null) {
tx.setPaymentCode(BIP47Meta.getInstance().getPCode4Addr(addr));
}
if(!xpub_txs.containsKey(addr)) {
xpub_txs.put(addr, new ArrayList<Tx>());
}
if(FormatsUtil.getInstance().isValidXpub(addr)) {
xpub_txs.get(addr).add(tx);
}
else {
xpub_txs.get(AddressFactory.getInstance().account2xpub().get(0)).add(tx);
}
if(height > 0L) {
RBFUtil.getInstance().remove(hash);
}
}
}
}
return true;
}
return false;
}
public synchronized JSONObject deleteXPUB(String xpub, boolean bip49) {
String _url = SamouraiWallet.getInstance().isTestNet() ? WebUtil.SAMOURAI_API2_TESTNET : WebUtil.SAMOURAI_API2;
JSONObject jsonObject = null;
try {
String response = null;
ECKey ecKey = null;
if(AddressFactory.getInstance(context).xpub2account().get(xpub) != null || xpub.equals(BIP49Util.getInstance(context).getWallet().getAccount(0).ypubstr())) {
HD_Address addr = null;
if(bip49) {
addr = BIP49Util.getInstance(context).getWallet().getAccountAt(0).getChange().getAddressAt(0);
}
else {
addr = HD_WalletFactory.getInstance(context).get().getAccount(0).getChain(AddressFactory.CHANGE_CHAIN).getAddressAt(0);
}
ecKey = addr.getECKey();
if(ecKey != null && ecKey.hasPrivKey()) {
String sig = ecKey.signMessage(xpub);
String address = null;
if(bip49) {
SegwitAddress segwitAddress = new SegwitAddress(ecKey.getPubKey(), SamouraiWallet.getInstance().getCurrentNetworkParams());
address = segwitAddress.getAddressAsString();
}
else {
address = ecKey.toAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString();
}
if(!TorUtil.getInstance(context).statusFromBroadcast()) {
StringBuilder args = new StringBuilder();
args.append("message=");
args.append(xpub);
args.append("address=");
args.append(address);
args.append("&signature=");
args.append(Uri.encode(sig));
Log.i("APIFactory", "delete XPUB:" + args.toString());
response = WebUtil.getInstance(context).deleteURL(_url + "delete/" + xpub, args.toString());
Log.i("APIFactory", "delete XPUB response:" + response);
}
else {
HashMap<String,String> args = new HashMap<String,String>();
args.put("message", xpub);
args.put("address", address);
args.put("signature", Uri.encode(sig));
Log.i("APIFactory", "delete XPUB:" + args.toString());
response = WebUtil.getInstance(context).tor_deleteURL(_url + "delete", args);
Log.i("APIFactory", "delete XPUB response:" + response);
}
try {
jsonObject = new JSONObject(response);
if(jsonObject.has("status") && jsonObject.getString("status").equals("ok")) {
;
}
}
catch(JSONException je) {
je.printStackTrace();
jsonObject = null;
}
}
}
}
catch(Exception e) {
jsonObject = null;
e.printStackTrace();
}
return jsonObject;
}
public synchronized JSONObject lockXPUB(String xpub, int purpose) {
String _url = SamouraiWallet.getInstance().isTestNet() ? WebUtil.SAMOURAI_API2_TESTNET : WebUtil.SAMOURAI_API2;
JSONObject jsonObject = null;
try {
String response = null;
ECKey ecKey = null;
if(AddressFactory.getInstance(context).xpub2account().get(xpub) != null || xpub.equals(BIP49Util.getInstance(context).getWallet().getAccount(0).ypubstr())) {
HD_Address addr = null;
switch(purpose) {
case 49:
addr = BIP49Util.getInstance(context).getWallet().getAccountAt(0).getChange().getAddressAt(0);
break;
case 84:
addr = BIP84Util.getInstance(context).getWallet().getAccountAt(0).getChange().getAddressAt(0);
break;
default:
addr = HD_WalletFactory.getInstance(context).get().getAccount(0).getChain(AddressFactory.CHANGE_CHAIN).getAddressAt(0);
break;
}
ecKey = addr.getECKey();
if(ecKey != null && ecKey.hasPrivKey()) {
String sig = ecKey.signMessage("lock");
String address = null;
switch(purpose) {
case 49:
SegwitAddress p2shp2wpkh = new SegwitAddress(ecKey.getPubKey(), SamouraiWallet.getInstance().getCurrentNetworkParams());
address = p2shp2wpkh.getAddressAsString();
break;
case 84:
SegwitAddress segwitAddress = new SegwitAddress(ecKey.getPubKey(), SamouraiWallet.getInstance().getCurrentNetworkParams());
address = segwitAddress.getBech32AsString();
break;
default:
address = ecKey.toAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString();
break;
}
if(!TorUtil.getInstance(context).statusFromBroadcast()) {
StringBuilder args = new StringBuilder();
args.append("address=");
args.append(address);
args.append("&signature=");
args.append(Uri.encode(sig));
args.append("&message=");
args.append("lock");
// Log.i("APIFactory", "lock XPUB:" + args.toString());
response = WebUtil.getInstance(context).postURL(_url + "xpub/" + xpub + "/lock/", args.toString());
// Log.i("APIFactory", "lock XPUB response:" + response);
}
else {
HashMap<String,String> args = new HashMap<String,String>();
args.put("address", address);
args.put("signature", Uri.encode(sig));
args.put("message", "lock");
// Log.i("APIFactory", "lock XPUB:" + args.toString());
response = WebUtil.getInstance(context).tor_postURL(_url + "xpub" + xpub + "/lock/", args);
// Log.i("APIFactory", "lock XPUB response:" + response);
}
try {
jsonObject = new JSONObject(response);
if(jsonObject.has("status") && jsonObject.getString("status").equals("ok")) {
switch(purpose) {
case 49:
PrefsUtil.getInstance(context).setValue(PrefsUtil.XPUB49LOCK, true);
break;
case 84:
PrefsUtil.getInstance(context).setValue(PrefsUtil.XPUB84LOCK, true);
break;
default:
PrefsUtil.getInstance(context).setValue(PrefsUtil.XPUB44LOCK, true);
break;
}
}
}
catch(JSONException je) {
je.printStackTrace();
jsonObject = null;
}
}
}
}
catch(Exception e) {
jsonObject = null;
e.printStackTrace();
}
return jsonObject;
}
public long getLatestBlockHeight() {
return latest_block_height;
}
public String getLatestBlockHash() {
return latest_block_hash;
}
public JSONObject getNotifTx(String hash, String addr) {
String _url = SamouraiWallet.getInstance().isTestNet() ? WebUtil.SAMOURAI_API2_TESTNET : WebUtil.SAMOURAI_API2;
JSONObject jsonObject = null;
try {
StringBuilder url = new StringBuilder(_url);
url.append("tx/");
url.append(hash);
url.append("?fees=1");
// Log.i("APIFactory", "Notif tx:" + url.toString());
String response = WebUtil.getInstance(null).getURL(url.toString());
// Log.i("APIFactory", "Notif tx:" + response);
try {
jsonObject = new JSONObject(response);
parseNotifTx(jsonObject, addr, hash);
}
catch(JSONException je) {
je.printStackTrace();
jsonObject = null;
}
}
catch(Exception e) {
jsonObject = null;
e.printStackTrace();
}
return jsonObject;
}
public JSONObject getNotifAddress(String addr) {
String _url = SamouraiWallet.getInstance().isTestNet() ? WebUtil.SAMOURAI_API2_TESTNET : WebUtil.SAMOURAI_API2;
JSONObject jsonObject = null;
try {
StringBuilder url = new StringBuilder(_url);
url.append("multiaddr?active=");
url.append(addr);
// Log.i("APIFactory", "Notif address:" + url.toString());
String response = WebUtil.getInstance(null).getURL(url.toString());
// Log.i("APIFactory", "Notif address:" + response);
try {
jsonObject = new JSONObject(response);
parseNotifAddress(jsonObject, addr);
}
catch(JSONException je) {
je.printStackTrace();
jsonObject = null;
}
}
catch(Exception e) {
jsonObject = null;
e.printStackTrace();
}
return jsonObject;
}
public void parseNotifAddress(JSONObject jsonObject, String addr) throws JSONException {
if(jsonObject != null && jsonObject.has("txs")) {
JSONArray txArray = jsonObject.getJSONArray("txs");
JSONObject txObj = null;
for(int i = 0; i < txArray.length(); i++) {
txObj = (JSONObject)txArray.get(i);
if(!txObj.has("block_height") || (txObj.has("block_height") && txObj.getLong("block_height") < 1L)) {
return;
}
String hash = null;
if(txObj.has("hash")) {
hash = (String)txObj.get("hash");
if(BIP47Meta.getInstance().getIncomingStatus(hash) == null) {
getNotifTx(hash, addr);
}
}
}
}
}
public void parseNotifTx(JSONObject jsonObject, String addr, String hash) throws JSONException {
Log.i("APIFactory", "notif address:" + addr);
Log.i("APIFactory", "hash:" + hash);
if(jsonObject != null) {
byte[] mask = null;
byte[] payload = null;
PaymentCode pcode = null;
if(jsonObject.has("inputs")) {
JSONArray inArray = (JSONArray)jsonObject.get("inputs");
if(inArray.length() > 0) {
JSONObject objInput = (JSONObject)inArray.get(0);
byte[] pubkey = null;
String strScript = objInput.getString("sig");
Log.i("APIFactory", "scriptsig:" + strScript);
if(strScript.startsWith("160014") && objInput.has("witness")) {
JSONArray witnessArray = (JSONArray)objInput.get("witness");
if(witnessArray.length() == 2) {
pubkey = Hex.decode((String)witnessArray.get(1));
}
}
else {
Script script = new Script(Hex.decode(strScript));
Log.i("APIFactory", "pubkey from script:" + Hex.toHexString(script.getPubKey()));
pubkey = script.getPubKey();
}
ECKey pKey = new ECKey(null, pubkey, true);
Log.i("APIFactory", "address from script:" + pKey.toAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString());
// Log.i("APIFactory", "uncompressed public key from script:" + Hex.toHexString(pKey.decompress().getPubKey()));
if(((JSONObject)inArray.get(0)).has("outpoint")) {
JSONObject received_from = ((JSONObject) inArray.get(0)).getJSONObject("outpoint");
String strHash = received_from.getString("txid");
int idx = received_from.getInt("vout");
byte[] hashBytes = Hex.decode(strHash);
Sha256Hash txHash = new Sha256Hash(hashBytes);
TransactionOutPoint outPoint = new TransactionOutPoint(SamouraiWallet.getInstance().getCurrentNetworkParams(), idx, txHash);
byte[] outpoint = outPoint.bitcoinSerialize();
Log.i("APIFactory", "outpoint:" + Hex.toHexString(outpoint));
try {
mask = BIP47Util.getInstance(context).getIncomingMask(pubkey, outpoint);
Log.i("APIFactory", "mask:" + Hex.toHexString(mask));
}
catch(Exception e) {
e.printStackTrace();
}
}
}
}
if(jsonObject.has("outputs")) {
JSONArray outArray = (JSONArray)jsonObject.get("outputs");
JSONObject outObj = null;
boolean isIncoming = false;
String _addr = null;
String script = null;
String op_return = null;
for(int j = 0; j < outArray.length(); j++) {
outObj = (JSONObject)outArray.get(j);
if(outObj.has("address")) {
_addr = outObj.getString("address");
if(addr.equals(_addr)) {
isIncoming = true;
}
}
if(outObj.has("scriptpubkey")) {
script = outObj.getString("scriptpubkey");
if(script.startsWith("6a4c50")) {
op_return = script;
}
}
}
if(isIncoming && op_return != null && op_return.startsWith("6a4c50")) {
payload = Hex.decode(op_return.substring(6));
}
}
if(mask != null && payload != null) {
try {
byte[] xlat_payload = PaymentCode.blind(payload, mask);
Log.i("APIFactory", "xlat_payload:" + Hex.toHexString(xlat_payload));
pcode = new PaymentCode(xlat_payload);
Log.i("APIFactory", "incoming payment code:" + pcode.toString());
if(!pcode.toString().equals(BIP47Util.getInstance(context).getPaymentCode().toString()) && pcode.isValid() && !BIP47Meta.getInstance().incomingExists(pcode.toString())) {
BIP47Meta.getInstance().setLabel(pcode.toString(), "");
BIP47Meta.getInstance().setIncomingStatus(hash);
}
}
catch(AddressFormatException afe) {
afe.printStackTrace();
}
}
// get receiving addresses for spends from decoded payment code
if(pcode != null) {
try {
// initial lookup
for(int i = 0; i < 3; i++) {
PaymentAddress receiveAddress = BIP47Util.getInstance(context).getReceiveAddress(pcode, i);
// Log.i("APIFactory", "receive from " + i + ":" + receiveAddress.getReceiveECKey().toAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString());
BIP47Meta.getInstance().setIncomingIdx(pcode.toString(), i, receiveAddress.getReceiveECKey().toAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString());
BIP47Meta.getInstance().getIdx4AddrLookup().put(receiveAddress.getReceiveECKey().toAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString(), i);
BIP47Meta.getInstance().getPCode4AddrLookup().put(receiveAddress.getReceiveECKey().toAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString(), pcode.toString());
// Log.i("APIFactory", "send to " + i + ":" + sendAddress.getSendECKey().toAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString());
}
}
catch(Exception e) {
;
}
}
}
}
public synchronized int getNotifTxConfirmations(String hash) {
String _url = SamouraiWallet.getInstance().isTestNet() ? WebUtil.SAMOURAI_API2_TESTNET : WebUtil.SAMOURAI_API2;
// Log.i("APIFactory", "Notif tx:" + hash);
JSONObject jsonObject = null;
try {
StringBuilder url = new StringBuilder(_url);
url.append("tx/");
url.append(hash);
url.append("?fees=1");
// Log.i("APIFactory", "Notif tx:" + url.toString());
String response = WebUtil.getInstance(null).getURL(url.toString());
// Log.i("APIFactory", "Notif tx:" + response);
jsonObject = new JSONObject(response);
// Log.i("APIFactory", "Notif tx json:" + jsonObject.toString());
return parseNotifTx(jsonObject);
}
catch(Exception e) {
jsonObject = null;
e.printStackTrace();
}
return 0;
}
public synchronized int parseNotifTx(JSONObject jsonObject) throws JSONException {
int cf = 0;
if(jsonObject != null && jsonObject.has("block") && jsonObject.getJSONObject("block").has("height")) {
long latestBlockHeght = getLatestBlockHeight();
long height = jsonObject.getJSONObject("block").getLong("height");
cf = (int)((latestBlockHeght - height) + 1);
if(cf < 0) {
cf = 0;
}
}
return cf;
}
public synchronized JSONObject getUnspentOutputs(String[] xpubs) {
String _url = SamouraiWallet.getInstance().isTestNet() ? WebUtil.SAMOURAI_API2_TESTNET : WebUtil.SAMOURAI_API2;
JSONObject jsonObject = null;
try {
String response = null;
if(!TorUtil.getInstance(context).statusFromBroadcast()) {
StringBuilder args = new StringBuilder();
args.append("active=");
args.append(StringUtils.join(xpubs, URLEncoder.encode("|", "UTF-8")));
response = WebUtil.getInstance(context).postURL(_url + "unspent?", args.toString());
}
else {
HashMap<String,String> args = new HashMap<String,String>();
args.put("active", StringUtils.join(xpubs, "|"));
response = WebUtil.getInstance(context).tor_postURL(_url + "unspent", args);
}
parseUnspentOutputs(response);
}
catch(Exception e) {
jsonObject = null;
e.printStackTrace();
}
return jsonObject;
}
private synchronized boolean parseUnspentOutputs(String unspents) {
if(unspents != null) {
try {
JSONObject jsonObj = new JSONObject(unspents);
if(jsonObj == null || !jsonObj.has("unspent_outputs")) {
return false;
}
JSONArray utxoArray = jsonObj.getJSONArray("unspent_outputs");
if(utxoArray == null || utxoArray.length() == 0) {
return false;
}
for (int i = 0; i < utxoArray.length(); i++) {
JSONObject outDict = utxoArray.getJSONObject(i);
byte[] hashBytes = Hex.decode((String)outDict.get("tx_hash"));
Sha256Hash txHash = Sha256Hash.wrap(hashBytes);
int txOutputN = ((Number)outDict.get("tx_output_n")).intValue();
BigInteger value = BigInteger.valueOf(((Number)outDict.get("value")).longValue());
String script = (String)outDict.get("script");
byte[] scriptBytes = Hex.decode(script);
int confirmations = ((Number)outDict.get("confirmations")).intValue();
try {
String address = null;
if(Bech32Util.getInstance().isBech32Script(script)) {
address = Bech32Util.getInstance().getAddressFromScript(script);
Log.d("address parsed:", address);
}
else {
address = new Script(scriptBytes).getToAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString();
}
Log.d("APIFactory", "address:" + address);
if(outDict.has("xpub")) {
JSONObject xpubObj = (JSONObject)outDict.get("xpub");
String path = (String)xpubObj.get("path");
String m = (String)xpubObj.get("m");
unspentPaths.put(address, path);
Log.d("APIFactory", "address:" + address + "," + path);
if(m.equals(BIP49Util.getInstance(context).getWallet().getAccount(0).xpubstr())) {
unspentBIP49.put(address, 0); // assume account 0
}
else if(m.equals(BIP84Util.getInstance(context).getWallet().getAccount(0).xpubstr())) {
unspentBIP84.put(address, 0); // assume account 0
}
else {
unspentAccounts.put(address, AddressFactory.getInstance(context).xpub2account().get(m));
}
}
// Construct the output
MyTransactionOutPoint outPoint = new MyTransactionOutPoint(txHash, txOutputN, value, scriptBytes, address);
outPoint.setConfirmations(confirmations);
if(utxos.containsKey(script)) {
utxos.get(script).getOutpoints().add(outPoint);
}
else {
UTXO utxo = new UTXO();
utxo.getOutpoints().add(outPoint);
utxos.put(script, utxo);
}
if(!BlockedUTXO.getInstance().contains(txHash.toString(), txOutputN)) {
if(Address.fromBase58(SamouraiWallet.getInstance().getCurrentNetworkParams(), address).isP2SHAddress()) {
UTXOFactory.getInstance().addP2SH_P2WPKH(script, utxos.get(script));
}
else {
UTXOFactory.getInstance().addP2PKH(script, utxos.get(script));
}
}
}
catch(Exception e) {
;
}
}
return true;
}
catch(JSONException je) {
;
}
}
return false;
}
public synchronized JSONObject getAddressInfo(String addr) {
return getXPUB(new String[] { addr }, false);
}
public synchronized JSONObject getTxInfo(String hash) {
String _url = SamouraiWallet.getInstance().isTestNet() ? WebUtil.SAMOURAI_API2_TESTNET : WebUtil.SAMOURAI_API2;
JSONObject jsonObject = null;
try {
StringBuilder url = new StringBuilder(_url);
url.append("tx/");
url.append(hash);
url.append("?fees=true");
String response = WebUtil.getInstance(context).getURL(url.toString());
jsonObject = new JSONObject(response);
}
catch(Exception e) {
jsonObject = null;
e.printStackTrace();
}
return jsonObject;
}
public synchronized JSONObject getBlockHeader(String hash) {
String _url = SamouraiWallet.getInstance().isTestNet() ? WebUtil.SAMOURAI_API2_TESTNET : WebUtil.SAMOURAI_API2;
JSONObject jsonObject = null;
try {
StringBuilder url = new StringBuilder(_url);
url.append("header/");
url.append(hash);
String response = WebUtil.getInstance(context).getURL(url.toString());
jsonObject = new JSONObject(response);
}
catch(Exception e) {
jsonObject = null;
e.printStackTrace();
}
return jsonObject;
}
public synchronized JSONObject getDynamicFees() {
JSONObject jsonObject = null;
try {
int sel = PrefsUtil.getInstance(context).getValue(PrefsUtil.FEE_PROVIDER_SEL, 0);
if(sel == 1) {
int[] blocks = new int[] { 2, 6, 24 };
List<SuggestedFee> suggestedFees = new ArrayList<SuggestedFee>();
JSONRPC jsonrpc = new JSONRPC(TrustedNodeUtil.getInstance().getUser(), TrustedNodeUtil.getInstance().getPassword(), TrustedNodeUtil.getInstance().getNode(), TrustedNodeUtil.getInstance().getPort());
for(int i = 0; i < blocks.length; i++) {
JSONObject feeObj = jsonrpc.getFeeEstimate(blocks[i]);
if(feeObj != null && feeObj.has("result")) {
double fee = feeObj.getDouble("result");
SuggestedFee suggestedFee = new SuggestedFee();
suggestedFee.setDefaultPerKB(BigInteger.valueOf((long)(fee * 1e8)));
suggestedFee.setStressed(false);
suggestedFee.setOK(true);
suggestedFees.add(suggestedFee);
}
}
if(suggestedFees.size() > 0) {
FeeUtil.getInstance().setEstimatedFees(suggestedFees);
}
}
else {
StringBuilder url = new StringBuilder(WebUtil.BITCOIND_FEE_URL);
// Log.i("APIFactory", "Dynamic fees:" + url.toString());
String response = WebUtil.getInstance(null).getURL(url.toString());
// Log.i("APIFactory", "Dynamic fees response:" + response);
try {
jsonObject = new JSONObject(response);
parseDynamicFees_bitcoind(jsonObject);
}
catch(JSONException je) {
je.printStackTrace();
jsonObject = null;
}
}
}
catch(Exception e) {
jsonObject = null;
e.printStackTrace();
}
return jsonObject;
}
private synchronized boolean parseDynamicFees_bitcoind(JSONObject jsonObject) throws JSONException {
if(jsonObject != null) {
// bitcoind
List<SuggestedFee> suggestedFees = new ArrayList<SuggestedFee>();
if(jsonObject.has("2")) {
long fee = jsonObject.getInt("2");
SuggestedFee suggestedFee = new SuggestedFee();
suggestedFee.setDefaultPerKB(BigInteger.valueOf(fee * 1000L));
suggestedFee.setStressed(false);
suggestedFee.setOK(true);
suggestedFees.add(suggestedFee);
}
if(jsonObject.has("6")) {
long fee = jsonObject.getInt("6");
SuggestedFee suggestedFee = new SuggestedFee();
suggestedFee.setDefaultPerKB(BigInteger.valueOf(fee * 1000L));
suggestedFee.setStressed(false);
suggestedFee.setOK(true);
suggestedFees.add(suggestedFee);
}
if(jsonObject.has("24")) {
long fee = jsonObject.getInt("24");
SuggestedFee suggestedFee = new SuggestedFee();
suggestedFee.setDefaultPerKB(BigInteger.valueOf(fee * 1000L));
suggestedFee.setStressed(false);
suggestedFee.setOK(true);
suggestedFees.add(suggestedFee);
}
if(suggestedFees.size() > 0) {
FeeUtil.getInstance().setEstimatedFees(suggestedFees);
// Log.d("APIFactory", "high fee:" + FeeUtil.getInstance().getHighFee().getDefaultPerKB().toString());
// Log.d("APIFactory", "suggested fee:" + FeeUtil.getInstance().getSuggestedFee().getDefaultPerKB().toString());
// Log.d("APIFactory", "low fee:" + FeeUtil.getInstance().getLowFee().getDefaultPerKB().toString());
}
return true;
}
return false;
}
public synchronized void validateAPIThread() {
final Handler handler = new Handler();
new Thread(new Runnable() {
@Override
public void run() {
Looper.prepare();
if(ConnectivityStatus.hasConnectivity(context)) {
try {
String response = WebUtil.getInstance(context).getURL(WebUtil.SAMOURAI_API_CHECK);
JSONObject jsonObject = new JSONObject(response);
if(!jsonObject.has("process")) {
showAlertDialog(context.getString(R.string.api_error), false);
}
}
catch(Exception e) {
showAlertDialog(context.getString(R.string.cannot_reach_api), false);
}
} else {
showAlertDialog(context.getString(R.string.no_internet), false);
}
handler.post(new Runnable() {
@Override
public void run() {
;
}
});
Looper.loop();
}
}).start();
}
private void showAlertDialog(final String message, final boolean forceExit){
if (!((Activity) context).isFinishing()) {
if(alertDialog != null)alertDialog.dismiss();
final AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage(message);
builder.setCancelable(false);
if(!forceExit) {
builder.setPositiveButton(R.string.retry,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface d, int id) {
d.dismiss();
//Retry
validateAPIThread();
}
});
}
builder.setNegativeButton(R.string.exit,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface d, int id) {
d.dismiss();
((Activity) context).finish();
}
});
alertDialog = builder.create();
alertDialog.show();
}
}
public synchronized void initWallet() {
Log.i("APIFactory", "initWallet()");
initWalletAmounts();
}
private synchronized void initWalletAmounts() {
APIFactory.getInstance(context).reset();
List<String> addressStrings = new ArrayList<String>();
String[] s = null;
try {
/*
if(PrefsUtil.getInstance(context).getValue(PrefsUtil.XPUB44REG, false) == false) {
registerXPUB(HD_WalletFactory.getInstance(context).get().getAccount(0).xpubstr(), false);
}
*/
if(PrefsUtil.getInstance(context).getValue(PrefsUtil.XPUB49REG, false) == false) {
registerXPUB(BIP49Util.getInstance(context).getWallet().getAccount(0).xpubstr(), 49);
}
if(PrefsUtil.getInstance(context).getValue(PrefsUtil.XPUB84REG, false) == false) {
registerXPUB(BIP84Util.getInstance(context).getWallet().getAccount(0).xpubstr(), 84);
}
xpub_txs.put(HD_WalletFactory.getInstance(context).get().getAccount(0).xpubstr(), new ArrayList<Tx>());
addressStrings.addAll(Arrays.asList(BIP47Meta.getInstance().getIncomingAddresses(false)));
for(String _s : Arrays.asList(BIP47Meta.getInstance().getIncomingLookAhead(context))) {
if(!addressStrings.contains(_s)) {
addressStrings.add(_s);
}
}
for(String pcode : BIP47Meta.getInstance().getUnspentProviders()) {
for(String addr : BIP47Meta.getInstance().getUnspentAddresses(context, pcode)) {
if(!addressStrings.contains(addr)) {
addressStrings.add(addr);
}
}
}
if(addressStrings.size() > 0) {
s = addressStrings.toArray(new String[0]);
// Log.i("APIFactory", addressStrings.toString());
getUnspentOutputs(s);
}
Log.d("APIFactory", "addresses:" + addressStrings.toString());
HD_Wallet hdw = HD_WalletFactory.getInstance(context).get();
if(hdw != null && hdw.getXPUBs() != null) {
String[] all = null;
if(s != null && s.length > 0) {
all = new String[hdw.getXPUBs().length + 2 + s.length];
all[0] = BIP49Util.getInstance(context).getWallet().getAccount(0).xpubstr();
all[1] = BIP84Util.getInstance(context).getWallet().getAccount(0).xpubstr();
System.arraycopy(hdw.getXPUBs(), 0, all, 2, hdw.getXPUBs().length);
System.arraycopy(s, 0, all, hdw.getXPUBs().length + 2, s.length);
}
else {
all = new String[hdw.getXPUBs().length + 2];
all[0] = BIP49Util.getInstance(context).getWallet().getAccount(0).xpubstr();
all[1] = BIP84Util.getInstance(context).getWallet().getAccount(0).xpubstr();
System.arraycopy(hdw.getXPUBs(), 0, all, 2, hdw.getXPUBs().length);
}
APIFactory.getInstance(context).getXPUB(all, true);
String[] xs = new String[4];
xs[0] = HD_WalletFactory.getInstance(context).get().getAccount(0).xpubstr();
xs[1] = HD_WalletFactory.getInstance(context).get().getAccount(1).xpubstr();
xs[2] = BIP49Util.getInstance(context).getWallet().getAccount(0).xpubstr();
xs[3] = BIP84Util.getInstance(context).getWallet().getAccount(0).xpubstr();
getUnspentOutputs(xs);
getDynamicFees();
}
List<String> seenOutputs = new ArrayList<String>();
List<UTXO> _utxos = getUtxos(false);
for(UTXO _u : _utxos) {
for(MyTransactionOutPoint _o : _u.getOutpoints()) {
seenOutputs.add(_o.getTxHash().toString() + "-" + _o.getTxOutputN());
}
}
for(String _s : BlockedUTXO.getInstance().getNotDustedUTXO()) {
Log.d("APIFactory", "not dusted:" + _s);
if(!seenOutputs.contains(_s)) {
BlockedUTXO.getInstance().removeNotDusted(_s);
Log.d("APIFactory", "not dusted removed:" + _s);
}
}
for(String _s : BlockedUTXO.getInstance().getBlockedUTXO().keySet()) {
Log.d("APIFactory", "blocked:" + _s);
if(!seenOutputs.contains(_s)) {
BlockedUTXO.getInstance().remove(_s);
Log.d("APIFactory", "blocked removed:" + _s);
}
}
}
catch (IndexOutOfBoundsException ioobe) {
ioobe.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();
}
}
public synchronized int syncBIP47Incoming(String[] addresses) {
JSONObject jsonObject = getXPUB(addresses, false);
int ret = 0;
try {
if(jsonObject != null && jsonObject.has("addresses")) {
JSONArray addressArray = (JSONArray)jsonObject.get("addresses");
JSONObject addrObj = null;
for(int i = 0; i < addressArray.length(); i++) {
addrObj = (JSONObject)addressArray.get(i);
long amount = 0L;
int nbTx = 0;
String addr = null;
String pcode = null;
int idx = -1;
if(addrObj.has("address")) {
addr = (String)addrObj.get("address");
pcode = BIP47Meta.getInstance().getPCode4Addr(addr);
idx = BIP47Meta.getInstance().getIdx4Addr(addr);
if(addrObj.has("final_balance")) {
amount = addrObj.getLong("final_balance");
if(amount > 0L) {
BIP47Meta.getInstance().addUnspent(pcode, idx);
}
else {
BIP47Meta.getInstance().removeUnspent(pcode, Integer.valueOf(idx));
}
}
if(addrObj.has("n_tx")) {
nbTx = addrObj.getInt("n_tx");
if(nbTx > 0) {
// Log.i("APIFactory", "sync receive idx:" + idx + ", " + addr);
ret++;
}
}
}
}
}
}
catch(Exception e) {
jsonObject = null;
e.printStackTrace();
}
return ret;
}
public synchronized int syncBIP47Outgoing(String[] addresses) {
JSONObject jsonObject = getXPUB(addresses, false);
int ret = 0;
try {
if(jsonObject != null && jsonObject.has("addresses")) {
JSONArray addressArray = (JSONArray)jsonObject.get("addresses");
JSONObject addrObj = null;
for(int i = 0; i < addressArray.length(); i++) {
addrObj = (JSONObject)addressArray.get(i);
int nbTx = 0;
String addr = null;
String pcode = null;
int idx = -1;
if(addrObj.has("address")) {
addr = (String)addrObj.get("address");
pcode = BIP47Meta.getInstance().getPCode4Addr(addr);
idx = BIP47Meta.getInstance().getIdx4Addr(addr);
if(addrObj.has("n_tx")) {
nbTx = addrObj.getInt("n_tx");
if(nbTx > 0) {
int stored = BIP47Meta.getInstance().getOutgoingIdx(pcode);
if(idx >= stored) {
// Log.i("APIFactory", "sync send idx:" + idx + ", " + addr);
BIP47Meta.getInstance().setOutgoingIdx(pcode, idx + 1);
}
ret++;
}
}
}
}
}
}
catch(Exception e) {
jsonObject = null;
e.printStackTrace();
}
return ret;
}
public long getXpubBalance() {
return xpub_balance - BlockedUTXO.getInstance().getTotalValueBlocked();
}
public void setXpubBalance(long value) {
xpub_balance = value;
}
public HashMap<String,Long> getXpubAmounts() {
return xpub_amounts;
}
public HashMap<String,List<Tx>> getXpubTxs() {
return xpub_txs;
}
public HashMap<String, String> getUnspentPaths() {
return unspentPaths;
}
public HashMap<String, Integer> getUnspentAccounts() {
return unspentAccounts;
}
public HashMap<String, Integer> getUnspentBIP49() {
return unspentBIP49;
}
public HashMap<String, Integer> getUnspentBIP84() {
return unspentBIP84;
}
public List<UTXO> getUtxos(boolean filter) {
List<UTXO> unspents = new ArrayList<UTXO>();
if(filter) {
for(String key : utxos.keySet()) {
UTXO u = new UTXO();
for(MyTransactionOutPoint out : utxos.get(key).getOutpoints()) {
if(!BlockedUTXO.getInstance().contains(out.getTxHash().toString(), out.getTxOutputN())) {
u.getOutpoints().add(out);
}
}
if(u.getOutpoints().size() > 0) {
unspents.add(u);
}
}
}
else {
unspents.addAll(utxos.values());
}
return unspents;
}
public void setUtxos(HashMap<String, UTXO> utxos) {
APIFactory.utxos = utxos;
}
public synchronized List<Tx> getAllXpubTxs() {
List<Tx> ret = new ArrayList<Tx>();
for(String key : xpub_txs.keySet()) {
List<Tx> txs = xpub_txs.get(key);
for(Tx tx : txs) {
ret.add(tx);
}
}
Collections.sort(ret, new TxMostRecentDateComparator());
return ret;
}
public synchronized UTXO getUnspentOutputsForSweep(String address) {
String _url = SamouraiWallet.getInstance().isTestNet() ? WebUtil.SAMOURAI_API2_TESTNET : WebUtil.SAMOURAI_API2;
try {
String response = null;
if(!TorUtil.getInstance(context).statusFromBroadcast()) {
StringBuilder args = new StringBuilder();
args.append("active=");
args.append(address);
// Log.d("APIFactory", args.toString());
response = WebUtil.getInstance(context).postURL(_url + "unspent?", args.toString());
// Log.d("APIFactory", response);
}
else {
HashMap<String,String> args = new HashMap<String,String>();
args.put("active", address);
// Log.d("APIFactory", args.toString());
response = WebUtil.getInstance(context).tor_postURL(_url + "unspent", args);
// Log.d("APIFactory", response);
}
return parseUnspentOutputsForSweep(response);
}
catch(Exception e) {
e.printStackTrace();
}
return null;
}
private synchronized UTXO parseUnspentOutputsForSweep(String unspents) {
UTXO utxo = null;
if(unspents != null) {
try {
JSONObject jsonObj = new JSONObject(unspents);
if(jsonObj == null || !jsonObj.has("unspent_outputs")) {
return null;
}
JSONArray utxoArray = jsonObj.getJSONArray("unspent_outputs");
if(utxoArray == null || utxoArray.length() == 0) {
return null;
}
// Log.d("APIFactory", "unspents found:" + outputsRoot.size());
for (int i = 0; i < utxoArray.length(); i++) {
JSONObject outDict = utxoArray.getJSONObject(i);
byte[] hashBytes = Hex.decode((String)outDict.get("tx_hash"));
Sha256Hash txHash = Sha256Hash.wrap(hashBytes);
int txOutputN = ((Number)outDict.get("tx_output_n")).intValue();
BigInteger value = BigInteger.valueOf(((Number)outDict.get("value")).longValue());
String script = (String)outDict.get("script");
byte[] scriptBytes = Hex.decode(script);
int confirmations = ((Number)outDict.get("confirmations")).intValue();
try {
String address = null;
if(Bech32Util.getInstance().isBech32Script(script)) {
address = Bech32Util.getInstance().getAddressFromScript(script);
Log.d("address parsed:", address);
}
else {
address = new Script(scriptBytes).getToAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString();
}
// Construct the output
MyTransactionOutPoint outPoint = new MyTransactionOutPoint(txHash, txOutputN, value, scriptBytes, address);
outPoint.setConfirmations(confirmations);
if(utxo == null) {
utxo = new UTXO();
}
utxo.getOutpoints().add(outPoint);
}
catch(Exception e) {
;
}
}
}
catch(JSONException je) {
;
}
}
return utxo;
}
public static class TxMostRecentDateComparator implements Comparator<Tx> {
public int compare(Tx t1, Tx t2) {
final int BEFORE = -1;
final int EQUAL = 0;
final int AFTER = 1;
int ret = 0;
if(t1.getTS() > t2.getTS()) {
ret = BEFORE;
}
else if(t1.getTS() < t2.getTS()) {
ret = AFTER;
}
else {
ret = EQUAL;
}
return ret;
}
}
}
|
package de.danoeh.antennapodsp.fragment;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.*;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.ListFragment;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import de.danoeh.antennapodsp.AppConfig;
import de.danoeh.antennapodsp.R;
import de.danoeh.antennapodsp.adapter.EpisodesListAdapter;
import de.danoeh.antennapodsp.asynctask.DownloadObserver;
import de.danoeh.antennapodsp.dialog.DownloadRequestErrorDialogCreator;
import de.danoeh.antennapodsp.feed.EventDistributor;
import de.danoeh.antennapodsp.feed.Feed;
import de.danoeh.antennapodsp.feed.FeedItem;
import de.danoeh.antennapodsp.feed.FeedMedia;
import de.danoeh.antennapodsp.service.download.Downloader;
import de.danoeh.antennapodsp.service.playback.PlaybackService;
import de.danoeh.antennapodsp.service.playback.PlayerStatus;
import de.danoeh.antennapodsp.storage.DBReader;
import de.danoeh.antennapodsp.storage.DBTasks;
import de.danoeh.antennapodsp.storage.DownloadRequestException;
import de.danoeh.antennapodsp.storage.DownloadRequester;
import org.apache.commons.lang3.StringUtils;
import java.util.List;
public class EpisodesFragment extends ListFragment {
private static final String TAG = "EpisodesFragment";
private static final String ARG_FEED_ID = "feedID";
private static final int EVENTS = EventDistributor.QUEUE_UPDATE
| EventDistributor.UNREAD_ITEMS_UPDATE
| EventDistributor.FEED_LIST_UPDATE
| EventDistributor.DOWNLOAD_HANDLED;
private Feed feed;
private EpisodesListAdapter episodesListAdapter;
private AsyncTask currentLoadTask = null;
private DownloadObserver downloadObserver = null;
private List<Downloader> downloaderList = null;
private boolean feedsLoaded = false;
private boolean listviewSetup = false;
public static EpisodesFragment newInstance(long feedID) {
EpisodesFragment f = new EpisodesFragment();
Bundle b = new Bundle();
b.putLong(ARG_FEED_ID, feedID);
f.setArguments(b);
return f;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
refreshFeed();
}
private void refreshFeed() {
AsyncTask<Void, Void, Feed> loadTask = new AsyncTask<Void, Void, Feed>() {
volatile long feedID;
@Override
protected void onPreExecute() {
super.onPreExecute();
feedID = getArguments().getLong(ARG_FEED_ID);
}
@Override
protected void onPostExecute(Feed result) {
super.onPostExecute(result);
if (result != null) {
onFeedLoaded(result);
}
}
@Override
protected Feed doInBackground(Void... params) {
Context context = getActivity();
if (context != null) {
return DBReader.getFeed(getActivity(), feedID);
} else {
return null;
}
}
};
loadTask.execute();
currentLoadTask = loadTask;
}
private void onFeedLoaded(Feed result) {
feed = result;
if (feedsLoaded && listviewSetup) {
// feed has only been refreshed
episodesListAdapter.notifyDataSetChanged();
} else {
EventDistributor.getInstance().register(contentUpdateListener);
downloadObserver = new DownloadObserver(getActivity(), new Handler(),
downloadObserverCallback);
downloadObserver.onResume();
feedsLoaded = true;
if (getListView() != null && !listviewSetup) {
setupListView();
}
}
}
private void setupListView() {
setListShown(true);
if (episodesListAdapter == null) {
episodesListAdapter = new EpisodesListAdapter(getActivity(), itemAccess);
getListView().setAdapter(episodesListAdapter);
}
listviewSetup = true;
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (feedsLoaded) {
downloadObserver.setActivity(activity);
downloadObserver.onResume();
}
if (listviewSetup) {
episodesListAdapter.notifyDataSetChanged();
}
EventDistributor.getInstance().register(contentUpdateListener);
activity.registerReceiver(playerStatusReceiver, new IntentFilter(PlaybackService.ACTION_PLAYER_STATUS_CHANGED));
}
@Override
public void onDetach() {
super.onDetach();
if (feedsLoaded) {
downloadObserver.onPause();
}
EventDistributor.getInstance().unregister(contentUpdateListener);
try {
getActivity().unregisterReceiver(playerStatusReceiver);
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
}
@Override
public void onDestroyView() {
super.onDestroyView();
currentLoadTask.cancel(true);
try {
getActivity().unregisterReceiver(playerStatusReceiver);
} catch (IllegalArgumentException e) {
if (AppConfig.DEBUG) e.printStackTrace();
}
listviewSetup = false;
episodesListAdapter = null;
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getListView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
position = position - getListView().getHeaderViewsCount();
if (position < 0) {
return;
}
final FeedItem item = (FeedItem) episodesListAdapter.getItem(position);
if (item.hasMedia() && item.getMedia().isDownloaded()) {
// episode downloaded
DBTasks.playMedia(getActivity(), item.getMedia(), false, true, false);
} else if (item.hasMedia()) {
final FeedMedia media = item.getMedia();
AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity());
dialog.setCancelable(true)
.setTitle(media.getEpisodeTitle());
if (DownloadRequester.getInstance().isDownloadingFile(media)) {
// episode downloading
dialog.setMessage(R.string.episode_dialog_downloading_msg)
.setNeutralButton(R.string.cancel_download_label, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
DownloadRequester.getInstance().cancelDownload(getActivity(), media);
}
});
dialog.create().show();
} else {
// episode not downloaded
try {
DBTasks.downloadFeedItems(getActivity(), item);
} catch (DownloadRequestException e) {
e.printStackTrace();
DownloadRequestErrorDialogCreator.newRequestErrorDialog(getActivity(), e.getMessage());
}
}
}
}
});
// add header so that list is below actionbar
int actionBarHeight = getResources().getDimensionPixelSize(android.support.v7.appcompat.R.dimen.abc_action_bar_default_height);
LinearLayout header = new LinearLayout(getActivity());
header.setOrientation(LinearLayout.HORIZONTAL);
AbsListView.LayoutParams lp = new AbsListView.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, actionBarHeight);
header.setLayoutParams(lp);
getListView().addHeaderView(header);
if (feedsLoaded) {
setupListView();
} else {
setListShown(false);
}
}
private final EpisodesListAdapter.ItemAccess itemAccess = new EpisodesListAdapter.ItemAccess() {
@Override
public int getCount() {
return (feed != null) ? feed.getItems().size() : 0;
}
@Override
public FeedItem getItem(int position) {
return (feed != null) ? feed.getItems().get(position) : null;
}
@Override
public int getItemDownloadProgressPercent(FeedItem item) {
if (downloaderList != null) {
for (Downloader downloader : downloaderList) {
if (downloader.getDownloadRequest().getFeedfileType() == FeedMedia.FEEDFILETYPE_FEEDMEDIA
&& downloader.getDownloadRequest().getFeedfileId() == item.getMedia().getId()) {
return downloader.getDownloadRequest().getProgressPercent();
}
}
}
return 0;
}
};
private final DownloadObserver.Callback downloadObserverCallback = new DownloadObserver.Callback() {
@Override
public void onContentChanged() {
if (episodesListAdapter != null) {
episodesListAdapter.notifyDataSetChanged();
}
}
@Override
public void onDownloadDataAvailable(List<Downloader> downloaderList) {
EpisodesFragment.this.downloaderList = downloaderList;
if (episodesListAdapter != null) {
episodesListAdapter.notifyDataSetChanged();
}
}
};
private final EventDistributor.EventListener contentUpdateListener = new EventDistributor.EventListener() {
@Override
public void update(EventDistributor eventDistributor, Integer arg) {
if ((arg & EVENTS) != 0) {
if (listviewSetup) {
refreshFeed();
episodesListAdapter.notifyDataSetChanged();
}
}
}
};
private final BroadcastReceiver playerStatusReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (StringUtils.equals(intent.getAction(), PlaybackService.ACTION_PLAYER_STATUS_CHANGED)) {
int statusOrdinal = intent.getIntExtra(PlaybackService.EXTRA_NEW_PLAYER_STATUS, -1);
if (statusOrdinal != -1) {
if (PlayerStatus.fromOrdinal(statusOrdinal) == PlayerStatus.INITIALIZED) {
if (episodesListAdapter != null) {
episodesListAdapter.notifyDataSetChanged();
}
}
}
}
}
};
}
|
package com.tableview.storage;
import com.tableview.storage.models.CellType;
import com.tableview.storage.models.RowModel;
import java.util.HashMap;
import java.util.LinkedHashMap;
public class CellTypeUtil {
public CellType getModelType(int viewType) {
Class aClass = this.rowTypes.get(Integer.valueOf(viewType));
int layResId = this.modelTypes.get(aClass).intValue();
return new CellType(aClass, layResId);
}
/**
* HashMap:
* key: cell's type, also is viewType.
* value: cell's class.
*/
private HashMap<Integer, Class> rowTypes = new LinkedHashMap<>();
private HashMap<Class, Integer> modelTypes = new LinkedHashMap<>();
public void registerType(CellType type) {
this.modelTypes.put(type.cellClazz, type.layoutResId);
if (this.isExistRegisterType(type.cellClazz) == false) {
this.rowTypes.put(this.rowTypes.size(), type.cellClazz);
}
}
public int getRowModelType(RowModel rowModel) {
for (Integer index : this.rowTypes.keySet()) {
Class clazz = this.rowTypes.get(index);
if (clazz == null)
throw new NullPointerException("Not found class called "+clazz.getName());
CellType cellType = rowModel.cellType;
if (cellType == null)
throw new NullPointerException("Not found cellType called ");
if (cellType.cellClazz.equals(clazz))
return index.intValue();
}
return 0;
}
private boolean isExistRegisterType(Class aClass) {
for (Integer index : this.rowTypes.keySet()) {
Class clazz = this.rowTypes.get(index);
if (aClass.equals(clazz))
return true;
}
return false;
}
}
|
package com.percero.agents.sync.access;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.concurrent.TimeUnit;
import com.percero.framework.vo.IPerceroObject;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import com.percero.agents.auth.services.IAuthService;
import com.percero.agents.sync.cw.ChangeWatcherReporting;
import com.percero.agents.sync.cw.IChangeWatcherHelper;
import com.percero.agents.sync.cw.IChangeWatcherHelperFactory;
import com.percero.agents.sync.datastore.ICacheDataStore;
import com.percero.agents.sync.exceptions.ClientException;
import com.percero.agents.sync.helpers.RedisPostClientHelper;
import com.percero.agents.sync.services.IPushSyncHelper;
import com.percero.agents.sync.vo.ClassIDPair;
import com.percero.agents.sync.vo.Client;
@Component
public class RedisAccessManager implements IAccessManager {
private static Logger log = Logger.getLogger(RedisAccessManager.class);
// TODO: Remove all AccessJournal objects for a User after they have been inactive for some amount of time.
// What should that amount of time be?...
public RedisAccessManager() {
}
@Autowired
IAuthService authService;
@Autowired
protected IChangeWatcherHelperFactory changeWatcherHelperFactory;
public void setChangeWatcherHelperFactory(IChangeWatcherHelperFactory value) {
changeWatcherHelperFactory = value;
}
@Autowired
protected Long userDeviceTimeout = Long.valueOf(60 * 60 * 24 * 14); // Two weeks
public void setUserDeviceTimeout(Long value) {
userDeviceTimeout = value;
}
@Autowired @Qualifier("executorWithCallerRunsPolicy")
protected TaskExecutor taskExecutor;
public void setTaskExecutor(TaskExecutor value) {
taskExecutor = value;
}
@Autowired
protected RedisPostClientHelper postClientHelper;
public void setPostClientHelper(RedisPostClientHelper value) {
postClientHelper = value;
}
//@Autowired
//MongoOperations mongoOperations;
@Autowired
ICacheDataStore cacheDataStore;
public void setCacheDataStore(ICacheDataStore cacheDataStore) {
this.cacheDataStore = cacheDataStore;
}
@Autowired
Boolean useChangeWatcherQueue = false;
public void setUseChangeWatcherQueue(Boolean useChangeWatcherQueue) {
this.useChangeWatcherQueue = useChangeWatcherQueue;
}
@Autowired
String changeWatcherRouteName;
public void setChangeWatcherRouteName(String changeWatcherRouteName) {
this.changeWatcherRouteName = changeWatcherRouteName;
}
@Autowired
IPushSyncHelper pushSyncHelper;
public void setPushSyncHelper(IPushSyncHelper pushSyncHelper) {
this.pushSyncHelper = pushSyncHelper;
}
/* (non-Javadoc)
* @see com.com.percero.agents.sync.services.IAccessManager#createClient(java.lang.String, java.lang.Integer, java.lang.String)
*/
public void createClient(String clientId, String userId, String deviceType, String deviceId) throws Exception {
String clientUserKey = RedisKeyUtils.clientUser(userId);
cacheDataStore.addSetValue(clientUserKey, clientId);
if (StringUtils.hasText(deviceId)) {
String userDeviceKey = RedisKeyUtils.userDeviceHash(userId);
cacheDataStore.setHashValue(userDeviceKey, deviceId, clientId);
String deviceKey = RedisKeyUtils.deviceHash(deviceId);
cacheDataStore.addSetValue(deviceKey, clientId);
}
// Set the client's userId.
cacheDataStore.setValue(RedisKeyUtils.client(clientId), userId);
// Add to ClientUser list
cacheDataStore.addSetValue(clientUserKey, clientId);
if (Client.PERSISTENT_TYPE.equalsIgnoreCase(deviceType)) {
cacheDataStore.addSetValue(RedisKeyUtils.clientsPersistent(), clientId);
}
else {
cacheDataStore.addSetValue(RedisKeyUtils.clientsNonPersistent(), clientId);
}
}
public Boolean isNonPersistentClient(String clientId) {
return cacheDataStore.getSetIsMember(RedisKeyUtils.clientsNonPersistent(), clientId);
}
public String getClientUserId(String clientId) {
return (String) cacheDataStore.getValue(RedisKeyUtils.client(clientId));
}
public Boolean findClientByClientIdUserId(String clientId, String userId) throws Exception {
return cacheDataStore.getSetIsMember(RedisKeyUtils.clientUser(userId), clientId);
}
@SuppressWarnings("unchecked")
public Set<String> findClientByUserIdDeviceId(String userId, String deviceId) throws Exception {
Set<String> deviceClientIds = (Set<String>) cacheDataStore.getSetValue(RedisKeyUtils.deviceHash(deviceId));
if (deviceClientIds == null) {
deviceClientIds = new HashSet<String>(1);
}
String result = (String) cacheDataStore.getHashValue(RedisKeyUtils.userDeviceHash(userId), deviceId);
if (!StringUtils.hasText(result)) {
deviceClientIds.add(result);
}
return deviceClientIds;
// return (String) redisDataStore.getHashValue(RedisKeyUtils.userDeviceHash(userId), deviceId);
}
public Boolean findClientByClientId(String clientId) {
if (cacheDataStore.getSetIsMember(RedisKeyUtils.clientsPersistent(), clientId))
return true;
else if (cacheDataStore.getSetIsMember(RedisKeyUtils.clientsNonPersistent(), clientId))
return true;
else
return false;
}
public Boolean validateClientByClientId(String clientId) {
return validateClientByClientId(clientId, true);
}
public Boolean validateClientByClientId(String clientId, Boolean setClientTimeouts) {
if (findClientByClientId(clientId)) {
if (setClientTimeouts) {
postClient(clientId);
}
return true;
}
else
return false;
}
private static final Set<String> CLIENT_KEYS_SET = new HashSet<String>(2);
static {
CLIENT_KEYS_SET.add(RedisKeyUtils.clientsPersistent());
CLIENT_KEYS_SET.add(RedisKeyUtils.clientsNonPersistent());
}
@SuppressWarnings("unchecked")
public Set<String> validateClients(Collection<String> clientIds) throws Exception {
Set<String> validClients = (Set<String>) cacheDataStore.getSetsContainsMembers(CLIENT_KEYS_SET, clientIds.toArray());
return validClients;
}
@SuppressWarnings("unchecked")
public Set<String> validateClientsIncludeFromDeviceHistory(Map<String, String> clientDevices) throws Exception {
Set<String> validClients = (Set<String>) cacheDataStore.getSetsContainsMembers(CLIENT_KEYS_SET, clientDevices.keySet().toArray());
// Now check each device to see if it has a corresponding clientId.
Iterator<Map.Entry<String, String>> itrClientDevices = clientDevices.entrySet().iterator();
while (itrClientDevices.hasNext()) {
Map.Entry<String, String> nextClientDevice = itrClientDevices.next();
String nextClient = nextClientDevice.getKey();
String nextDevice = nextClientDevice.getValue();
if (cacheDataStore.getSetIsMember(RedisKeyUtils.deviceHash(nextDevice), nextClient)) {
validClients.add(nextClient);
}
}
return validClients;
}
@SuppressWarnings("unchecked")
public String validateAndRetrieveCurrentClientId(String clientId, String deviceId) {
if (validateClientByClientId(clientId)) {
// Client is both Valid AND Current.
return clientId;
}
else {
// Client is NOT current, but could still be valid.
if (cacheDataStore.getSetIsMember(RedisKeyUtils.deviceHash(deviceId), clientId)) {
// Client IS valid, now get current Client.
Set<String> validDeviceClientIds = (Set<String>) cacheDataStore.getSetValue(RedisKeyUtils.deviceHash(deviceId));
Iterator<String> itrValidDeviceClientIds = validDeviceClientIds.iterator();
while (itrValidDeviceClientIds.hasNext()) {
String nextClientId = itrValidDeviceClientIds.next();
if (validateClientByClientId(nextClientId)) {
// Found ClientID that is both Valid AND Current.
return nextClientId;
}
}
// If we have gotten here then there is NO current and valid ClientId.
}
return null;
}
}
/* (non-Javadoc)
* @see com.com.percero.agents.sync.services.IAccessManager#registerClient(java.lang.String, java.lang.Integer)
*/
public void registerClient(String clientId, String userId, String deviceId) throws Exception {
registerClient(clientId, userId, deviceId, null);
}
/* (non-Javadoc)
* @see com.com.percero.agents.sync.services.IAccessManager#registerClient(java.lang.String, java.lang.Integer)
*/
public void registerClient(String clientId, String userId, String deviceId, String deviceType) throws Exception {
Boolean isValidClient = findClientByClientIdUserId(clientId, userId);
if (!isValidClient)
createClient(clientId, userId, deviceType, deviceId);
cacheDataStore.addSetValue(RedisKeyUtils.clientsLoggedIn(), clientId);
cacheDataStore.deleteHashKey(RedisKeyUtils.clientsHibernated(), clientId);
postClient(clientId);
}
/* (non-Javadoc)
* @see com.com.percero.agents.sync.access.IAccessManager#hibernateClient(java.lang.String, java.lang.String)
*/
// TODO: Is it possible for this to get hit out of order and inadvertantly hibernate a client that has already logged back in?
public Boolean hibernateClient(String clientId, String userId) throws Exception {
// Make sure this client/user combo is a valid one.
if (findClientByClientIdUserId(clientId, userId)) {
// Remove the client from the LoggedIn list and add it to the Hibernated list.
cacheDataStore.setHashValue(RedisKeyUtils.clientsHibernated(), clientId, System.currentTimeMillis());
cacheDataStore.removeSetValue(RedisKeyUtils.clientsLoggedIn(), clientId);
// NOTE: The client is still in either the "client persistent" or "client non-persistent" list and
// is therefore still considered a valid client.
postClient(clientId);
return true;
}
else {
return false;
}
}
public Boolean upgradeClient(String clientId, String deviceId, String deviceType, String userId) throws Exception {
Boolean result = false;
// Make sure this is a valid client.
Boolean isValidClient = findClientByClientIdUserId(clientId, userId);
if (!isValidClient)
throw new ClientException(ClientException.INVALID_CLIENT, ClientException.INVALID_CLIENT_CODE);
Set<String> previousClientIds = null;
if (deviceId != null && deviceId.length() > 0) {
previousClientIds = findClientByUserIdDeviceId(userId, deviceId);
}
if (StringUtils.hasText(clientId)) {
try {
// Remove from NonPersistent list.
cacheDataStore.removeSetValue(RedisKeyUtils.clientsNonPersistent(), clientId);
// Add to Persistent List.
cacheDataStore.addSetValue(RedisKeyUtils.clientsPersistent(), clientId);
// Add to LoggedIn list
cacheDataStore.addSetValue(RedisKeyUtils.clientsLoggedIn(), clientId);
// Remove from Hibernated list
cacheDataStore.deleteHashKey(RedisKeyUtils.clientsHibernated(), clientId);
if (previousClientIds != null && !previousClientIds.isEmpty()) {
Iterator<String> itrPreviousClientIds = previousClientIds.iterator();
while (itrPreviousClientIds.hasNext()) {
String nextPreviousClient = itrPreviousClientIds.next();
if (StringUtils.hasText(nextPreviousClient) && nextPreviousClient.equals(clientId)) {
// Remove from NonPersistent list.
cacheDataStore.removeSetValue(RedisKeyUtils.clientsNonPersistent(), nextPreviousClient);
renameClient(nextPreviousClient, clientId);
}
}
}
else {
// Add to ClientUser list
cacheDataStore.addSetValue(RedisKeyUtils.clientUser(userId), clientId);
}
result = true;
} catch(Exception e) {
log.error("Error upgrading client " + clientId + ", user " + userId, e);
result = false;
}
}
return result;
}
@SuppressWarnings("unchecked")
public void renameClient(String thePreviousClient, String clientId) {
if (thePreviousClient == null || clientId == null) {
return;
}
else if (thePreviousClient.equals(clientId)) {
return;
}
// Get the existing UserId.
String userId = (String) cacheDataStore.getValue(RedisKeyUtils.client(thePreviousClient));
log.debug("Renaming client " + thePreviousClient + " to " + clientId);
if (StringUtils.hasText(userId)) {
log.debug("Renaming user " + userId + " from client " + thePreviousClient + " to " + clientId);
// Remove Previous Client from ClientUser list
cacheDataStore.removeSetValue(RedisKeyUtils.clientUser(userId), thePreviousClient);
// Add to ClientUser list
cacheDataStore.addSetValue(RedisKeyUtils.clientUser(userId), clientId);
// Update the UserDevice ClientID.
String userDeviceHashKey = RedisKeyUtils.userDeviceHash(userId);
Collection<String> userDeviceKeys = cacheDataStore.getHashKeys(userDeviceHashKey);
Iterator<String> itrUserDevices = userDeviceKeys.iterator();
while (itrUserDevices.hasNext()) {
String nextDeviceKey = itrUserDevices.next();
if (thePreviousClient.equals(cacheDataStore.getHashValue(userDeviceHashKey, nextDeviceKey))) {
cacheDataStore.addSetValue(RedisKeyUtils.deviceHash(nextDeviceKey), clientId);
cacheDataStore.setHashValue(userDeviceHashKey, nextDeviceKey, clientId);
}
}
// Set the Client's userId
cacheDataStore.setValue(RedisKeyUtils.client(clientId), userId);
// Remove the Previous Client's userId
cacheDataStore.deleteKey(RedisKeyUtils.client(thePreviousClient));
}
else {
log.debug("Previous Client" + thePreviousClient + " has no corresponding UserID");
}
// Swap NonPersistent list.
cacheDataStore.swapSetValue(RedisKeyUtils.clientsNonPersistent(), thePreviousClient, clientId);
// Swap Persistent list.
cacheDataStore.swapSetValue(RedisKeyUtils.clientsPersistent(), thePreviousClient, clientId);
// Swap LoggedIn list.
cacheDataStore.swapSetValue(RedisKeyUtils.clientsLoggedIn(), thePreviousClient, clientId);
// Swap Hibernated list.
cacheDataStore.swapHashKey(RedisKeyUtils.clientsHibernated(), thePreviousClient, clientId);
// Rename the UpdateJournals list.
String prevUpdateJournalKey = RedisKeyUtils.updateJournal(thePreviousClient);
if (cacheDataStore.hasKey(prevUpdateJournalKey)) {
if (!cacheDataStore.renameIfAbsent(prevUpdateJournalKey, RedisKeyUtils.updateJournal(clientId))) {
// If new list already exists, then merge the two.
cacheDataStore.setUnionAndStore(RedisKeyUtils.updateJournal(thePreviousClient), RedisKeyUtils.updateJournal(clientId), RedisKeyUtils.updateJournal(clientId));
// Delete the old Key
cacheDataStore.deleteKey(RedisKeyUtils.updateJournal(thePreviousClient));
}
}
// Rename the DeleteJournals list.
String prevDeleteJournalKey = RedisKeyUtils.deleteJournal(thePreviousClient);
if (cacheDataStore.hasKey(prevDeleteJournalKey)) {
if (!cacheDataStore.renameIfAbsent(RedisKeyUtils.deleteJournal(thePreviousClient), RedisKeyUtils.deleteJournal(clientId))) {
// If new list already exists, then merge the two.
cacheDataStore.setUnionAndStore(RedisKeyUtils.deleteJournal(thePreviousClient), RedisKeyUtils.deleteJournal(clientId), RedisKeyUtils.deleteJournal(clientId));
// Delete the old Key
cacheDataStore.deleteKey(RedisKeyUtils.deleteJournal(thePreviousClient));
}
}
// Merge sets of Access Journals.
String prevClientAccessJournalKey = RedisKeyUtils.clientAccessJournal(thePreviousClient);
if (cacheDataStore.hasKey(prevClientAccessJournalKey)) {
Set<String> accessJournalIds = (Set<String>)cacheDataStore.getSetValue(prevClientAccessJournalKey);
Iterator<String> itrAccessJournalIds = accessJournalIds.iterator();
while (itrAccessJournalIds.hasNext()) {
String nextAccessJournalId = itrAccessJournalIds.next();
cacheDataStore.swapSetValue(RedisKeyUtils.accessJournal(nextAccessJournalId), thePreviousClient, clientId);
}
}
cacheDataStore.setUnionAndStore(RedisKeyUtils.clientAccessJournal(clientId), RedisKeyUtils.clientAccessJournal(thePreviousClient), RedisKeyUtils.clientAccessJournal(clientId));
// Merge sets of ChangeWatchers.
String prevWatcherClientKey = RedisKeyUtils.watcherClient(thePreviousClient);
if (cacheDataStore.hasKey(prevWatcherClientKey)) {
Set<String> changeWatcherIds = (Set<String>)cacheDataStore.getSetValue(prevWatcherClientKey);
Iterator<String> itrChangeWatcherIds = changeWatcherIds.iterator();
while (itrChangeWatcherIds.hasNext()) {
String nextChangeWatcherId = itrChangeWatcherIds.next();
cacheDataStore.swapSetValue(nextChangeWatcherId, thePreviousClient, clientId);
}
}
cacheDataStore.setUnionAndStore(RedisKeyUtils.watcherClient(clientId), RedisKeyUtils.watcherClient(thePreviousClient), RedisKeyUtils.watcherClient(clientId));
// // Rename the TransactionJournals list.
// Collection<String> transKeys = redisDataStore.keys(RedisKeyUtils.transactionJournal(clientId, "*"));
// Iterator<String> itrTransKeys = transKeys.iterator();
// while(itrTransKeys.hasNext()) {
// String nextKey = itrTransKeys.next();
// redisDataStore.rename(nextKey, RedisKeyUtils.transactionJournal(clientId, RedisKeyUtils.transJournalTransactionId(nextKey)));
}
/* (non-Javadoc)
* @see com.com.percero.agents.sync.services.IAccessManager#logoutClient(java.lang.String)
*/
@Transactional
public void logoutClient(String clientId, Boolean pleaseDestroyClient) {
if (!StringUtils.hasText(clientId)) {
return;
}
log.debug("Logging out client " + clientId + " [" + (pleaseDestroyClient != null && pleaseDestroyClient ? "T" : "F") + "]");
// Remove from LoggedIn Clients
cacheDataStore.removeSetValue(RedisKeyUtils.clientsLoggedIn(), clientId);
// Check to see if this is a non-persistent client type.
Boolean isNonPersistent = cacheDataStore.getSetIsMember(RedisKeyUtils.clientsNonPersistent(), clientId);
if (isNonPersistent || pleaseDestroyClient) {
destroyClient(clientId);
}
else {
// Set timeouts for client.
postClient(clientId);
}
}
@Transactional
public void destroyClient(String clientId) {
if (!StringUtils.hasText(clientId)) {
return;
}
// Get the client's userId.
String userId = (String) cacheDataStore.getValue(RedisKeyUtils.client(clientId));
Boolean validUser = StringUtils.hasText(userId);
// Remove from ClientUser list
if (validUser) {
cacheDataStore.removeSetValue(RedisKeyUtils.clientUser(userId), clientId);
}
// Remove from Client's User ID.
cacheDataStore.deleteKey(RedisKeyUtils.client(clientId));
// Remove from LoggedIn Clients
cacheDataStore.removeSetValue(RedisKeyUtils.clientsLoggedIn(), clientId);
// Remove from Hibernated Clients
cacheDataStore.deleteHashKey(RedisKeyUtils.clientsHibernated(), clientId);
// Remove from NonPersistent Clients
cacheDataStore.removeSetValue(RedisKeyUtils.clientsNonPersistent(), clientId);
// Remove from Persistent Clients
cacheDataStore.removeSetValue(RedisKeyUtils.clientsPersistent(), clientId);
// Delete all UpdateJournals for this Client.
String updateJournalKey = RedisKeyUtils.updateJournal(clientId);
// Set<String> updateJournalIds = (Set<String>)redisDataStore.getSetValue(updateJournalKey);
// redisDataStore.removeSetsValue(updateJournalIds, clientId);
cacheDataStore.deleteKey(updateJournalKey);
// Delete all DeleteJournals for this Client.
cacheDataStore.deleteKey(RedisKeyUtils.deleteJournal(clientId));
// // Delete all TransactionJournals for this Client.
// Collection<String> transJournalKeys = redisDataStore.keys(RedisKeyUtils.transactionJournal(clientId, "*"));
// redisDataStore.deleteKeys(transJournalKeys);
// Delete Client's UserDevice.
if (validUser) {
String userDeviceHashKey = RedisKeyUtils.userDeviceHash(userId);
Collection<String> userDeviceKeys = cacheDataStore.getHashKeys(userDeviceHashKey);
int originalSize = userDeviceKeys.size();
int countRemoved = 0;
Iterator<String> itrUserDevices = userDeviceKeys.iterator();
while (itrUserDevices.hasNext()) {
String nextDeviceKey = itrUserDevices.next();
if (clientId.equals(cacheDataStore.getHashValue(userDeviceHashKey, nextDeviceKey))) {
// Since the client id being destroyed, the whole device history related to this client is also to be destroyed.
// However, as a safety precaution, set the expiration for the device hash.
cacheDataStore.expire(RedisKeyUtils.deviceHash(nextDeviceKey), userDeviceTimeout, TimeUnit.SECONDS);
cacheDataStore.removeSetValue(RedisKeyUtils.deviceHash(nextDeviceKey), clientId);
cacheDataStore.deleteHashKey(userDeviceHashKey, nextDeviceKey);
countRemoved++;
}
}
if (countRemoved >= originalSize) {
// Remove the UserDevice Hash.
cacheDataStore.deleteKey(userDeviceHashKey);
}
}
deleteClientAccessJournals(clientId);
deleteClientWatchers(clientId);
// // Remove Change Watcher.
// String watcherClient = RedisKeyUtils.watcherClient(clientId);
// if (redisDataStore.hasKey(watcherClient)) {
// Collection<String> changeWatcherIds = (Collection<String>) redisDataStore.getSetValue(watcherClient);
// Iterator<String> itrChangeWatchers = changeWatcherIds.iterator();
// while (itrChangeWatchers.hasNext()) {
// String nextChangeWatcherId = itrChangeWatchers.next();
// // Remove from the ChangeWatchers List.
// redisDataStore.removeSetValue(nextChangeWatcherId, clientId);
// //Long size = redisDataStore.removeSetValueAndGetSize(nextChangeWatcherId, clientId);
// redisDataStore.deleteKey(watcherClient);
/** CLEANUP **/
// Remove from PushSyncHelper.
pushSyncHelper.removeClient(clientId);
// Remove from AuthService.
authService.logoutUser(userId, null, clientId);
}
/**
* This function checks to see if a User has no more UserDevices. If they do not have
* any, then it removes all the User's entries in ALL AccessJournal sets.
*
* @param clientId
*/
@SuppressWarnings("unchecked")
@Transactional
private void deleteClientAccessJournals(String clientId) {
String clientAccessJournalsKey = RedisKeyUtils.clientAccessJournal(clientId);
Set<String> clientAccessJournals = (Set<String>) cacheDataStore.getSetValue(clientAccessJournalsKey);
cacheDataStore.removeSetsValue(RedisKeyUtils.ACCESS_JOURNAL_PREFIX, clientAccessJournals, clientId);
// Now remove the Client's AccessJournal key.
cacheDataStore.deleteKey(clientAccessJournalsKey);
// Check to see if each Object's access journal set is empty and if so remove it
// from the class access journal set
for(String caj : clientAccessJournals){
if(cacheDataStore.getSetIsEmpty(RedisKeyUtils.ACCESS_JOURNAL_PREFIX+caj)){
String[] parts = caj.split(":");
String className = parts[0];
String ID = parts[1];
String classAccessJournalKey = RedisKeyUtils.classAccessJournal(className);
cacheDataStore.removeSetValue(classAccessJournalKey, ID);
}
}
}
@SuppressWarnings("unchecked")
@Transactional
private void deleteClientWatchers(String clientId) {
String watcherClientKey = RedisKeyUtils.watcherClient(clientId);
Set<String> watcherClientIds = (Set<String>) cacheDataStore.getSetValue(watcherClientKey);
cacheDataStore.removeSetsValue("", watcherClientIds, clientId);
// Now remove the Client's Watcher key.
cacheDataStore.deleteKey(watcherClientKey);
}
/**
* Looks through a list of post AccessJournals and removes all Clients that are no longer valid.
*/
@SuppressWarnings("unchecked")
// @Scheduled(fixedRate=600000) // 10 Minutes
@Scheduled(fixedRate=60000) // 60 Seconds
// @Scheduled(fixedRate=300000) // 5 Minutes
public void postAccessJournals() {
log.debug("Posting " + postAccessJournals.size() + " Access Journal" + (postAccessJournals.size() == 1 ? "" : "s"));
/**if (taskExecutor != null) {
taskExecutor.execute(new RedisPostClientTask(postClientHelper, postClientIds));
} else {*/
Set<String> invalidClients = new HashSet<String>();
Set<String> accessJournalsToDelete = new HashSet<String>(postAccessJournals.size());
synchronized (postAccessJournals) {
Iterator<String> itrAccessJournals = postAccessJournals.iterator();
while (itrAccessJournals.hasNext()) {
String nextAccessJournal = itrAccessJournals.next();
accessJournalsToDelete.add(nextAccessJournal);
}
}
// We are looking for invalid Client's in Access Journals to keep those Access Journals clean.
Iterator<String> itrAccessJournals = accessJournalsToDelete.iterator();
while (itrAccessJournals.hasNext()) {
String nextAccessJournal = itrAccessJournals.next();
Set<String> accessJournalClients = (Set<String>)cacheDataStore.getSetValue(nextAccessJournal);
if (accessJournalClients != null) {
Set<String> clientIdsToRemove = new HashSet<String>();
Iterator<String> itrAccessJournalClients = accessJournalClients.iterator();
while (itrAccessJournalClients.hasNext()) {
String nextClientId = itrAccessJournalClients.next();
if (invalidClients.contains(nextClientId)) {
clientIdsToRemove.add(nextClientId);
}
else if (!findClientByClientId(nextClientId) || !StringUtils.hasText(getClientUserId(nextClientId)) ) {
// This is an invalid Client, so add to the list of clients to remove and the list of invalid clients.
invalidClients.add(nextClientId);
clientIdsToRemove.add(nextClientId);
}
}
if (!clientIdsToRemove.isEmpty()) {
cacheDataStore.removeSetValues(nextAccessJournal, clientIdsToRemove);
}
}
}
synchronized (postAccessJournals) {
postAccessJournals.removeAll(accessJournalsToDelete);
}
Iterator<String> itrInvalidClients = invalidClients.iterator();
while (itrInvalidClients.hasNext()) {
String nextInvalidClientId = itrInvalidClients.next();
logoutClient(nextInvalidClientId, true);
}
}
// @Scheduled(fixedRate=600000) // 10 Minutes
@Scheduled(fixedRate=300000) // 5 Minutes
// @Scheduled(fixedRate=120000) // 2 Minutes
public void postClients() {
log.debug("Posting " + postClientIds.size() + " client" + (postClientIds.size() == 1 ? "" : "s"));
/**if (taskExecutor != null) {
taskExecutor.execute(new RedisPostClientTask(postClientHelper, postClientIds));
} else {*/
Collection<String> clientIdsToRemove = new HashSet<String>();
synchronized (postClientIds) {
Iterator<String> itrClientIds = postClientIds.iterator();
while (itrClientIds.hasNext()) {
String nextClientId = itrClientIds.next();
clientIdsToRemove.add(nextClientId);
}
}
Iterator<String> itrClientIdsToRemove = clientIdsToRemove.iterator();
while (itrClientIdsToRemove.hasNext()) {
try {
String nextClientId = itrClientIdsToRemove.next();
postClientHelper.postClient(nextClientId);
} catch(Exception e) {
log.error("Unable to post client", e);
}
}
synchronized (postClientIds) {
itrClientIdsToRemove = clientIdsToRemove.iterator();
while (itrClientIdsToRemove.hasNext()) {
postClientIds.remove(itrClientIdsToRemove.next());
}
}
// Now check Hibernating clients to see if any of those need to be removed
Map<String, Object> hibernatingClients = cacheDataStore.getHashEntries(RedisKeyUtils.clientsHibernated());
Iterator<Map.Entry<String,Object>> itrHibernatingClientsEntries = hibernatingClients.entrySet().iterator();
while (itrHibernatingClientsEntries.hasNext()) {
Map.Entry<String,Object> nextEntry = itrHibernatingClientsEntries.next();
String nextHibernatingClientId = null;
try {
nextHibernatingClientId = (String) nextEntry.getKey();
} catch(Exception e) {
// This is an invalid key, so remove it from the hash.
try {
cacheDataStore.deleteHashKey(RedisKeyUtils.clientsHibernated(), nextEntry.getKey());
} catch(Exception e1) {
log.error("Invalid hash key in " + RedisKeyUtils.clientsHibernated());
}
continue;
}
Long nextHibernateTime = null;
try {
nextHibernateTime = (Long) nextEntry.getValue();
} catch(Exception e) {
// This timeout is not in a valid format, set to current time and move on.
try {
cacheDataStore.setHashValue(RedisKeyUtils.clientsHibernated(), nextHibernatingClientId, nextEntry.getValue());
} catch(Exception e1) {
log.error("Invalid hash value in " + RedisKeyUtils.clientsHibernated());
}
continue;
}
// Now check the time.
long currenTimeMillis = System.currentTimeMillis();
if ((currenTimeMillis-nextHibernateTime) > userDeviceTimeout * 1000) {
// The client has timed out, so logout and destroy this client.
try {
logoutClient(nextHibernatingClientId, true);
} catch (Exception e) {
log.error("Unable to remove hibernating client " + nextHibernatingClientId);
}
}
}
}
private Collection<String> postClientIds = Collections.synchronizedSet(new HashSet<String>());
public void postClient(String clientId) {
postClientIds.add(clientId);
}
private Collection<String> postAccessJournals = Collections.synchronizedSet(new HashSet<String>());
public void postAccessJournal(String id) {
postAccessJournals.add(id);
}
public void saveUpdateJournalClients(ClassIDPair pair, Collection<String> clientIds, Boolean guaranteeDelivery, String pusherClient, Boolean sendToPusher) throws Exception {
if (clientIds != null && clientIds.size() > 0) {
try {
String classValue = RedisKeyUtils.classIdPair(pair.getClassName(), pair.getID());
for(String nextClient : clientIds) {
if (!StringUtils.hasText(nextClient)) {
continue;
}
if (!sendToPusher && pusherClient != null) {
// Don't send to pushing Client
if (nextClient.equals(pusherClient)) {
continue;
}
}
String key = RedisKeyUtils.updateJournal(nextClient);
cacheDataStore.addSetValue(key, classValue);
}
} catch(Exception e) {
log.error("Error saving UpdateJournal for " + pair.toString(), e);
}
}
}
public Long deleteUpdateJournal(String clientId, String className, String classId) {
return cacheDataStore.removeSetValue(RedisKeyUtils.updateJournal(clientId), RedisKeyUtils.classIdPair(className, classId));
}
public void deleteUpdateJournals(String clientId, ClassIDPair[] objects) {
for(ClassIDPair nextObject : objects) {
cacheDataStore.removeSetValue(RedisKeyUtils.updateJournal(clientId), RedisKeyUtils.classIdPair(nextObject.getClassName(), nextObject.getID()));
}
}
public void saveDeleteJournalClients(ClassIDPair pair, Collection<String> clientIds, Boolean guaranteeDelivery, String pusherClient, Boolean sendToPusher) throws Exception {
if (clientIds != null && clientIds.size() > 0) {
try {
String classValue = RedisKeyUtils.classIdPair(pair.getClassName(), pair.getID());
for(String nextClient : clientIds) {
if (!sendToPusher && pusherClient != null) {
// Don't send to pushing Client
if (nextClient.equals(pusherClient)) {
continue;
}
}
String key = RedisKeyUtils.deleteJournal(nextClient);
cacheDataStore.addSetValue(key, classValue);
}
} catch(Exception e) {
log.error("Error saving DeleteJournal for " + pair.toString(), e);
}
}
}
public Long deleteDeleteJournal(String clientId, String className, String classId) {
return cacheDataStore.removeSetValue(RedisKeyUtils.deleteJournal(clientId), RedisKeyUtils.classIdPair(className, classId));
}
public void deleteDeleteJournals(String clientId, ClassIDPair[] objects) {
for(ClassIDPair nextObject : objects) {
cacheDataStore.removeSetValue(RedisKeyUtils.deleteJournal(clientId), RedisKeyUtils.classIdPair(nextObject.getClassName(), nextObject.getID()));
}
}
public boolean saveAccessJournal(List<ClassIDPair> theList, String userId, String clientId) throws Exception {
boolean saveAccessJournalFailure = false;
for(ClassIDPair nextObject : theList) {
if (!saveAccessJournal(nextObject, userId, clientId))
saveAccessJournalFailure = true;
}
return !saveAccessJournalFailure;
}
public boolean saveAccessJournal(ClassIDPair classIdPair, String userId, String clientId) throws Exception {
return (upsertRedisAccessJournal(userId, clientId, classIdPair.getClassName(), classIdPair.getID()) >= 0);
}
private Long upsertRedisAccessJournal(String userId, String clientId, String className, String classId) {
String key = RedisKeyUtils.accessJournal(className, classId);
try {
// Need to add the ObjectID to the Client's AccessJournals set.
String clientAccessJournalKey = RedisKeyUtils.clientAccessJournal(clientId);
cacheDataStore.addSetValue(clientAccessJournalKey, RedisKeyUtils.objectId(className, classId));
// Add to the class's AccessJournals set
if(classId != null && !classId.isEmpty()) { // && !classId.equals("0")) {
log.debug("Adding to class AccessJournals: "+classId);
String classAccessJournalKey = RedisKeyUtils.classAccessJournal(className);
cacheDataStore.addSetValue(classAccessJournalKey, classId);
}
// Need to add the ClientID to the Object's AccessJournal set.
return cacheDataStore.addSetValue(key, clientId);
} catch(Exception e) {
log.error("Unable to upsertRedisAccessJournal", e);
} finally {
postAccessJournal(key);
}
return null;
}
/* (non-Javadoc)
* @see com.com.percero.agents.sync.services.IAccessManager#getObjectAccessJournals(java.lang.String, java.lang.Integer)
*/
@SuppressWarnings("unchecked")
//@SuppressWarnings("unchecked")
@Transactional
public List<String> getObjectAccessJournals(String className, String classId) throws Exception {
List<String> result = new ArrayList<String>();
// Collection<String> keysNames = new HashSet<String>();
// keysNames.add(RedisKeyUtils.accessJournal(className, classId));
String allObjectAccessJournalKey = RedisKeyUtils.accessJournal(className, "0");
String objectAccessJournalKey = RedisKeyUtils.accessJournal(className, classId);
// keysNames.add(allObjectAccessJournalKey);
// Need to get list of all classes that inherit from this class.
/* MappedClass mc = MappedClassManagerFactory.getMappedClassManager().getMappedClassByClassName(className);
while (mc != null && mc.parentMappedClass != null) {
keysNames.add(RedisKeyUtils.accessJournal(mc.parentMappedClass.className, classId));
keysNames.add(RedisKeyUtils.accessJournal(mc.parentMappedClass.className, "0"));
mc = mc.parentMappedClass;
}*/
//moveAccessJournals();
// TODO: Use a class id map instead of class name for faster lookup.
// Use hash of full class name to generate ID?
Set<String> redisClassIdSet = (Set<String>) cacheDataStore.getSetUnion(objectAccessJournalKey, allObjectAccessJournalKey);
result.addAll(redisClassIdSet);
// RedisKeyUtils.accessJournal(className, classId),
// RedisKeyUtils.accessJournal(className, "0"));
//System.out.println(redisClassIdSet.size());
// result = checkUserListAccessRights(redisClassIdSet, className, classId);
postAccessJournal(allObjectAccessJournalKey);
postAccessJournal(objectAccessJournalKey);
return result;
}
@SuppressWarnings("unchecked")
public Set<String> getClassAccessJournalIDs(String className){
return (Set<String>) cacheDataStore.getSetValue(RedisKeyUtils.classAccessJournal(className));
}
public long getNumClientsInterestedInWholeClass(String className){
return cacheDataStore.getSetSize(RedisKeyUtils.accessJournal(className,"0"));
}
public List<String> checkUserListAccessRights(Collection<Object> clientIdList, String className, String classId) throws Exception {
List<String> result = new ArrayList<String>();
for(Object nextClientId : clientIdList) {
if (StringUtils.hasText((String)nextClientId))
result.add((String)nextClientId);
}
return result;
}
/* (non-Javadoc)
* @see com.com.percero.agents.sync.services.IAccessManager#getClientUpdateJournals(java.lang.String)
*/
@SuppressWarnings("unchecked")
public Collection<String> getClientUpdateJournals(String clientId, Boolean loggedInOnly) throws Exception {
String key = RedisKeyUtils.updateJournal(clientId);
Collection<String> updateJournalSet = null;
if (loggedInOnly) {
if (cacheDataStore.getSetIsMember(RedisKeyUtils.clientsLoggedIn(), clientId)) {
updateJournalSet = (Set<String>) cacheDataStore.getSetValue(key);
}
else {
updateJournalSet = new HashSet<String>(0);
}
}
else {
updateJournalSet = (Set<String>) cacheDataStore.getSetValue(key);
}
return updateJournalSet;
}
/* (non-Javadoc)
* @see com.com.percero.agents.sync.services.IAccessManager#getClientDeleteJournals(java.lang.String)
*/
@SuppressWarnings("unchecked")
public Collection<String> getClientDeleteJournals(String clientId, Boolean loggedInOnly) throws Exception {
String key = RedisKeyUtils.deleteJournal(clientId);
Collection<String> deleteJournalSet = null;
if (loggedInOnly) {
if (cacheDataStore.getSetIsMember(RedisKeyUtils.clientsLoggedIn(), clientId)) {
deleteJournalSet = (Set<String>) cacheDataStore.getSetValue(key);
}
else {
deleteJournalSet = new HashSet<String>(0);
}
}
else {
deleteJournalSet = (Set<String>) cacheDataStore.getSetValue(key);
}
return deleteJournalSet;
}
/* (non-Javadoc)
* @see com.com.percero.agents.sync.services.IAccessManager#removeUpdateJournals(java.util.List)
*/
public void removeUpdateJournals(String clientId, Collection<Object> updateJournalsToRemove) throws Exception {
String key = RedisKeyUtils.updateJournal(clientId);
cacheDataStore.removeSetValues(key, updateJournalsToRemove);
}
/* (non-Javadoc)
* @see com.com.percero.agents.sync.services.IAccessManager#removeUpdateJournalsByObject(ClassIDPair)
*/
public void removeUpdateJournalsByObject(ClassIDPair classIdPair) throws Exception {
// Don't do anything since having removed objects in the UpdateJournal are not a problem.
}
@SuppressWarnings("unchecked")
public void removeAccessJournalsByObject(ClassIDPair classIdPair) {
String objectId = RedisKeyUtils.objectId(classIdPair.getClassName(), classIdPair.getID());
String accessJournalKey = RedisKeyUtils.accessJournal(classIdPair.getClassName(), classIdPair.getID());
Set<String> clientIds = (Set<String>) cacheDataStore.getSetValue(accessJournalKey);
Set<String> clientAccessJournalKeys = new HashSet<String>(clientIds.size());
Iterator<String> itrClientIds = clientIds.iterator();
while (itrClientIds.hasNext()) {
String nextClientId = itrClientIds.next();
// Remove Class ID Pair from Client's AccessJournal
String clientAccessJournalsKey = RedisKeyUtils.clientAccessJournal(nextClientId);
clientAccessJournalKeys.add(clientAccessJournalsKey);
}
cacheDataStore.removeSetsValue(clientAccessJournalKeys, objectId);
// Iterator<String> itrClientIds = clientIds.iterator();
// while (itrClientIds.hasNext()) {
// String nextClientId = itrClientIds.next();
// // Remove Class ID Pair from Client's AccessJournal
// String clientAccessJournalsKey = RedisKeyUtils.clientAccessJournal(nextClientId);
// redisDataStore.removeSetValue(clientAccessJournalsKey, objectId);
// // If Client's AccessJournal set is empty, then remove that key.
// if (redisDataStore.getSetIsEmpty(clientAccessJournalsKey)) {
// redisDataStore.deleteKey(clientAccessJournalsKey);
String classAccessJournalKey = RedisKeyUtils.classAccessJournal(classIdPair.getClassName());
cacheDataStore.removeSetValue(classAccessJournalKey, classIdPair.getID());
// Now delete the AccessJournal record.
cacheDataStore.deleteKey(accessJournalKey);
}
public void removeObjectModJournalsByObject(ClassIDPair classIdPair) {
cacheDataStore.deleteKey(RedisKeyUtils.objectModJournal(classIdPair.getClassName(), classIdPair.getID()));
}
public void removeHistoricalObjectsByObject(ClassIDPair classIdPair) {
cacheDataStore.deleteKey(RedisKeyUtils.historicalObject(classIdPair.getClassName(), classIdPair.getID()));
}
// HELPER FUNCTIONS
// CHANGE WATCHER
public void addWatcherField(ClassIDPair classIdPair, String fieldName, Collection<String> collection) {
addWatcherField(classIdPair, fieldName, collection, null);
}
public void addWatcherField(ClassIDPair classIdPair, String fieldName, Collection<String> collection, String[] params) {
addWatcherField(classIdPair.getClassName(), classIdPair.getID(), fieldName, collection, params);
}
public void addWatcherField(String category, String subCategory, String fieldName, Collection<String> collection) {
addWatcherField(category, subCategory, fieldName, collection, null);
}
public void addWatcherField(String category, String subCategory, String fieldName, Collection<String> collection, String[] params) {
String fieldWatcherId = "";
if (params != null)
fieldWatcherId = RedisKeyUtils.fieldWatcher(RedisKeyUtils.changeWatcherWithParams(category, subCategory, fieldName, params));
else
fieldWatcherId = RedisKeyUtils.fieldWatcher(RedisKeyUtils.changeWatcher(category, subCategory, fieldName));
if (collection != null)
collection.add(fieldWatcherId);
}
@Transactional
public void addWatcherClient(ClassIDPair classIdPair, String fieldName, String clientId) {
addWatcherClient(classIdPair, fieldName, clientId, null);
}
@Transactional
public void addWatcherClient(ClassIDPair classIdPair, String fieldName, String clientId, String[] params) {
String changeWatcherId = "";
if (params != null)
changeWatcherId = RedisKeyUtils.clientWatcher(RedisKeyUtils.changeWatcherWithParams(classIdPair.getClassName(), classIdPair.getID(), fieldName, params));
else
changeWatcherId = RedisKeyUtils.clientWatcher(RedisKeyUtils.changeWatcher(classIdPair.getClassName(), classIdPair.getID(), fieldName));
// Add the ClientID to the ChangeWatcher client Set
cacheDataStore.addSetValue(changeWatcherId, clientId);
// Also add the ChangeWatcher ID to the client ChangeWatcher Set
cacheDataStore.addSetValue(RedisKeyUtils.watcherClient(clientId), changeWatcherId);
}
public void updateWatcherFields(ClassIDPair classIdPair, String fieldName, Collection<String> fieldsToWatch) {
updateWatcherFields(classIdPair, fieldName, fieldsToWatch, null);
}
public void updateWatcherFields(ClassIDPair classIdPair, String fieldName, Collection<String> fieldsToWatch, String[] params) {
updateWatcherFields(classIdPair.getClassName(), classIdPair.getID(), fieldName, fieldsToWatch, params);
}
public void updateWatcherFields(String category, String subCategory, String fieldName, Collection<String> fieldsToWatch) {
updateWatcherFields(category, subCategory, fieldName, fieldsToWatch, null);
}
@SuppressWarnings("unchecked")
@Transactional
public void updateWatcherFields(String category, String subCategory, String fieldName, Collection<String> fieldsToWatch, String[] params) {
String changeWatcherId = "";
String watcherField = "";
if (params != null) {
changeWatcherId = RedisKeyUtils.changeWatcherWithParams(category, subCategory, fieldName, params);
watcherField = RedisKeyUtils.watcherField(RedisKeyUtils.changeWatcher(category, subCategory, fieldName));
}
else {
changeWatcherId = RedisKeyUtils.changeWatcher(category, subCategory, fieldName);
watcherField = RedisKeyUtils.watcherField(changeWatcherId);
}
Collection<String> watchedFields = (Set<String>) cacheDataStore.getSetValue(watcherField);
// Remove current set of fields to watch and replace with new set.
cacheDataStore.replaceSet(watcherField, fieldsToWatch);
if (fieldsToWatch != null) {
Iterator<String> itrFieldsToWatch = fieldsToWatch.iterator();
while (itrFieldsToWatch.hasNext()) {
String nextField = itrFieldsToWatch.next();
// Also add this ChangeWatcher from the FieldWatcher.
cacheDataStore.addSetValue(nextField, changeWatcherId);
// Keep track of field that is being watched at an object level.
String[] nextFieldArr = nextField.split(":");
if (nextFieldArr.length >= 7) {
String nextFieldClassName = nextFieldArr[4];
String nextFieldClassId = nextFieldArr[5];
String nextFieldFieldName = nextFieldArr[6];
String hashKey = "";
if (nextFieldArr.length > 7) {
String[] nextFieldParams = new String[nextFieldArr.length-7];
for(int i=7; i<nextFieldArr.length; i++) {
nextFieldParams[i-7] = nextFieldArr[i];
}
hashKey = RedisKeyUtils.fieldWithParams(nextFieldFieldName, nextFieldParams);
}
else {
hashKey = RedisKeyUtils.field(nextFieldFieldName);
}
String objectWatchedFieldKey = RedisKeyUtils.objectWatchedFields(nextFieldClassName, nextFieldClassId);
cacheDataStore.setHashValue(objectWatchedFieldKey, hashKey, nextField);
}
if (watchedFields != null) {
watchedFields.remove(nextField);
}
}
}
// Now remove any remaining watchedFields (since they no longer belong).
if (watchedFields != null) {
Iterator<String> itrOldWatchedFields = watchedFields.iterator();
while (itrOldWatchedFields.hasNext()) {
String nextOldField = itrOldWatchedFields.next();
// Also remove this ChangeWatcher from the FieldWatcher.
cacheDataStore.removeSetValue(nextOldField, changeWatcherId);
}
}
}
public void removeChangeWatchersByObject(ClassIDPair classIdPair) {
removeChangeWatchers(classIdPair.getClassName(), classIdPair.getID());
}
/**
*
* @param category
* @param subCategory
*/
@SuppressWarnings("unchecked")
public void removeChangeWatchers(String category, String subCategory) {
String categoryKey = RedisKeyUtils.changeWatcherClass(category, subCategory);
// Get all change watcher values associated with this
// category/sub-category.
// For each stored change watcher property, a set of hash keys may exist
// that contain both a "RESULT" hash key and a "TIMESTAMP" hash key. The
// RESULT was calculated and stored at the TIMESTAMP.
// Example:
// "propertyName:r"
// "propertyName:t"
Set<String> changeWatcherValueKeys = cacheDataStore.getHashKeys(categoryKey);
Iterator<String> itrChangeWatcherValueKeys = changeWatcherValueKeys.iterator();
while (itrChangeWatcherValueKeys.hasNext()) {
String nextChangeWatcherValueKey = itrChangeWatcherValueKeys.next();
// For each RESULT hash key, we need to remove the Change Watcher structure setup in the cache.
if (nextChangeWatcherValueKey.endsWith(":" + RedisKeyUtils.RESULT)) {
int resultIndex = nextChangeWatcherValueKey.lastIndexOf(":" + RedisKeyUtils.RESULT);
// The changeWatcherKey for this property is of the form "<categoryKey>:<propertyName>".
// Example:
// "cw:cf:com.namespace.mo.MyObject:ID:someProperty"
String changeWatcherKey = categoryKey + ":" + nextChangeWatcherValueKey.substring(0, resultIndex);
String key = changeWatcherKey;
// The list of clients that are "watching" this change watcher
// property is in the cache by the key:
// client:<changeWatcherKey>". This set of clients should be
// notified when this value changes.
// Example:
// "client:cw:cf:com.namespace.mo.MyObject:ID:someProperty"
String clientWatcherKey = RedisKeyUtils.clientWatcher(changeWatcherKey);
// For every watcherField, find the corresponding set and remove
// this changeWatcherKey from that set. The set of watchers
// fields is the set of properties that this ChangeWatcher is
// watching, meaning that if any of those properties change then
// this ChangeWatcher should be reprocessed.
// This takes the form: "cw:watcher:<changeWatcherKey>"
// Example:
// "cw:watcher:cw:cf:com.namespace.mo.MyObject:ID:someProperty"
String watcherField = RedisKeyUtils.watcherField(changeWatcherKey);
Set<String> watcherFieldValues = (Set<String>) cacheDataStore.getSetValue(watcherField);
Iterator<String> itrWatcherFieldValues = watcherFieldValues.iterator();
while (itrWatcherFieldValues.hasNext()) {
String nextWatcherFieldValue = itrWatcherFieldValues.next();
// This represents the reverse lookup: this is the set of
// ChangeWatchers to notify when nextWathcerFieldValue
// changes. So basically, we are saying "don't notify me"
// since this object is being removed.
cacheDataStore.removeSetValue(nextWatcherFieldValue, changeWatcherKey);
}
// This is the list of all properties that this ChangeWatcher is
// listening to. Since it is being deleted, we can simply delete
// this key from the cache as well.
String fieldWatcher = RedisKeyUtils.fieldWatcher(changeWatcherKey);
// Now remove all keys associated with this Change Watcher Value.
cacheDataStore.deleteKey(key);
cacheDataStore.deleteKey(clientWatcherKey);
cacheDataStore.deleteKey(watcherField);
cacheDataStore.deleteKey(fieldWatcher);
}
}
String objectWatchedFieldKey = RedisKeyUtils.objectWatchedFields(category, subCategory);
Set<String> objectWatcherValueKeys = cacheDataStore.getHashKeys(objectWatchedFieldKey);
Iterator<String> itrObjectWatcherValueKeys = objectWatcherValueKeys.iterator();
while (itrObjectWatcherValueKeys.hasNext()) {
String nextObjectWatcherValueKey = itrObjectWatcherValueKeys.next();
// Get all fields for this object that are being watched and remove them.
String changeWatcherKey = (String) cacheDataStore.getHashValue(objectWatchedFieldKey, nextObjectWatcherValueKey);
cacheDataStore.deleteKey(changeWatcherKey);
}
cacheDataStore.deleteKey(objectWatchedFieldKey); // Removes ALL change watcher values for this Object.
cacheDataStore.deleteKey(categoryKey); // Removes ALL change watcher values for this Object.
}
public void saveChangeWatcherResult(ClassIDPair classIdPair, String fieldName, Object result) {
saveChangeWatcherResult(classIdPair, fieldName, result, null);
}
@Transactional
public void saveChangeWatcherResult(ClassIDPair classIdPair, String fieldName, Object result, String[] params) {
String classKey = RedisKeyUtils.changeWatcherClass(classIdPair.getClassName(), classIdPair.getID());
HashMap<String, Object> resultHash = new HashMap<String, Object>();
resultHash.put(RedisKeyUtils.changeWatcherValueTimestamp(fieldName, params), System.currentTimeMillis());
resultHash.put(RedisKeyUtils.changeWatcherValueResult(fieldName, params), result);
cacheDataStore.setAllHashValues(classKey, resultHash);
}
public void removeChangeWatcherResult(ClassIDPair classIdPair, String fieldName) {
removeChangeWatcherResult(classIdPair, fieldName, null);
}
@Transactional
public void removeChangeWatcherResult(ClassIDPair classIdPair, String fieldName, String[] params) {
String key = RedisKeyUtils.changeWatcherClass(classIdPair.getClassName(), classIdPair.getID());
cacheDataStore.deleteHashKey(key, RedisKeyUtils.changeWatcherValueTimestamp(fieldName, params));
cacheDataStore.deleteHashKey(key, RedisKeyUtils.changeWatcherValueResult(fieldName, params));
}
public Long getChangeWatcherResultTimestamp(ClassIDPair classIdPair, String fieldName) {
return getChangeWatcherResultTimestamp(classIdPair, fieldName, null);
}
public Long getChangeWatcherResultTimestamp(ClassIDPair classIdPair, String fieldName, String[] params) {
String key = RedisKeyUtils.changeWatcherClass(classIdPair.getClassName(), classIdPair.getID());
Long result = (Long) cacheDataStore.getHashValue(key, RedisKeyUtils.changeWatcherValueTimestamp(fieldName, params));
return result;
}
protected Object[] parseChangeWatcherId(String changeWatcherId) {
Object[] result = new Object[3];
if (!StringUtils.hasText(changeWatcherId)) {
return null;
}
else {
String[] params = changeWatcherId.split(":");
if (params.length >= 5) {
String className = params[2];
String classId = params[3];
result[0] = new ClassIDPair(classId, className);
String fieldName = params[4];
result[1] = fieldName;
String[] otherParams = null;
if (params.length > 5) {
otherParams = new String[params.length-5];
for(int i=5; i < params.length; i++) {
try {
otherParams[i-5] = URLDecoder.decode(params[i], "UTF-8");
} catch (Exception e) {
log.error(e);
}
}
}
result[2] = otherParams;
}
return result;
}
}
public Boolean getChangeWatcherResultExists(String changeWatcherId) {
Object[] parsed = parseChangeWatcherId(changeWatcherId);
if (parsed != null) {
return getChangeWatcherResultExists((ClassIDPair) parsed[0], (String) parsed[1], (String[]) parsed[2]);
}
else {
return false;
}
}
public Boolean getChangeWatcherResultExists(ClassIDPair classIdPair, String fieldName) {
return getChangeWatcherResultExists(classIdPair, fieldName, null);
}
public Boolean getChangeWatcherResultExists(ClassIDPair classIdPair, String fieldName, String[] params) {
String key = RedisKeyUtils.changeWatcherClass(classIdPair.getClassName(), classIdPair.getID());
Boolean hasKey = cacheDataStore.hasHashKey(key, RedisKeyUtils.changeWatcherValueResult(fieldName, params));
return hasKey;
}
public Object getChangeWatcherResult(ClassIDPair classIdPair, String fieldName) {
return getChangeWatcherResult(classIdPair, fieldName, null);
}
public Object getChangeWatcherResult(ClassIDPair classIdPair, String fieldName, String[] params) {
String key = RedisKeyUtils.changeWatcherClass(classIdPair.getClassName(), classIdPair.getID());
return cacheDataStore.getHashValue(key, RedisKeyUtils.changeWatcherValueResult(fieldName, params));
}
public void checkChangeWatchers(ClassIDPair classIdPair) {
checkChangeWatchers(classIdPair, null, null, null);
}
public void checkChangeWatchers(ClassIDPair classIdPair, String[] fieldNames, String[] params, IPerceroObject oldValue) {
Collection<String> changeWatchers = getChangeWatchersForField(classIdPair, fieldNames, params);
// If there are ChangeWatchers, then recalculate for each one.
if (changeWatchers != null) {
Iterator<String> itrChangeWatchers = changeWatchers.iterator();
while (itrChangeWatchers.hasNext()) {
String nextChangeWatcher = itrChangeWatchers.next();
// TODO: Test this optimization.
// if (getChangeWatcherResultExists(nextChangeWatcher)) {
// If the type is CUSTOM, need to append the ClassIDPair, if it exists.
if (nextChangeWatcher.startsWith("cw:cf:CUSTOM:")) {
if (classIdPair != null) {
nextChangeWatcher += ":" + classIdPair.getClassName() + ":" + classIdPair.getID();
}
}
setupRecalculateChangeWatcher(nextChangeWatcher, oldValue);
// else {
// // Remove this change watcher from the list.
// log.warn("Change Watcher Result does not exist, NOT setting up to recalculate: " + nextChangeWatcher + " (" + classIdPair.toString() + ")");
// removeChangeWatcherForField(classIdPair, fieldNames, params, nextChangeWatcher);
}
}
}
@SuppressWarnings("unchecked")
protected Collection<String> getChangeWatchersForField(ClassIDPair classIdPair, String[] fieldNames, String[] params) {
Set<String> fieldWatcherKeys = new HashSet<String>();
if (fieldNames == null || fieldNames.length == 0) {
fieldWatcherKeys = getAllFieldWatchersForObject(classIdPair);
}
else {
for(String fieldName : fieldNames) {
if (fieldName.equals("*")) {
fieldWatcherKeys.addAll(getAllFieldWatchersForObject(classIdPair));
}
else {
String fieldWatcherKey = "";
// Also add for ALL objects of this class type
String allClassObjectsFieldWatcherKey = "";
if (params != null) {
fieldWatcherKey = RedisKeyUtils.fieldWatcher(RedisKeyUtils.changeWatcherWithParams(classIdPair.getClassName(), classIdPair.getID(), fieldName, params));
allClassObjectsFieldWatcherKey = RedisKeyUtils.fieldWatcher(RedisKeyUtils.changeWatcherWithParams(classIdPair.getClassName(), "0", fieldName, params));
}
else {
fieldWatcherKey = RedisKeyUtils.fieldWatcher(RedisKeyUtils.changeWatcher(classIdPair.getClassName(), classIdPair.getID(), fieldName));
allClassObjectsFieldWatcherKey = RedisKeyUtils.fieldWatcher(RedisKeyUtils.changeWatcher(classIdPair.getClassName(), "0", fieldName));
}
fieldWatcherKeys.add(fieldWatcherKey);
fieldWatcherKeys.add(allClassObjectsFieldWatcherKey);
}
}
}
// Also add for this object of this class type with NO field name
String noFieldWatcherKey = "";
// Also add for ALL objects of this class type with NO field name
String allClassObjectsNoFieldWatcherKey = "";
if (params != null) {
noFieldWatcherKey = RedisKeyUtils.fieldWatcher(RedisKeyUtils.changeWatcherWithParams(classIdPair.getClassName(), classIdPair.getID(), "", params));
allClassObjectsNoFieldWatcherKey = RedisKeyUtils.fieldWatcher(RedisKeyUtils.changeWatcherWithParams(classIdPair.getClassName(), "0", "", params));
}
else {
noFieldWatcherKey = RedisKeyUtils.fieldWatcher(RedisKeyUtils.changeWatcher(classIdPair.getClassName(), classIdPair.getID(), ""));
allClassObjectsNoFieldWatcherKey = RedisKeyUtils.fieldWatcher(RedisKeyUtils.changeWatcher(classIdPair.getClassName(), "0", ""));
}
fieldWatcherKeys.add(noFieldWatcherKey);
fieldWatcherKeys.add(allClassObjectsNoFieldWatcherKey);
Collection<String> changeWatchers = null;
if (fieldWatcherKeys.size() > 0) {
changeWatchers = (Set<String>) cacheDataStore.getSetUnion(noFieldWatcherKey, fieldWatcherKeys);
}
return changeWatchers;
}
protected Set<String> getAllFieldWatchersForObject(ClassIDPair classIdPair) {
Set<String> fieldWatcherKeys = new HashSet<String>();
String objectWatchedFieldKey = RedisKeyUtils.objectWatchedFields(classIdPair.getClassName(), classIdPair.getID());
// Also add for ALL objects of this class type
String allObjectsWatchedFieldKey = RedisKeyUtils.objectWatchedFields(classIdPair.getClassName(), "0");
String[] fieldKeys = {objectWatchedFieldKey, allObjectsWatchedFieldKey};
for(int i=0; i<fieldKeys.length; i++) {
String nextKey = fieldKeys[i];
Set<String> objectWatcherValueKeys = cacheDataStore.getHashKeys(nextKey);
Iterator<String> itrObjectWatcherValueKeys = objectWatcherValueKeys.iterator();
while (itrObjectWatcherValueKeys.hasNext()) {
String nextObjectWatcherValueKey = itrObjectWatcherValueKeys.next();
// Get all fields for this object that are being watched and remove them.
String changeWatcherKey = (String) cacheDataStore.getHashValue(nextKey, nextObjectWatcherValueKey);
fieldWatcherKeys.add(changeWatcherKey);
}
}
return fieldWatcherKeys;
}
protected Long removeChangeWatcherForField(ClassIDPair classIdPair, String[] fieldNames, String[] params, String changeWatcherId) {
Long result = Long.valueOf(0);
Set<String> fieldWatcherKeys = new HashSet<String>();
if (fieldNames == null || fieldNames.length == 0) {
fieldWatcherKeys = getAllFieldWatchersForObject(classIdPair);
}
else {
for(String fieldName : fieldNames) {
if (fieldName.equals("*")) {
fieldWatcherKeys.addAll(getAllFieldWatchersForObject(classIdPair));
}
else {
String fieldWatcherKey = "";
if (params != null)
fieldWatcherKey = RedisKeyUtils.fieldWatcher(RedisKeyUtils.changeWatcherWithParams(classIdPair.getClassName(), classIdPair.getID(), fieldName, params));
else
fieldWatcherKey = RedisKeyUtils.fieldWatcher(RedisKeyUtils.changeWatcher(classIdPair.getClassName(), classIdPair.getID(), fieldName));
fieldWatcherKeys.add(fieldWatcherKey);
}
}
}
if (fieldWatcherKeys.size() > 0) {
Iterator<String> itrFieldWatcherKeys = fieldWatcherKeys.iterator();
while (itrFieldWatcherKeys.hasNext()) {
String nextFieldWatcherKey = itrFieldWatcherKeys.next();
Long countRemoved = cacheDataStore.removeSetValue(nextFieldWatcherKey, changeWatcherId);
result += countRemoved;
}
}
return result;
}
protected void setupRecalculateChangeWatcher(String changeWatcherId, IPerceroObject oldValue) {
ChangeWatcherReporting.internalRequestsCounter++;
if (useChangeWatcherQueue && pushSyncHelper != null) {
pushSyncHelper.pushStringToRoute( (new StringBuilder(changeWatcherId).append(":TS:").append(System.currentTimeMillis())).toString(), changeWatcherRouteName);
}
else {
recalculateChangeWatcher(changeWatcherId, oldValue);
}
}
@SuppressWarnings("unchecked")
public void recalculateChangeWatcher(String changeWatcherId, IPerceroObject oldValue) {
try {
// Check to see if a timestamp has been included.
String[] changeWatcherTsArray = changeWatcherId.split(":TS:");
Long requestTimestamp = System.currentTimeMillis();
if (changeWatcherTsArray.length > 1) {
requestTimestamp = Long.valueOf(changeWatcherTsArray[1]);
changeWatcherId = changeWatcherTsArray[0];
}
// Need to break up
String[] params = changeWatcherId.split(":");
// 3rd var should be category.
String category = params[2];
// 4th var should be subCategory.
String subCategory = params[3];
// 5th var should be fieldName.
String fieldName = params[4];
String[] otherParams = null;
if (params.length > 5) {
otherParams = new String[params.length-5];
for(int i=5; i < params.length; i++) {
otherParams[i-5] = URLDecoder.decode(params[i], "UTF-8");
}
}
if (changeWatcherHelperFactory != null)
{
Collection <String> clientIds = (Set<String>) cacheDataStore.getSetValue(RedisKeyUtils.clientWatcher(changeWatcherId)); // The list of ClientID's who are interested in this object.
IChangeWatcherHelper cwh = changeWatcherHelperFactory.getHelper(category);
cwh.reprocess(category, subCategory, fieldName, clientIds, otherParams, requestTimestamp, oldValue);
/**
// If no clients interested in this value, then remove it from the cache.
if (clientIds == null || clientIds.isEmpty()) {
removeChangeWatcherResult(pair, fieldName, otherParams);
updateWatcherFields(pair, fieldName, fieldsToWatch, params);
if (watchedFields != null) {
Iterator<Object> itrOldWatchedFields = watchedFields.iterator();
while (itrOldWatchedFields.hasNext()) {
String nextOldField = (String) itrOldWatchedFields.next();
redisDataStore.removeSetValue(watcherField, nextOldField);
// Also remove this ChangeWatcher from the FieldWatcher.
redisDataStore.removeSetValue(nextOldField, changeWatcherId);
}
}
}**/
}
} catch(Exception e) {
log.error("Error recalculating Change Watcher: " + changeWatcherId, e);
}
}
public class ChangeWatcherTree {
public ChangeWatcherTree() {
this.changeWatcherMap = new TreeMap<String, List<String>>();
this.circularKeys = new TreeMap<String, List<String>>();
}
private SortedMap<String, List<String>> changeWatcherMap;
public SortedMap<String, List<String>> getChangeWatcherMap() {
return changeWatcherMap;
}
public void setChangeWatcherMap(SortedMap<String, List<String>> changeWatcherMap) {
this.changeWatcherMap = changeWatcherMap;
}
private SortedMap<String, List<String>> circularKeys;
public SortedMap<String, List<String>> getCircularKeys() {
return circularKeys;
}
public void setCircularKeys(SortedMap<String, List<String>> circularKeys) {
this.circularKeys = circularKeys;
}
}
/**
*
private static Boolean isWalkingChangeWatcherTree = false;
@Scheduled(fixedDelay=1000)
public void walkChangeWatcherTree() throws ClassNotFoundException {
if (isWalkingChangeWatcherTree) {
return;
}
else {
isWalkingChangeWatcherTree = true;
}
// Get all Change Watcher Keys
String fieldWatcherKey = RedisKeyUtils.fieldWatcher("*");
Collection<String> fieldWatcherKeys = new HashSet<String>();
fieldWatcherKeys.addAll(redisDataStore.keys(fieldWatcherKey));
Map<String, LinkedHashSet<String>> parentFieldWatcherMap = new HashMap<String, LinkedHashSet<String>>();
ChangeWatcherTree cwTree = new ChangeWatcherTree();
getChangeWatchersTree(cwTree, fieldWatcherKey, null, parentFieldWatcherMap);
for(String nextKey : parentFieldWatcherMap.keySet()) {
fillInParentChangeWatchers(nextKey, parentFieldWatcherMap);
}
Collection<Object> changeWatchers = null;
if (fieldWatcherKeys.size() > 0) {
changeWatchers = redisDataStore.getSetUnion(null, fieldWatcherKeys);
}
Map<Class, Map<String, Object>> watchersMap = new HashMap<Class, Map<String, Object>>();
for(Object nextChangeWatcher : changeWatchers) {
// Should be of the form: cw:cf:com.psiglobal.mo.LongHaul:9d23fbaa-cf9a-49a0-becb-e3bc4e458282:vessels:...
// Break down into parts
String strChangeWatcher = (String) nextChangeWatcher;
String[] parts = strChangeWatcher.split(":");
if (parts.length >= 5) {
String className = parts[2];
Class clazz = Class.forName(className);
String classId = parts[3];
String fieldName = parts[4];
Map<String, Object> classMap = watchersMap.get(clazz);
if (classMap == null) {
classMap = new HashMap<String, Object>();
watchersMap.put(clazz, classMap);
}
}
System.out.println("Next Change Watcher");
}
isWalkingChangeWatcherTree = false;
}
public void fillInParentChangeWatchers(String nextKey, Map<String, LinkedHashSet<String>> parentFieldWatcherMap) {
LinkedHashSet<String> nextSet = parentFieldWatcherMap.get(nextKey);
Set<String> itemsToAdd = new HashSet<String>();
for(String nextSetKey : nextSet) {
fillInParentChangeWatchers(nextSetKey, parentFieldWatcherMap);
LinkedHashSet<String> nextSetSet = parentFieldWatcherMap.get(nextSetKey);
itemsToAdd.addAll(nextSetSet);
if (nextSetSet.contains(nextKey)) {
System.out.println("Houston, we have a problem: " + nextKey);
String strProblemPath = "";
for(String nextProblemKey : nextSetSet) {
strProblemPath += ", " + nextProblemKey;
}
System.out.println(strProblemPath);
}
// if (nextSetSet != null) {
// for(String nextSetSetKey : nextSetSet) {
// if (nextSetSetKey.equalsIgnoreCase(nextKey)) {
// System.out.println("Houston, we have a problem...");
// }
// else {
// nextSet.add(nextSetSetKey);
// }
// }
// }
}
nextSet.addAll(itemsToAdd);
}
**/
}
|
package de.fuberlin.wiwiss.pubby.servlets;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.context.Context;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.Resource;
import de.fuberlin.wiwiss.pubby.Configuration;
import de.fuberlin.wiwiss.pubby.MappedResource;
import de.fuberlin.wiwiss.pubby.ResourceDescription;
/**
* A servlet for serving the HTML page describing a resource.
* Invokes a Velocity template.
*
* @author Richard Cyganiak (richard@cyganiak.de)
* @version $Id$
*/
public class PageURLServlet extends BaseURLServlet {
public boolean doGet(MappedResource resource,
HttpServletRequest request,
HttpServletResponse response,
Configuration config) throws ServletException, IOException {
Model description = getResourceDescription(resource);
if (description.size() == 0) {
return false;
}
Velocity.setProperty("velocimacro.context.localscope", Boolean.TRUE);
ResourceDescription resourceDescription = new ResourceDescription(
resource, description, config);
String discoLink = "http://www4.wiwiss.fu-berlin.de/rdf_browser/?browse_uri=" +
URLEncoder.encode(resource.getWebURI(), "utf-8");
String tabulatorLink = "http://dig.csail.mit.edu/2005/ajar/ajaw/tab.html?uri=" +
URLEncoder.encode(resource.getWebURI(), "utf-8");
String openLinkLink = "http://linkeddata.uriburner.com/ode/?uri=" +
URLEncoder.encode(resource.getWebURI(), "utf-8");
VelocityHelper template = new VelocityHelper(getServletContext(), response);
Context context = template.getVelocityContext();
context.put("project_name", config.getProjectName());
context.put("project_link", config.getProjectLink());
context.put("uri", resourceDescription.getURI());
context.put("server_base", config.getWebApplicationBaseURI());
context.put("rdf_link", resource.getDataURL());
context.put("disco_link", discoLink);
context.put("tabulator_link", tabulatorLink);
context.put("openlink_link", openLinkLink);
context.put("sparql_endpoint", resource.getDataset().getDataSource().getEndpointURL());
context.put("title", resourceDescription.getLabel());
context.put("comment", resourceDescription.getComment());
context.put("image", resourceDescription.getImageURL());
context.put("properties", resourceDescription.getProperties());
try {
Model metadata = ModelFactory.createDefaultModel();
Resource documentRepresentation = resource.getDataset().addMetadataFromTemplate( metadata, resource, getServletContext() );
// Replaced the commented line by the following one because the
// RDF graph we want to talk about is a specific representation
// of the data identified by the getDataURL() URI.
// Olaf, May 28, 2010
// context.put("metadata", metadata.getResource(resource.getDataURL()));
context.put("metadata", documentRepresentation);
Map nsSet = metadata.getNsPrefixMap();
nsSet.putAll(description.getNsPrefixMap());
context.put("prefixes", nsSet.entrySet());
context.put("blankNodesMap", new HashMap());
}
catch (Exception e) {
context.put("metadata", Boolean.FALSE);
}
template.renderXHTML("page.vm");
return true;
}
}
|
package de.schooltec.datapass;
import android.util.Log;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Class providing all necessary data from the T-Mobile datapass homepage. Therefore: creates a server connection,
* retrieves and parses the html content and extracts the desired information according to a given regex
*
* @author Martin Hellwig
* @author Markus Hettig
*/
class DataSupplier
{
private final static String URL = "http://datapass.de/";
private final static String TRAFFIC_REGEX = "(\\d{0,1}\\.?\\d{1,3},?\\d{0,4}.(GB|MB|KB))";
private final static String LAST_UPDATE_REGEX = "(\\d{2}\\.\\d{2}\\.\\d{4}.{4}\\d{2}:\\d{2})";
private String trafficWasted;
private String trafficAvailable;
private int trafficWastedPercentage = 0;
private String lastUpdate;
/**
* Initializes the DataSupplier.
*
* @return True if all data were gathered successfully, false otherwise.
*/
boolean initialize()
{
try
{
String htmlContent = getStringFromUrl();
// First: get the two traffic relevant values
Pattern pattern = Pattern.compile(TRAFFIC_REGEX);
Matcher matcher = pattern.matcher(htmlContent);
int i = 0;
while (matcher.find())
{
if (i == 0) trafficWasted = matcher.group(1).trim();
if (i == 1) trafficAvailable = matcher.group(1).trim();
i++;
}
float trafficWastedFloat = Float
.parseFloat(trafficWasted.substring(0, trafficWasted.length() - 3)
.replace(".", "").replace(",", "."));
float trafficAvailableFloat = Float
.parseFloat(trafficAvailable.substring(0, trafficAvailable.length() - 3)
.replace(".", "").replace(",", "."));
// Calculate percentages used according to used unit (MB or GB)
if (trafficWasted.contains("GB"))
{
if (trafficAvailable.contains("GB"))
{
trafficWastedPercentage = (int) ((trafficWastedFloat / trafficAvailableFloat) * 100f);
}
else
{ //We assume the trafficAvailable is in MB (rare edge case)
trafficWastedPercentage = (int) ((trafficWastedFloat * 1024f / trafficAvailableFloat) * 100f);
}
}
else if (trafficWasted.contains("MB"))
{
if (trafficAvailable.contains("GB"))
{
trafficWastedPercentage = (int) ((trafficWastedFloat / (trafficAvailableFloat * 1024f)) * 100f);
}
else
{ //We assume the trafficAvailable is in MB
trafficWastedPercentage = (int) ((trafficWastedFloat / trafficAvailableFloat) * 100f);
}
}
// Second: get the date of last update
pattern = Pattern.compile(LAST_UPDATE_REGEX);
matcher = pattern.matcher(htmlContent);
while (matcher.find())
{
Date inputDate = new SimpleDateFormat("dd.MM.yyyy 'um' HH:mm", Locale.GERMAN).parse(matcher.group(1));
SimpleDateFormat outputDate = new SimpleDateFormat("dd.MM - HH:mm", Locale.GERMAN);
lastUpdate = outputDate.format(inputDate);
}
return true;
}
catch (Exception e)
{
e.printStackTrace();
return false;
}
}
/**
* "Connects" to the data passe homepage, parses the content and return it as a string.
*
* @return Parsed homepage.
*
* @throws IOException
* If connection fails.
*/
private String getStringFromUrl() throws IOException
{
HttpURLConnection conn = (HttpURLConnection) new URL(URL).openConnection();
// Set Timeout and method
conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 5.1; rv:19.0) Gecko/20100101 Firefox/19.0");
conn.setReadTimeout(7000);
conn.setConnectTimeout(7000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
// Add any data you wish to post here
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.flush();
writer.close();
os.close();
conn.connect();
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
// Convert BufferedReader to String
String result = "";
String inputLine;
while ((inputLine = br.readLine()) != null)
{
result += inputLine;
}
return result;
}
/**
* @return The traffic used by the user (e.g. 125MB from 500MB totally available).
*/
String getTrafficWasted()
{
return trimTrafficString(trafficWasted);
}
/**
* @return The traffic available for the current period according to the contract (e.g. 500MB).
*/
String getTrafficAvailable()
{
return trimTrafficString(trafficAvailable);
}
/**
* Trims the input string by the unit (MB or GB). Additionally removes all decimal places for MB values.
*
* @param input
* Input string.
*
* @return Trimmed output string.
*/
private String trimTrafficString(String input)
{
// Ignore digits after the decimal point for MB values as it is not very informative and takes too much space
if (this.trafficAvailable.contains("MB")) input = input.replaceFirst(",[0-9]+", "");
// Remove unit
return input.replaceFirst("\\s(MB|GB)", "");
}
/**
* @return The unit (MB or GB) of the used / available traffic.
*/
String getTrafficUnit()
{
return trafficWasted.split("\\s")[1] + "/" + trafficAvailable.split("\\s")[1];
}
/**
* @return The used traffic as a percentage value (e.g. 42%).
*/
int getTrafficWastedPercentage()
{
return this.trafficWastedPercentage;
}
/**
* @return Timestamp when the values where updated by T-Mobile. Might lay a few hours in the past.
*/
String getLastUpdate()
{
return this.lastUpdate;
}
}
|
package com.plaid.client.response;
import java.util.List;
/**
* Response object for /transactions/get endpoint.
*/
public final class TransactionsGetResponse extends BaseResponse {
private ItemStatus item;
private List<Account> accounts;
private List<Transaction> transactions;
private Integer totalTransactions;
public ItemStatus getItem() {
return item;
}
public List<Account> getAccounts() {
return accounts;
}
public List<Transaction> getTransactions() {
return transactions;
}
public Integer getTotalTransactions() {
return totalTransactions;
}
public static final class Transaction {
private String accountId;
private Double amount;
private String isoCurrencyCode;
private String unofficialCurrencyCode;
private List<String> category;
private String categoryId;
private String date;
private Location location;
private String merchantName;
private String name;
private String originalDescription;
private PaymentMeta paymentMeta;
private Boolean pending;
private String pendingTransactionId;
private String transactionId;
private String transactionType;
private String accountOwner;
private String authorizedDate;
private String transactionCode;
private String paymentChannel;
public String getTransactionId() {
return transactionId;
}
public String getAccountId() {
return accountId;
}
public Boolean getPending() {
return pending;
}
public String getPendingTransactionId() {
return pendingTransactionId;
}
public String getTransactionType() {
return transactionType;
}
public PaymentMeta getPaymentMeta() {
return paymentMeta;
}
public String getDate() {
return date;
}
public String getMerchantName() {
return merchantName;
}
public String getName() {
return name;
}
public Double getAmount() {
return amount;
}
public String getIsoCurrencyCode() {
return isoCurrencyCode;
}
public String getUnofficialCurrencyCode() {
return unofficialCurrencyCode;
}
public List<String> getCategory() {
return category;
}
public String getCategoryId() {
return categoryId;
}
public Location getLocation() {
return location;
}
public String getOriginalDescription() {
return originalDescription;
}
public String getAccountOwner() {
return accountOwner;
}
public String getAuthorizedDate() {
return authorizedDate;
}
public String getTransactionCode() {
return transactionCode;
}
public String getPaymentChannel() {
return paymentChannel;
}
public static final class PaymentMeta {
private String byOrderOf;
private String payee;
private String payer;
private String paymentMethod;
private String paymentProcessor;
private String ppdId;
private String reason;
private String referenceNumber;
public String getByOrderOf() {
return byOrderOf;
}
public String getPayee() {
return payee;
}
public String getPayer() {
return payer;
}
public String getPaymentMethod() {
return paymentMethod;
}
public String getPaymentProcessor() {
return paymentProcessor;
}
public String getPpdId() {
return ppdId;
}
public String getReason() {
return reason;
}
public String getReferenceNumber() {
return referenceNumber;
}
}
public static final class Location {
private String address;
private String city;
private Double lat;
private Double lon;
private String region;
private String storeNumber;
private String postalCode;
private String country;
public String getAddress() {
return address;
}
public String getCity() {
return city;
}
public Double getLat() {
return lat;
}
public Double getLon() {
return lon;
}
public String getRegion() {
return region;
}
public String getStoreNumber() {
return storeNumber;
}
public String getPostalCode() {
return postalCode;
}
public String getCountry() {
return country;
}
}
}
}
|
package de.gurkenlabs.litiengine.environment;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.Shape;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import de.gurkenlabs.litiengine.Game;
import de.gurkenlabs.litiengine.IUpdateable;
import de.gurkenlabs.litiengine.annotation.EntityInfo;
import de.gurkenlabs.litiengine.configuration.Quality;
import de.gurkenlabs.litiengine.entities.CollisionBox;
import de.gurkenlabs.litiengine.entities.Creature;
import de.gurkenlabs.litiengine.entities.ICollisionEntity;
import de.gurkenlabs.litiengine.entities.ICombatEntity;
import de.gurkenlabs.litiengine.entities.IEntity;
import de.gurkenlabs.litiengine.entities.IMobileEntity;
import de.gurkenlabs.litiengine.entities.Prop;
import de.gurkenlabs.litiengine.entities.Trigger;
import de.gurkenlabs.litiengine.environment.tilemap.IMap;
import de.gurkenlabs.litiengine.environment.tilemap.IMapObject;
import de.gurkenlabs.litiengine.environment.tilemap.IMapObjectLayer;
import de.gurkenlabs.litiengine.environment.tilemap.MapArea;
import de.gurkenlabs.litiengine.environment.tilemap.MapLoader;
import de.gurkenlabs.litiengine.environment.tilemap.MapProperty;
import de.gurkenlabs.litiengine.environment.tilemap.MapUtilities;
import de.gurkenlabs.litiengine.environment.tilemap.Spawnpoint;
import de.gurkenlabs.litiengine.graphics.AmbientLight;
import de.gurkenlabs.litiengine.graphics.DebugRenderer;
import de.gurkenlabs.litiengine.graphics.IRenderable;
import de.gurkenlabs.litiengine.graphics.LightSource;
import de.gurkenlabs.litiengine.graphics.RenderType;
import de.gurkenlabs.litiengine.graphics.StaticShadow;
import de.gurkenlabs.litiengine.graphics.StaticShadowLayer;
import de.gurkenlabs.litiengine.graphics.StaticShadowType;
import de.gurkenlabs.litiengine.graphics.particles.Emitter;
import de.gurkenlabs.litiengine.util.TimeUtilities;
import de.gurkenlabs.litiengine.util.geom.GeometricUtilities;
import de.gurkenlabs.litiengine.util.io.FileUtilities;
public class Environment implements IEnvironment {
private static final Logger log = Logger.getLogger(Environment.class.getName());
private static final Map<String, IMapObjectLoader> mapObjectLoaders;
private final Map<Integer, ICombatEntity> combatEntities;
private final Map<Integer, IMobileEntity> mobileEntities;
private final Map<RenderType, Map<Integer, IEntity>> entities;
private final Map<String, List<IEntity>> entitiesByTag;
private final Map<RenderType, Collection<EnvironmentRenderListener>> renderListeners;
private final List<EnvironmentListener> listeners;
private final List<EnvironmentEntityListener> entityListeners;
private final Map<RenderType, Collection<IRenderable>> renderables;
private final Collection<CollisionBox> colliders;
private final Collection<LightSource> lightSources;
private final Collection<StaticShadow> staticShadows;
private final Collection<Trigger> triggers;
private final Collection<Prop> props;
private final Collection<Emitter> emitters;
private final Collection<Creature> creatures;
private final Collection<Spawnpoint> spawnPoints;
private final Collection<MapArea> mapAreas;
private AmbientLight ambientLight;
private StaticShadowLayer staticShadowLayer;
private boolean loaded;
private boolean initialized;
private IMap map;
private int localIdSequence = 0;
private int mapIdSequence;
static {
mapObjectLoaders = new ConcurrentHashMap<>();
registerDefaultMapObjectLoaders();
}
public Environment(final IMap map) {
this();
this.map = map;
this.mapIdSequence = MapUtilities.getMaxMapId(this.getMap());
Game.getPhysicsEngine().setBounds(this.getMap().getBounds());
}
public Environment(final String mapPath) {
this();
final IMap loadedMap = Game.getMap(FileUtilities.getFileName(mapPath));
if (loadedMap == null) {
this.map = MapLoader.load(mapPath);
} else {
this.map = loadedMap;
}
this.mapIdSequence = MapUtilities.getMaxMapId(this.getMap());
Game.getPhysicsEngine().setBounds(new Rectangle(this.getMap().getSizeInPixels()));
}
private Environment() {
this.entitiesByTag = new ConcurrentHashMap<>();
this.entities = Collections.synchronizedMap(new EnumMap<>(RenderType.class));
this.combatEntities = new ConcurrentHashMap<>();
this.mobileEntities = new ConcurrentHashMap<>();
this.lightSources = Collections.newSetFromMap(new ConcurrentHashMap<LightSource, Boolean>());
this.colliders = Collections.newSetFromMap(new ConcurrentHashMap<CollisionBox, Boolean>());
this.triggers = Collections.newSetFromMap(new ConcurrentHashMap<Trigger, Boolean>());
this.mapAreas = Collections.newSetFromMap(new ConcurrentHashMap<MapArea, Boolean>());
this.staticShadows = Collections.newSetFromMap(new ConcurrentHashMap<StaticShadow, Boolean>());
this.props = Collections.newSetFromMap(new ConcurrentHashMap<Prop, Boolean>());
this.emitters = Collections.newSetFromMap(new ConcurrentHashMap<Emitter, Boolean>());
this.creatures = Collections.newSetFromMap(new ConcurrentHashMap<Creature, Boolean>());
this.spawnPoints = Collections.newSetFromMap(new ConcurrentHashMap<Spawnpoint, Boolean>());
this.renderables = Collections.synchronizedMap(new EnumMap<>(RenderType.class));
this.renderListeners = Collections.synchronizedMap(new EnumMap<>(RenderType.class));
this.listeners = new CopyOnWriteArrayList<>();
this.entityListeners = new CopyOnWriteArrayList<>();
for (RenderType renderType : RenderType.values()) {
this.entities.put(renderType, new ConcurrentHashMap<>());
this.renderListeners.put(renderType, Collections.newSetFromMap(new ConcurrentHashMap<EnvironmentRenderListener, Boolean>()));
this.renderables.put(renderType, Collections.newSetFromMap(new ConcurrentHashMap<IRenderable, Boolean>()));
}
}
@Override
public void addRenderListener(RenderType renderType, EnvironmentRenderListener listener) {
this.renderListeners.get(renderType).add(listener);
}
@Override
public void removeRenderListener(EnvironmentRenderListener listener) {
for (Collection<EnvironmentRenderListener> rends : this.renderListeners.values()) {
rends.remove(listener);
}
}
@Override
public void addListener(EnvironmentListener listener) {
this.listeners.add(listener);
}
@Override
public void removeListener(EnvironmentListener listener) {
this.listeners.remove(listener);
}
@Override
public void addEntityListener(EnvironmentEntityListener listener) {
this.entityListeners.add(listener);
}
@Override
public void removeEntityListener(EnvironmentEntityListener listener) {
this.entityListeners.remove(listener);
}
@Override
public void add(final IEntity entity) {
if (entity == null) {
return;
}
// set local map id if none is set for the entity
if (entity.getMapId() == 0) {
entity.setMapId(this.getLocalMapId());
}
if (entity instanceof Emitter) {
Emitter emitter = (Emitter) entity;
this.addEmitter(emitter);
}
if (entity instanceof ICombatEntity) {
this.combatEntities.put(entity.getMapId(), (ICombatEntity) entity);
}
if (entity instanceof IMobileEntity) {
this.mobileEntities.put(entity.getMapId(), (IMobileEntity) entity);
}
if (entity instanceof Prop) {
this.props.add((Prop) entity);
}
if (entity instanceof Creature) {
this.creatures.add((Creature) entity);
}
if (entity instanceof CollisionBox) {
this.colliders.add((CollisionBox) entity);
}
if (entity instanceof LightSource) {
this.lightSources.add((LightSource) entity);
}
if (entity instanceof Trigger) {
this.triggers.add((Trigger) entity);
}
if (entity instanceof Spawnpoint) {
this.spawnPoints.add((Spawnpoint) entity);
}
if (entity instanceof StaticShadow) {
this.staticShadows.add((StaticShadow) entity);
} else if (entity instanceof MapArea) {
this.mapAreas.add((MapArea) entity);
}
for (String rawTag : entity.getTags()) {
if (rawTag == null) {
continue;
}
final String tag = rawTag.trim().toLowerCase();
if (tag.isEmpty()) {
continue;
}
if (this.getEntitiesByTag().containsKey(tag)) {
this.getEntitiesByTag().get(tag).add(entity);
continue;
}
this.getEntitiesByTag().put(tag, new CopyOnWriteArrayList<>());
this.getEntitiesByTag().get(tag).add(entity);
}
// if the environment has already been loaded,
// we need to load the new entity manually
if (this.loaded) {
this.load(entity);
}
this.entities.get(entity.getRenderType()).put(entity.getMapId(), entity);
this.fireEntityEvent(l -> l.entityAdded(entity));
}
private void addEmitter(Emitter emitter) {
this.manageEmitterRenderables(emitter, (rends, instance) -> rends.add(instance));
this.emitters.add(emitter);
}
private void removeEmitter(Emitter emitter) {
this.manageEmitterRenderables(emitter, (rends, instance) -> rends.remove(instance));
this.emitters.remove(emitter);
}
private void manageEmitterRenderables(Emitter emitter, BiConsumer<Collection<IRenderable>, IRenderable> cons) {
for (RenderType renderType : RenderType.values()) {
if (renderType == RenderType.NONE) {
continue;
}
IRenderable renderable = emitter.getRenderable(renderType);
if (renderable != null) {
cons.accept(this.getRenderables(renderType), renderable);
}
}
this.emitters.remove(emitter);
}
private void updateColorLayers(IEntity entity) {
if (this.staticShadowLayer != null) {
this.staticShadowLayer.updateSection(entity.getBoundingBox());
}
if (this.ambientLight != null) {
this.ambientLight.updateSection(entity.getBoundingBox());
}
}
@Override
public void add(IRenderable renderable, RenderType renderType) {
this.getRenderables(renderType).add(renderable);
}
@Override
public void clear() {
Game.getPhysicsEngine().clear();
this.dispose(this.getEntities());
this.dispose(this.getTriggers());
this.getCombatEntities().clear();
this.getMobileEntities().clear();
this.getLightSources().clear();
this.getCollisionBoxes().clear();
this.getSpawnPoints().clear();
this.getAreas().clear();
this.getTriggers().clear();
this.getEntitiesByTag().clear();
for (Map<Integer, IEntity> type : this.entities.values()) {
type.clear();
}
this.initialized = false;
this.fireEvent(l -> l.environmentCleared(this));
}
@Override
public List<ICombatEntity> findCombatEntities(final Shape shape) {
return this.findCombatEntities(shape, entity -> true);
}
@Override
public List<ICombatEntity> findCombatEntities(final Shape shape, final Predicate<ICombatEntity> condition) {
final ArrayList<ICombatEntity> foundCombatEntities = new ArrayList<>();
if (shape == null) {
return foundCombatEntities;
}
// for rectangle we can just use the intersects method
if (shape instanceof Rectangle2D) {
final Rectangle2D rect = (Rectangle2D) shape;
for (final ICombatEntity combatEntity : this.getCombatEntities().stream().filter(condition).collect(Collectors.toList())) {
if (combatEntity.getHitBox().intersects(rect)) {
foundCombatEntities.add(combatEntity);
}
}
return foundCombatEntities;
}
// for other shapes, we check if the shape's bounds intersect the hitbox and
// if so, we then check if the actual shape intersects the hitbox
for (final ICombatEntity combatEntity : this.getCombatEntities().stream().filter(condition).collect(Collectors.toList())) {
if (combatEntity.getHitBox().intersects(shape.getBounds()) && GeometricUtilities.shapeIntersects(combatEntity.getHitBox(), shape)) {
foundCombatEntities.add(combatEntity);
}
}
return foundCombatEntities;
}
@Override
public List<IEntity> findEntities(final Shape shape) {
final ArrayList<IEntity> foundEntities = new ArrayList<>();
if (shape == null) {
return foundEntities;
}
if (shape instanceof Rectangle2D) {
final Rectangle2D rect = (Rectangle2D) shape;
for (final IEntity entity : this.getEntities()) {
if (entity.getBoundingBox().intersects(rect)) {
foundEntities.add(entity);
}
}
return foundEntities;
}
// for other shapes, we check if the shape's bounds intersect the hitbox
// and
// if so, we then check if the actual shape intersects the hitbox
for (final IEntity entity : this.getEntities()) {
if (entity.getBoundingBox().intersects(shape.getBounds()) && GeometricUtilities.shapeIntersects(entity.getBoundingBox(), shape)) {
foundEntities.add(entity);
}
}
return foundEntities;
}
@Override
public IEntity get(final int mapId) {
for (RenderType type : RenderType.values()) {
IEntity entity = this.entities.get(type).get(mapId);
if (entity != null) {
return entity;
}
}
return null;
}
@Override
public <T extends IEntity> T get(Class<T> clss, int mapId) {
IEntity ent = this.get(mapId);
if (ent == null || !clss.isInstance(ent)) {
return null;
}
return (T) ent;
}
@Override
public IEntity get(final String name) {
if (name == null || name.isEmpty()) {
return null;
}
for (RenderType type : RenderType.values()) {
for (final IEntity entity : this.entities.get(type).values()) {
if (entity.getName() != null && entity.getName().equals(name)) {
return entity;
}
}
}
return null;
}
@Override
public <T extends IEntity> T get(Class<T> clss, String name) {
IEntity ent = this.get(name);
if (ent == null || !clss.isInstance(ent)) {
return null;
}
return (T) ent;
}
@Override
public <T extends IEntity> Collection<T> getByTag(String... tags) {
return this.getByTag(null, tags);
}
@Override
public <T extends IEntity> Collection<T> getByTag(Class<T> clss, String... tags) {
List<T> foundEntities = new ArrayList<>();
for (String rawTag : tags) {
String tag = rawTag.toLowerCase();
if (!this.getEntitiesByTag().containsKey(tag)) {
continue;
}
for (IEntity ent : this.getEntitiesByTag().get(tag)) {
if ((clss == null || clss.isInstance(ent)) && !foundEntities.contains((T) ent)) {
foundEntities.add((T) ent);
}
}
}
return foundEntities;
}
@Override
public AmbientLight getAmbientLight() {
return this.ambientLight;
}
@Override
public Collection<MapArea> getAreas() {
return this.mapAreas;
}
@Override
public MapArea getArea(final int mapId) {
return getById(this.getAreas(), mapId);
}
@Override
public MapArea getArea(final String name) {
return getByName(this.getAreas(), name);
}
@Override
public Collection<Emitter> getEmitters() {
return this.emitters;
}
@Override
public Emitter getEmitter(int mapId) {
return getById(this.getEmitters(), mapId);
}
@Override
public Emitter getEmitter(String name) {
return getByName(this.getEmitters(), name);
}
@Override
public Collection<CollisionBox> getCollisionBoxes() {
return this.colliders;
}
@Override
public CollisionBox getCollisionBox(int mapId) {
return getById(this.getCollisionBoxes(), mapId);
}
@Override
public CollisionBox getCollisionBox(String name) {
return getByName(this.getCollisionBoxes(), name);
}
@Override
public Collection<ICombatEntity> getCombatEntities() {
return this.combatEntities.values();
}
@Override
public ICombatEntity getCombatEntity(final int mapId) {
return getById(this.getCombatEntities(), mapId);
}
@Override
public ICombatEntity getCombatEntity(String name) {
return getByName(this.getCombatEntities(), name);
}
@Override
public Collection<IEntity> getEntities() {
final ArrayList<IEntity> ent = new ArrayList<>();
for (Map<Integer, IEntity> type : this.entities.values()) {
ent.addAll(type.values());
}
return ent;
}
@Override
public Collection<IEntity> getEntities(final RenderType renderType) {
return this.entities.get(renderType).values();
}
public Map<String, List<IEntity>> getEntitiesByTag() {
return this.entitiesByTag;
}
@Override
public <T extends IEntity> Collection<T> getByType(Class<T> cls) {
List<T> foundEntities = new ArrayList<>();
for (IEntity ent : this.getEntities()) {
if (cls.isInstance(ent)) {
foundEntities.add((T) ent);
}
}
return foundEntities;
}
@Override
public Collection<LightSource> getLightSources() {
return this.lightSources;
}
@Override
public LightSource getLightSource(final int mapId) {
return getById(this.getLightSources(), mapId);
}
@Override
public LightSource getLightSource(String name) {
return getByName(this.getLightSources(), name);
}
/**
* Negative map ids are only used locally.
*/
@Override
public synchronized int getLocalMapId() {
return --localIdSequence;
}
@Override
public IMap getMap() {
return this.map;
}
@Override
public Collection<IMobileEntity> getMobileEntities() {
return this.mobileEntities.values();
}
@Override
public IMobileEntity getMobileEntity(final int mapId) {
return getById(this.getMobileEntities(), mapId);
}
@Override
public IMobileEntity getMobileEntity(String name) {
return getByName(this.getMobileEntities(), name);
}
@Override
public synchronized int getNextMapId() {
return ++mapIdSequence;
}
@Override
public Collection<IRenderable> getRenderables(RenderType renderType) {
return this.renderables.get(renderType);
}
@Override
public Collection<Prop> getProps() {
return this.props;
}
@Override
public Prop getProp(int mapId) {
return getById(this.getProps(), mapId);
}
@Override
public Prop getProp(String name) {
return getByName(this.getProps(), name);
}
@Override
public Creature getCreature(int mapId) {
return getById(this.getCreatures(), mapId);
}
@Override
public Creature getCreature(String name) {
return getByName(this.getCreatures(), name);
}
@Override
public Collection<Creature> getCreatures() {
return this.creatures;
}
@Override
public Spawnpoint getSpawnpoint(final int mapId) {
return getById(this.getSpawnPoints(), mapId);
}
@Override
public Spawnpoint getSpawnpoint(final String name) {
return getByName(this.getSpawnPoints(), name);
}
@Override
public Collection<Spawnpoint> getSpawnPoints() {
return this.spawnPoints;
}
@Override
public Collection<StaticShadow> getStaticShadows() {
return this.staticShadows;
}
@Override
public StaticShadow getStaticShadow(int mapId) {
return getById(this.getStaticShadows(), mapId);
}
@Override
public StaticShadow getStaticShadow(String name) {
return getByName(this.getStaticShadows(), name);
}
@Override
public StaticShadowLayer getStaticShadowLayer() {
return this.staticShadowLayer;
}
@Override
public Trigger getTrigger(final int mapId) {
return getById(this.getTriggers(), mapId);
}
@Override
public Trigger getTrigger(final String name) {
return getByName(this.getTriggers(), name);
}
@Override
public Collection<Trigger> getTriggers() {
return this.triggers;
}
@Override
public List<String> getUsedTags() {
final List<String> tags = this.getEntitiesByTag().keySet().stream().collect(Collectors.toList());
Collections.sort(tags);
return tags;
}
@Override
public final void init() {
if (this.initialized) {
return;
}
this.loadMapObjects();
this.addStaticShadows();
this.addAmbientLight();
this.fireEvent(l -> l.environmentInitialized(this));
this.initialized = true;
}
@Override
public boolean isLoaded() {
return this.loaded;
}
@Override
public void load() {
this.init();
if (this.loaded) {
return;
}
Game.getPhysicsEngine().setBounds(new Rectangle2D.Double(0, 0, this.getMap().getSizeInPixels().getWidth(), this.getMap().getSizeInPixels().getHeight()));
for (final IEntity entity : this.getEntities()) {
this.load(entity);
}
this.loaded = true;
this.fireEvent(l -> l.environmentLoaded(this));
}
@Override
public void loadFromMap(final int mapId) {
for (final IMapObjectLayer layer : this.getMap().getMapObjectLayers()) {
Optional<IMapObject> opt = layer.getMapObjects().stream().filter(mapObject -> mapObject.getType() != null && !mapObject.getType().isEmpty() && mapObject.getId() == mapId).findFirst();
if (opt.isPresent()) {
this.load(opt.get());
break;
}
}
}
/**
* Registers a custom loader instance that is responsible for loading and initializing entities of the defined
* MapObjectType.
* <br>
* <br>
* There can only be one loader for a particular type. Calling this method again for the same type will overwrite the previously registered loader.
*
* @param mapObjectLoader
* The MapObjectLoader instance to be registered.
*
* @see IMapObjectLoader#getMapObjectType()
*/
public static void registerMapObjectLoader(IMapObjectLoader mapObjectLoader) {
mapObjectLoaders.put(mapObjectLoader.getMapObjectType(), mapObjectLoader);
}
/**
* Registers a custom <code>IEntity</code> implementation to support being loaded from an <code>IMap</code> instance.
* Note that the specified class needs to be accessible in a static manner. Inner classes that aren't declared statically are not supported.
*
* This is an overload of the {@link #registerCustomEntityType(Class)} method that allows to explicitly specify the <code>MapObjectType</code>
* without
* having to provide an <code>EntityInfo</code> annotation containing this information.
*
* @param <T>
* The type of the custom entity.
* @param mapObjectType
* The custom mapobjectType that is used by <code>IMapObjects</code> to determine the target entity implementation.
* @param entityType
* The class type of the custom entity implementation.
*
* @see IMapObject#getType()
* @see EntityInfo#customMapObjectType()
*/
public static <T extends IEntity> void registerCustomEntityType(String mapObjectType, Class<T> entityType) {
CustomMapObjectLoader<T> mapObjectLoader = new CustomMapObjectLoader<>(mapObjectType, entityType);
registerMapObjectLoader(mapObjectLoader);
}
/**
* Registers a custom <code>IEntity</code> implementation to support being loaded from an <code>IMap</code> instance.
* Note that the specified class needs to be accessible in a static manner. Inner classes that aren't declared statically are not supported.
*
* This implementation uses the provided <code>EntityInfo.customMapObjectType()</code> to determine for which type the specified class should be
* used.
*
* @param <T>
* The type of the custom entity.
* @param entityType
* The class type of the custom entity implementation.
*
* @see Environment#registerCustomEntityType(String, Class)
* @see IMapObject#getType()
* @see EntityInfo#customMapObjectType()
*/
public static <T extends IEntity> void registerCustomEntityType(Class<T> entityType) {
EntityInfo info = entityType.getAnnotation(EntityInfo.class);
if (info == null || info.customMapObjectType().isEmpty()) {
throw new IllegalArgumentException(
"Cannot register a custom entity type without the related EntityInfo.customMapObjectType being specified.\n Add an EntityInfo annotation to the " + entityType + " class and provide the required information or use the registerCustomEntityType overload and provide the type explicitly.");
}
registerCustomEntityType(info.customMapObjectType(), entityType);
}
@Override
public void reloadFromMap(final int mapId) {
this.remove(mapId);
this.loadFromMap(mapId);
}
@Override
public void remove(final IEntity entity) {
if (entity == null) {
return;
}
if (this.entities.get(entity.getRenderType()) != null) {
this.entities.get(entity.getRenderType()).entrySet().removeIf(e -> e.getValue().getMapId() == entity.getMapId());
}
for (String tag : entity.getTags()) {
this.getEntitiesByTag().get(tag).remove(entity);
if (this.getEntitiesByTag().get(tag).isEmpty()) {
this.getEntitiesByTag().remove(tag);
}
}
if (entity instanceof Emitter) {
Emitter emitter = (Emitter) entity;
this.removeEmitter(emitter);
}
if (entity instanceof MapArea) {
this.mapAreas.remove(entity);
}
if (entity instanceof Prop) {
this.props.remove(entity);
}
if (entity instanceof Creature) {
this.creatures.remove(entity);
}
if (entity instanceof CollisionBox) {
this.colliders.remove(entity);
this.staticShadows.removeIf(x -> x.getOrigin() != null && x.getOrigin().equals(entity));
}
if (entity instanceof LightSource) {
this.lightSources.remove(entity);
this.updateColorLayers(entity);
}
if (entity instanceof Trigger) {
this.triggers.remove(entity);
}
if (entity instanceof Spawnpoint) {
this.spawnPoints.remove(entity);
}
if (entity instanceof StaticShadow) {
this.staticShadows.remove(entity);
this.updateColorLayers(entity);
}
if (entity instanceof IMobileEntity) {
this.mobileEntities.values().remove(entity);
}
if (entity instanceof ICombatEntity) {
this.combatEntities.values().remove(entity);
}
this.unload(entity);
this.fireEntityEvent(l -> l.entityRemoved(entity));
}
@Override
public void remove(final int mapId) {
final IEntity ent = this.get(mapId);
if (ent == null) {
return;
}
this.remove(ent);
}
@Override
public <T extends IEntity> void remove(Collection<T> entities) {
if (entities == null) {
return;
}
for (T ent : entities) {
this.remove(ent);
}
}
@Override
public void removeRenderable(final IRenderable renderable) {
for (Collection<IRenderable> rends : this.renderables.values()) {
rends.remove(renderable);
}
}
@Override
public void render(final Graphics2D g) {
g.scale(Game.getCamera().getRenderScale(), Game.getCamera().getRenderScale());
StringBuilder renderDetails = new StringBuilder();
long renderStart = System.nanoTime();
renderDetails.append(this.render(g, RenderType.BACKGROUND));
renderDetails.append(this.render(g, RenderType.GROUND));
if (Game.getConfiguration().debug().isDebug()) {
DebugRenderer.renderMapDebugInfo(g, this.getMap());
}
renderDetails.append(this.render(g, RenderType.SURFACE));
renderDetails.append(this.render(g, RenderType.NORMAL));
long shadowRenderStart = System.nanoTime();
if (this.getStaticShadows().stream().anyMatch(x -> x.getShadowType() != StaticShadowType.NONE)) {
this.getStaticShadowLayer().render(g);
}
final double shadowTime = TimeUtilities.nanoToMs(System.nanoTime() - shadowRenderStart);
renderDetails.append(this.render(g, RenderType.OVERLAY));
long ambientStart = System.nanoTime();
if (Game.getConfiguration().graphics().getGraphicQuality().ordinal() >= Quality.MEDIUM.ordinal() && this.getAmbientLight() != null && this.getAmbientLight().getAlpha() != 0) {
this.getAmbientLight().render(g);
}
final double ambientTime = TimeUtilities.nanoToMs(System.nanoTime() - ambientStart);
renderDetails.append(this.render(g, RenderType.UI));
if (Game.getConfiguration().debug().isLogDetailedRenderTimes()) {
final double totalRenderTime = TimeUtilities.nanoToMs(System.nanoTime() - renderStart);
log.log(Level.INFO, "total render time: {0}ms \n{1} \tSHADOWS: {2}ms \n\tAMBIENT: {3}ms ", new Object[] { totalRenderTime, renderDetails, shadowTime, ambientTime });
}
g.scale(1.0 / Game.getCamera().getRenderScale(), 1.0 / Game.getCamera().getRenderScale());
}
private void fireEvent(Consumer<EnvironmentListener> cons) {
for (EnvironmentListener listener : this.listeners) {
cons.accept(listener);
}
}
private void fireRenderEvent(Graphics2D g, RenderType type) {
for (EnvironmentRenderListener listener : this.renderListeners.get(type)) {
listener.rendered(g, type);
}
}
private void fireEntityEvent(Consumer<EnvironmentEntityListener> cons) {
for (EnvironmentEntityListener listener : this.entityListeners) {
cons.accept(listener);
}
}
@Override
public void unload() {
if (!this.loaded) {
return;
}
// unregister all updatable entities from the current environment
for (final IEntity entity : this.getEntities()) {
this.unload(entity);
}
this.loaded = false;
this.fireEvent(l -> l.environmentUnloaded(this));
}
@Override
public Collection<IEntity> load(final IMapObject mapObject) {
if (mapObjectLoaders.containsKey(mapObject.getType())) {
Collection<IEntity> loadedEntities = mapObjectLoaders.get(mapObject.getType()).load(this, mapObject);
for (IEntity entity : loadedEntities) {
if (entity != null) {
this.add(entity);
}
}
return loadedEntities;
}
return new ArrayList<>();
}
private static <T extends IEntity> T getById(Collection<T> entities, int mapId) {
for (final T m : entities) {
if (m.getMapId() == mapId) {
return m;
}
}
return null;
}
private static <T extends IEntity> T getByName(Collection<T> entities, String name) {
if (name == null || name.isEmpty()) {
return null;
}
for (final T m : entities) {
if (m.getName() != null && m.getName().equals(name)) {
return m;
}
}
return null;
}
private String render(Graphics2D g, RenderType renderType) {
long renderStart = System.nanoTime();
// 1. Render map layers
Game.getRenderEngine().render(g, this.getMap(), renderType);
// 2. Render renderables
for (final IRenderable rend : this.getRenderables(renderType)) {
rend.render(g);
}
// 3. Render entities
Game.getRenderEngine().renderEntities(g, this.entities.get(renderType).values(), renderType == RenderType.NORMAL);
// 4. fire event
this.fireRenderEvent(g, renderType);
if (Game.getConfiguration().debug().isLogDetailedRenderTimes()) {
final double renderTime = TimeUtilities.nanoToMs(System.nanoTime() - renderStart);
return "\t" + renderType + ": " + renderTime + "ms ("
+ this.getMap().getRenderLayers().stream().filter(m -> m.getRenderType() == renderType).count() + " layers, "
+ this.getRenderables(renderType).size() + " renderables, "
+ this.entities.get(renderType).size() + " entities)\n";
}
return null;
}
private void addAmbientLight() {
final int ambientAlpha = this.getMap().getCustomPropertyInt(MapProperty.AMBIENTALPHA);
final Color ambientColor = this.getMap().getCustomPropertyColor(MapProperty.AMBIENTCOLOR, Color.WHITE);
this.ambientLight = new AmbientLight(this, ambientColor, ambientAlpha);
}
private void addStaticShadows() {
final int alpha = this.getMap().getCustomPropertyInt(MapProperty.SHADOWALPHA, StaticShadow.DEFAULT_ALPHA);
final Color color = this.getMap().getCustomPropertyColor(MapProperty.SHADOWCOLOR, StaticShadow.DEFAULT_COLOR);
this.staticShadowLayer = new StaticShadowLayer(this, alpha, color);
}
private void dispose(final Collection<? extends IEntity> entities) {
for (final IEntity entity : entities) {
if (entity instanceof IUpdateable) {
Game.getLoop().detach((IUpdateable) entity);
}
entity.detachControllers();
}
}
/**
* Loads the specified entity by performing the following steps:
* <ol>
* <li>add to physics engine</li>
* <li>register entity for update</li>
* <li>register animation controller for update</li>
* <li>register movement controller for update</li>
* <li>register AI controller for update</li>
* </ol>
*
* @param entity
*/
private void load(final IEntity entity) {
// 1. add to physics engine
this.loadPhysicsEntity(entity);
// 2. register for update or activate
this.loadUpdatableOrEmitterEntity(entity);
// 3. attach all controllers
entity.attachControllers();
if (entity instanceof LightSource || entity instanceof StaticShadow) {
this.updateColorLayers(entity);
}
}
private void loadPhysicsEntity(IEntity entity) {
if (entity instanceof CollisionBox) {
final CollisionBox coll = (CollisionBox) entity;
if (coll.isObstacle()) {
Game.getPhysicsEngine().add(coll.getBoundingBox());
} else {
Game.getPhysicsEngine().add(coll);
}
} else if (entity instanceof ICollisionEntity) {
final ICollisionEntity coll = (ICollisionEntity) entity;
if (coll.hasCollision()) {
Game.getPhysicsEngine().add(coll);
}
}
}
private void loadUpdatableOrEmitterEntity(IEntity entity) {
if (entity instanceof Emitter) {
final Emitter emitter = (Emitter) entity;
if (emitter.isActivateOnInit()) {
emitter.activate();
}
} else if (entity instanceof IUpdateable) {
Game.getLoop().attach((IUpdateable) entity);
}
}
private void loadMapObjects() {
for (final IMapObjectLayer layer : this.getMap().getMapObjectLayers()) {
for (final IMapObject mapObject : layer.getMapObjects()) {
if (mapObject.getType() == null || mapObject.getType().isEmpty()) {
continue;
}
this.load(mapObject);
}
}
}
private static void registerDefaultMapObjectLoaders() {
registerMapObjectLoader(new PropMapObjectLoader());
registerMapObjectLoader(new CollisionBoxMapObjectLoader());
registerMapObjectLoader(new TriggerMapObjectLoader());
registerMapObjectLoader(new EmitterMapObjectLoader());
registerMapObjectLoader(new LightSourceMapObjectLoader());
registerMapObjectLoader(new SpawnpointMapObjectLoader());
registerMapObjectLoader(new MapAreaMapObjectLoader());
registerMapObjectLoader(new StaticShadowMapObjectLoader());
registerMapObjectLoader(new CreatureMapObjectLoader());
}
/**
* Unload the specified entity by performing the following steps:
* <ol>
* <li>remove entities from physics engine</li>
* <li>unregister units from update</li>
* <li>unregister ai controller from update</li>
* <li>unregister animation controller from update</li>
* <li>unregister movement controller from update</li>
* </ol>
*
* @param entity
*/
private void unload(final IEntity entity) {
// 1. remove from physics engine
if (entity instanceof CollisionBox) {
final CollisionBox coll = (CollisionBox) entity;
if (coll.isObstacle()) {
Game.getPhysicsEngine().remove(coll.getBoundingBox());
} else {
Game.getPhysicsEngine().remove(coll);
}
} else if (entity instanceof ICollisionEntity) {
final ICollisionEntity coll = (ICollisionEntity) entity;
Game.getPhysicsEngine().remove(coll);
}
// 2. unregister from update
if (entity instanceof IUpdateable) {
Game.getLoop().detach((IUpdateable) entity);
}
// 3. detach all controllers
entity.detachControllers();
if (entity instanceof Emitter) {
Emitter em = (Emitter) entity;
em.deactivate();
}
}
}
|
package com.redhat.ceylon.compiler.js;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import com.redhat.ceylon.cmr.api.RepositoryManager;
import com.redhat.ceylon.cmr.ceylon.OutputRepoUsingTool;
import com.redhat.ceylon.common.Constants;
import com.redhat.ceylon.common.FileUtil;
import com.redhat.ceylon.common.config.DefaultToolOptions;
import com.redhat.ceylon.common.tool.Argument;
import com.redhat.ceylon.common.tool.Description;
import com.redhat.ceylon.common.tool.Option;
import com.redhat.ceylon.common.tool.OptionArgument;
import com.redhat.ceylon.common.tool.ParsedBy;
import com.redhat.ceylon.common.tool.RemainingSections;
import com.redhat.ceylon.common.tool.StandardArgumentParsers;
import com.redhat.ceylon.common.tool.Summary;
import com.redhat.ceylon.common.tools.SourceArgumentsResolver;
import com.redhat.ceylon.compiler.Options;
import com.redhat.ceylon.compiler.loader.JsModuleManagerFactory;
import com.redhat.ceylon.compiler.typechecker.TypeChecker;
import com.redhat.ceylon.compiler.typechecker.TypeCheckerBuilder;
import com.redhat.ceylon.compiler.typechecker.context.PhasedUnit;
import com.redhat.ceylon.compiler.typechecker.io.VirtualFile;
@Summary("Compiles Ceylon source code to JavaScript and directly produces " +
"module and source archives in a module repository")
@RemainingSections(
OutputRepoUsingTool.DOCSECTION_CONFIG_COMPILER +
"\n\n" +
OutputRepoUsingTool.DOCSECTION_REPOSITORIES)
public class CeylonCompileJsTool extends OutputRepoUsingTool {
public static class AppendableWriter extends Writer {
private Appendable out;
public AppendableWriter(Appendable out) {
this.out = out;
}
@Override
public void close() throws IOException {
}
@Override
public void flush() throws IOException {
}
@Override
public void write(char[] cbuf, int off, int len) throws IOException {
out.append(new String(cbuf, off, len));
}
@Override
public void write(String str) throws IOException {
out.append(str);
}
}
private boolean profile = false;
private boolean optimize = true;
private boolean modulify = true;
private boolean indent = true;
private boolean comments = false;
private boolean skipSrc = false;
private String encoding;
private List<File> roots = DefaultToolOptions.getCompilerSourceDirs();
private List<File> resources = DefaultToolOptions.getCompilerResourceDirs();
private String resourceRootName = DefaultToolOptions.getCompilerResourceRootName();
private List<String> files = Arrays.asList("*");
private DiagnosticListener diagnosticListener;
private boolean throwOnError;
public CeylonCompileJsTool() {
super(CeylonCompileJsMessages.RESOURCE_BUNDLE);
}
@OptionArgument(shortName='E', argumentName="encoding")
@Description("Sets the encoding used for reading source files (default: platform-specific)")
public void setEncoding(String encoding) {
this.encoding = encoding;
}
public String getEncoding(){
return encoding;
}
@Option
@Description("Time the compilation phases (results are printed to standard error)")
public void setProfile(boolean profile) {
this.profile = profile;
}
@Option
@Description("Create lexical scope-style JS code")
public void setLexicalScopeStyle(boolean flag) {
this.optimize = !flag;
}
@Option(longName="no-module")
@Description("Do **not** wrap generated code as CommonJS module")
public void setNoModulify(boolean nomodulify) {
this.modulify = !nomodulify;
}
@Option
@Description("Do **not** indent code")
public void setNoIndent(boolean noindent) {
this.indent = !noindent;
}
@Option
@Description("Equivalent to `--no-indent` `--no-comments`")
public void setCompact(boolean compact) {
this.setNoIndent(compact);
this.setNoComments(compact);
}
@Option
@Description("Do **not** generate any comments")
public void setNoComments(boolean nocomments) {
this.comments = !nocomments;
}
public List<String> getFilesAsStrings(final List<File> files) {
if (files != null) {
List<String> result = new ArrayList<>(files.size());
for (File f : files) {
result.add(f.getPath());
}
return result;
} else {
return Collections.emptyList();
}
}
@OptionArgument(shortName='s', longName="src", argumentName="dirs")
@ParsedBy(StandardArgumentParsers.PathArgumentParser.class)
@Description("Path to source files. " +
"Can be specified multiple times; you can also specify several " +
"paths separated by your operating system's `PATH` separator." +
" (default: `./source`)")
public void setSrc(List<File> src) {
roots = src;
}
@OptionArgument(longName="source", argumentName="dirs")
@ParsedBy(StandardArgumentParsers.PathArgumentParser.class)
@Description("An alias for `--src`" +
" (default: `./source`)")
public void setSource(List<File> source) {
setSrc(source);
}
@OptionArgument(shortName='r', longName="resource", argumentName="dirs")
@ParsedBy(StandardArgumentParsers.PathArgumentParser.class)
@Description("Path to directory containing resource files. " +
"Can be specified multiple times; you can also specify several " +
"paths separated by your operating system's `PATH` separator." +
" (default: `./resource`)")
public void setResource(List<File> resource) {
this.resources = resource;
}
@OptionArgument(shortName='R', argumentName="folder-name")
@Description("Sets the special resource folder name whose files will " +
"end up in the root of the resulting module CAR file (default: ROOT).")
public void setResourceRoot(String resourceRootName) {
this.resourceRootName = resourceRootName;
}
public String getOut() {
return (out != null) ? out : DefaultToolOptions.getCompilerOutputRepo();
}
@Option
@Description("Do **not** generate .src archive - useful when doing joint compilation")
public void setSkipSrcArchive(boolean skip) {
skipSrc = skip;
}
public boolean isSkipSrcArchive() {
return skipSrc;
}
@Argument(argumentName="moduleOrFile", multiplicity="*")
public void setModule(List<String> moduleOrFile) {
this.files = moduleOrFile;
}
@Override
public void initialize() throws IOException {
}
@Override
public void run() throws Exception {
setSystemProperties();
AppendableWriter writer = new AppendableWriter(getOutAppendable());
final Options opts = new Options()
.cwd(cwd)
.repos(getRepositoryAsStrings())
.sourceDirs(roots)
.resourceDirs(resources)
.resourceRootName(resourceRootName)
.systemRepo(systemRepo)
.outRepo(getOut())
.user(user)
.pass(pass)
.optimize(optimize)
.modulify(modulify)
.indent(indent)
.comment(comments)
.verbose(getVerbose())
.profile(profile)
.stdin(false)
.generateSourceArchive(!skipSrc)
.encoding(encoding)
.diagnosticListener(diagnosticListener)
.outWriter(writer);
final TypeChecker typeChecker;
if (opts.hasVerboseFlag("cmr")) {
append("Using repositories: "+getRepositoryAsStrings());
newline();
}
final RepositoryManager repoman = getRepositoryManager();
long t0, t1, t2, t3, t4;
final TypeCheckerBuilder tcb;
List<File> onlySources = null;
List<File> onlyResources = null;
if (opts.isStdin()) {
VirtualFile src = new VirtualFile() {
@Override
public boolean isFolder() {
return false;
}
@Override
public String getName() {
return "SCRIPT.ceylon";
}
@Override
public String getPath() {
return getName();
}
@Override
public InputStream getInputStream() {
return System.in;
}
@Override
public List<VirtualFile> getChildren() {
return Collections.emptyList();
}
@Override
public int hashCode() {
return getPath().hashCode();
}
@Override
public boolean equals(Object obj) {
if (obj instanceof VirtualFile) {
return ((VirtualFile) obj).getPath().equals(getPath());
}
else {
return super.equals(obj);
}
}
};
t0 = System.nanoTime();
tcb = new TypeCheckerBuilder()
.addSrcDirectory(src);
} else {
t0=System.nanoTime();
tcb = new TypeCheckerBuilder();
SourceArgumentsResolver resolver = new SourceArgumentsResolver(roots, resources, Constants.CEYLON_SUFFIX, Constants.JS_SUFFIX);
resolver
.cwd(cwd)
.expandAndParse(files);
onlySources = resolver.getSourceFiles();
onlyResources = resolver.getResourceFiles();
if (opts.isVerbose()) {
append("Adding source directories to typechecker:" + roots).newline();
}
for (File root : roots) {
tcb.addSrcDirectory(root);
}
if (!resolver.getSourceModules().isEmpty()) {
tcb.setModuleFilters(resolver.getSourceModules());
}
tcb.statistics(opts.isProfile());
JsModuleManagerFactory.setVerbose(opts.isVerbose());
tcb.moduleManagerFactory(new JsModuleManagerFactory(encoding));
}
//getting the type checker does process all types in the source directory
tcb.verbose(opts.isVerbose()).setRepositoryManager(repoman);
tcb.usageWarnings(false).encoding(encoding);
typeChecker = tcb.getTypeChecker();
if (onlySources != null) {
for (PhasedUnit pu : typeChecker.getPhasedUnits().getPhasedUnits()) {
File unitFile = new File(pu.getUnitFile().getPath());
if (!FileUtil.containsFile(onlySources, unitFile)) {
if (opts.isVerbose()) {
append("Removing phased unit " + pu).newline();
}
typeChecker.getPhasedUnits().removePhasedUnitForRelativePath(pu.getPathRelativeToSrcDir());
}
}
}
t1=System.nanoTime();
typeChecker.process(true);
t2=System.nanoTime();
JsCompiler jsc = new JsCompiler(typeChecker, opts);
if (onlySources != null) {
if (opts.isVerbose()) {
append("Only these files will be compiled: " + onlySources).newline();
}
jsc.setSourceFiles(onlySources);
}
if (onlyResources != null) {
jsc.setResourceFiles(onlyResources);
}
t3=System.nanoTime();
if (!jsc.generate()) {
if (jsc.getExitCode() != 0) {
if(throwOnError)
throw new RuntimeException("Compiler exited with non-zero exit code: "+jsc.getExitCode());
else {
jsc.printErrorsAndCount(writer);
System.exit(jsc.getExitCode());
}
}
int count = jsc.printErrors(writer);
throw new CompilerErrorException(String.format("%d errors.", count));
}
t4=System.nanoTime();
if (opts.isProfile() || opts.hasVerboseFlag("benchmark")) {
System.err.println("PROFILING INFORMATION");
System.err.printf("TypeChecker creation: %6d nanos%n", t1-t0);
System.err.printf("TypeChecker processing: %6d nanos%n", t2-t1);
System.err.printf("JS compiler creation: %6d nanos%n", t3-t2);
System.err.printf("JS compilation: %6d nanos%n", t4-t3);
System.out.println("Compilation finished.");
}
}
/**
* Sets the diagnostic listener. Not part of the command-line contract, only used by APIs.
*/
public void setDiagnosticListener(DiagnosticListener diagnosticListener) {
this.diagnosticListener = diagnosticListener;
}
/**
* Tell the tool not to exit on a non-zero exit code from node, but throw otherwise. This is not
* used by the command-line, but can be useful when invoked via the API.
* @param throwOnError true to throw instead of calling System.exit. Defaults to false.
*/
public void setThrowOnError(boolean throwOnError) {
this.throwOnError = throwOnError;
}
/**
* Check if we throw on a non-zero exit code from node, rather than exit. This is not
* used by the command-line, but can be useful when invoked via the API.
* @return true to throw instead of calling System.exit. Defaults to false.
*/
public boolean isThrowOnError() {
return throwOnError;
}
}
|
package com.stablekernel.standardlib;
import com.squareup.okhttp.Interceptor;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import java.io.IOException;
public abstract class AuthRetryInterceptor implements Interceptor {
private static final String TAG = "AuthRetryInterceptor";
private final Object lockObject = new Object();
@Override
public Response intercept(Chain chain) throws IOException {
String token = getAccessToken();
Request.Builder builder = chain.request().newBuilder();
Response response = chain.proceed(builder.build());
if (response.code() == 401) {
synchronized (lockObject) {
String currentToken = getAccessToken();
if (currentToken != null && currentToken.equals(token)) {
return performRefresh(chain, builder);
}
}
}
return response;
}
private Response performRefresh(Chain chain, Request.Builder builder) throws IOException {
try {
IOException exception = refreshAccessToken();
Response response = chain.proceed(builder.build());
if (response.code() < 200 || response.code() >= 300) {
throw exception;
}
return response;
} catch (IOException e) {
performRefreshFailure(e);
throw e;
}
}
public abstract String getAccessToken();
public abstract IOException refreshAccessToken();
public abstract void performRefreshFailure(IOException e);
}
|
package org.stepic.droid.util;
import org.jetbrains.annotations.Nullable;
public class AppConstants {
public static final String FILE_SCHEME_PREFIX = "file:
public static final String FILE_PROVIDER_AUTHORITY = ".my.package.name.provider";
public static final String SVG_EXTENSION = ".svg";
public static final String APP_SCHEME = "stepic:
public static final String QUERY_ERROR = "error";
public static final String ERROR_SOCIAL_AUTH_WITH_EXISTING_EMAIL = "social_signup_with_existing_email";
public static final String USER_LOG_IN = "user_login_clicked";
public static final String KEY_EMAIL_BUNDLE = "email";
public static final String KEY_COURSE_BUNDLE = "course";
public static final String KEY_COURSE_LONG_ID = "course_id_key";
public static final String KEY_SECTION_BUNDLE = "section";
public static final String KEY_UNIT_BUNDLE = "unit";
public static final String KEY_LESSON_BUNDLE = "lesson";
public static final String KEY_STEP_BUNDLE = "step";
public static final String DEFAULT_QUALITY = "360";
public static final String MAX_QUALITY = "720";
public static final int MAX_QUALITY_INT = 720;
public static final String KEY_LOAD_TYPE = "KEY_LOAD_TYPE";
public static final String KEY_TABLE_TYPE = "table_type";
public static final String COMMENT_DATE_TIME_PATTERN = "dd.MM.yyyy HH:mm";
public static final String WEB_URI_SEPARATOR = "/";
//Types of steps:
public static final String TYPE_TEXT = "text";
public static final String TYPE_VIDEO = "video";
public static final String TYPE_MATCHING = "matching";
public static final String TYPE_SORTING = "sorting";
public static final String TYPE_MATH = "math";
public static final String TYPE_FREE_ANSWER = "free-answer";
public static final String TYPE_TABLE = "table";
public static final String TYPE_STRING = "string";
public static final String TYPE_CHOICE = "choice";
public static final String TYPE_NUMBER = "number";
public static final String TYPE_DATASET = "dataset";
public static final String TYPE_ANIMATION = "animation";
public static final String TYPE_CHEMICAL = "chemical";
public static final String TYPE_FILL_BLANKS = "fill-blanks";
public static final String TYPE_PUZZLE = "puzzle";
public static final String TYPE_PYCHARM = "pycharm";
public static final String TYPE_CODE = "code";
public static final String TYPE_ADMIN = "admin";
public static final String TYPE_SQL = "sql";
public static final String TYPE_LINUX_CODE = "linux-code";
public static final String TYPE_NULL = "null_type";
public static final int REQUEST_EXTERNAL_STORAGE = 13;
public static final String KEY_ASSIGNMENT_BUNDLE = "key_assignment";
public static final String COURSE_ID_KEY = "course_id";
public static final String ENROLLMENT_KEY = "is_enrolled";
public static final int REQUEST_CODE_DETAIL = 1;
public static final java.lang.String THUMBNAIL_POSTFIX_EXTENSION = ".png";
public static final java.lang.String DELIMITER_TEXT_SCORE = "/";
public static final java.lang.String NOTIFICATION_CANCELED = "notification_canceled";
public static final String OPEN_NOTIFICATION_FOR_CHECK_COURSE = "Open_notification_check_course";
public static final String OPEN_NOTIFICATION_FOR_ENROLL_REMINDER = "open_notificatoin_for_enroll_reminder";
public static final String OPEN_NOTIFICATION_FROM_STREAK = "open_notification_from_streak";
public static final String OPEN_NOTIFICATION = "Open_notification";
public static final long MILLIS_IN_24HOURS = 86400000L;
public static final long MILLIS_IN_1HOUR = 3600000L;
public static final String APP_INDEXING_COURSE_DETAIL_MANIFEST_HACK = "course_app";
public static final String APP_INDEXING_SYLLABUS_MANIFEST = "syllabus";
public static final long TWO_DAY_IN_MINUTES = 2880L;
public static final long MILLIS_IN_1MONTH = 2592000000L;
public static final String COMMA = ",";
public static final int REQUEST_CALENDAR_PERMISSION = 1122;
public static final String LINKEDIN_ADD_URL = "https:
public static final String LINKEDIN_ED_ID = "0_uInsUtRlLF5qiDUg80Aftvf5K-uMiiQPc0IVksZ_0oh1hhPRasb5cWi8eD5WXfgDaSgvthvZk7wTBMS3S-m0L6A6mLjErM6PJiwMkk6nYZylU7__75hCVwJdOTZCAkdv";//// TODO: 02.08.16 add to configs?
public static final int REQUEST_CODE_GOOGLE_SIGN_IN = 7007;
public static final int ENROLLED_FILTER = 1;
public static final int FEATURED_FILTER = 2;
public static final int DEFAULT_NUMBER_IDS_IN_QUERY = 100;
public static final java.lang.String KEY_MODULE_POSITION = "section_long_id";
public static final int LAUNCHES_FOR_EXPERT_USER = 20;
public static final long MILLIS_IN_SEVEN_DAYS = 604800000L;
public static final String NOTIFICATION_CANCELED_REMINDER = "notification_canceled_reminder";
public static final int MAX_NUMBER_OF_SHOWING_STREAK_DIALOG = 3;
public static final int NUMBER_OF_DAYS_BETWEEN_STREAK_SHOWING = 2;
public static final int MAX_NUMBER_OF_NOTIFICATION_STREAK = 5;
@Nullable
public static final String NOTIFICATION_CANCELED_STREAK = "notification_canceled_streaks";
public static final String FIND_COURSES_SHORTCUT_ID = "find_courses";
public static final String OPEN_SHORTCUT_FIND_COURSES = "open_shortcut_find_courses";
public static final String PROFILE_SHORTCUT_ID = "profile";
public static final String OPEN_SHORTCUT_PROFILE = "open_shortcut_profile";
public static final String INTERNAL_STEPIK_ACTION = "internal_stepik_action";
public static final String setCookieHeaderName = "Set-Cookie";
public static final String authorizationHeaderName = "Authorization";
public static final String cookieHeaderName = "Cookie";
public static final String refererHeaderName = "Referer";
public static final String csrfTokenHeaderName = "X-CSRFToken";
public final static String FROM_MAIN_FEED_FLAG = "from_main_feed";
public final static String ANALYTIC_CODE_SCREEN_KEY = "size";
}
|
package de.sebhn.algorithm.excercise1.helper;
import de.sebhn.algorithm.excercise1.OutputCounter;
import de.sebhn.algorithm.excercise1.helper.direction.LeftUp;
import de.sebhn.algorithm.excercise1.helper.direction.Right;
import de.sebhn.algorithm.excercise1.helper.direction.RightDown;
import de.sebhn.algorithm.excercise1.helper.direction.RightUp;
import de.sebhn.algorithm.excercise1.helper.direction.Up;
public class GridVisitor {
public static void findPath(Grid grid, GraphMatrix matrix) {
int startingPoint = grid.getConverter().convert(new Position(0, 0));
int endPoint =
grid.getConverter().convert(new Position(grid.getTargetNumber(), grid.getTargetNumber()));
int size = grid.getSize();
OutputCounter outputCounter = new OutputCounter(grid.getConverter());
matrix.findAllPath(startingPoint, endPoint, new boolean[size * size], outputCounter);
outputCounter.printSize();
// outputCounter.printPaths(grid.getTargetNumber()); // uncomment to show paths
}
public static GraphMatrix createPossibleEdges(Grid grid) {
int gridSize = grid.getSize();
GraphMatrix matrix = new GraphMatrix(gridSize * gridSize);
PositionToIntConverter converter = grid.getConverter();
boolean isGoneRightUp = false, isGoneRightDown = false, isGoneLeftUp = false, isGoneUp = false,
isGoneRight = false;
for (int y = 0; y < gridSize; y++) {
for (int x = 0; x < gridSize; x++) {
boolean walkedAllDirections = false;
Position currentPosition = new Position(x, y);
while (!walkedAllDirections) {
if (RightUp.isAllowedToWalk(currentPosition,
RightUp.getNewPosition(currentPosition, grid), grid) && !isGoneRightUp) {
Position position = RightUp.getNewPosition(currentPosition, grid);
matrix.addEdge(converter.convert(currentPosition), converter.convert(position));
isGoneRightUp = true;
} else if (RightDown.isAllowedToWalk(currentPosition,
RightDown.getNewPosition(currentPosition, grid), grid) && !isGoneRightDown) {
Position position = RightDown.getNewPosition(currentPosition, grid);
matrix.addEdge(converter.convert(currentPosition), converter.convert(position));
isGoneRightDown = true;
} else if (LeftUp.isAllowedToWalk(LeftUp.getNewPosition(currentPosition, grid), grid,
currentPosition) && !isGoneLeftUp) {
Position position = LeftUp.getNewPosition(currentPosition, grid);
matrix.addEdge(converter.convert(currentPosition), converter.convert(position));
isGoneLeftUp = true;
} else if (Up.isAllowedToWalk(currentPosition, Up.getNewPosition(currentPosition, grid),
grid) && !isGoneUp) {
Position position = Up.getNewPosition(currentPosition, grid);
matrix.addEdge(converter.convert(currentPosition), converter.convert(position));
isGoneUp = true;
} else if (Right.isAllowedToWalk(currentPosition,
Right.getNewPosition(currentPosition, grid), grid) && !isGoneRight) {
Position position = Right.getNewPosition(currentPosition, grid);
matrix.addEdge(converter.convert(currentPosition), converter.convert(position));
isGoneRight = true;
} else {
// System.out.println(String.format(
// "Possible directions on " + currentPosition
// + " rightup=%s rightdown=%s leftup=%s up=%s right=%s",
// isGoneRightUp, isGoneRightDown, isGoneLeftUp, isGoneUp, isGoneRight));
isGoneRightUp = false;
isGoneRightDown = false;
isGoneLeftUp = false;
isGoneUp = false;
isGoneRight = false;
walkedAllDirections = true;
}
}
}
}
return matrix;
}
}
|
package com.telekom.m2m.cot.restsdk.realtime;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.telekom.m2m.cot.restsdk.CloudOfThingsRestClient;
import com.telekom.m2m.cot.restsdk.util.CotSdkException;
import com.telekom.m2m.cot.restsdk.util.GsonUtils;
public class CepConnector implements Runnable {
public static final String CONTENT_TYPE = "application/json";
// TODO: find out what versions exist and which ones we can support:
public static final String PROTOCOL_VERSION_REQUESTED = "1.0";
public static final String PROTOCOL_VERSION_MINIMUM = "1.0";
private static final int DEFAULT_READ_TIMEOUT_MILLIS = 60000;
private static final int DEFAULT_RECONNECT_INTERVAL_MILLIS = 100;
private static final int THREAD_JOIN_GRACE_MILLIS = 1000;
private String notificationPath;
private CloudOfThingsRestClient cloudOfThingsRestClient;
private boolean connected = false;
private boolean shallDisconnect = false;
private String clientId;
// Read timeout in milliseconds for the connect request:
private int timeout = DEFAULT_READ_TIMEOUT_MILLIS;
// Interval in milliseconds between connect requests:
private int interval = DEFAULT_RECONNECT_INTERVAL_MILLIS;
private Set<String> channels = new CopyOnWriteArraySet<>();
private Set<SubscriptionListener> listeners = new CopyOnWriteArraySet<>();
private Gson gson = GsonUtils.createGson();
private Thread pollingThread;
/**
* Construct a new CepConnector.
*
* @param cloudOfThingsRestClient
* the client to use for connection to the cloud
*
* @param notificationPath a String with REST endpoint path for notification requests (handshake, subscribe, connect...)
* without host, leading and trailing slashes e.g. cep/realtime
*/
public CepConnector(CloudOfThingsRestClient cloudOfThingsRestClient, String notificationPath) {
this.cloudOfThingsRestClient = cloudOfThingsRestClient;
this.notificationPath = notificationPath;
}
* to be subscribed to. Can include * as a wildcard (e.g. "/alarms/*").
*/
public void subscribe(String channel) {
if (channel == null) {
throw new CotSdkException("Subscription must not have null as its channel.");
}
channels.add(channel);
if (clientId != null) {
JsonArray body = new JsonArray();
JsonObject obj = new JsonObject();
obj.addProperty("channel", "/meta/subscribe");
obj.addProperty("clientId", clientId);
obj.addProperty("subscription", channel);
body.add(obj);
cloudOfThingsRestClient.doPostRequest(body.toString(), notificationPath, CONTENT_TYPE);
}
}
/**
* The method used to unsubscribe from a channel that was previously
* subscribed to.
*
* @param channel
* to unsubscribe from
*/
public void unsubscribe(String channel) {
if (channels.remove(channel)) {
JsonArray body = new JsonArray();
JsonObject obj = new JsonObject();
obj.addProperty("channel", "/meta/unsubscribe");
obj.addProperty("clientId", clientId);
obj.addProperty("subscription", channel);
body.add(obj);
cloudOfThingsRestClient.doPostRequest(body.toString(), notificationPath, CONTENT_TYPE);
}
}
/**
* The method to initiate the connection. It checks the pre-requisite
* conditions to establish a connection. When the conditions are satisfied
* it starts the run cycle.
*/
public void connect() {
shallDisconnect = false;
if (connected) {
throw new CotSdkException("Already connected. Please disconnect first.");
}
if (clientId == null) {
doHandShake();
}
if (clientId == null) {
throw new CotSdkException("Handshake failed, could not get clientId.");
}
pollingThread = new Thread(this);
pollingThread.setName("CepConnector.pollingThread");
pollingThread.start();
}
public void disconnect() {
shallDisconnect = true;
if (pollingThread != null) {
pollingThread.interrupt();
try {
pollingThread.join(THREAD_JOIN_GRACE_MILLIS); // One second should be more than enough to end the loop.
} catch (InterruptedException ex) {
throw new CotSdkException("Real time polling thread didn't finish properly when asked to disconnect.", ex);
}
}
}
public void addListener(SubscriptionListener listener) {
listeners.add(listener);
}
public void removeListener(SubscriptionListener listener) {
listeners.remove(listener);
}
/**
* The current read timeout.
*
* @return the timeout in milliseconds
*/
public int getTimeout() {
return timeout;
}
/**
* Set the read timeout for the polling connect request.
* Default is {@value DEFAULT_READ_TIMEOUT_MILLIS}.
*
* @param timeout the timeout in milliseconds
*/
public void setTimeout(int timeout) {
this.timeout = timeout;
}
/**
* The current interval, which is the time that the polling thread waits before it reconnects, after receiving a response.
*
* @return the waiting interval in milliseconds
*/
public int getInterval() {
return interval;
}
/**
* Set the time that the polling thread waits before it reconnects, after receiving a response.
* Default is {@value DEFAULT_RECONNECT_INTERVAL_MILLIS}.
*
* @param interval the waiting interval in milliseconds
*/
public void setInterval(int interval) {
this.interval = interval;
}
/**
* Get the clientId that was assigned by the server during handshake.
*
* @return the clientId or null, if we are not currently connected.
*/
public String getClientId() {
return clientId;
}
/**
* Whether there is currently a polling thread connected to the server.
*
* @return true = yes; false = no
*/
public boolean isConnected() {
return connected;
}
/**
* The method that does the post request to establish a connection.
*
* @return the response of the cloud as a string.
*/
protected String doConnect() {
JsonArray body = new JsonArray();
JsonObject obj = new JsonObject();
obj.addProperty("channel", "/meta/connect");
obj.addProperty("clientId", clientId);
obj.addProperty("connectionType", "long-polling");
body.add(obj);
String result = cloudOfThingsRestClient.doRealTimePollingRequest(body.toString(), notificationPath, CONTENT_TYPE, timeout);
return result;
}
protected void doHandShake() {
JsonObject obj = new JsonObject();
obj.addProperty("channel", "/meta/handshake");
obj.addProperty("version", PROTOCOL_VERSION_REQUESTED);
obj.addProperty("minimumVersion", PROTOCOL_VERSION_MINIMUM);
JsonArray supportedConnectionTypes = new JsonArray();
supportedConnectionTypes.add("long-polling");
obj.add("supportedConnectionTypes", supportedConnectionTypes);
// TODO: find out what this advice even does...
JsonObject advice = new JsonObject();
advice.addProperty("timeout", timeout);
advice.addProperty("interval", interval);
obj.add("advice", advice);
JsonArray body = new JsonArray();
body.add(obj);
String result = cloudOfThingsRestClient.doPostRequest(body.toString(), notificationPath, CONTENT_TYPE);
JsonArray r = gson.fromJson(result, JsonArray.class);
clientId = r.get(0).getAsJsonObject().get("clientId").getAsString();
}
/**
* Post the subscriptions for all channels that were added before we were connected.
*/
protected void doInitialSubscriptions() {
if (clientId == null) {
throw new CotSdkException("Subscription failed because we don't have a clientId yet.");
}
if (channels.isEmpty()) {
return;
}
JsonArray body = new JsonArray();
// We can request multiple subscriptions in one go.
// (unlike with SmartREST, where we need one request for each channel).
for (String channel : channels) {
JsonObject obj = new JsonObject();
obj.addProperty("channel", "/meta/subscribe");
obj.addProperty("clientId", clientId);
obj.addProperty("subscription", channel);
body.add(obj);
}
cloudOfThingsRestClient.doPostRequest(body.toString(), notificationPath, CONTENT_TYPE);
}
/**
* Starts the connector in a separate thread. Not meant to be called directly,
* please use {@link #connect()} to start the connector.
*/
@Override
public void run() {
connected = true;
try {
doInitialSubscriptions();
do {
String responseString = doConnect();
if (responseString != null) {
JsonArray response = gson.fromJson(responseString, JsonArray.class);
for (JsonElement element : response) {
// TODO: evaluate advice?
// TODO: pass errors to our listeners?
JsonObject jsonObject = element.getAsJsonObject();
String notificationChannel = jsonObject.get("channel").getAsString();
// We don't pass on failures and meta data to the listeners.
if (!notificationChannel.startsWith("/meta/")) {
for (SubscriptionListener listener : listeners) {
// Now filter out the unnecessary fields from
// the JsonElement and pass the required
// information to the notification object:
JsonObject jsonNotification = new JsonObject();
jsonNotification.add("data", jsonObject.get("data"));
jsonNotification.add("channel", jsonObject.get("channel"));
listener.onNotification(notificationChannel, new Notification(jsonNotification));
}
}
}
}
try {
if (!shallDisconnect) {
Thread.sleep(interval);
}
} catch (InterruptedException e) {
shallDisconnect = true;
}
} while (!shallDisconnect);
} finally {
clientId = null;
connected = false;
}
}
}
|
package de.st_ddt.crazyspawner.listener;
import java.util.List;
import org.bukkit.Location;
import org.bukkit.entity.Entity;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Monster;
import org.bukkit.entity.TNTPrimed;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityDamageEvent.DamageCause;
import org.bukkit.event.entity.EntityDeathEvent;
import org.bukkit.event.entity.EntityTargetEvent;
import org.bukkit.metadata.MetadataValue;
import de.st_ddt.crazyspawner.CrazySpawner;
import de.st_ddt.crazyspawner.data.CustomCreature.CustomDamage;
import de.st_ddt.crazyspawner.data.CustomCreature.CustomDrops;
import de.st_ddt.crazyspawner.data.CustomCreature.CustomXP;
import de.st_ddt.crazyspawner.data.meta.AlarmMeta;
import de.st_ddt.crazyspawner.data.meta.NameMeta;
import de.st_ddt.crazyspawner.data.meta.PeacefulMeta;
import de.st_ddt.crazyspawner.tasks.HealthTask;
public class CreatureListener implements Listener
{
private final CrazySpawner plugin;
private final HealthTask health;
public CreatureListener(final CrazySpawner plugin)
{
super();
this.plugin = plugin;
this.health = new HealthTask(plugin);
}
@EventHandler(ignoreCancelled = true)
public void CreatureExplosion(final EntityDamageByEntityEvent event)
{
if (plugin.isMonsterExplosionDamageEnabled() || event.getCause() != DamageCause.ENTITY_EXPLOSION)
return;
if (!(event.getEntity() instanceof Monster))
return;
if (event.getDamager() instanceof TNTPrimed)
return;
event.setCancelled(true);
}
@EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR)
public void CreatureDamaged(final EntityDamageEvent event)
{
if (event.getEntity() instanceof LivingEntity)
health.queue((LivingEntity) event.getEntity());
}
@EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR)
public void CreatureDamagedbyEntity(final EntityDamageByEntityEvent event)
{
final Entity entity = event.getEntity();
entity.removeMetadata(PeacefulMeta.METAHEADER, plugin);
double alarmRange = plugin.getDefaultAlarmRange();
final List<MetadataValue> metas = entity.getMetadata(AlarmMeta.METAHEADER);
for (final MetadataValue meta : metas)
if (meta instanceof AlarmMeta)
{
final AlarmMeta alarm = (AlarmMeta) meta;
alarmRange = alarm.asDouble();
break;
}
final Location location = entity.getLocation();
for (final LivingEntity nearby : entity.getWorld().getEntitiesByClass(LivingEntity.class))
if (location.distance(nearby.getLocation()) < alarmRange)
nearby.removeMetadata(PeacefulMeta.METAHEADER, plugin);
}
@EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST)
public void CreatureDamager(final EntityDamageByEntityEvent event)
{
final Entity entity = event.getDamager();
final List<MetadataValue> damageMetas = entity.getMetadata(CustomDamage.METAHEADER);
for (final MetadataValue meta : damageMetas)
if (meta instanceof CustomDamage)
{
final CustomDamage damage = (CustomDamage) meta;
event.setDamage(damage.getDamage());
break;
}
}
@EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST)
public void EntityTargetEvent(final EntityTargetEvent event)
{
if (event.getTarget() == null)
return;
if (event.getEntity().hasMetadata(PeacefulMeta.METAHEADER))
event.setCancelled(true);
}
@EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST)
public void CreatureDeath(final EntityDeathEvent event)
{
final LivingEntity entity = event.getEntity();
final List<MetadataValue> nameMetas = entity.getMetadata(NameMeta.METAHEADER);
for (final MetadataValue meta : nameMetas)
if (meta.getOwningPlugin() == plugin)
{
final NameMeta name = (NameMeta) meta;
entity.setCustomName(name.asString());
break;
}
final List<MetadataValue> dropsMeta = entity.getMetadata(CustomDrops.METAHEADER);
for (final MetadataValue meta : dropsMeta)
if (meta instanceof CustomDrops)
{
((CustomDrops) meta).updateDrops(event.getDrops());
break;
}
final List<MetadataValue> xpMeta = entity.getMetadata(CustomXP.METAHEADER);
for (final MetadataValue meta : xpMeta)
if (meta instanceof CustomXP)
{
event.setDroppedExp(((CustomXP) meta).getXP());
break;
}
}
}
|
package de.braintags.netrelay.util;
import io.vertx.codegen.annotations.Nullable;
import io.vertx.core.AsyncResult;
import io.vertx.core.Handler;
import io.vertx.core.MultiMap;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.http.HttpMethod;
import io.vertx.core.http.HttpServerResponse;
/**
*
*
* @author Michael Remme
*
*/
public class MockHttpServerResponse implements HttpServerResponse {
public MockHttpServerResponse() {
}
/*
* (non-Javadoc)
*
* @see io.vertx.core.streams.WriteStream#writeQueueFull()
*/
@Override
public boolean writeQueueFull() {
return false;
}
/*
* (non-Javadoc)
*
* @see io.vertx.core.http.HttpServerResponse#exceptionHandler(io.vertx.core.Handler)
*/
@Override
public HttpServerResponse exceptionHandler(Handler<Throwable> handler) {
return null;
}
/*
* (non-Javadoc)
*
* @see io.vertx.core.http.HttpServerResponse#write(io.vertx.core.buffer.Buffer)
*/
@Override
public HttpServerResponse write(Buffer data) {
return null;
}
/*
* (non-Javadoc)
*
* @see io.vertx.core.http.HttpServerResponse#setWriteQueueMaxSize(int)
*/
@Override
public HttpServerResponse setWriteQueueMaxSize(int maxSize) {
return null;
}
/*
* (non-Javadoc)
*
* @see io.vertx.core.http.HttpServerResponse#drainHandler(io.vertx.core.Handler)
*/
@Override
public HttpServerResponse drainHandler(Handler<Void> handler) {
return null;
}
/*
* (non-Javadoc)
*
* @see io.vertx.core.http.HttpServerResponse#getStatusCode()
*/
@Override
public int getStatusCode() {
return 0;
}
/*
* (non-Javadoc)
*
* @see io.vertx.core.http.HttpServerResponse#setStatusCode(int)
*/
@Override
public HttpServerResponse setStatusCode(int statusCode) {
return null;
}
/*
* (non-Javadoc)
*
* @see io.vertx.core.http.HttpServerResponse#getStatusMessage()
*/
@Override
public String getStatusMessage() {
return null;
}
/*
* (non-Javadoc)
*
* @see io.vertx.core.http.HttpServerResponse#setStatusMessage(java.lang.String)
*/
@Override
public HttpServerResponse setStatusMessage(String statusMessage) {
return null;
}
/*
* (non-Javadoc)
*
* @see io.vertx.core.http.HttpServerResponse#setChunked(boolean)
*/
@Override
public HttpServerResponse setChunked(boolean chunked) {
return null;
}
/*
* (non-Javadoc)
*
* @see io.vertx.core.http.HttpServerResponse#isChunked()
*/
@Override
public boolean isChunked() {
return false;
}
/*
* (non-Javadoc)
*
* @see io.vertx.core.http.HttpServerResponse#headers()
*/
@Override
public MultiMap headers() {
return null;
}
/*
* (non-Javadoc)
*
* @see io.vertx.core.http.HttpServerResponse#putHeader(java.lang.String, java.lang.String)
*/
@Override
public HttpServerResponse putHeader(String name, String value) {
return null;
}
/*
* (non-Javadoc)
*
* @see io.vertx.core.http.HttpServerResponse#putHeader(java.lang.CharSequence, java.lang.CharSequence)
*/
@Override
public HttpServerResponse putHeader(CharSequence name, CharSequence value) {
return null;
}
/*
* (non-Javadoc)
*
* @see io.vertx.core.http.HttpServerResponse#putHeader(java.lang.String, java.lang.Iterable)
*/
@Override
public HttpServerResponse putHeader(String name, Iterable<String> values) {
return null;
}
/*
* (non-Javadoc)
*
* @see io.vertx.core.http.HttpServerResponse#putHeader(java.lang.CharSequence, java.lang.Iterable)
*/
@Override
public HttpServerResponse putHeader(CharSequence name, Iterable<CharSequence> values) {
return null;
}
/*
* (non-Javadoc)
*
* @see io.vertx.core.http.HttpServerResponse#trailers()
*/
@Override
public MultiMap trailers() {
return null;
}
/*
* (non-Javadoc)
*
* @see io.vertx.core.http.HttpServerResponse#putTrailer(java.lang.String, java.lang.String)
*/
@Override
public HttpServerResponse putTrailer(String name, String value) {
return null;
}
/*
* (non-Javadoc)
*
* @see io.vertx.core.http.HttpServerResponse#putTrailer(java.lang.CharSequence, java.lang.CharSequence)
*/
@Override
public HttpServerResponse putTrailer(CharSequence name, CharSequence value) {
return null;
}
/*
* (non-Javadoc)
*
* @see io.vertx.core.http.HttpServerResponse#putTrailer(java.lang.String, java.lang.Iterable)
*/
@Override
public HttpServerResponse putTrailer(String name, Iterable<String> values) {
return null;
}
/*
* (non-Javadoc)
*
* @see io.vertx.core.http.HttpServerResponse#putTrailer(java.lang.CharSequence, java.lang.Iterable)
*/
@Override
public HttpServerResponse putTrailer(CharSequence name, Iterable<CharSequence> value) {
return null;
}
/*
* (non-Javadoc)
*
* @see io.vertx.core.http.HttpServerResponse#closeHandler(io.vertx.core.Handler)
*/
@Override
public HttpServerResponse closeHandler(@Nullable Handler<Void> handler) {
return null;
}
/*
* (non-Javadoc)
*
* @see io.vertx.core.http.HttpServerResponse#write(java.lang.String, java.lang.String)
*/
@Override
public HttpServerResponse write(String chunk, String enc) {
return null;
}
/*
* (non-Javadoc)
*
* @see io.vertx.core.http.HttpServerResponse#write(java.lang.String)
*/
@Override
public HttpServerResponse write(String chunk) {
return null;
}
/*
* (non-Javadoc)
*
* @see io.vertx.core.http.HttpServerResponse#writeContinue()
*/
@Override
public HttpServerResponse writeContinue() {
return null;
}
/*
* (non-Javadoc)
*
* @see io.vertx.core.http.HttpServerResponse#end(java.lang.String)
*/
@Override
public void end(String chunk) {
}
/*
* (non-Javadoc)
*
* @see io.vertx.core.http.HttpServerResponse#end(java.lang.String, java.lang.String)
*/
@Override
public void end(String chunk, String enc) {
}
/*
* (non-Javadoc)
*
* @see io.vertx.core.http.HttpServerResponse#end(io.vertx.core.buffer.Buffer)
*/
@Override
public void end(Buffer chunk) {
}
/*
* (non-Javadoc)
*
* @see io.vertx.core.http.HttpServerResponse#end()
*/
@Override
public void end() {
}
/*
* (non-Javadoc)
*
* @see io.vertx.core.http.HttpServerResponse#sendFile(java.lang.String, long, long)
*/
@Override
public HttpServerResponse sendFile(String filename, long offset, long length) {
return null;
}
/*
* (non-Javadoc)
*
* @see io.vertx.core.http.HttpServerResponse#sendFile(java.lang.String, long, long, io.vertx.core.Handler)
*/
@Override
public HttpServerResponse sendFile(String filename, long offset, long length,
Handler<AsyncResult<Void>> resultHandler) {
return null;
}
/*
* (non-Javadoc)
*
* @see io.vertx.core.http.HttpServerResponse#close()
*/
@Override
public void close() {
}
/*
* (non-Javadoc)
*
* @see io.vertx.core.http.HttpServerResponse#ended()
*/
@Override
public boolean ended() {
return false;
}
/*
* (non-Javadoc)
*
* @see io.vertx.core.http.HttpServerResponse#closed()
*/
@Override
public boolean closed() {
return false;
}
/*
* (non-Javadoc)
*
* @see io.vertx.core.http.HttpServerResponse#headWritten()
*/
@Override
public boolean headWritten() {
return false;
}
/*
* (non-Javadoc)
*
* @see io.vertx.core.http.HttpServerResponse#headersEndHandler(io.vertx.core.Handler)
*/
@Override
public HttpServerResponse headersEndHandler(@Nullable Handler<Void> handler) {
return null;
}
/*
* (non-Javadoc)
*
* @see io.vertx.core.http.HttpServerResponse#bodyEndHandler(io.vertx.core.Handler)
*/
@Override
public HttpServerResponse bodyEndHandler(@Nullable Handler<Void> handler) {
return null;
}
/*
* (non-Javadoc)
*
* @see io.vertx.core.http.HttpServerResponse#bytesWritten()
*/
@Override
public long bytesWritten() {
return 0;
}
/*
* (non-Javadoc)
*
* @see io.vertx.core.http.HttpServerResponse#streamId()
*/
@Override
public int streamId() {
return 0;
}
/*
* (non-Javadoc)
*
* @see io.vertx.core.http.HttpServerResponse#push(io.vertx.core.http.HttpMethod, java.lang.String, java.lang.String,
* io.vertx.core.Handler)
*/
@Override
public HttpServerResponse push(HttpMethod method, String host, String path,
Handler<AsyncResult<HttpServerResponse>> handler) {
return null;
}
/*
* (non-Javadoc)
*
* @see io.vertx.core.http.HttpServerResponse#push(io.vertx.core.http.HttpMethod, java.lang.String,
* io.vertx.core.MultiMap, io.vertx.core.Handler)
*/
@Override
public HttpServerResponse push(HttpMethod method, String path, MultiMap headers,
Handler<AsyncResult<HttpServerResponse>> handler) {
return null;
}
/*
* (non-Javadoc)
*
* @see io.vertx.core.http.HttpServerResponse#push(io.vertx.core.http.HttpMethod, java.lang.String,
* io.vertx.core.Handler)
*/
@Override
public HttpServerResponse push(HttpMethod method, String path, Handler<AsyncResult<HttpServerResponse>> handler) {
return null;
}
/*
* (non-Javadoc)
*
* @see io.vertx.core.http.HttpServerResponse#push(io.vertx.core.http.HttpMethod, java.lang.String, java.lang.String,
* io.vertx.core.MultiMap, io.vertx.core.Handler)
*/
@Override
public HttpServerResponse push(HttpMethod method, String host, String path, MultiMap headers,
Handler<AsyncResult<HttpServerResponse>> handler) {
return null;
}
/*
* (non-Javadoc)
*
* @see io.vertx.core.http.HttpServerResponse#reset(long)
*/
@Override
public void reset(long code) {
}
/*
* (non-Javadoc)
*
* @see io.vertx.core.http.HttpServerResponse#writeCustomFrame(int, int, io.vertx.core.buffer.Buffer)
*/
@Override
public HttpServerResponse writeCustomFrame(int type, int flags, Buffer payload) {
return null;
}
/*
* (non-Javadoc)
*
* @see io.vertx.core.http.HttpServerResponse#endHandler(io.vertx.core.Handler)
*/
@Override
public HttpServerResponse endHandler(@Nullable Handler<Void> handler) {
return null;
}
}
|
package dr.inference.operators;
import dr.inference.model.Parameter;
import dr.inference.model.Variable;
import dr.inferencexml.operators.RandomWalkIntegerOperatorParser;
import dr.math.MathUtils;
/**
* A generic random walk operator for use with a multi-dimensional Integer parameters.
*
* @author Michael Defoin Platel
* @version $Id: RandomWalkIntegerOperator.java$
*/
public class RandomWalkIntegerOperator extends SimpleMCMCOperator {
public RandomWalkIntegerOperator(Variable parameter, int windowSize, double weight) {
this.parameter = parameter;
this.windowSize = windowSize;
setWeight(weight);
}
/**
* @return the parameter this operator acts on.
*/
public Parameter getParameter() {
return (Parameter) parameter;
}
public final int getWindowSize() {
return windowSize;
}
/**
* change the parameter and return the hastings ratio.
*/
double logq;
public double doOperation() {
logq = 0.0;
// a random dimension to perturb
int index = MathUtils.nextInt(parameter.getSize()); // use getSize(), which = getDimension()
if (parameter instanceof Parameter) {
int newValue = calculateNewValue(index);
((Parameter) parameter).setParameterValue(index, newValue);
//System.out.println("newValue: "+newValue);
} else if (parameter instanceof Variable) { // todo this code is improper if we are going to use Variable<Double>
int newValue = calculateNewValue(index);
((Variable<Integer>) parameter).setValue(index, newValue);
}
return logq;
}
protected int calculateNewValue(int index) {
// a random non zero integer around old value within windowSize * 2
int oldValue;
int upper;
int lower;
if (parameter instanceof Parameter) {
oldValue = (int) ((Parameter) parameter).getParameterValue(index);
upper = (int) (double) ((Parameter) parameter).getBounds().getUpperLimit(index);
lower = (int) (double) ((Parameter) parameter).getBounds().getLowerLimit(index);
} else if (parameter instanceof Variable) { // todo this code is improper if we are going to use Variable<Double>
oldValue = ((Variable<Integer>) parameter).getValue(index);
upper = ((Variable<Integer>) parameter).getBounds().getUpperLimit(index);
lower = ((Variable<Integer>) parameter).getBounds().getLowerLimit(index);
} else {
throw new RuntimeException("The parameter (" + parameter.getId() + ") uses invalid class!");
}
if (upper == lower) return upper;
int maxWindowSize = upper - lower;
if(windowSize> maxWindowSize){
windowSize = maxWindowSize;
System.err.println("The maximum window size should be smaller than the total number of possible integer values.");
}
int newValue;
int roll = MathUtils.nextInt(2 * windowSize); // windowSize="1"; roll = {0, 1}
if (roll >= windowSize) { // roll = 1
//roll - window is the positive step size
int step = 1 + (roll - windowSize);
newValue = oldValue + step;
if (newValue > upper){
newValue = 2 * upper - newValue; //reflect down
}
} else { // roll = 0
newValue = oldValue - 1 - roll;
if (newValue < lower){
newValue = 2 * lower - newValue; //reflect up
}
}
//New and seemingly correct (accoding to the running MCMC with uniform prior)
//calculation of the hastings ratio --CHW
int newToOldCount = 0;
int oldToNewCount = 0;
if(newValue != oldValue){
oldToNewCount = oldToNewCount +1;
newToOldCount = newToOldCount +1;
}
int temp = oldValue + windowSize;
if(temp > upper){
if((2*upper - temp) <= newValue && newValue != upper){
oldToNewCount = oldToNewCount+1;
}
}
temp = oldValue - windowSize;
if(temp < lower){
if((2*lower - temp) >= newValue && newValue != lower){
oldToNewCount = oldToNewCount+1;
}
}
temp = newValue + windowSize;
if( temp > upper){
if((2*upper - temp) <= oldValue && oldValue != upper){
newToOldCount = newToOldCount+1;
}
}
temp = newValue - windowSize;
if( temp < lower){
if((2*lower - temp) >= oldValue && oldValue != lower){
newToOldCount = newToOldCount+1;
}
}
logq = Math.log(newToOldCount)- Math.log(oldToNewCount);
return newValue;
}
//MCMCOperator INTERFACE
public String getOperatorName() {
return "randomWalkInteger(" + parameter.getId() + ")";
}
public double getTargetAcceptanceProbability() {
return 0.234;
}
public double getMinimumAcceptanceLevel() {
return 0.1;
}
public double getMaximumAcceptanceLevel() {
return 0.4;
}
public double getMinimumGoodAcceptanceLevel() {
return 0.20;
}
public double getMaximumGoodAcceptanceLevel() {
return 0.30;
}
public final String getPerformanceSuggestion() {
double prob = Utils.getAcceptanceProbability(this);
double targetProb = getTargetAcceptanceProbability();
double maxDelta = 0;
if (parameter instanceof Parameter) {
maxDelta = ((Parameter) parameter).getParameterValue(0) * 2.0;
} else if (parameter instanceof Variable) {
maxDelta = ((Variable<Integer>) parameter).getValue(0) * 2.0;
}
long ws = Math.round(OperatorUtils.optimizeWindowSize(windowSize, maxDelta * 2.0, prob, targetProb));
if (prob < getMinimumGoodAcceptanceLevel()) {
if(ws <= 1){
return "";
}
return "Try decreasing windowSize to about " + ws;
} else if (prob > getMaximumGoodAcceptanceLevel()) {
return "Try increasing windowSize to about " + ws;
} else return "";
}
public String toString() {
return RandomWalkIntegerOperatorParser.RANDOM_WALK_INTEGER_OPERATOR + "(" + parameter.getId() + ", " + windowSize + ", " + getWeight() + ")";
}
//PRIVATE STUFF
protected Variable parameter = null;
protected int windowSize = 1;
}
|
package de.bwaldvogel.mongo.backend.memory;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.apache.log4j.Logger;
import org.bson.BSONObject;
import org.bson.BasicBSONObject;
import org.jboss.netty.channel.Channel;
import com.mongodb.BasicDBObject;
import de.bwaldvogel.mongo.backend.Constants;
import de.bwaldvogel.mongo.backend.MongoCollection;
import de.bwaldvogel.mongo.backend.Utils;
import de.bwaldvogel.mongo.backend.memory.index.UniqueIndex;
import de.bwaldvogel.mongo.exception.MongoServerError;
import de.bwaldvogel.mongo.exception.MongoServerException;
import de.bwaldvogel.mongo.exception.MongoSilentServerException;
import de.bwaldvogel.mongo.exception.NoSuchCommandException;
import de.bwaldvogel.mongo.wire.message.MongoDelete;
import de.bwaldvogel.mongo.wire.message.MongoInsert;
import de.bwaldvogel.mongo.wire.message.MongoQuery;
import de.bwaldvogel.mongo.wire.message.MongoUpdate;
public class MemoryDatabase extends CommonDatabase {
private static final Logger log = Logger.getLogger(MemoryDatabase.class);
private Map<String, MongoCollection> collections = new HashMap<String, MongoCollection>();
private Map<Channel, MongoServerError> lastExceptions = new HashMap<Channel, MongoServerError>();
private Map<Channel, BSONObject> lastUpdates = new HashMap<Channel, BSONObject>();
private MemoryBackend backend;
private MongoCollection namespaces;
private MongoCollection indexes;
public MemoryDatabase(MemoryBackend backend, String databaseName) throws MongoServerException {
super(databaseName);
this.backend = backend;
namespaces = new MemoryNamespacesCollection(getDatabaseName());
collections.put(namespaces.getCollectionName(), namespaces);
indexes = new MemoryIndexesCollection(getDatabaseName());
addNamespace(indexes);
}
private synchronized MongoCollection resolveCollection(String collectionName, boolean throwIfNotFound)
throws MongoServerException {
checkCollectionName(collectionName);
MongoCollection collection = collections.get(collectionName);
if (collection == null && throwIfNotFound) {
throw new MongoServerException("ns not found");
}
return collection;
}
private void checkCollectionName(String collectionName) throws MongoServerException {
if (collectionName.length() > Constants.MAX_NS_LENGTH)
throw new MongoServerError(10080, "ns name too long, max size is " + Constants.MAX_NS_LENGTH);
if (collectionName.isEmpty())
throw new MongoServerError(16256, "Invalid ns [" + collectionName + "]");
}
public MongoServerError getLastException(int clientId) {
return lastExceptions.get(Integer.valueOf(clientId));
}
@Override
public boolean isEmpty() {
return collections.isEmpty();
}
@Override
public Iterable<BSONObject> handleQuery(MongoQuery query) throws MongoServerException {
String collectionName = query.getCollectionName();
MongoCollection collection = resolveCollection(collectionName, false);
if (collection == null) {
return Collections.emptyList();
}
return collection.handleQuery(query.getQuery(), query.getNumberToSkip(), query.getNumberToReturn(),
query.getReturnFieldSelector());
}
@Override
public void handleClose(Channel channel) {
lastExceptions.remove(channel);
lastUpdates.remove(channel);
}
@Override
public void handleInsert(MongoInsert insert) throws MongoServerException {
lastUpdates.remove(insert.getChannel());
try {
String collectionName = insert.getCollectionName();
if (collectionName.equals(indexes.getCollectionName())) {
for (BSONObject indexDescription : insert.getDocuments()) {
addIndex(indexDescription);
}
return;
}
if (collectionName.startsWith("system.")) {
throw new MongoServerError(16459, "attempt to insert in system namespace");
}
MongoCollection collection = resolveCollection(collectionName, false);
if (collection == null) {
collection = createCollection(collectionName);
}
int n = collection.handleInsert(insert);
lastUpdates.put(insert.getChannel(), new BasicBSONObject("n", Integer.valueOf(n)));
} catch (MongoServerError e) {
log.error("failed to insert " + insert, e);
lastExceptions.put(insert.getChannel(), e);
}
}
private void addIndex(BSONObject indexDescription) throws MongoServerException {
String ns = indexDescription.get("ns").toString();
int index = ns.indexOf('.');
String collectionName = ns.substring(index + 1);
MongoCollection collection = resolveCollection(collectionName, false);
if (collection == null) {
collection = createCollection(collectionName);
}
indexes.addDocument(indexDescription);
BSONObject key = (BSONObject) indexDescription.get("key");
if (key.keySet().equals(Collections.singleton("_id"))) {
boolean ascending = Utils.normalizeValue(key.get("_id")).equals(Double.valueOf(1.0));
collection.addIndex(new UniqueIndex("_id", ascending));
} else {
// non-id indexes not yet implemented
// we can ignore that for a moment since it will not break the
// functionality
}
}
private MongoCollection createCollection(String collectionName) throws MongoServerException {
checkCollectionName(collectionName);
if (collectionName.contains("$")) {
throw new MongoServerError(10093, "cannot insert into reserved $ collection");
}
MongoCollection collection = new MemoryCollection(getDatabaseName(), collectionName, "_id");
addNamespace(collection);
BSONObject indexDescription = new BasicBSONObject();
indexDescription.put("name", "_id_");
indexDescription.put("ns", collection.getFullName());
indexDescription.put("key", new BasicBSONObject("_id", Integer.valueOf(1)));
addIndex(indexDescription);
return collection;
}
protected void addNamespace(MongoCollection collection) throws MongoServerException {
collections.put(collection.getCollectionName(), collection);
namespaces.addDocument(new BasicDBObject("name", collection.getFullName()));
}
@Override
public void handleDelete(MongoDelete delete) throws MongoServerException {
lastUpdates.remove(delete.getChannel());
try {
String collectionName = delete.getCollectionName();
if (collectionName.startsWith("system.")) {
throw new MongoServerError(12050, "cannot delete from system namespace");
}
MongoCollection collection = resolveCollection(collectionName, false);
int n;
if (collection == null) {
n = 0;
} else {
n = collection.handleDelete(delete);
}
lastUpdates.put(delete.getChannel(), new BasicBSONObject("n", Integer.valueOf(n)));
} catch (MongoServerError e) {
log.error("failed to delete " + delete, e);
lastExceptions.put(delete.getChannel(), e);
}
}
@Override
public void handleUpdate(MongoUpdate update) throws MongoServerException {
lastUpdates.remove(update.getChannel());
try {
String collectionName = update.getCollectionName();
if (collectionName.startsWith("system.")) {
throw new MongoServerError(10156, "cannot update system collection");
}
MongoCollection collection = resolveCollection(collectionName, false);
if (collection == null) {
collection = createCollection(collectionName);
}
BSONObject result = collection.handleUpdate(update);
lastUpdates.put(update.getChannel(), result);
} catch (MongoServerError e) {
log.error("failed to update " + update, e);
lastExceptions.put(update.getChannel(), e);
}
}
@Override
public BSONObject handleCommand(Channel channel, String command, BSONObject query) throws MongoServerException {
if (command.equalsIgnoreCase("count")) {
return commandCount(command, query);
} else if (command.equalsIgnoreCase("getlasterror")) {
return commandGetLastError(channel, command, query);
} else if (command.equalsIgnoreCase("distinct")) {
String collectionName = query.get(command).toString();
MongoCollection collection = resolveCollection(collectionName, true);
return collection.handleDistinct(query);
} else if (command.equalsIgnoreCase("drop")) {
return commandDrop(query);
} else if (command.equalsIgnoreCase("dropDatabase")) {
return commandDropDatabase();
} else if (command.equalsIgnoreCase("dbstats")) {
return commandDatabaseStats();
} else if (command.equalsIgnoreCase("collstats")) {
String collectionName = query.get("collstats").toString();
MongoCollection collection = resolveCollection(collectionName, true);
return collection.getStats();
} else if (command.equalsIgnoreCase("validate")) {
String collectionName = query.get("validate").toString();
MongoCollection collection = resolveCollection(collectionName, true);
return collection.validate();
} else if (command.equalsIgnoreCase("findAndModify")) {
String collectionName = query.get(command).toString();
MongoCollection collection = resolveCollection(collectionName, false);
if (collection == null) {
collection = createCollection(collectionName);
}
return collection.findAndModify(query);
} else {
log.error("unknown query: " + query);
}
throw new NoSuchCommandException(command);
}
private BSONObject commandDatabaseStats() throws MongoServerException {
BSONObject response = new BasicBSONObject("db", getDatabaseName());
response.put("collections", Integer.valueOf(namespaces.count()));
long indexSize = 0;
long objects = 0;
long dataSize = 0;
double averageObjectSize = 0;
for (MongoCollection collection : collections.values()) {
BSONObject stats = collection.getStats();
objects += ((Number) stats.get("count")).longValue();
dataSize += ((Number) stats.get("size")).longValue();
BSONObject indexSizes = (BSONObject) stats.get("indexSize");
for (String indexName : indexSizes.keySet()) {
indexSize += ((Number) indexSizes.get(indexName)).longValue();
}
}
if (objects > 0) {
averageObjectSize = dataSize / ((double) objects);
}
response.put("objects", Long.valueOf(objects));
response.put("avgObjSize", Double.valueOf(averageObjectSize));
response.put("dataSize", Long.valueOf(dataSize));
response.put("storageSize", Long.valueOf(0));
response.put("numExtents", Integer.valueOf(0));
response.put("indexes", Integer.valueOf(indexes.count()));
response.put("indexSize", Long.valueOf(indexSize));
response.put("fileSize", Integer.valueOf(0));
response.put("nsSizeMB", Integer.valueOf(0));
Utils.markOkay(response);
return response;
}
private BSONObject commandDropDatabase() {
backend.dropDatabase(this);
BSONObject response = new BasicBSONObject("dropped", getDatabaseName());
Utils.markOkay(response);
return response;
}
private BSONObject commandDrop(BSONObject query) throws MongoServerException {
String collectionName = query.get("drop").toString();
MongoCollection collection = collections.remove(collectionName);
if (collection == null) {
throw new MongoSilentServerException("ns not found");
}
BSONObject response = new BasicBSONObject();
namespaces.removeDocument(new BasicBSONObject("name", collection.getFullName()));
response.put("nIndexesWas", Integer.valueOf(collection.getNumIndexes()));
response.put("ns", collection.getFullName());
Utils.markOkay(response);
return response;
}
private BSONObject commandGetLastError(Channel channel, String command, BSONObject query)
throws MongoServerException {
Iterator<String> it = query.keySet().iterator();
String cmd = it.next();
if (!cmd.equals(command))
throw new IllegalStateException();
if (it.hasNext()) {
String subCommand = it.next();
if (!subCommand.equals("w")) {
throw new MongoServerException("unknown subcommand: " + subCommand);
}
}
BSONObject result = new BasicBSONObject();
Utils.markOkay(result);
if (lastExceptions != null) {
MongoServerError ex = lastExceptions.remove(channel);
if (ex != null) {
BSONObject obj = new BasicBSONObject("err", ex.getMessage());
obj.put("code", Integer.valueOf(ex.getCode()));
obj.put("connectionId", channel.getId());
Utils.markOkay(obj);
return obj;
}
BSONObject lastUpdate = lastUpdates.remove(channel);
if (lastUpdate != null) {
result.putAll(lastUpdate);
}
}
return result;
}
private BSONObject commandCount(String command, BSONObject query) throws MongoServerException {
String collection = query.get(command).toString();
BSONObject response = new BasicBSONObject();
MongoCollection coll = collections.get(collection);
if (coll == null) {
response.put("missing", Boolean.TRUE);
response.put("n", Integer.valueOf(0));
} else {
response.put("n", Integer.valueOf(coll.count((BSONObject) query.get("query"))));
}
Utils.markOkay(response);
return response;
}
}
|
package de.uni_potsdam.hpi.bpt.bp2014.database;
import javax.annotation.Resource;
import javax.sql.DataSource;
import java.io.*;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Connection {
private static Connection instance = null;
private static File file;
private static String username;
private static String password;
private static String url;
public static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
@Resource(name="jdbc/jengine")
private DataSource ds;
private Connection(String path){
if(ds == null) {
file = new File(path);
file = file.getAbsoluteFile();
username = this.getUsername();
password = this.getPassword();
url = this.getUrl();
}
}
public static Connection getInstance(String path) {
if (instance == null) {
instance = new Connection(path);
}
return instance;
}
public static Connection getInstance() {
if (instance == null) {
//instance = new Connection("C:/xampp/tomcat/webapps/JEngine/WEB-INF/classes/database_connection");
instance = new Connection("src/main/resources/database_connection");
}
return instance;
}
private static String getUsername(){
FileReader fr = null;
try {
fr = new FileReader(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
BufferedReader br = new BufferedReader(fr);
String username = "";
try {
username = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return username;
}
private static String getPassword(){
FileReader fr = null;
try {
fr = new FileReader(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
BufferedReader br = new BufferedReader(fr);
String password = "";
try {
br.readLine();
password = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return password;
}
private static String getUrl(){
FileReader fr = null;
try {
fr = new FileReader(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
//System.err.println(file.getAbsoluteFile());
BufferedReader br = new BufferedReader(fr);
String url = "";
try {
br.readLine();
br.readLine();
url = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return url;
}
public java.sql.Connection connect() {
java.sql.Connection conn = null;
try {
if(ds != null) {
return ds.getConnection();
}//Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
//Open a connection
conn = DriverManager.getConnection(url, password, username);
} catch (SQLException se) {
//Handle errors for JDBC
se.printStackTrace();
} catch (Exception e) {
//Handle errors for Class.forName
e.printStackTrace();
}
return conn;
}
}
|
package edu.harvard.iq.dataverse;
import java.io.Serializable;
import java.util.Collection;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Index;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OrderBy;
import javax.persistence.Table;
/**
*
* @author skraffmiller
*/
@Entity
@Table(indexes = {@Index(columnList="datasetfield_id"),
@Index(columnList="defaultvalueset_id"),
@Index(columnList="parentdatasetfielddefaultvalue_id"),
@Index(columnList="displayorder")})
public class DatasetFieldDefaultValue implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public DatasetFieldDefaultValue() {
}
public DatasetFieldDefaultValue(DatasetFieldType sf, DefaultValueSet dvs, String val) {
setDatasetField(sf);
setDefaultValueSet(dvs);
setStrValue(val);
}
@ManyToOne
@JoinColumn(nullable=false)
private DatasetFieldType datasetField;
public DatasetFieldType getDatasetField() {
return datasetField;
}
public void setDatasetField(DatasetFieldType datasetField) {
this.datasetField = datasetField;
}
@ManyToOne
@JoinColumn(nullable=false)
private DefaultValueSet defaultValueSet;
public DefaultValueSet getDefaultValueSet() {
return defaultValueSet;
}
public void setDefaultValueSet(DefaultValueSet defaultValueSet) {
this.defaultValueSet = defaultValueSet;
}
@OneToMany(mappedBy = "parentDatasetFieldDefaultValue", cascade = {CascadeType.REMOVE, CascadeType.MERGE, CascadeType.PERSIST})
@OrderBy("displayOrder ASC")
private Collection<DatasetFieldDefaultValue> childDatasetFieldDefaultValues;
public Collection<DatasetFieldDefaultValue> getChildDatasetFieldDefaultValues() {
return this.childDatasetFieldDefaultValues;
}
public void setChildDatasetFieldDefaultValues(Collection<DatasetFieldDefaultValue> childDatasetFieldDefaultValues) {
this.childDatasetFieldDefaultValues = childDatasetFieldDefaultValues;
}
@ManyToOne(cascade = CascadeType.MERGE)
private DatasetFieldDefaultValue parentDatasetFieldDefaultValue;
public DatasetFieldDefaultValue getParentDatasetFieldDefaultValue() {
return parentDatasetFieldDefaultValue;
}
public void setParentDatasetFieldValue(DatasetFieldDefaultValue parentDatasetFieldDefaultValue) {
this.parentDatasetFieldDefaultValue = parentDatasetFieldDefaultValue;
}
@Column(columnDefinition="TEXT", nullable=false )
private String strValue;
public String getStrValue() {
return strValue;
}
public void setStrValue(String strValue) {
this.strValue = strValue;
}
@Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
if (!(object instanceof DatasetField)) {
return false;
}
DatasetFieldDefaultValue other = (DatasetFieldDefaultValue) object;
return !((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id)));
}
@Override
public String toString() {
return "edu.harvard.iq.dataverse.DatasetFieldDefaultValue[ id=" + id + " ]";
}
public boolean isEmpty() {
return ((strValue==null || strValue.trim().equals("")));
}
private int displayOrder;
public int getDisplayOrder() { return this.displayOrder;}
public void setDisplayOrder(int displayOrder) {this.displayOrder = displayOrder;}
}
|
/**
* EditFieldScreen
*
* Class representing the screen that allows users to edit
* the properties of a local or global field.
*
* @author Willy McHie
* Wheaton College, CSCI 335, Spring 2013
*/
package edu.wheaton.simulator.gui.screen;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import edu.wheaton.simulator.gui.BoxLayoutAxis;
import edu.wheaton.simulator.gui.Gui;
import edu.wheaton.simulator.gui.HorizontalAlignment;
import edu.wheaton.simulator.gui.MaxSize;
import edu.wheaton.simulator.gui.MinSize;
import edu.wheaton.simulator.gui.PrefSize;
import edu.wheaton.simulator.gui.ScreenManager;
import edu.wheaton.simulator.gui.SimulatorFacade;
public class EditFieldScreen extends Screen {
private static final long serialVersionUID = 8001531208716520432L;
private JDialog parentWindow;
private JTextField nameField;
private JTextField initValue;
private String prevName;
public EditFieldScreen(final SimulatorFacade gm, JDialog parentWindow) {
super(gm);
this.parentWindow = parentWindow;
this.setLayout(new GridBagLayout());
JLabel header = new JLabel("Edit Field");
JLabel nameLabel = new JLabel("Field Name: ");
nameField = Gui.makeTextField(null,40, MaxSize.NULL,null);
nameField.setMinimumSize(new MinSize(100,30));
JLabel valueLabel = new JLabel("Initial Value: ");
initValue = Gui.makeTextField(null,40,MaxSize.NULL,null);
initValue.setMinimumSize(new MinSize(100,30));
JButton cancel = Gui.makeButton("Cancel",PrefSize.NULL,
new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
ScreenManager sm = getScreenManager();
sm.load(sm.getScreen("View Simulation"));
}
});
JButton finish = Gui.makeButton("Finish",PrefSize.NULL,
new FinishListener());
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
c.insets = new Insets(0,0,15,0);
this.add(header,c);
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 1;
this.add(nameLabel,c);
c = new GridBagConstraints();
c.gridx = 1;
c.gridy = 1;
this.add(nameField,c);
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 2;
this.add(valueLabel,c);
c = new GridBagConstraints();
c.gridx = 1;
c.gridy = 2;
this.add(initValue,c);
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 3;
this.add(cancel,c);
c = new GridBagConstraints();
c.gridx = 1;
c.gridy = 3;
this.add(finish,c);
}
public void reset() {
nameField.setText("");
initValue.setText("");
prevName = "";
}
public void load(String n) {
//edit listener should call this?
reset();
nameField.setText(n);
initValue.setText(getGuiManager().getGlobalField(n).getValue());
prevName = n;
}
@Override
public void load() {
//What is this here for?
//GUIToAgentFacade facade = gm.getFacade();
//facade.getPrototype(nameField.getText());
//add listener should call this
reset();
}
private class FinishListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent ae) {
boolean toMove = true;
try {
SimulatorFacade gm = getGuiManager();
String nameFieldText = nameField.getText();
String initValueText = initValue.getText();
if (nameFieldText.equals("") ||
initValueText.equals("")) {
throw new Exception("All fields must have input");
}
if (FieldScreen.getEditing()){
gm.removeGlobalField(prevName);
gm.addGlobalField(nameFieldText,initValueText);
}
else
gm.addGlobalField(nameFieldText,initValueText);
} catch (Exception e) {
toMove = false;
JOptionPane.showMessageDialog(null, e.getMessage());
}
if(toMove) {
ScreenManager sm = getScreenManager();
Screen viewSimScreen = sm.getScreen("View Simulation");
viewSimScreen.load();
parentWindow.dispose();
//sm.load(viewSimScreen);
}
}
}
}
|
package edu.harvard.iq.dataverse;
import edu.harvard.iq.dataverse.engine.UserRoleAssignments;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Set;
import java.util.logging.Logger;
import javax.ejb.Stateless;
import javax.inject.Named;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
/**
*
* @author michael
*/
@Stateless
@Named
public class DataverseRoleServiceBean {
private static final Logger logger = Logger.getLogger(DataverseRoleServiceBean.class.getName());
@PersistenceContext(unitName = "VDCNet-ejbPU")
private EntityManager em;
public DataverseRole save( DataverseRole aRole ) {
if ( aRole.getId() == null ) {
em.persist(aRole);
return aRole;
} else {
return em.merge( aRole );
}
}
public RoleAssignment save( RoleAssignment assignment ) {
if ( assignment.getId() == null ) {
em.persist(assignment);
em.flush();
return assignment;
} else {
return em.merge( assignment );
}
}
public DataverseRole find( Long id ) {
return em.find( DataverseRole.class, id );
}
public List<DataverseRole> findAll() {
return em.createNamedQuery("DataverseRole.listAll", DataverseRole.class).getResultList();
}
public void delete( Long id ) {
em.createNamedQuery("DataverseRole.deleteById", DataverseRole.class)
.setParameter("id", id)
.executeUpdate();
}
public List<DataverseRole> findByOwnerId( Long ownerId ) {
return em.createNamedQuery("DataverseRole.findByOwnerId", DataverseRole.class)
.setParameter("ownerId", ownerId)
.getResultList();
}
public void revoke( Set<DataverseRole> roles, DataverseUser user, DvObject defPoint ) {
for ( DataverseRole role : roles ) {
em.createNamedQuery("RoleAssignment.deleteByUserRoleIdDefinitionPointId")
.setParameter("userId", user.getId())
.setParameter("roleId", role.getId())
.setParameter("definitionPointId", defPoint.getId())
.executeUpdate();
em.refresh(role);
}
em.refresh(user);
}
public void revoke( RoleAssignment ra ) {
if ( ! em.contains(ra) ) {
ra = em.merge(ra);
}
em.remove(ra);
}
public UserRoleAssignments roleAssignments( DataverseUser user, Dataverse dv ) {
UserRoleAssignments retVal = new UserRoleAssignments(user);
while ( dv != null ) {
retVal.add( directRoleAssignments(user, dv) );
if ( dv.isPermissionRoot() ) break;
dv = dv.getOwner();
}
return retVal;
}
public UserRoleAssignments assignmentsFor( final DataverseUser u, final DvObject d ) {
return d.accept( new DvObject.Visitor<UserRoleAssignments>() {
@Override
public UserRoleAssignments visit(Dataverse dv) {
return roleAssignments(u, dv);
}
@Override
public UserRoleAssignments visit(Dataset ds) {
UserRoleAssignments asgn = ds.getOwner().accept(this);
asgn.add( directRoleAssignments(u, ds) );
return asgn;
}
@Override
public UserRoleAssignments visit(DataFile df) {
UserRoleAssignments asgn = df.getOwner().accept(this);
asgn.add( directRoleAssignments(u, df) );
return asgn;
}
});
}
public Set<RoleAssignment> rolesAssignments( Dataverse dv ) {
Set<RoleAssignment> ras = new HashSet<>();
while ( ! dv.isEffectivlyPermissionRoot() ) {
ras.addAll( em.createNamedQuery("RoleAssignment.listByDefinitionPointId", RoleAssignment.class)
.setParameter("definitionPointId", dv.getId() ).getResultList() );
dv = dv.getOwner();
}
ras.addAll( em.createNamedQuery("RoleAssignment.listByDefinitionPointId", RoleAssignment.class)
.setParameter("definitionPointId", dv.getId() ).getResultList() );
return ras;
}
/**
* Retrieves the roles assignments for {@code user}, directly on {@code dv}.
* No traversal on the containment hierarchy is done.
* @param user the user whose roles are given
* @param dvo the object where the roles are defined.
* @return Set of roles defined for the user in the given dataverse.
* @see #roleAssignments(edu.harvard.iq.dataverse.DataverseUser, edu.harvard.iq.dataverse.Dataverse)
*/
public List<RoleAssignment> directRoleAssignments( DataverseUser user, DvObject dvo ) {
if ( user==null ) throw new IllegalArgumentException("User cannot be null");
TypedQuery<RoleAssignment> query = em.createNamedQuery(
"RoleAssignment.listByUserIdDefinitionPointId",
RoleAssignment.class);
query.setParameter("userId", user.getId());
query.setParameter("definitionPointId", dvo.getId());
return query.getResultList();
}
/**
* Retrieves the roles assignments for {@code user}, directly on {@code dv}.
* No traversal on the containment hierarchy is done.
* @param user the user whose roles are given
* @param dvo the object where the roles are defined.
* @return Set of roles defined for the user in the given dataverse.
* @see #roleAssignments(edu.harvard.iq.dataverse.DataverseUser, edu.harvard.iq.dataverse.Dataverse)
*/
public List<RoleAssignment> directRoleAssignments( DvObject dvo ) {
TypedQuery<RoleAssignment> query = em.createNamedQuery(
"RoleAssignment.listByDefinitionPointId",
RoleAssignment.class);
query.setParameter("definitionPointId", dvo.getId());
return query.getResultList();
}
/**
* Get all the available roles in a given dataverse, mapped by the
* dataverse that defines them. Map entries are ordered by reversed hierarchy
* (root is always last).
* @param dvId The id of dataverse whose available roles we query
* @return map of available roles.
*/
public LinkedHashMap<Dataverse,Set<DataverseRole>> availableRoles( Long dvId ) {
LinkedHashMap<Dataverse,Set<DataverseRole>> roles = new LinkedHashMap<>();
Dataverse dv = em.find(Dataverse.class, dvId);
roles.put( dv, dv.getRoles() );
while( !dv.isEffectivlyPermissionRoot() ) {
dv = dv.getOwner();
roles.put( dv, dv.getRoles() );
}
return roles;
}
}
|
package hudson.plugins.promoted_builds;
import hudson.DescriptorExtensionList;
import hudson.ExtensionPoint;
import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;
import hudson.model.Describable;
import hudson.model.Hudson;
import java.util.ArrayList;
import java.util.List;
/**
* Extension point for defining a promotion criteria.
*
* @author Kohsuke Kawaguchi
*/
public abstract class PromotionCondition implements ExtensionPoint, Describable<PromotionCondition> {
/**
* Checks if the promotion criteria is met.
*
* @param build
* The build for which the promotion is considered.
* @return
* non-null if the promotion condition is met. This object is then recorded so that
* we know how a build was promoted.
* Null if otherwise, meaning it shouldn't be promoted.
*/
public abstract PromotionBadge isMet(AbstractBuild<?,?> build);
public PromotionConditionDescriptor getDescriptor() {
return (PromotionConditionDescriptor)Hudson.getInstance().getDescriptor(getClass());
}
/**
* Returns all the registered {@link PromotionConditionDescriptor}s.
*/
public static DescriptorExtensionList<PromotionCondition,PromotionConditionDescriptor> all() {
return Hudson.getInstance().<PromotionCondition,PromotionConditionDescriptor>getDescriptorList(PromotionCondition.class);
}
/**
* Returns a subset of {@link PromotionConditionDescriptor}s that applys to the given project.
*/
public static List<PromotionConditionDescriptor> getApplicableTriggers(AbstractProject<?,?> p) {
List<PromotionConditionDescriptor> r = new ArrayList<PromotionConditionDescriptor>();
for (PromotionConditionDescriptor t : all()) {
if(t.isApplicable(p))
r.add(t);
}
return r;
}
}
|
package hudson.plugins.promoted_builds;
import hudson.model.Descriptor.FormException;
import hudson.model.AbstractBuild;
import hudson.util.DescribableList;
import net.sf.json.JSONObject;
import org.kohsuke.stapler.StaplerRequest;
import java.io.IOException;
/**
* Criteria for a build to be promoted.
*
* @author Kohsuke Kawaguchi
*/
public final class PromotionCriterion implements DescribableList.Owner {
private final String name;
/**
* {@link PromotionCondition}s.
*/
private final DescribableList<PromotionCondition,PromotionConditionDescriptor> conditions =
new DescribableList<PromotionCondition, PromotionConditionDescriptor>(this);
/*package*/ PromotionCriterion(StaplerRequest req, JSONObject c) throws FormException {
this.name = c.getString("name");
conditions.rebuild(req,c,PromotionConditions.CONDITIONS,"condition");
}
/**
* Checks if all the conditions to promote a build is met.
*/
public boolean isMet(AbstractBuild<?,?> build) {
for (PromotionCondition cond : conditions)
if(!cond.isMet(build))
return false;
return true;
}
/**
* Gets the human readable name set by the user.
*/
public String getName() {
return name;
}
/**
* @deprecated
* Save is not supported on this level.
*/
public void save() throws IOException {
// TODO?
}
/**
* {@link PromotionCondition}s that constitute this criteria.
*/
public DescribableList<PromotionCondition, PromotionConditionDescriptor> getConditions() {
return conditions;
}
}
|
package hudson.plugins.report.jck;
import com.google.gson.GsonBuilder;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import hudson.Launcher;
import hudson.model.AbstractBuild;
import hudson.model.BuildListener;
import hudson.model.Result;
import hudson.plugins.report.jck.model.Report;
import hudson.plugins.report.jck.model.ReportFull;
import hudson.plugins.report.jck.model.Suite;
import hudson.plugins.report.jck.model.SuiteTests;
import hudson.plugins.report.jck.parsers.ReportParser;
import hudson.tasks.BuildStepMonitor;
import hudson.tasks.Recorder;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.stream.Collectors;
import org.kohsuke.stapler.DataBoundSetter;
import static hudson.plugins.report.jck.Constants.REPORT_JSON;
import static hudson.plugins.report.jck.Constants.REPORT_TESTS_LIST_JSON;
import hudson.plugins.report.jck.model.BuildReport;
import java.util.Arrays;
abstract public class AbstractReportPublisher extends Recorder {
private String reportFileGlob;
private String resultsBlackList;
private String resultsWhiteList;
private String maxBuilds;
private int rangeAroundWlist;
public AbstractReportPublisher(String reportFileGlob) {
this.reportFileGlob = reportFileGlob;
}
abstract protected String defaultReportFileGlob();
abstract protected ReportParser createReportParser();
abstract protected String prefix();
@Override
@SuppressFBWarnings(value = {"NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE", "RCN_REDUNDANT_NULLCHECK_WOULD_HAVE_BEEN_A_NPE"}, justification = " npe of spotbugs sucks")
final public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException {
String reportFileGlob = getReportFileGlob();
if (reportFileGlob == null || reportFileGlob.trim().isEmpty()) {
reportFileGlob = defaultReportFileGlob();
}
if (!reportFileGlob.startsWith("glob:")) {
reportFileGlob = "glob:" + reportFileGlob;
}
List<Suite> report = build.getWorkspace().act(
new ReportParserCallable(reportFileGlob, createReportParser()));
if (report.stream().anyMatch(
s -> s.getReport() != null && (s.getReport().getTestsError() != 0 || s.getReport().getTestsFailed() != 0))) {
build.setResult(Result.UNSTABLE);
}
if (report.stream().anyMatch(
s -> s.getReport() != null && (s.getReport().getTestsTotal() <= 0 || s.getReport().getTestsTotal() == s.getReport().getTestsNotRun()))) {
build.setResult(Result.FAILURE);
}
storeFailuresSummary(report, new File(build.getRootDir(), prefix() + "-" + REPORT_JSON));
storeFullTestsList(report, new File(build.getRootDir(), prefix() + "-" + REPORT_TESTS_LIST_JSON));
addReportAction(build);
return true;
}
private void addReportAction(AbstractBuild<?, ?> build) {
ReportAction action = build.getAction(ReportAction.class);
if (action == null) {
action = new ReportAction(build);
action.addPrefix(prefix());
build.addAction(action);
} else {
action.addPrefix(prefix());
}
}
private void storeFailuresSummary(List<Suite> reportFull, File jsonFile) throws IOException {
List<Suite> reportShort = reportFull.stream()
.sequential()
.map(s -> new Suite(
s.getName(),
new Report(
s.getReport().getTestsPassed(),
s.getReport().getTestsNotRun(),
s.getReport().getTestsFailed(),
s.getReport().getTestsError(),
s.getReport().getTestsTotal(),
s.getReport().getTestProblems())))
.sorted()
.collect(Collectors.toList());
try (Writer out = new OutputStreamWriter(new BufferedOutputStream(new FileOutputStream(jsonFile)),
StandardCharsets.UTF_8)) {
new GsonBuilder().setPrettyPrinting().create().toJson(reportShort, out);
}
cacheReport(reportShort, jsonFile);
}
private void cacheReport(List<Suite> reportShort, File jsonFile) {
try {
int passedSumm = 0;
int notRunSumm = 0;
int failedSumm = 0;
int errorSumm = 0;
int totalSumm = 0;
StringBuilder nameb = new StringBuilder();
for (Suite s : reportShort) {
passedSumm += s.getReport().getTestsPassed();
notRunSumm += s.getReport().getTestsNotRun();
failedSumm += s.getReport().getTestsFailed();
errorSumm += s.getReport().getTestsError();
totalSumm += s.getReport().getTestsTotal();
nameb.append(s.getName()).append(" ");
}
File buildDir = jsonFile.getParentFile();
int buildNumber = Integer.parseInt(buildDir.getName());
BuildReport br = new BuildReport(buildNumber, nameb.toString().trim(), passedSumm, failedSumm, errorSumm, reportShort, totalSumm, notRunSumm);
ReportProjectAction.cacheSumms(buildDir.getParentFile().getParentFile(), Arrays.asList(new BuildReport[]{br}));
} catch (Exception ex) {
ex.printStackTrace();
}
}
private void storeFullTestsList(List<Suite> reportFull, File jsonFile) throws IOException {
List<SuiteTests> suites = reportFull.stream()
.sequential()
.map(s -> new SuiteTests(
s.getName(),
s.getReport() instanceof ReportFull ? ((ReportFull) s.getReport()).getTestsList() : null))
.sorted()
.collect(Collectors.toList());
try (Writer out = new OutputStreamWriter(new BufferedOutputStream(new FileOutputStream(jsonFile)),
StandardCharsets.UTF_8)) {
new GsonBuilder().create().toJson(suites, out);
}
}
@Override
final public BuildStepMonitor getRequiredMonitorService() {
return BuildStepMonitor.NONE;
}
@DataBoundSetter
public void setReportFileGlob(String reportFileGlob) {
this.reportFileGlob = reportFileGlob;
}
public String getReportFileGlob() {
return reportFileGlob;
}
@DataBoundSetter
public void setResultsBlackList(String resultsBlackList) {
this.resultsBlackList = resultsBlackList;
}
public String getResultsBlackList() {
return resultsBlackList;
}
@DataBoundSetter
public void setMaxBuilds(String maxBuilds) {
this.maxBuilds = maxBuilds;
}
public String getMaxBuilds() {
if (maxBuilds == null) {
return "10";
}
return maxBuilds;
}
public int getIntMaxBuilds() {
try {
return Integer.parseInt(getMaxBuilds().trim());
} catch (NumberFormatException ex) {
return 10;
}
}
public String getResultsWhiteList() {
return resultsWhiteList;
}
@DataBoundSetter
public void setResultsWhiteList(String resultsWhiteList) {
this.resultsWhiteList = resultsWhiteList;
}
public int getRangeAroundWlist() {
return rangeAroundWlist;
}
@DataBoundSetter
public void setRangeAroundWlist(int rangeAroundWlist) {
this.rangeAroundWlist = rangeAroundWlist;
}
}
|
package iguanaman.iguanatweaks.config;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.item.Item;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemStack;
import iguanaman.iguanatweaks.IguanaTweaks;
import iguanaman.iguanatweaks.util.IguanaJsonReader;
public class IguanaWeightsConfig {
private static HashMap<String, Double> weights;
public static void init(File file) {
if(file.exists()) {
weights = IguanaJsonReader.readWeightsJson(file);
} else {
try {
if(file.createNewFile()) {
PrintWriter writer = new PrintWriter(file);
writer.println("[");
writer.println("]");
writer.close();
}
} catch(IOException e) {
IguanaTweaks.log.error("There was an error in creating the weights.json file");
e.printStackTrace();
}
}
}
/**
* Obtains the weight of a given block or item, either specified in the <I>weights.json</I> file, or by using it's default value if a different one is not specified in the <I>weights.json</I> file.<br/>
* Blocks' default value are based on their material, while all Items are one constant value.
* @param stack The ItemStack to get the weight for
* @return The weight of the block as a double
*/
public static double getWeight(ItemStack stack) {
if(weights != null && weights.containsKey(Item.itemRegistry.getNameForObject(stack.getItem()))) {
return weights.get(Item.itemRegistry.getNameForObject(stack.getItem()));
} else {
return getDefaultWeight(stack);
}
}
private static double getDefaultWeight(ItemStack stack) {
if(!(stack.getItem() instanceof ItemBlock)) {
return 1D / 64D;
}
Block block = Block.getBlockFromItem(stack.getItem());
Material blockMaterial = block.getMaterial();
if(blockMaterial == Material.iron || blockMaterial == Material.anvil) {
return 1.5D;
} else if(blockMaterial == Material.rock) {
return 1.0D;
} else if(blockMaterial == Material.grass || blockMaterial == Material.ground || blockMaterial == Material.sand || blockMaterial == Material.snow || blockMaterial == Material.wood || blockMaterial == Material.glass || blockMaterial == Material.ice || blockMaterial == Material.tnt) {
return 0.5D;
} else if(blockMaterial == Material.cloth) {
return 0.25D;
} else {
return 1D / 16D;
}
}
}
|
package il.ac.bgu.cs.bp.bpjs.analysis;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import il.ac.bgu.cs.bp.bpjs.model.BProgram;
import il.ac.bgu.cs.bp.bpjs.model.BEvent;
import il.ac.bgu.cs.bp.bpjs.internal.ExecutorServiceMaker;
import il.ac.bgu.cs.bp.bpjs.model.BProgramSyncSnapshot;
import java.util.Optional;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.atomic.AtomicInteger;
/**
*
* Takes a {@link BProgram}, and verifies that it does not run into false
* assertions, given all possible event selections.
* Take care to use the appropriate {@link VisitedStateStore} for the
* {@link BProgram} being verified.
*
* States are scanned using a DFS.
*
* @author michael
*/
public class DfsBProgramVerifier {
private static final AtomicInteger INSTANCE_COUNTER = new AtomicInteger();
public final static long DEFAULT_MAX_TRACE = 100;
/**
* Default number of iterations between invocation of {@link ProgressListener#iterationCount(long, long, il.ac.bgu.cs.bp.bpjs.verification.DfsBProgramVerifier)
* }.
*/
public final static long DEFAULT_ITERATION_COUNT_GAP = 1000;
/**
* A listener to the progress of the DFS state scanning.
*/
public static interface ProgressListener {
void started(DfsBProgramVerifier v);
void iterationCount(long count, long statesHit, DfsBProgramVerifier v);
void maxTraceLengthHit(List<Node> trace, DfsBProgramVerifier v);
void done(DfsBProgramVerifier v);
}
private long visitedStatesCount;
private VisitedStateStore visited = new BProgramStateVisitedStateStore();
private long maxTraceLength = DEFAULT_MAX_TRACE;
private final ArrayList<Node> currentPath = new ArrayList<>();
private Optional<ProgressListener> listenerOpt = Optional.empty();
private long iterationCountGap = DEFAULT_ITERATION_COUNT_GAP;
private BProgram currentBProgram;
private boolean debugMode = false;
private boolean detectDeadlocks = true;
public VerificationResult verify(BProgram aBp) throws Exception {
currentBProgram = aBp;
visitedStatesCount = 1;
currentPath.clear();
visited.clear();
ExecutorService execSvc = ExecutorServiceMaker.makeWithName("DfsBProgramRunner-" + INSTANCE_COUNTER.incrementAndGet());
long start = System.currentTimeMillis();
listenerOpt.ifPresent(l -> l.started(this));
VerificationResult vr = dfsUsingStack(Node.getInitialNode(aBp, execSvc), execSvc);
long end = System.currentTimeMillis();
listenerOpt.ifPresent(l -> l.done(this));
execSvc.shutdown();
return new VerificationResult(vr.getViolationType(), vr.getFailedAssertion(), vr.getCounterExampleTrace(), end-start, visitedStatesCount);
}
protected VerificationResult dfsUsingStack(Node aStartNode, ExecutorService execSvc) throws Exception {
long iterationCount = 0;
visitedStatesCount = 0;
visited.store(aStartNode);
push(aStartNode);
while (!isPathEmpty()) {
if (debugMode) {
printStatus(iterationCount, Collections.unmodifiableList(currentPath));
}
Node curNode = peek();
if ( curNode != null ) {
if ( isDetectDeadlocks() &&
hasRequestedEvents( curNode.getSystemState() ) &&
curNode.getSelectableEvents().isEmpty()
) {
// detected deadlock
return new VerificationResult(VerificationResult.ViolationType.Deadlock, null, currentPath);
}
if ( ! curNode.getSystemState().isStateValid() ) {
// detected assertion failure.
return new VerificationResult(VerificationResult.ViolationType.FailedAssertion,
curNode.getSystemState().getFailedAssertion(),
currentPath);
}
}
iterationCount++;
if (pathLength() == maxTraceLength) {
if (listenerOpt.isPresent()) {
listenerOpt.get().maxTraceLengthHit(currentPath, this);
}
// fold stack;
pop();
} else {
Node nextNode = getUnvisitedNextNode(curNode, execSvc);
if (nextNode == null) {
// fold stack, retry next iteration;
pop();
if (isDebugMode()) {
System.out.println("-pop!-");
}
} else {
// go deeper
visited.store(nextNode);
if (isDebugMode()) {
System.out.println("-visiting: " + nextNode);
}
push(nextNode);
visitedStatesCount++;
}
}
if (iterationCount % iterationCountGap == 0 && listenerOpt.isPresent()) {
listenerOpt.get().iterationCount(iterationCount, visitedStatesCount, this);
}
}
return new VerificationResult(VerificationResult.ViolationType.None, null, null);
}
protected Node getUnvisitedNextNode(Node src, ExecutorService execSvc) throws Exception {
while (src.getEventIterator().hasNext()) {
final BEvent nextEvent = src.getEventIterator().next();
Node possibleNextNode = src.getNextNode(nextEvent, execSvc);
if ( !visited.isVisited(possibleNextNode) ) {
return possibleNextNode;
}
}
return null;
}
public void setMaxTraceLength(long maxTraceLength) {
this.maxTraceLength = maxTraceLength;
}
public long getMaxTraceLength() {
return maxTraceLength;
}
public void setVisitedNodeStore(VisitedStateStore aVisitedNodeStore) {
visited = aVisitedNodeStore;
}
public VisitedStateStore getVisitedNodeStore() {
return visited;
}
public void setProgressListener(ProgressListener pl) {
listenerOpt = Optional.of(pl);
}
public void setIterationCountGap(long iterationCountGap) {
this.iterationCountGap = iterationCountGap;
}
public long getIterationCountGap() {
return iterationCountGap;
}
public BProgram getCurrentBProgram() {
return currentBProgram;
}
void printStatus(long iteration, List<Node> path) {
System.out.println("Iteration " + iteration);
System.out.println(" visited: " + visitedStatesCount);
path.forEach(n -> System.out.println(" " + n.getLastEvent()));
}
private void push(Node n) {
currentPath.add(n);
}
private int pathLength() {
return currentPath.size();
}
private boolean isPathEmpty() {
return pathLength() == 0;
}
private Node peek() {
return isPathEmpty() ? null : currentPath.get(currentPath.size() - 1);
}
private Node pop() {
return currentPath.remove(currentPath.size() - 1);
}
public boolean isDebugMode() {
return debugMode;
}
public void setDebugMode(boolean debugMode) {
this.debugMode = debugMode;
}
public boolean isDetectDeadlocks() {
return detectDeadlocks;
}
public void setDetectDeadlocks(boolean detectDeadlocks) {
this.detectDeadlocks = detectDeadlocks;
}
private boolean hasRequestedEvents( BProgramSyncSnapshot bpss ) {
return bpss.getBThreadSnapshots().stream().anyMatch(btss -> (!btss.getBSyncStatement().getRequest().isEmpty()) );
}
}
|
package innovimax.mixthem.operation;
import innovimax.mixthem.MixException;
import innovimax.mixthem.arguments.RuleParam;
import innovimax.mixthem.arguments.ParamValue;
import innovimax.mixthem.io.DefaultByteWriter;
import innovimax.mixthem.io.IByteOutput;
import innovimax.mixthem.io.IMultiChannelByteInput;
import innovimax.mixthem.io.InputResource;
import innovimax.mixthem.io.MultiChannelByteReader;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;
/**
* <p>Abstract class for all byte operation.</p>
* @see IByteOperation
* @author Innovimax
* @version 1.0
*/
public abstract class AbstractByteOperation extends AbstractOperation implements IByteOperation {
/**
* Constructor
* @param params The list of parameters (maybe empty)
* @see innovimax.mixthem.arguments.RuleParam
* @see innovimax.mixthem.arguments.ParamValue
*/
public AbstractByteOperation(final Map<RuleParam, ParamValue> params) {
super(params);
}
@Override
public void processFiles(final List<InputResource> inputs, final OutputStream output) throws MixException, IOException {
final IMultiChannelByteInput reader = new MultiChannelByteReader(inputs);
final IByteOutput writer = new DefaultByteWriter(output);
final ByteResult result = new ByteResult();
while (reader.hasByte()) {
final byte[] byteRange = reader.nextByteRange();
process(byteRange, result);
if (result.hasResult()) {
result.getResult().forEach(i -> {
try {
writer.writeByte((byte) i);
} catch (IOException e) {
throw new RuntimeException(e);
}
});
}
result.reset();
}
reader.close();
writer.close();
}
}
|
package innovimax.mixthem.operation;
import innovimax.mixthem.MixException;
import innovimax.mixthem.arguments.RuleParam;
import innovimax.mixthem.arguments.ParamValue;
import innovimax.mixthem.io.DefaultCharReader;
import innovimax.mixthem.io.DefaultCharWriter;
import innovimax.mixthem.io.IInputChar;
import innovimax.mixthem.io.IOutputChar;
import innovimax.mixthem.io.InputResource;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;
/**
* <p>Abstract class for all character operation.</p>
* @see ICharOperation
* @author Innovimax
* @version 1.0
*/
public abstract class AbstractCharOperation extends AbstractOperation implements ICharOperation {
/**
* Constructor
* @param params The list of parameters (maybe empty)
* @see innovimax.mixthem.arguments.RuleParam
* @see innovimax.mixthem.arguments.ParamValue
*/
public AbstractCharOperation(final Map<RuleParam, ParamValue> params) {
super(params);
}
@Override
public void processFiles(final InputResource input1, final InputResource input2, final OutputStream out) throws MixException, IOException {
final IInputChar reader1 = new DefaultCharReader(input1);
final IInputChar reader2 = new DefaultCharReader(input2);
final IOutputChar writer = new DefaultCharWriter(out);
final CharResult result = new CharResult();
while (reader1.hasCharacter() || reader2.hasCharacter()) {
final int c1 = reader1.nextCharacter();
final int c2 = reader2.nextCharacter();
process(c1, c2, result);
if (result.hasResult()) {
result.getResult().forEach(c -> {
try {
writer.writeCharacter(c);
} catch (IOException e) {
throw new RuntimeException(e);
}
});
}
}
reader1.close();
reader2.close();
writer.close();
}
}
|
package innovimax.mixthem.operation;
import innovimax.mixthem.MixException;
import innovimax.mixthem.arguments.RuleParam;
import innovimax.mixthem.arguments.ParamValue;
import innovimax.mixthem.io.InputResource;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;
import java.util.List;
/**
* <p>Abstract class for all character operation.</p>
* @see ICopyOperation
* @author Innovimax
* @version 1.0
*/
public abstract class AbstractCopyOperation extends AbstractOperation implements ICopyOperation {
protected final static int BUFFER_SIZE = 1024;
private final CopyMode copyMode;
/**
* Constructor
* @param copyMode The copy mode to process
* @param params The list of parameters (maybe empty)
* @see innovimax.mixthem.arguments.RuleParam
* @see innovimax.mixthem.arguments.ParamValue
*/
public AbstractCopyOperation(final CopyMode copyMode, final Map<RuleParam, ParamValue> params) {
super(params);
this.copyMode = copyMode;
}
@Override
public void processFiles(final List<InputResource> inputs, final OutputStream output) throws MixException, IOException {
switch(copyMode) {
case FIRST:
process(inputs.get(0), output);
break;
case SECOND:
process(inputs.get(1), output);
break;
case UMPTEENTH:
int index = params.get(RuleParam.SEL_FILE).asInt();
process(inputs.get(index), output);
break;
case ALL:
default:
inputs.stream().forEach(input -> {
try {
process(input, output);
} catch (IOException e) {
throw new RuntimeException(e);
}
});
}
}
}
|
package com.codeup.auth.jdbc;
import com.codeup.auth.User;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static org.junit.Assert.*;
public class UsersMapperTest {
@Test
public void it_maps_correctly_a_user() {
UsersMapper mapper = new UsersMapper();
List<Object> values = new ArrayList<>();
values.addAll(Arrays.asList(7L, "luis", "changeme"));
User user = mapper.mapRow(values);
assertEquals(7L, user.id());
assertEquals("luis", user.username());
assertTrue("changeme".equals(user.password().toString()));
}
}
|
package io.github.teamdevintia.devathlon3.util;
import org.bukkit.Location;
import org.bukkit.entity.Entity;
import org.bukkit.util.Vector;
/**
* @author MiniDigger
*/
public class EntityUtil {
/**
* Pushes all entities in a certain radius away from one point
*
* @param center the center point
* @param range the range in which entities should be affected
* @param force the force that should be applied
*/
public static void pushAway(Location center, double range, double force) {
Vector centerV = center.toVector();
for (Entity entity : center.getWorld().getNearbyEntities(center, range, range, range)) {
Vector entityV = entity.getLocation().toVector();
Vector velocity = entityV.subtract(centerV).multiply(force);
velocity.setY(0.5);
entity.setVelocity(velocity);
}
}
}
|
package org.voltdb.messaging;
import java.io.IOException;
import java.nio.ByteBuffer;
import org.voltcore.messaging.TransactionInfoBaseMessage;
import org.voltdb.messaging.VoltDbMessageFactory;
/**
* Informs the initiators that the command log for this partition has reached
* the end. The SPI should release any MP txn for replay immediately when it
* sees the first fragment.
*/
public class Iv2EndOfLogMessage extends TransactionInfoBaseMessage
{
// true if this EOL message is from the MPI to the SPIs indicating the
// end of MP transactions
private boolean m_isMP = false;
public Iv2EndOfLogMessage() {
super();
}
public Iv2EndOfLogMessage(boolean isMP)
{
super(0l, 0l, 0l, 0l, false, true);
m_isMP = isMP;
}
public boolean isMP()
{
return m_isMP;
}
@Override
public boolean isSinglePartition() {
return true;
}
@Override
public int getSerializedSize() {
int msgsize = super.getSerializedSize();
msgsize += 1; // m_isMP
return msgsize;
}
@Override
public void initFromBuffer(ByteBuffer buf) throws IOException
{
super.initFromBuffer(buf);
m_isMP = buf.get() == 1;
}
@Override
public void flattenToBuffer(ByteBuffer buf) throws IOException
{
buf.put(VoltDbMessageFactory.IV2_EOL_ID);
super.flattenToBuffer(buf);
buf.put(m_isMP ? 1 : (byte) 0);
assert(buf.capacity() == buf.position());
buf.limit(buf.position());
}
@Override
public String toString() {
return "END OF COMMAND LOG FOR PARTITION, MP: " + m_isMP;
}
}
|
package it.unimib.disco.bimib.cyTRON.view;
import it.unimib.disco.bimib.cyTRON.R.RConnectionManager;
import it.unimib.disco.bimib.cyTRON.controller.StatisticsController;
import it.unimib.disco.bimib.cyTRON.model.Dataset;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JOptionPane;
import javax.swing.SwingWorker;
public class StatisticsPanel extends javax.swing.JPanel {
private static final long serialVersionUID = 2423195685394129580L;
private final StatisticsController statisticsController;
private final MainFrame mainFrame;
private final VisualizationPanel visualizationPanel;
private final DefaultComboBoxModel<String> statisticsDefaultComboBoxModel;
private final DefaultComboBoxModel<String> typessDefaultComboBoxModel;
public StatisticsPanel(MainFrame mainFrame, VisualizationPanel visualizationPanel) {
// get the main frame and the controllers
statisticsController = new StatisticsController();
this.mainFrame = mainFrame;
this.visualizationPanel = visualizationPanel;
// creates the models
statisticsDefaultComboBoxModel = new DefaultComboBoxModel<>(StatisticsController.STATISTICS);
typessDefaultComboBoxModel = new DefaultComboBoxModel<>(StatisticsController.TYPES);
// draw the interface
initComponents();
// update the default for the first statistics
statisticsComboBoxItemStateChanged(null);
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
infoPanel = new javax.swing.JPanel();
currentAlgorithmLabel = new javax.swing.JLabel();
currentAlgorithmValueLabel = new javax.swing.JLabel();
statisticsLabel = new javax.swing.JLabel();
statisticsComboBox = new javax.swing.JComboBox<>();
runButton = new javax.swing.JButton();
jPanel1 = new javax.swing.JPanel();
typeLabel = new javax.swing.JLabel();
typeComboBox = new javax.swing.JComboBox<>();
bootstrapSamplingsLabel = new javax.swing.JLabel();
bootstrapSamplingsSpinner = new javax.swing.JSpinner();
coresRatioLabel = new javax.swing.JLabel();
coresRatioSpinner = new javax.swing.JSpinner();
runsLabel = new javax.swing.JLabel();
runsSpinner = new javax.swing.JSpinner();
groupsLabel = new javax.swing.JLabel();
groupsSpinner = new javax.swing.JSpinner();
setMaximumSize(new java.awt.Dimension(940, 660));
setMinimumSize(new java.awt.Dimension(940, 660));
setPreferredSize(new java.awt.Dimension(940, 660));
infoPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Info"));
infoPanel.setPreferredSize(new java.awt.Dimension(928, 46));
currentAlgorithmLabel.setText("Current algorithm:");
javax.swing.GroupLayout infoPanelLayout = new javax.swing.GroupLayout(infoPanel);
infoPanel.setLayout(infoPanelLayout);
infoPanelLayout.setHorizontalGroup(
infoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(infoPanelLayout.createSequentialGroup()
.addContainerGap()
.addComponent(currentAlgorithmLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(currentAlgorithmValueLabel)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
infoPanelLayout.setVerticalGroup(
infoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(infoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(currentAlgorithmLabel)
.addComponent(currentAlgorithmValueLabel))
);
statisticsLabel.setText("Statistics:");
statisticsComboBox.setModel(statisticsDefaultComboBoxModel);
statisticsComboBox.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
statisticsComboBoxItemStateChanged(evt);
}
});
runButton.setText("Run");
runButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
runButtonActionPerformed(evt);
}
});
jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Parameters"));
typeLabel.setText("Type:");
typeComboBox.setModel(typessDefaultComboBoxModel);
bootstrapSamplingsLabel.setText("Bootstrap samplings:");
bootstrapSamplingsSpinner.setModel(new javax.swing.SpinnerNumberModel(100, 5, 10000, 1));
coresRatioLabel.setText("Cores ratio:");
coresRatioSpinner.setModel(new javax.swing.SpinnerNumberModel(Float.valueOf(1.0f), Float.valueOf(0.0f), Float.valueOf(1.0f), Float.valueOf(0.1f)));
runsLabel.setText("Runs:");
runsLabel.setToolTipText("");
runsSpinner.setModel(new javax.swing.SpinnerNumberModel(10, 1, 1000, 1));
groupsLabel.setText("Groups:");
groupsSpinner.setModel(new javax.swing.SpinnerNumberModel(10, 1, 1000, 1));
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(343, 343, 343)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(typeLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(typeComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(bootstrapSamplingsLabel)
.addComponent(coresRatioLabel))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(bootstrapSamplingsSpinner, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(coresRatioSpinner, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(runsLabel)
.addComponent(groupsLabel))
.addGap(102, 102, 102)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(runsSpinner, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(groupsSpinner, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(161, 161, 161)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(typeLabel)
.addComponent(typeComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(bootstrapSamplingsLabel)
.addComponent(bootstrapSamplingsSpinner, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(coresRatioLabel)
.addComponent(coresRatioSpinner, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(runsLabel)
.addComponent(runsSpinner, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(groupsLabel)
.addComponent(groupsSpinner, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(173, Short.MAX_VALUE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(infoPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addGap(6, 6, 6)
.addComponent(statisticsLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(statisticsComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 727, Short.MAX_VALUE)
.addComponent(runButton)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(infoPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(statisticsLabel)
.addComponent(statisticsComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(runButton))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
}// </editor-fold>//GEN-END:initComponents
private void statisticsComboBoxItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_statisticsComboBoxItemStateChanged
if (evt == null || evt.getStateChange() == java.awt.event.ItemEvent.SELECTED) {
// get the selected algorithm
Object statistics = statisticsComboBox.getSelectedItem();
// enable/disable inputs
if (statistics.equals(StatisticsController.BOOTSTRAP)) {
typeComboBox.setEnabled(true);
bootstrapSamplingsSpinner.setEnabled(true);
coresRatioSpinner.setEnabled(true);
runsSpinner.setEnabled(false);
groupsSpinner.setEnabled(false);
} else if (statistics.equals(StatisticsController.ELOSS)) {
typeComboBox.setEnabled(false);
bootstrapSamplingsSpinner.setEnabled(false);
coresRatioSpinner.setEnabled(false);
runsSpinner.setEnabled(true);
groupsSpinner.setEnabled(true);
} else if (statistics.equals(StatisticsController.POSTERR) || statistics.equals(StatisticsController.PREDERR)) {
typeComboBox.setEnabled(false);
bootstrapSamplingsSpinner.setEnabled(false);
coresRatioSpinner.setEnabled(true);
runsSpinner.setEnabled(true);
groupsSpinner.setEnabled(true);
}
}
}//GEN-LAST:event_statisticsComboBoxItemStateChanged
private void runButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_runButtonActionPerformed
// get the dataset
Dataset dataset = mainFrame.getSelectedDataset();
// check if a dataset is not selected
if (dataset == null || dataset.getInference().getAlgorithm().equals("")) {
// show the warning message
JOptionPane.showConfirmDialog(this, "A model has to be inferred before assessing statistics.", "Model required", JOptionPane.PLAIN_MESSAGE);
// return
return;
}
// get the confirmation
int confirmation = JOptionPane.showConfirmDialog(this, "This operation could take a while.\nRemember to save the datasets you might reuse.\nDo you want to proceed?", "", JOptionPane.OK_CANCEL_OPTION);
// if confirmed
if (confirmation == JOptionPane.OK_OPTION) {
// get the selected statistics
Object statistics = statisticsComboBox.getSelectedItem();
// get the input for all statistics
String type = (String) typeComboBox.getSelectedItem();
Integer bootstrapSamplings = (Integer) bootstrapSamplingsSpinner.getValue();
Float coresRatio = (Float) coresRatioSpinner.getValue();
Integer runs = (Integer) runsSpinner.getValue();
Integer groups = (Integer) groupsSpinner.getValue();
// get the statistics
StatisticsAlgorithm statisticsAlgorithm = new StatisticsAlgorithm(dataset, statisticsController, statistics, type, bootstrapSamplings, coresRatio, runs, groups);
statisticsAlgorithm.execute();
// show the option pane for exiting the algorithm
JOptionPane.showOptionDialog(this, "Exit this window to kill the algorithm.", "", JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, null, new Object[]{}, null);
// cancel the thread and stop the current R command if the statistics is not completed
if (!statisticsAlgorithm.isDone()) {
statisticsAlgorithm.cancel();
// if the algorithm is not cancelled and the last message is not regular
} else if (!statisticsAlgorithm.isCancelled() && !RConnectionManager.getTextConsole().isLastMessageRegular()) {
// show an error message
JOptionPane.showConfirmDialog(this, RConnectionManager.getTextConsole().getLastConsoleMessage(), RConnectionManager.ERROR, JOptionPane.PLAIN_MESSAGE);
}
visualizationPanel.updateStatisticsList(dataset);
}
}//GEN-LAST:event_runButtonActionPerformed
public void updateSelectedDataset() {
// get the selected dataset
Dataset dataset = mainFrame.getSelectedDataset();
// update the current inference algorithm label
currentAlgorithmValueLabel.setText(dataset.getInference().getAlgorithm());
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel bootstrapSamplingsLabel;
private javax.swing.JSpinner bootstrapSamplingsSpinner;
private javax.swing.JLabel coresRatioLabel;
private javax.swing.JSpinner coresRatioSpinner;
private javax.swing.JLabel currentAlgorithmLabel;
private javax.swing.JLabel currentAlgorithmValueLabel;
private javax.swing.JLabel groupsLabel;
private javax.swing.JSpinner groupsSpinner;
private javax.swing.JPanel infoPanel;
private javax.swing.JPanel jPanel1;
private javax.swing.JButton runButton;
private javax.swing.JLabel runsLabel;
private javax.swing.JSpinner runsSpinner;
private javax.swing.JComboBox<String> statisticsComboBox;
private javax.swing.JLabel statisticsLabel;
private javax.swing.JComboBox<String> typeComboBox;
private javax.swing.JLabel typeLabel;
// End of variables declaration//GEN-END:variables
private class StatisticsAlgorithm extends SwingWorker<Void, Void> {
private final Dataset dataset;
private final StatisticsController statisticsController;
private final Object statistics;
private final String type;
private final Integer bootstrapSamplings;
private final Float coresRatio;
private final Integer runs;
private final Integer groups;
public StatisticsAlgorithm(Dataset dataset, StatisticsController statisticsController,
Object statistics, String type, Integer bootstrapSamplings, Float coresRatio, Integer runs,
Integer groups) {
this.dataset = dataset;
this.statisticsController = statisticsController;
this.statistics = statistics;
this.type = type;
this.bootstrapSamplings = bootstrapSamplings;
this.coresRatio = coresRatio;
this.runs = runs;
this.groups = groups;
}
@Override
protected Void doInBackground() {
statisticsController.statistics(dataset, statistics, type, bootstrapSamplings, coresRatio, runs, groups);
return null;
}
@Override
protected void done() {
super.done();
// close the option panel
MainFrame.disposeJOptionPanes();
}
public void cancel() {
// cancel the thread and stop the current R command
RConnectionManager.getConnection().rniStop(0);
super.cancel(true);
}
}
}
|
package com.google.refine;
import java.awt.Desktop;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.BindException;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import org.apache.log4j.Level;
import org.mortbay.jetty.Connector;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.bio.SocketConnector;
import org.mortbay.jetty.servlet.ServletHolder;
import org.mortbay.jetty.webapp.WebAppContext;
import org.mortbay.util.Scanner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.codeberry.jdatapath.DataPath;
import com.codeberry.jdatapath.JDataPathSystem;
import com.google.util.threads.ThreadPoolExecutorAdapter;
/**
* Main class for Refine server application. Starts an instance of the
* Jetty HTTP server / servlet container (inner class Refine Server).
*/
public class Refine {
static private final String DEFAULT_HOST = "127.0.0.1";
static private final int DEFAULT_PORT = 3333;
static private int port;
static private String host;
final static Logger logger = LoggerFactory.getLogger("refine");
public static void main(String[] args) throws Exception {
// tell jetty to use SLF4J for logging instead of its own stuff
System.setProperty("VERBOSE","false");
System.setProperty("org.mortbay.log.class","org.mortbay.log.Slf4jLog");
// tell macosx to keep the menu associated with the screen and what the app title is
System.setProperty("apple.laf.useScreenMenuBar", "true");
System.setProperty("com.apple.eawt.CocoaComponent.CompatibilityMode", "false");
System.setProperty("com.apple.mrj.application.apple.menu.about.name", "OpenRefine");
// tell the signpost library to log
//System.setProperty("debug","true");
// set the log verbosity level
org.apache.log4j.Logger.getRootLogger().setLevel(Level.toLevel(Configurations.get("refine.verbosity","info")));
port = Configurations.getInteger("refine.port",DEFAULT_PORT);
host = Configurations.get("refine.host",DEFAULT_HOST);
Refine refine = new Refine();
refine.init(args);
}
public void init(String[] args) throws Exception {
RefineServer server = new RefineServer();
server.init(host,port);
boolean headless = Configurations.getBoolean("refine.headless",false);
if (headless) {
System.setProperty("java.awt.headless", "true");
logger.info("Running in headless mode");
} else {
try {
RefineClient client = new RefineClient();
client.init(host,port);
} catch (Exception e) {
logger.warn("Sorry, some error prevented us from launching the browser for you.\n\n Point your browser to http://" + host + ":" + port + "/ to start using Refine.");
}
}
// hook up the signal handlers
Runtime.getRuntime().addShutdownHook(
new Thread(new ShutdownSignalHandler(server))
);
server.join();
}
}
class RefineServer extends Server {
final static Logger logger = LoggerFactory.getLogger("refine_server");
private ThreadPoolExecutor threadPool;
public void init(String host, int port) throws Exception {
logger.info("Starting Server bound to '" + host + ":" + port + "'");
String memory = Configurations.get("refine.memory");
if (memory != null) {
logger.info("refine.memory size: " + memory + " JVM Max heap: " + Runtime.getRuntime().maxMemory());
}
int maxThreads = Configurations.getInteger("refine.queue.size", 30);
int maxQueue = Configurations.getInteger("refine.queue.max_size", 300);
long keepAliveTime = Configurations.getInteger("refine.queue.idle_time", 60);
LinkedBlockingQueue<Runnable> queue = new LinkedBlockingQueue<Runnable>(maxQueue);
threadPool = new ThreadPoolExecutor(maxThreads, maxQueue, keepAliveTime, TimeUnit.SECONDS, queue);
this.setThreadPool(new ThreadPoolExecutorAdapter(threadPool));
Connector connector = new SocketConnector();
connector.setPort(port);
connector.setHost(host);
connector.setMaxIdleTime(Configurations.getInteger("refine.connection.max_idle_time",60000));
connector.setStatsOn(false);
this.addConnector(connector);
File webapp = new File(Configurations.get("refine.webapp","main/webapp"));
if (!isWebapp(webapp)) {
webapp = new File("main/webapp");
if (!isWebapp(webapp)) {
webapp = new File("webapp");
if (!isWebapp(webapp)) {
logger.warn("Warning: Failed to find web application at '" + webapp.getAbsolutePath() + "'");
System.exit(-1);
}
}
}
final String contextPath = Configurations.get("refine.context_path","/");
final int maxFormContentSize = Configurations.getInteger("refine.max_form_content_size", 1048576);
logger.info("Initializing context: '" + contextPath + "' from '" + webapp.getAbsolutePath() + "'");
WebAppContext context = new WebAppContext(webapp.getAbsolutePath(), contextPath);
context.setMaxFormContentSize(maxFormContentSize);
this.setHandler(context);
this.setStopAtShutdown(true);
this.setSendServerVersion(true);
// Enable context autoreloading
if (Configurations.getBoolean("refine.autoreload",false)) {
scanForUpdates(webapp, context);
}
// start the server
try {
this.start();
} catch (BindException e) {
logger.error("Failed to start server - is there another copy running already on this port/address?");
throw e;
}
configure(context);
}
@Override
protected void doStop() throws Exception {
try {
// shutdown our scheduled tasks first, if any
if (threadPool != null) {
threadPool.shutdown();
}
// then let the parent stop
super.doStop();
} catch (InterruptedException e) {
// ignore
}
}
static private boolean isWebapp(File dir) {
if (dir == null) {
return false;
}
if (!dir.exists() || !dir.canRead()) {
return false;
}
File webXml = new File(dir, "WEB-INF/web.xml");
return webXml.exists() && webXml.canRead();
}
static private void scanForUpdates(final File contextRoot, final WebAppContext context) {
List<File> scanList = new ArrayList<File>();
scanList.add(new File(contextRoot, "WEB-INF/web.xml"));
findFiles(".class", new File(contextRoot, "WEB-INF/classes"), scanList);
findFiles(".jar", new File(contextRoot, "WEB-INF/lib"), scanList);
logger.info("Starting autoreloading scanner... ");
Scanner scanner = new Scanner();
scanner.setScanInterval(Configurations.getInteger("refine.scanner.period",1));
scanner.setScanDirs(scanList);
scanner.setReportExistingFilesOnStartup(false);
scanner.addListener(new Scanner.BulkListener() {
@Override
public void filesChanged(@SuppressWarnings("rawtypes") List changedFiles) {
try {
logger.info("Stopping context: " + contextRoot.getAbsolutePath());
context.stop();
logger.info("Starting context: " + contextRoot.getAbsolutePath());
context.start();
configure(context);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
});
scanner.start();
}
static private void findFiles(final String extension, File baseDir, final Collection<File> found) {
baseDir.listFiles(new FileFilter() {
@Override
public boolean accept(File pathname) {
if (pathname.isDirectory()) {
findFiles(extension, pathname, found);
} else if (pathname.getName().endsWith(extension)) {
found.add(pathname);
}
return false;
}
});
}
// inject configuration parameters in the servlets
// NOTE: this is done *after* starting the server because jetty might override the init
// parameters if we set them in the webapp context upon reading the web.xml file
static private void configure(WebAppContext context) throws Exception {
ServletHolder servlet = context.getServletHandler().getServlet("refine");
if (servlet != null) {
servlet.setInitParameter("refine.data", getDataDir());
servlet.setInitParameter("butterfly.modules.path", getDataDir() + "/extensions");
servlet.setInitOrder(1);
servlet.doStart();
}
servlet = context.getServletHandler().getServlet("refine-broker");
if (servlet != null) {
servlet.setInitParameter("refine.data", getDataDir() + "/broker");
servlet.setInitParameter("refine.development", Configurations.get("refine.development","false"));
servlet.setInitOrder(1);
servlet.doStart();
}
}
static private String getDataDir() {
String data_dir = Configurations.get("refine.data_dir");
if (data_dir != null) {
return data_dir;
}
File dataDir = null;
File grefineDir = null;
File gridworksDir = null;
String os = System.getProperty("os.name").toLowerCase();
if (os.contains("windows")) {
try {
// NOTE(SM): finding the "local data app" in windows from java is actually a PITA
// so we're using a library that uses JNI to ask directly the win32 APIs,
// it's not elegant but it's the safest bet.
dataDir = new File(fixWindowsUnicodePath(JDataPathSystem.getLocalSystem()
.getLocalDataPath("OpenRefine").getPath()));
DataPath localDataPath = JDataPathSystem.getLocalSystem().getLocalDataPath("Google");
// new: ./Google/Refine old: ./Gridworks
grefineDir = new File(new File(fixWindowsUnicodePath(localDataPath.getPath())), "Refine");
gridworksDir = new File(fixWindowsUnicodePath(JDataPathSystem.getLocalSystem()
.getLocalDataPath("Gridworks").getPath()));
} catch (Error e) {
/*
* The above trick can fail, particularly on a 64-bit OS as the jdatapath.dll
* we include is compiled for 32-bit. In this case, we just have to dig up
* environment variables and try our best to find a user-specific path.
*/
logger.warn("Failed to use jdatapath to detect user data path: resorting to environment variables");
File parentDir = null;
String appData = System.getenv("APPDATA");
if (appData != null && appData.length() > 0) {
// e.g., C:\Users\[userid]\AppData\Roaming
parentDir = new File(appData);
} else {
String userProfile = System.getenv("USERPROFILE");
if (userProfile != null && userProfile.length() > 0) {
// e.g., C:\Users\[userid]
parentDir = new File(userProfile);
}
}
if (parentDir == null) {
parentDir = new File(".");
}
dataDir = new File(parentDir, "OpenRefine");
grefineDir = new File(new File(parentDir, "Google"), "Refine");
gridworksDir = new File(parentDir, "Gridworks");
}
} else if (os.contains("mac os x")) {
// on macosx, use "~/Library/Application Support"
String home = System.getProperty("user.home");
String data_home = (home != null) ? home + "/Library/Application Support/OpenRefine" : ".openrefine";
dataDir = new File(data_home);
String grefine_home = (home != null) ? home + "/Library/Application Support/Google/Refine" : ".google-refine";
grefineDir = new File(grefine_home);
String gridworks_home = (home != null) ? home + "/Library/Application Support/Gridworks" : ".gridworks";
gridworksDir = new File(gridworks_home);
} else { // most likely a UNIX flavor
// start with the XDG environment
String data_home = System.getenv("XDG_DATA_HOME");
if (data_home == null) { // if not found, default back to ~/.local/share
String home = System.getProperty("user.home");
if (home == null) {
home = ".";
}
data_home = home + "/.local/share";
}
dataDir = new File(data_home + "/openrefine");
grefineDir = new File(data_home + "/google/refine");
gridworksDir = new File(data_home + "/gridworks");
}
// If refine data dir doesn't exist, try to find and move Google Refine or Gridworks data dir over
if (!dataDir.exists()) {
if (grefineDir.exists()) {
if (gridworksDir.exists()) {
logger.warn("Found both Gridworks: " + gridworksDir
+ " & Googld Refine dirs " + grefineDir) ;
}
if (grefineDir.renameTo(dataDir)) {
logger.info("Renamed Google Refine directory " + grefineDir
+ " to " + dataDir);
} else {
logger.error("FAILED to rename Google Refine directory "
+ grefineDir
+ " to " + dataDir);
}
} else if (gridworksDir.exists()) {
if (gridworksDir.renameTo(dataDir)) {
logger.info("Renamed Gridworks directory " + gridworksDir
+ " to " + dataDir);
} else {
logger.error("FAILED to rename Gridworks directory "
+ gridworksDir
+ " to " + dataDir);
}
}
}
// Either rename failed or nothing to rename - create a new one
if (!dataDir.exists()) {
logger.info("Creating new workspace directory " + dataDir);
if (!dataDir.mkdirs()) {
logger.error("FAILED to create new workspace directory " + dataDir);
}
}
return dataDir.getAbsolutePath();
}
/**
* For Windows file paths that contain user IDs with non ASCII characters,
* those characters might get replaced with ?. We need to use the environment
* APPDATA value to substitute back the original user ID.
*/
static private String fixWindowsUnicodePath(String path) {
int q = path.indexOf('?');
if (q < 0) {
return path;
}
int pathSep = path.indexOf(File.separatorChar, q);
String goodPath = System.getenv("APPDATA");
if (goodPath == null || goodPath.length() == 0) {
goodPath = System.getenv("USERPROFILE");
if (!goodPath.endsWith(File.separator)) {
goodPath = goodPath + File.separator;
}
}
int goodPathSep = goodPath.indexOf(File.separatorChar, q);
return path.substring(0, q) + goodPath.substring(q, goodPathSep) + path.substring(pathSep);
}
}
class RefineClient extends JFrame implements ActionListener {
private static final long serialVersionUID = 7886547342175227132L;
final static Logger logger = LoggerFactory.getLogger("refine-client");
private URI uri;
public void init(String host, int port) throws Exception {
uri = new URI("http://" + host + ":" + port + "/");
openBrowser();
}
@Override
public void actionPerformed(ActionEvent e) {
String item = e.getActionCommand();
if (item.startsWith("Open")) {
openBrowser();
}
}
private void openBrowser() {
if (!Desktop.isDesktopSupported()) {
logger.warn("Java Desktop class not supported on this platform. Please open %s in your browser",uri.toString());
}
try {
Desktop.getDesktop().browse(uri);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
class ShutdownSignalHandler implements Runnable {
private Server _server;
public ShutdownSignalHandler(Server server) {
this._server = server;
}
@Override
public void run() {
// Tell the server we want to try and shutdown gracefully
// this means that the server will stop accepting new connections
// right away but it will continue to process the ones that
// are in execution for the given timeout before attempting to stop
// NOTE: this is *not* a blocking method, it just sets a parameter
// that _server.stop() will rely on
_server.setGracefulShutdown(3000);
try {
_server.stop();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
}
|
package ml.duncte123.skybot.listeners;
import ml.duncte123.skybot.objects.command.Command;
import ml.duncte123.skybot.objects.guild.GuildSettings;
import ml.duncte123.skybot.utils.CustomCommandUtils;
import ml.duncte123.skybot.utils.GuildSettingsUtils;
import ml.duncte123.skybot.utils.GuildUtils;
import net.dv8tion.jda.bot.sharding.ShardManager;
import net.dv8tion.jda.core.Permission;
import net.dv8tion.jda.core.entities.*;
import net.dv8tion.jda.core.events.guild.member.*;
import org.jetbrains.annotations.NotNull;
import java.util.List;
import java.util.stream.Collectors;
import static me.duncte123.botcommons.messaging.MessageUtils.sendMsg;
public class GuildMemberListener extends BaseListener {
@Override
public void onGuildMemberJoin(GuildMemberJoinEvent event) {
final Guild guild = event.getGuild();
if (event.getMember().equals(guild.getSelfMember())) {
return;
}
final GuildSettings settings = GuildSettingsUtils.getGuild(guild, variables);
if (settings.isEnableJoinMessage() && settings.getWelcomeLeaveChannel() > 0) {
final long welcomeLeaveChannelId = settings.getWelcomeLeaveChannel();
final TextChannel welcomeLeaveChannel = guild.getTextChannelById(welcomeLeaveChannelId);
final String msg = parseGuildVars(settings.getCustomJoinMessage(), event);
if (!msg.isEmpty() && !"".equals(msg.trim()) && welcomeLeaveChannel != null) {
sendMsg(welcomeLeaveChannel, msg);
}
}
if (settings.isAutoroleEnabled() && guild.getSelfMember().hasPermission(Permission.MANAGE_ROLES)) {
final Role r = guild.getRoleById(settings.getAutoroleRole());
if (r != null && !guild.getPublicRole().equals(r) && guild.getSelfMember().canInteract(r)) {
guild.getController()
.addSingleRoleToMember(event.getMember(), r).queue(null, it -> {
});
}
}
}
@Override
public void onGuildMemberLeave(GuildMemberLeaveEvent event) {
final Guild guild = event.getGuild();
if (event.getMember().equals(guild.getSelfMember())) {
return;
}
final GuildSettings settings = GuildSettingsUtils.getGuild(guild, variables);
if (settings.isEnableJoinMessage() && settings.getWelcomeLeaveChannel() > 0) {
final long welcomeLeaveChannelId = settings.getWelcomeLeaveChannel();
final TextChannel welcomeLeaveChannel = guild.getTextChannelById(welcomeLeaveChannelId);
final String msg = parseGuildVars(settings.getCustomLeaveMessage(), event);
if (!msg.isEmpty() && !"".equals(msg.trim()) && welcomeLeaveChannel != null) {
sendMsg(welcomeLeaveChannel, msg);
}
}
if (guild.getIdLong() == Command.supportGuildId) {
handlePatronRemoval(event.getUser().getIdLong(), event.getJDA().asBot().getShardManager());
}
}
@Override
public void onGuildMemberRoleRemove(GuildMemberRoleRemoveEvent event) {
if (event.getGuild().getIdLong() != Command.supportGuildId) {
return;
}
for (final Role role : event.getRoles()) {
final long roleId = role.getIdLong();
if (roleId != Command.patronsRole && roleId != Command.guildPatronsRole && roleId != Command.oneGuildPatronsRole) {
continue;
}
handlePatronRemoval(event.getUser().getIdLong(), event.getJDA().asBot().getShardManager());
}
}
@Override
public void onGuildMemberRoleAdd(GuildMemberRoleAddEvent event) {
if (event.getGuild().getIdLong() != Command.supportGuildId) {
return;
}
final User user = event.getUser();
final long userId = user.getIdLong();
final ShardManager manager = event.getJDA().asBot().getShardManager();
for (final Role role : event.getRoles()) {
final long roleId = role.getIdLong();
if (roleId == Command.patronsRole) {
Command.patrons.add(userId);
}
if (roleId == Command.guildPatronsRole) {
final List<Long> guilds = manager.getMutualGuilds(user).stream()
.filter((it) -> {
Member member = it.getMember(user);
return it.getOwner().equals(member) || member.hasPermission(Permission.ADMINISTRATOR);
})
.map(Guild::getIdLong)
.collect(Collectors.toList());
Command.guildPatrons.addAll(guilds);
}
if (roleId == Command.oneGuildPatronsRole) {
handleNewOneGuildPatron(userId);
}
}
}
@NotNull
private String parseGuildVars(String rawMessage, GenericGuildMemberEvent event) {
if (!(event instanceof GuildMemberJoinEvent) && !(event instanceof GuildMemberLeaveEvent)) {
return "NOPE";
}
if ("".equals(rawMessage.trim().toLowerCase())) {
return "";
}
final Guild guild = event.getGuild();
final GuildSettings s = GuildSettingsUtils.getGuild(guild, variables);
final long welcomeLeaveChannel = s.getWelcomeLeaveChannel();
final String message = CustomCommandUtils.PARSER.clear()
.put("user", event.getUser())
.put("guild", event.getGuild())
.put("channel", event.getGuild().getTextChannelById(welcomeLeaveChannel))
.put("args", "")
.parse(rawMessage);
return message.replaceAll("\\{\\{USER_MENTION}}", event.getUser().getAsMention())
.replaceAll("\\{\\{USER_NAME}}", event.getUser().getName())
.replaceAll("\\{\\{USER_FULL}}", event.getUser().getAsTag())
.replaceAll("\\{\\{IS_USER_BOT}}", String.valueOf(event.getUser().isBot()))
.replaceAll("\\{\\{GUILD_NAME}}", guild.getName())
.replaceAll("\\{\\{GUILD_USER_COUNT}}", guild.getMemberCache().size() + "")
.replaceAll("\\{\\{EVENT_TYPE}}", event instanceof GuildMemberJoinEvent ? "joined" : "left");
}
private void handlePatronRemoval(long userId, ShardManager manager) {
// Remove the user from the patrons list
Command.patrons.remove(userId);
if (Command.oneGuildPatrons.containsKey(userId)) {
// Remove the user from the one guild patrons
Command.oneGuildPatrons.remove(userId);
GuildUtils.removeOneGuildPatron(userId, variables.getDatabaseAdapter());
}
final User user = manager.getUserById(userId);
if (user != null) {
manager.getMutualGuilds(user).forEach(
(guild) -> Command.guildPatrons.remove(guild.getIdLong())
);
}
}
private void handleNewOneGuildPatron(long userId) {
variables.getDatabaseAdapter().getOneGuildPatron(userId,
(results) -> {
results.forEachEntry(
(a, guildId) -> {
Command.oneGuildPatrons.put(userId, guildId);
return true;
}
);
return null;
}
);
}
}
|
package ml.duncte123.skybot.utils;
import ml.duncte123.skybot.Author;
import ml.duncte123.skybot.Authors;
import net.dv8tion.jda.core.MessageBuilder;
import net.dv8tion.jda.core.Permission;
import net.dv8tion.jda.core.entities.ChannelType;
import net.dv8tion.jda.core.entities.Message;
import net.dv8tion.jda.core.entities.TextChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static me.duncte123.botcommons.messaging.EmbedUtils.defaultEmbed;
@SuppressWarnings({"unused"})
@Authors(authors = {
@Author(nickname = "Sanduhr32", author = "Maurice R S"),
@Author(nickname = "duncte123", author = "Duncan Sterken")
})
public class JSONMessageErrorsHelper {
private static Logger logger = LoggerFactory.getLogger(JSONMessageErrorsHelper.class);
public static void sendErrorJSON(Message message, Throwable error, final boolean print) {
if (print) {
logger.error(error.getLocalizedMessage(), error);
}
//Makes no difference if we use sendError or check here both perm types
if (message.getChannelType() == ChannelType.TEXT) {
final TextChannel channel = message.getTextChannel();
if (!channel.getGuild().getSelfMember().hasPermission(channel, Permission.MESSAGE_READ,
Permission.MESSAGE_WRITE, Permission.MESSAGE_ATTACH_FILES, Permission.MESSAGE_ADD_REACTION)) {
return;
}
}
message.addReaction("").queue(null, (ignored) -> {});
message.getChannel().sendFile(EarthUtils.throwableToJSONObject(error).toString(4).getBytes(), "error.json",
new MessageBuilder().setEmbed(defaultEmbed().setTitle("We got an error!").setDescription(String.format("Error type: %s",
error.getClass().getSimpleName())).build()).build()
).queue();
}
}
|
package net.atos.entng.rbs.controllers;
import static net.atos.entng.rbs.Rbs.RBS_NAME;
import static org.entcore.common.http.response.DefaultResponseHandler.arrayResponseHandler;
import static org.entcore.common.http.response.DefaultResponseHandler.notEmptyResponseHandler;
import static org.entcore.common.http.response.DefaultResponseHandler.defaultResponseHandler;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import fr.wseduc.webutils.I18n;
import net.atos.entng.rbs.Rbs;
import net.atos.entng.rbs.core.constants.Actions;
import net.atos.entng.rbs.core.constants.Field;
import net.atos.entng.rbs.filters.TypeAndResourceAppendPolicy;
import net.atos.entng.rbs.filters.TypeOwnerSharedOrLocalAdmin;
import net.atos.entng.rbs.service.ResourceService;
import net.atos.entng.rbs.service.ResourceServiceSqlImpl;
import org.entcore.common.controller.ControllerHelper;
import org.entcore.common.events.EventHelper;
import org.entcore.common.events.EventStore;
import org.entcore.common.events.EventStoreFactory;
import org.entcore.common.http.filter.ResourceFilter;
import org.entcore.common.http.filter.Trace;
import org.entcore.common.user.UserInfos;
import org.entcore.common.user.UserUtils;
import io.vertx.core.Handler;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import fr.wseduc.rs.ApiDoc;
import fr.wseduc.rs.Delete;
import fr.wseduc.rs.Get;
import fr.wseduc.rs.Post;
import fr.wseduc.rs.Put;
import fr.wseduc.security.ActionType;
import fr.wseduc.security.SecuredAction;
import fr.wseduc.webutils.Either;
import fr.wseduc.webutils.http.Renders;
import fr.wseduc.webutils.request.RequestUtils;
public class ResourceController extends ControllerHelper {
static final String RESOURCE_NAME = "resource";
private static final String RESOURCE_AVAILABLE_EVENT_TYPE = RBS_NAME + "_RESOURCE_AVAILABLE";
private static final String RESOURCE_UNAVAILABLE_EVENT_TYPE = RBS_NAME + "_RESOURCE_UNAVAILABLE";
private static final String SCHEMA_RESOURCE_CREATE = "createResource";
private static final String SCHEMA_RESOURCE_UPDATE = "updateResource";
private final ResourceService resourceService;
private final EventHelper eventHelper;
public ResourceController() {
resourceService = new ResourceServiceSqlImpl();
final EventStore eventStore = EventStoreFactory.getFactory().getEventStore(Rbs.class.getSimpleName());
this.eventHelper = new EventHelper(eventStore);
}
// TODO : refactor ResourceController to use resourceService instead of crudService
private JsonObject getPushNotification(HttpServerRequest request, String notificationName,
String resourceName) {
JsonObject notification = new JsonObject()
.put("title", "rbs.push.notif." + notificationName);
String body = I18n.getInstance().translate(
"rbs.push.notif." + notificationName + ".body",
getHost(request),
I18n.acceptLanguage(request),
resourceName);
notification.put("body", body);
return notification;
}
@Override
@Get("/resources")
@ApiDoc("List all resources visible by current user")
@SecuredAction("rbs.resource.list")
public void list(final HttpServerRequest request) {
UserUtils.getUserInfos(eb, request, new Handler<UserInfos>() {
@Override
public void handle(final UserInfos user) {
if (user != null) {
String typeId = request.params().get(Field.TYPEID);
final List<String> groupsAndUserIds = (typeId == null) ? new ArrayList<>() : null;
if (groupsAndUserIds != null) {
groupsAndUserIds.add(user.getUserId());
if (user.getGroupsIds() != null) {
groupsAndUserIds.addAll(user.getGroupsIds());
}
}
resourceService.listResources(groupsAndUserIds, user, typeId, arrayResponseHandler(request));
}
else {
log.debug("User not found in session.");
unauthorized(request);
}
}
});
}
@Get("/resource/:id")
@ApiDoc("Get resource")
@ResourceFilter(TypeAndResourceAppendPolicy.class)
@SecuredAction(value = "rbs.read", type = ActionType.RESOURCE)
public void get(final HttpServerRequest request) {
UserUtils.getUserInfos(eb, request, new Handler<UserInfos>() {
@Override
public void handle(final UserInfos user) {
String id = request.params().get("id");
crudService.retrieve(id, notEmptyResponseHandler(request));
}
});
}
@Override
@Post("/type/:id/resource") // Parameter "id" is the resourceTypeId
@ApiDoc("Create resource")
@ResourceFilter(TypeOwnerSharedOrLocalAdmin.class)
@SecuredAction(value = "rbs.manager", type = ActionType.RESOURCE)
@Trace(Actions.CREATE_RESOURCE)
public void create(final HttpServerRequest request) {
UserUtils.getUserInfos(eb, request, new Handler<UserInfos>() {
@Override
public void handle(final UserInfos user) {
if (user != null) {
RequestUtils.bodyToJson(request, pathPrefix + SCHEMA_RESOURCE_CREATE, new Handler<JsonObject>() {
@Override
public void handle(JsonObject resource) {
long minDelay = resource.getLong("min_delay", -1L);
long maxDelay = resource.getLong("max_delay", -1L);
if(minDelay > -1L && maxDelay > -1L && minDelay >= maxDelay) {
badRequest(request, "rbs.resource.bad.request.min_delay.greater.than.max_delay");
}
String resourceTypeId = request.params().get("id");
resource.put("type_id", resourceTypeId);
final Handler<Either<String, JsonObject>> handler = notEmptyResponseHandler(request);
resourceService.createResource(resource, user, eventHelper.onCreateResource(request, RESOURCE_NAME, handler));
}
});
} else {
log.debug("User not found in session.");
Renders.unauthorized(request);
}
}
});
}
@Override
@Put("/resource/:id")
@ApiDoc("Update resource")
@ResourceFilter(TypeAndResourceAppendPolicy.class)
@SecuredAction(value = "rbs.publish", type = ActionType.RESOURCE)
@Trace(Actions.UPDATE_RESOURCE)
public void update(final HttpServerRequest request) {
UserUtils.getUserInfos(eb, request, new Handler<UserInfos>() {
@Override
public void handle(final UserInfos user) {
if (user != null) {
RequestUtils.bodyToJson(request, pathPrefix + SCHEMA_RESOURCE_UPDATE, new Handler<JsonObject>() {
@Override
public void handle(JsonObject resource) {
String id = request.params().get("id");
final boolean isAvailable = resource.getBoolean("is_available");
final boolean wasAvailable = resource.getBoolean("was_available");
long minDelay = resource.getLong("min_delay", -1L);
long maxDelay = resource.getLong("max_delay", -1L);
if(minDelay > -1L && maxDelay > -1L && minDelay >= maxDelay) {
badRequest(request, "rbs.resource.bad.request.min_delay.greater.than.max_delay");
}
Handler<Either<String, JsonObject>> handler = new Handler<Either<String, JsonObject>>() {
@Override
public void handle(Either<String, JsonObject> event) {
if (event.isRight()) {
Renders.renderJson(request, event.right().getValue(), 200);
notifyResourceAvailability(request, user, event.right().getValue(),
isAvailable, wasAvailable);
} else {
JsonObject error = new JsonObject()
.put("error", event.left().getValue());
Renders.renderJson(request, error, 400);
}
}
};
resourceService.updateResource(id, resource, handler);
}
});
} else {
log.debug("User not found in session.");
Renders.unauthorized(request);
}
}
});
}
/**
* Notify booking owners that a resource is now (un)available
*/
private void notifyResourceAvailability(final HttpServerRequest request, final UserInfos user,
final JsonObject message, final boolean isAvailable, final boolean wasAvailable){
// Notify only if the availability has been changed
if(wasAvailable != isAvailable) {
final long resourceId = message.getLong("id", 0L);
final String resourceName = message.getString("name", null);
final String eventType;
final String notificationName;
if (isAvailable) {
eventType = RESOURCE_AVAILABLE_EVENT_TYPE;
notificationName = "resource-available";
}
else {
eventType = RESOURCE_UNAVAILABLE_EVENT_TYPE;
notificationName = "resource-unavailable";
}
if (resourceId == 0L || resourceName == null) {
log.error("Could not get resourceId or resourceName from response. Unable to send timeline "+ eventType + " notification.");
return;
}
resourceService.getBookingOwnersIds(resourceId, new Handler<Either<String, JsonArray>>() {
@Override
public void handle(Either<String, JsonArray> event) {
if (event.isRight()) {
Set<String> recipientSet = new HashSet<>();
for(Object o : event.right().getValue()){
if(!(o instanceof JsonObject)){
continue;
}
JsonObject jo = (JsonObject) o;
recipientSet.add(jo.getString("owner"));
}
if(!recipientSet.isEmpty()) {
List<String> recipients = new ArrayList<>(recipientSet);
JsonObject params = new JsonObject();
params.put("resource_name", resourceName);
params.put("pushNotif", getPushNotification(request, notificationName, resourceName));
notification.notifyTimeline(request, "rbs." + notificationName, user, recipients, String.valueOf(resourceId), params);
}
} else {
log.error("Error when calling service getBookingOwnersIds. Unable to send timeline "
+ eventType + " notification.");
}
}
});
resourceService.getUserNotification(resourceId, user, new Handler<Either<String, JsonArray>>() {
@Override
public void handle(Either<String, JsonArray> event) {
if (event.isRight()) {
Set<String> recipientSet = new HashSet<>();
for(Object o : event.right().getValue()){
if(!(o instanceof JsonObject)){
continue;
}
JsonObject jo = (JsonObject) o;
recipientSet.add(jo.getString("user_id"));
}
if(!recipientSet.isEmpty()) {
List<String> recipients = new ArrayList<>(recipientSet);
JsonObject params = new JsonObject();
params.put("resource_name", resourceName);
notification.notifyTimeline(request, "rbs." + notificationName, user, recipients, String.valueOf(resourceId), params);
}
} else {
log.error("Error when calling service getUserNotification. Unable to send timeline "
+ eventType + " notification.");
}
}
});
}
}
@Override
@Delete("/resource/:id")
@ApiDoc("Delete resource")
@ResourceFilter(TypeAndResourceAppendPolicy.class)
@SecuredAction(value = "rbs.manager", type = ActionType.RESOURCE)
@Trace(Actions.DELETE_RESOURCE)
public void delete(final HttpServerRequest request) {
UserUtils.getUserInfos(eb, request, new Handler<UserInfos>() {
@Override
public void handle(final UserInfos user) {
if (user != null) {
String id = request.params().get("id");
crudService.delete(id, user, defaultResponseHandler(request));
} else {
log.debug("User not found in session.");
Renders.unauthorized(request);
}
}
});
}
@Post("/resource/notification/add/:id")
@ApiDoc("Add notification")
@ResourceFilter(TypeAndResourceAppendPolicy.class)
@SecuredAction(value = "rbs.read", type = ActionType.RESOURCE)
@Trace(Actions.ADD_NOTIFICATION)
public void addNotification (final HttpServerRequest request){
UserUtils.getUserInfos(eb, request, new Handler<UserInfos>() {
@Override
public void handle(final UserInfos user) {
if (user != null) {
String id = request.params().get("id");
resourceService.addNotification (id, user, defaultResponseHandler(request));
} else {
log.debug("User not found in session.");
Renders.unauthorized(request);
}
}
});
}
@Delete("/resource/notification/remove/:id")
@ApiDoc("Remove notification")
@ResourceFilter(TypeAndResourceAppendPolicy.class)
@SecuredAction(value = "rbs.read", type = ActionType.RESOURCE)
@Trace(Actions.REMOVE_NOTIFICATION)
public void removeNotification (final HttpServerRequest request){
UserUtils.getUserInfos(eb, request, new Handler<UserInfos>() {
@Override
public void handle(final UserInfos user) {
if (user != null) {
String id = request.params().get("id");
resourceService.removeNotification (id, user, defaultResponseHandler(request));
} else {
log.debug("User not found in session.");
Renders.unauthorized(request);
}
}
});
}
@Get("/resource/notifications")
@ApiDoc("Get notification")
@SecuredAction(value = "", type = ActionType.AUTHENTICATED)
public void getNotifications (final HttpServerRequest request){
UserUtils.getUserInfos(eb, request, new Handler<UserInfos>() {
@Override
public void handle(final UserInfos user) {
if (user != null) {
resourceService.getNotifications (user, arrayResponseHandler(request));
} else {
log.debug("User not found in session.");
Renders.unauthorized(request);
}
}
});
}
@Get("/resource/share/json/:id")
@ApiDoc("List rights for a given resource")
@ResourceFilter(TypeAndResourceAppendPolicy.class)
@SecuredAction(value = "rbs.manager", type = ActionType.RESOURCE)
public void share(final HttpServerRequest request) {
super.shareJson(request, false);
}
@Put("/resource/share/json/:id")
@ApiDoc("Add rights for a given resource")
@ResourceFilter(TypeAndResourceAppendPolicy.class)
@SecuredAction(value = "rbs.manager", type = ActionType.RESOURCE)
@Trace(Actions.SHARE_RESOURCE_SUBMIT)
public void shareSubmit(final HttpServerRequest request) {
super.shareJsonSubmit(request, null, false);
}
@Put("/resource/share/remove/:id")
@ApiDoc("Remove rights for a given resource")
@ResourceFilter(TypeAndResourceAppendPolicy.class)
@SecuredAction(value = "rbs.manager", type = ActionType.RESOURCE)
@Trace(Actions.SHARE_RESOURCE_REMOVE)
public void shareRemove(final HttpServerRequest request) {
super.removeShare(request, false);
}
}
|
package net.hillsdon.reviki.jira.renderer;
import net.hillsdon.reviki.wiki.renderer.creole.LinkParts;
import net.hillsdon.reviki.wiki.renderer.creole.LinkResolutionContext;
import net.hillsdon.reviki.wiki.renderer.creole.SimpleLinkHandler;
public class JiraLinkHandler extends SimpleLinkHandler {
public JiraLinkHandler(String fmat, LinkResolutionContext context) {
super(fmat, context);
}
/**
* Allow all LinkParts to be links, non-JIRA issues have been filtered
* by JiraInternalLinker
*/
@Override
public boolean isAcronymNotLink(LinkParts parts) {
return false;
}
}
|
package net.nunnerycode.bukkit.mythicdrops.utils;
import net.nunnerycode.bukkit.mythicdrops.MythicDropsPlugin;
import net.nunnerycode.bukkit.mythicdrops.api.tiers.Tier;
import net.nunnerycode.bukkit.mythicdrops.tiers.TierMap;
import org.apache.commons.lang.math.RandomUtils;
import org.apache.commons.lang3.Validate;
import org.bukkit.ChatColor;
import org.bukkit.inventory.ItemStack;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
public final class TierUtil {
private TierUtil() {
// do nothing
}
public static Tier randomTier(Collection<Tier> collection) {
Validate.notNull(collection, "Collection<Tier> cannot be null");
Tier[] array = collection.toArray(new Tier[collection.size()]);
return array[RandomUtils.nextInt(array.length)];
}
public static Tier randomTierWithChance(Collection<Tier> values) {
Validate.notNull(values, "Collection<Tier> cannot be null");
double totalWeight = 0;
List<Tier> v = new ArrayList<>(values);
Collections.shuffle(v);
for (Tier t : v) {
totalWeight += t.getSpawnChance();
}
double chosenWeight = MythicDropsPlugin.getInstance().getRandom().nextDouble() * totalWeight;
double currentWeight = 0;
for (Tier t : v) {
currentWeight += t.getSpawnChance();
if (currentWeight >= chosenWeight) {
return t;
}
}
return null;
}
@Deprecated
public static Tier randomTierWithChance(Collection<Tier> values, String worldName) {
Validate.notNull(values, "Collection<Tier> cannot be null");
return randomTierWithChance(values);
}
public static Tier randomTierWithIdentifyChance(Collection<Tier> values) {
Validate.notNull(values, "Collection<Tier> cannot be null");
double totalWeight = 0;
List<Tier> v = new ArrayList<>(values);
Collections.shuffle(v);
for (Tier t : v) {
totalWeight += t.getIdentifyChance();
}
double chosenWeight = MythicDropsPlugin.getInstance().getRandom().nextDouble() * totalWeight;
double currentWeight = 0;
for (Tier t : v) {
currentWeight += t.getIdentifyChance();
if (currentWeight >= chosenWeight) {
return t;
}
}
return null;
}
@Deprecated
public static Tier randomTierWithIdentifyChance(Collection<Tier> values, String worldName) {
Validate.notNull(values, "Collection<Tier> cannot be null");
return randomTierWithIdentifyChance(values);
}
public static Collection<Tier> getTiersFromStrings(Collection<String> strings) {
Validate.notNull(strings, "Collection<String> cannot be null");
Set<Tier> tiers = new LinkedHashSet<>();
for (String s : strings) {
Tier t = getTier(s);
if (t != null) {
tiers.add(t);
}
}
return tiers;
}
public static Tier getTier(String name) {
Validate.notNull(name, "String cannot be null");
for (Tier t : TierMap.getInstance().values()) {
if (t.getName().equalsIgnoreCase(name)) {
return t;
}
if (t.getDisplayName().equalsIgnoreCase(name)) {
return t;
}
}
return null;
}
public static List<String> getStringsFromTiers(Collection<Tier> collection) {
Validate.notNull(collection, "Collection<Tier> cannot be null");
List<String> col = new ArrayList<>();
for (Tier t : collection) {
col.add(t.getName());
}
return col;
}
private static ChatColor findColor(final String s) {
char[] c = s.toCharArray();
for (int i = 0; i < c.length; i++) {
if (c[i] == (char) 167 && (i + 1) < c.length) {
return ChatColor.getByChar(c[i + 1]);
}
}
return null;
}
public static Tier getTierFromItemStack(ItemStack itemStack) {
return getTierFromItemStack(itemStack, TierMap.getInstance().values());
}
public static Tier getTierFromItemStack(ItemStack itemStack, Collection<Tier> tiers) {
Validate.notNull(itemStack);
Validate.notNull(tiers);
if (!itemStack.hasItemMeta()) {
return null;
}
if (!itemStack.getItemMeta().hasDisplayName()) {
return null;
}
String displayName = itemStack.getItemMeta().getDisplayName();
ChatColor initColor = findColor(displayName);
String colors = ChatColor.getLastColors(displayName);
ChatColor
endColor =
ChatColor.getLastColors(displayName).contains(String.valueOf(ChatColor.COLOR_CHAR)) ?
ChatColor.getByChar(colors.substring(1, 2)) : null;
if (initColor == null || endColor == null || initColor == endColor) {
return null;
}
for (Tier t : tiers) {
if (t.getDisplayColor() == initColor && t.getIdentificationColor() == endColor) {
return t;
}
}
return null;
}
public static Collection<Tier> skewTierCollectionToRarer(Collection<Tier> values,
int numberToKeep) {
Validate.notNull(values);
List<Tier> v = new ArrayList<>(values);
Collections.sort(v);
return v.subList(0, Math.abs(numberToKeep) <= v.size() ? Math.abs(numberToKeep) : v.size());
}
}
|
package nom.bdezonia.zorbage.type.algebra;
import nom.bdezonia.zorbage.procedure.Procedure3;
import nom.bdezonia.zorbage.procedure.Procedure4;
/**
*
* @author Barry DeZonia
*
* @param <U>
*/
public interface ModularDivision<U> {
Procedure3<U,U,U> div();
Procedure3<U,U,U> mod();
Procedure4<U,U,U,U> divMod();
// TODO add quot/rem/quotRem
// Maybe this is helpful:
// Also it might be best to copy Fortran's definition of div/mod/quot/rem. Investigate.
}
|
package org.voltdb;
import java.io.File;
import java.io.IOException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.junit.AfterClass;
import org.junit.Test;
import org.voltdb.VoltDB.Configuration;
import org.voltdb.client.Client;
import org.voltdb.client.ClientFactory;
import org.voltdb.client.NoConnectionsException;
import org.voltdb.client.ProcCallException;
import org.voltdb.compiler.VoltProjectBuilder;
import org.voltdb.regressionsuites.LocalCluster;
import org.voltdb.types.TimestampType;
import org.voltdb.utils.MiscUtils;
import org.voltdb.utils.VoltFile;
public class TestAdHocQueries extends AdHocQueryTester {
Client m_client;
private final static boolean m_debug = false;
@AfterClass
public static void tearDownClass()
{
try {
VoltFile.recursivelyDelete(new File("/tmp/" + System.getProperty("user.name")));
}
catch (IOException e) {};
}
@Test
public void testProcedureAdhoc() throws Exception {
VoltDB.Configuration config = setUpSPDB();
ServerThread localServer = new ServerThread(config);
try {
localServer.start();
localServer.waitForInitialization();
// do the test
m_client = ClientFactory.createClient();
m_client.createConnection("localhost", config.m_port);
m_client.callProcedure("@AdHoc", "insert into PARTED1 values ( 23, 3 )");
// Test that a basic multipartition select works as well as a parameterized
// query (it's in the procedure)
VoltTable results[] = m_client.callProcedure(
"executeSQLSP",
23,
"select * from PARTED1").getResults();
assertTrue(
results[0].advanceRow());
assertTrue(results[1].advanceRow());
results = m_client.callProcedure(
"executeSQLMP",
23,
" select * from PARTED1").getResults();
assertTrue(
results[0].advanceRow());
assertTrue(results[1].advanceRow());
// Validate that doing an insert from a RO procedure fails
try {
m_client.callProcedure("executeSQLSP", 24, "insert into parted1 values (24,5)");
fail("Procedure call should not have succeded");
} catch (ProcCallException e) {}
try {
m_client.callProcedure("executeSQLMP", 24, "insert into parted1 values (24,5)");
fail("Procedure call should not have succeded");
} catch (ProcCallException e) {}
// Validate one sql statement per
try {
m_client.callProcedure("executeSQLSP", 24, "insert into parted1 values (24,5); select * from parted1;");
fail("Procedure call should not have succeded");
} catch (ProcCallException e) {}
try {
m_client.callProcedure("executeSQLSP", 24, "drop table parted1");
fail("Procedure call should not have succeded");
} catch (ProcCallException e) {}
// Validate that an insert does work from a write procedure
m_client.callProcedure("executeSQLSPWRITE", 24, "insert into parted1 values (24, 4);");
m_client.callProcedure("executeSQLMPWRITE", 25, "insert into parted1 values (25, 5);");
// Query the inserts and all the rest do it once for singe and once for multi
results = m_client.callProcedure("executeSQLMP", 24, "select * from parted1 order by partval").getResults();
assertEquals( 3, results[0].getRowCount());
for (int ii = 3; ii < 6; ii++) {
assertTrue(results[0].advanceRow());
assertEquals(20 + ii, results[0].getLong(0));
assertEquals(ii, results[0].getLong(1));
}
//Output from the first preplanned statement
assertEquals( 3, results[1].getRowCount());
assertTrue(results[1].advanceRow());
assertEquals( 23, results[1].getLong(0));
assertEquals( 3, results[1].getLong(1));
//Output from the second adhoc statement
assertEquals( 1, results[2].getRowCount());
assertTrue(results[2].advanceRow());
assertEquals( 24, results[2].getLong(0));
assertEquals( 4, results[2].getLong(1));
//Output from the second preplanned statement
assertEquals( 3, results[3].getRowCount());
assertTrue(results[3].advanceRow());
assertEquals( 23, results[3].getLong(0));
assertEquals( 3, results[3].getLong(1));
if (TheHashinator.getConfiguredHashinatorType() == TheHashinator.HashinatorType.LEGACY) {
results = m_client.callProcedure("executeSQLSP", 24, "select * from parted1 order by partval").getResults();
for (int ii = 0; ii < 4; ii++) {
assertEquals( 1, results[ii].getRowCount());
assertTrue(results[ii].advanceRow());
assertEquals(24, results[ii].getLong(0));
assertEquals( 4, results[ii].getLong(1));
}
} else {
results = m_client.callProcedure("executeSQLSP", 23, "select * from parted1 order by partval").getResults();
for (int ii = 0; ii < 4; ii++) {
//The third statement does an exact equality match
if (ii == 2) {
assertEquals( 1, results[ii].getRowCount());
assertTrue(results[ii].advanceRow());
assertEquals(23, results[ii].getLong(0));
assertEquals( 3, results[ii].getLong(1));
continue;
}
assertEquals( 2, results[ii].getRowCount());
assertTrue(results[ii].advanceRow());
assertEquals(23, results[ii].getLong(0));
assertEquals( 3, results[ii].getLong(1));
assertTrue(results[ii].advanceRow());
assertEquals(25, results[ii].getLong(0));
assertEquals( 5, results[ii].getLong(1));
}
}
}
catch (Exception e) {
e.printStackTrace();
fail();
}
finally {
if (m_client != null) m_client.close();
m_client = null;
if (localServer != null) {
localServer.shutdown();
localServer.join();
}
localServer = null;
// no clue how helpful this is
System.gc();
}
}
@Test
public void testSP() throws Exception {
VoltDB.Configuration config = setUpSPDB();
ServerThread localServer = new ServerThread(config);
try {
localServer.start();
localServer.waitForInitialization();
// do the test
m_client = ClientFactory.createClient();
m_client.createConnection("localhost", config.m_port);
VoltTable modCount;
// Unlike TestAdHocPlans, TestAdHocQueries runs the queries against actual (minimal) data.
// Load that, here.
modCount = m_client.callProcedure("@AdHoc", "INSERT INTO PARTED1 VALUES (0, 0);").getResults()[0];
assertEquals(1, modCount.getRowCount());
assertEquals(1, modCount.asScalarLong());
modCount = m_client.callProcedure("@AdHoc", "INSERT INTO PARTED1 VALUES (1, 1);").getResults()[0];
assertEquals(1, modCount.getRowCount());
assertEquals(1, modCount.asScalarLong());
modCount = m_client.callProcedure("@AdHoc", "INSERT INTO PARTED2 VALUES (0, 0);").getResults()[0];
assertEquals(1, modCount.getRowCount());
assertEquals(1, modCount.asScalarLong());
modCount = m_client.callProcedure("@AdHoc", "INSERT INTO PARTED2 VALUES (2, 2);").getResults()[0];
assertEquals(1, modCount.getRowCount());
assertEquals(1, modCount.asScalarLong());
modCount = m_client.callProcedure("@AdHoc", "INSERT INTO PARTED3 VALUES (0, 0);").getResults()[0];
assertEquals(1, modCount.getRowCount());
assertEquals(1, modCount.asScalarLong());
modCount = m_client.callProcedure("@AdHoc", "INSERT INTO PARTED3 VALUES (3, 3);").getResults()[0];
assertEquals(1, modCount.getRowCount());
assertEquals(1, modCount.asScalarLong());
modCount = m_client.callProcedure("@AdHoc", "INSERT INTO REPPED1 VALUES (0, 0);").getResults()[0];
assertEquals(1, modCount.getRowCount());
assertEquals(1, modCount.asScalarLong());
modCount = m_client.callProcedure("@AdHoc", "INSERT INTO REPPED1 VALUES (1, 1);").getResults()[0];
assertEquals(1, modCount.getRowCount());
assertEquals(1, modCount.asScalarLong());
modCount = m_client.callProcedure("@AdHoc", "INSERT INTO REPPED2 VALUES (0, 0);").getResults()[0];
assertEquals(1, modCount.getRowCount());
assertEquals(1, modCount.asScalarLong());
modCount = m_client.callProcedure("@AdHoc", "INSERT INTO REPPED2 VALUES (2, 2);").getResults()[0];
assertEquals(1, modCount.getRowCount());
assertEquals(1, modCount.asScalarLong());
runAllAdHocSPtests();
}
finally {
if (m_client != null) m_client.close();
m_client = null;
if (localServer != null) {
localServer.shutdown();
localServer.join();
}
localServer = null;
// no clue how helpful this is
System.gc();
}
}
/**
* @param query
* @param hashable - used to pick a single partition for running the query
* @param spPartialSoFar - counts from prior SP queries to compensate for unpredictable hashing
* @param expected - expected value of MP query (and of SP query, adjusting by spPartialSoFar, and only if validatingSPresult).
* @param validatingSPresult - disables validation for non-deterministic SP results (so we don't have to second-guess the hashinator)
* @return
* @throws IOException
* @throws NoConnectionsException
* @throws ProcCallException
*/
@Override
public int runQueryTest(String query, int hashable, int spPartialSoFar, int expected, int validatingSPresult)
throws IOException, NoConnectionsException, ProcCallException {
VoltTable result;
result = m_client.callProcedure("@AdHoc", query).getResults()[0];
System.out.println(result.toString());
assertEquals(expected, result.getRowCount());
result = m_client.callProcedure("@AdHoc", query, hashable).getResults()[0];
int spResult = result.getRowCount();
System.out.println(result.toString());
if (validatingSPresult != 0) {
assertEquals(expected, spPartialSoFar + spResult);
}
return spResult;
}
String m_catalogJar = "adhoc.jar";
String m_pathToCatalog = Configuration.getPathToCatalogForTest(m_catalogJar);
String m_pathToDeployment = Configuration.getPathToCatalogForTest("adhoc.xml");
@Test
public void testSimple() throws Exception {
TestEnv env = new TestEnv(m_catalogJar, m_pathToDeployment, 2, 2, 1);
try {
env.setUp();
VoltTable modCount = env.m_client.callProcedure("@AdHoc", "INSERT INTO BLAH VALUES (1, 1, 1);").getResults()[0];
assertEquals(1, modCount.getRowCount());
assertEquals(1, modCount.asScalarLong());
VoltTable result = env.m_client.callProcedure("@AdHoc", "SELECT * FROM BLAH;").getResults()[0];
assertEquals(1, result.getRowCount());
System.out.println(result.toString());
// test single-partition stuff
result = env.m_client.callProcedure("@AdHoc", "SELECT * FROM BLAH;", TheHashinator.getConfiguredHashinatorType() == TheHashinator.HashinatorType.LEGACY ? 0 : 2).getResults()[0];
System.out.println(result.toString());
assertEquals(0, result.getRowCount());
result = env.m_client.callProcedure("@AdHoc", "SELECT * FROM BLAH;", TheHashinator.getConfiguredHashinatorType() == TheHashinator.HashinatorType.LEGACY ? 1 : 0).getResults()[0];
System.out.println(result.toString());
assertEquals(1, result.getRowCount());
try {
env.m_client.callProcedure("@AdHoc", "INSERT INTO BLAH VALUES (0, 0, 0);", 2);
fail("Badly partitioned insert failed to throw expected exception");
}
catch (Exception e) {}
try {
env.m_client.callProcedure("@AdHoc", "SLEECT * FROOM NEEEW_OOORDERERER;");
fail("Bad SQL failed to throw expected exception");
}
catch (Exception e) {}
// try a huge bigint literal
modCount = env.m_client.callProcedure("@AdHoc", "INSERT INTO BLAH VALUES (974599638818488300, '2011-06-24 10:30:26.123012', 5);").getResults()[0];
modCount = env.m_client.callProcedure("@AdHoc", "INSERT INTO BLAH VALUES (974599638818488301, '2011-06-24 10:30:28', 5);").getResults()[0];
assertEquals(1, modCount.getRowCount());
assertEquals(1, modCount.asScalarLong());
result = env.m_client.callProcedure("@AdHoc", "SELECT * FROM BLAH WHERE IVAL = 974599638818488300;").getResults()[0];
assertEquals(1, result.getRowCount());
System.out.println(result.toString());
result = env.m_client.callProcedure("@AdHoc", "SELECT * FROM BLAH WHERE TVAL = '2011-06-24 10:30:26.123012';").getResults()[0];
assertEquals(1, result.getRowCount());
System.out.println(result.toString());
result = env.m_client.callProcedure("@AdHoc", "SELECT * FROM BLAH WHERE TVAL > '2011-06-24 10:30:25';").getResults()[0];
assertEquals(2, result.getRowCount());
System.out.println(result.toString());
result = env.m_client.callProcedure("@AdHoc", "SELECT * FROM BLAH WHERE TVAL < '2011-06-24 10:30:27';").getResults()[0];
System.out.println(result.toString());
// We inserted a 1,1,1 row way earlier
assertEquals(2, result.getRowCount());
// try something like the queries in ENG-1242
try {
env.m_client.callProcedure("@AdHoc", "select * from blah; dfvsdfgvdf select * from blah WHERE IVAL = 1;");
fail("Bad SQL failed to throw expected exception");
}
catch (Exception e) {}
env.m_client.callProcedure("@AdHoc", "select\n* from blah;");
// try a decimal calculation (ENG-1093)
modCount = env.m_client.callProcedure("@AdHoc", "INSERT INTO BLAH VALUES (2, '2011-06-24 10:30:26', 1.12345*1);").getResults()[0];
assertEquals(1, modCount.getRowCount());
assertEquals(1, modCount.asScalarLong());
result = env.m_client.callProcedure("@AdHoc", "SELECT * FROM BLAH WHERE IVAL = 2;").getResults()[0];
assertEquals(1, result.getRowCount());
System.out.println(result.toString());
}
finally {
env.tearDown();
}
}
@Test
public void testAdHocBatches() throws Exception {
TestEnv env = new TestEnv(m_catalogJar, m_pathToDeployment, 2, 1, 0);
try {
env.setUp();
Batcher batcher = new Batcher(env);
// a few inserts (with a couple of ignored blank statements)
batcher.add("INSERT INTO BLAH VALUES (100, '2012-05-21 12:00:00.000000', 1000)", 1);
batcher.add("", null);
batcher.add("INSERT INTO BLAH VALUES (101, '2012-05-21 12:01:00.000000', 1001)", 1);
batcher.add("", null);
batcher.add("INSERT INTO BLAH VALUES (102, '2012-05-21 12:02:00.000000', 1002)", 1);
batcher.add("INSERT INTO BLAH VALUES (103, '2012-05-21 12:03:00.000000', 1003)", 1);
batcher.add("INSERT INTO BLAH VALUES (104, '2012-05-21 12:04:00.000000', 1004)", 1);
batcher.run();
// a few selects using data inserted by previous batch
batcher.add("SELECT * FROM BLAH WHERE IVAL = 102", 1);
batcher.add("SELECT * FROM BLAH WHERE DVAL >= 1001 AND DVAL <= 1002", 2);
batcher.add("SELECT * FROM BLAH WHERE DVAL >= 1002 AND DVAL <= 1004", 3);
batcher.run();
// mixed reads and writes (start from a clean slate)
batcher.addUnchecked("DELETE FROM BLAH");
batcher.run();
System.out.println("Running problem batch");
batcher.add("INSERT INTO BLAH VALUES (100, '2012-05-21 12:00:00.000000', 1000)", 1);
batcher.add("INSERT INTO BLAH VALUES (101, '2012-05-21 12:00:00.000000', 1001)", 1);
batcher.add("INSERT INTO BLAH VALUES (102, '2012-05-21 12:00:00.000000', 1002)", 1);
batcher.add("DELETE FROM BLAH WHERE IVAL = 100", 1);
batcher.add("SELECT * FROM BLAH", 2);
batcher.add("DELETE FROM BLAH WHERE IVAL = 101", 1);
batcher.add("SELECT * FROM BLAH WHERE IVAL = 101", 0);
batcher.add("UPDATE BLAH SET DVAL = 0 WHERE IVAL = 102", 1);
batcher.run();
// mix replicated and partitioned
batcher.addUnchecked("DELETE FROM PARTED1");
batcher.addUnchecked("DELETE FROM REPPED1");
for (int i = 1; i <= 10; i++) {
batcher.add(String.format("INSERT INTO PARTED1 VALUES (%d, %d)", i, 100+i), 1);
batcher.add(String.format("INSERT INTO REPPED1 VALUES (%d, %d)", i, 100+i), 1);
}
batcher.run();
batcher.add("SELECT * FROM PARTED1", 10);
batcher.add("SELECT * FROM REPPED1", 10);
batcher.add("DELETE FROM PARTED1 WHERE PARTVAL > 5", 5);
batcher.add("DELETE FROM REPPED1 WHERE REPPEDVAL > 5", 5);
batcher.add("SELECT * FROM PARTED1", 5);
batcher.add("SELECT * FROM REPPED1", 5);
batcher.run();
// roll-back entire batch if one statement fails (start from a clean slate)
batcher.addUnchecked("DELETE FROM BLAH");
batcher.run();
batcher.add("INSERT INTO BLAH VALUES (100, '2012-05-21 12:00:00.000000', 1000)", 1);
batcher.run();
// this should succeed, but won't due to the failure below
batcher.add("INSERT INTO BLAH VALUES (101, '2012-05-21 12:00:00.000000', 1001)", 0);
// this will fail the batch due to a PK constraint violation
batcher.add("INSERT INTO BLAH VALUES (100, '2012-05-21 12:00:00.000000', 1000)", 0);
batcher.runWithException();
// expect 1 row, not 2.
batcher.add("SELECT * FROM BLAH", 1);
batcher.run();
}
finally {
env.tearDown();
}
}
@Test
public void testXopenSubSelectQueries() throws Exception {
TestEnv env = new TestEnv(m_catalogJar, m_pathToDeployment, 2, 1, 0);
String adHocQuery;
try {
env.setUp();
adHocQuery = " UPDATE STAFF \n" +
" SET GRADE=10*STAFF.GRADE \n" +
" WHERE STAFF.EMPNUM NOT IN \n" +
" (SELECT WORKS.EMPNUM \n" +
" FROM WORKS \n" +
" WHERE STAFF.EMPNUM = WORKS.EMPNUM);";
try {
env.m_client.callProcedure("@AdHoc", adHocQuery);
fail("did not fail on subquery");
}
catch (ProcCallException pcex) {
assertTrue(pcex.getMessage().indexOf("not support subqueries") > 0);
}
adHocQuery = " SELECT 'ZZ', EMPNUM, EMPNAME, -99 \n" +
" FROM STAFF \n" +
" WHERE NOT EXISTS (SELECT * FROM WORKS \n" +
" WHERE WORKS.EMPNUM = STAFF.EMPNUM) \n" +
" ORDER BY EMPNUM;";
try {
env.m_client.callProcedure("@AdHoc", adHocQuery);
fail("did not fail on exists clause");
}
catch (ProcCallException pcex) {
assertTrue(pcex.getMessage().indexOf("not support subqueries") > 0);
}
adHocQuery = " SELECT STAFF.EMPNAME \n" +
" FROM STAFF \n" +
" WHERE STAFF.EMPNUM IN \n" +
" (SELECT WORKS.EMPNUM \n" +
" FROM WORKS \n" +
" WHERE WORKS.PNUM IN \n" +
" (SELECT PROJ.PNUM \n" +
" FROM PROJ \n" +
" WHERE PROJ.CITY='Tampa')); \n" +
"";
try {
env.m_client.callProcedure("@AdHoc", adHocQuery);
fail("did not fail on subquery");
}
catch (ProcCallException pcex) {
assertTrue(pcex.getMessage().indexOf("not support subqueries") > 0);
}
adHocQuery = "SELECT FIRST1.EMPNUM, SECOND2.EMPNUM \n" +
" FROM STAFF FIRST1, STAFF SECOND2 \n" +
" WHERE FIRST1.CITY = SECOND2.CITY \n" +
" AND FIRST1.EMPNUM < SECOND2.EMPNUM;";
try {
env.m_client.callProcedure("@AdHoc", adHocQuery);
fail("did not fail on selfjoin");
}
catch (ProcCallException pcex) {
System.out.println("DEBUG what?" + pcex.getMessage());
assertTrue(pcex.getMessage().indexOf("not support self joins") > 0);
}
adHocQuery = "SELECT PNAME \n" +
" FROM PROJ \n" +
" WHERE 'Tampa' NOT BETWEEN CITY AND 'Vienna' \n" +
" AND PNUM > 'P2';";
try {
env.m_client.callProcedure("@AdHoc", adHocQuery);
fail("did not fail on static clause");
}
catch (ProcCallException pcex) {
assertTrue(pcex.getMessage().indexOf("does not support WHERE clauses containing only constants") > 0);
}
adHocQuery = "CREATE TABLE ICAST2 (C1 INT, C2 FLOAT);";
try {
env.m_client.callProcedure("@AdHoc", adHocQuery);
fail("did not fail on invalid ");
}
catch (ProcCallException pcex) {
assertTrue(pcex.getMessage().indexOf("Unsupported SQL verb in statement") > 0);
}
adHocQuery = "CREATE INDEX IDX_PROJ_PNAME ON PROJ(PNAME);";
try {
env.m_client.callProcedure("@AdHoc", adHocQuery);
fail("did not fail on invalid SQL verb");
}
catch (ProcCallException pcex) {
assertTrue(pcex.getMessage().indexOf("Unsupported SQL verb in statement") > 0);
}
adHocQuery = "ROLLBACK;";
try {
env.m_client.callProcedure("@AdHoc", adHocQuery);
fail("did not fail on invalid SQL verb");
}
catch (ProcCallException pcex) {
assertTrue(pcex.getMessage().indexOf("Unsupported SQL verb in statement") > 0);
}
adHocQuery = "DROP TABLE PROJ;";
try {
env.m_client.callProcedure("@AdHoc", adHocQuery);
fail("did not fail on invalid SQL verb");
}
catch (ProcCallException pcex) {
assertTrue(pcex.getMessage().indexOf("Unsupported SQL verb in statement") > 0);
}
adHocQuery = "PARTITION TABLE PROJ ON COLUMN PNUM;";
try {
env.m_client.callProcedure("@AdHoc", adHocQuery);
fail("did not fail with unexpected token");
}
catch (ProcCallException pcex) {
assertTrue(pcex.getMessage().indexOf("unexpected token: PARTITION") > 0);
}
adHocQuery = "CREATE PROCEDURE AS SELECT 1 FROM PROJ;";
try {
env.m_client.callProcedure("@AdHoc", adHocQuery);
fail("did not fail with unexpected token");
}
catch (ProcCallException pcex) {
assertTrue(pcex.getMessage().indexOf("unexpected token: AS") > 0);
}
adHocQuery = "CREATE PROCEDURE FROM CLASS bar.Foo;";
try {
env.m_client.callProcedure("@AdHoc", adHocQuery);
fail("did not fail with unexpected token");
}
catch (ProcCallException pcex) {
assertTrue(pcex.getMessage().indexOf("unexpected token: FROM") > 0);
}
adHocQuery = "SELECT PNUM \n" +
" FROM WORKS \n" +
" WHERE PNUM > 'P1' \n" +
" GROUP BY PNUM \n" +
" HAVING COUNT(*) > 1;";
try {
env.m_client.callProcedure("@AdHoc", adHocQuery);
fail("did not fail on having clause");
}
catch (ProcCallException pcex) {
assertTrue(pcex.getMessage().indexOf("not support the HAVING clause") > 0);
}
}
finally {
env.tearDown();
}
}
@Test
// ENG-4151 a bad string timestamp insert causes various errors when a constraint
// violation occurs because the bad timestamp column is serialized as a string
// instead of a timestamp. It was mis-handling the timestamp datatype during planning.
// Testing with ad hoc because that's how it was discovered.
public void testTimestampInsert() throws Exception {
TestEnv env = new TestEnv(m_catalogJar, m_pathToDeployment, 1, 1, 0);
try {
env.setUp();
// bad timestamp should result in a clean compiler error.
try {
String sql = "INSERT INTO TS_CONSTRAINT_EXCEPTION VALUES ('aaa','{}');";
env.m_client.callProcedure("@AdHoc", sql).getResults();
fail("Compilation should have failed.");
}
catch(ProcCallException e) {
assertTrue(e.getMessage().contains("Error compiling"));
}
// double insert should cause a clean constraint violation, not a crash
try {
String sql = String.format("INSERT INTO TS_CONSTRAINT_EXCEPTION VALUES ('%s','{}');",
new TimestampType().toString());
VoltTable modCount = env.m_client.callProcedure("@AdHoc", sql).getResults()[0];
assertEquals(1, modCount.getRowCount());
assertEquals(1, modCount.asScalarLong());
modCount = env.m_client.callProcedure("@AdHoc", sql).getResults()[0];
assertEquals(1, modCount.getRowCount());
assertEquals(1, modCount.asScalarLong());
}
catch(ProcCallException e) {
assertTrue(e.getMessage().contains("CONSTRAINT VIOLATION"));
}
}
finally {
env.tearDown();
}
}
/**
* Builds and validates query batch runs.
*/
private static class Batcher {
private final TestEnv m_env;
private final List<Integer> m_expectedCounts = new ArrayList<Integer>();
private final List<String> m_queries = new ArrayList<String>();
public Batcher(final TestEnv env) {
m_env = env;
}
void add(String query, Integer expectedCount) {
m_queries.add(query);
if (expectedCount != null) {
m_expectedCounts.add(expectedCount);
}
}
void addUnchecked(String query) {
m_queries.add(query);
m_expectedCounts.add(-1);
}
void run() throws Exception {
runAndCheck(false);
}
void runWithException() throws Exception {
runAndCheck(true);
}
private void runAndCheck(boolean expectException) throws Exception {
try {
VoltTable[] results = m_env.m_client.callProcedure("@AdHoc",
StringUtils.join(m_queries, "; ")).getResults();
int i = 0;
assertEquals(m_expectedCounts.size(), results.length);
for (String query : m_queries) {
int expectedCount = m_expectedCounts.get(i);
if (expectedCount >= 0) {
String s = query.toLowerCase().trim();
if (!s.isEmpty()) {
if ( s.startsWith("insert")
|| s.startsWith("update")
|| s.startsWith("delete")) {
assertEquals(String.format("%s (row count):",query),
1, results[i].getRowCount());
assertEquals(String.format("%s (result count):",query),
expectedCount, results[i].asScalarLong());
} else {
assertEquals(String.format("%s (row count):",query),
expectedCount, results[i].getRowCount());
}
i++;
}
}
}
}
catch(ProcCallException e) {
assertTrue("Unexpected exception for batch: " + e.getMessage(), expectException);
}
finally {
m_queries.clear();
m_expectedCounts.clear();
}
}
}
/**
* Test environment with configured schema and server.
*/
private static class TestEnv {
final VoltProjectBuilder m_builder;
LocalCluster m_cluster;
Client m_client = null;
TestEnv(String pathToCatalog, String pathToDeployment,
int siteCount, int hostCount, int kFactor) {
// hack for no k-safety in community version
if (!MiscUtils.isPro()) {
kFactor = 0;
}
m_builder = new VoltProjectBuilder();
try {
m_builder.addLiteralSchema("create table BLAH (" +
"IVAL bigint default 0 not null, " +
"TVAL timestamp default null," +
"DVAL decimal default null," +
"PRIMARY KEY(IVAL));\n" +
"PARTITION TABLE BLAH ON COLUMN IVAL;\n" +
"\n" +
"CREATE TABLE AAA (A1 VARCHAR(2), A2 VARCHAR(2), A3 VARCHAR(2));\n" +
"CREATE TABLE BBB (B1 VARCHAR(2), B2 VARCHAR(2), B3 VARCHAR(2) NOT NULL UNIQUE);\n" +
"CREATE TABLE CCC (C1 VARCHAR(2), C2 VARCHAR(2), C3 VARCHAR(2));\n" +
"\n" +
"CREATE TABLE CHAR_TEST (COL1 VARCHAR(254));\n" +
"CREATE TABLE INT_TEST (COL1 INTEGER);\n" +
"CREATE TABLE SMALL_TEST (COL1 SMALLINT);\n" +
"CREATE TABLE REAL_TEST (REF VARCHAR(1),COL1 REAL);\n" +
"CREATE TABLE REAL3_TEST (COL1 REAL,COL2 REAL,COL3 REAL);\n" +
"CREATE TABLE DOUB_TEST (REF VARCHAR(1),COL1 FLOAT);\n" +
"CREATE TABLE DOUB3_TEST (COL1 FLOAT,COL2 FLOAT\n" +
" PRECISION,COL3 FLOAT);\n" +
"\n" +
"-- Users may provide an explicit precision for FLOAT_TEST.COL1\n" +
"\n" +
"CREATE TABLE FLOAT_TEST (REF VARCHAR(1),COL1 FLOAT);\n" +
"\n" +
"CREATE TABLE INDEXLIMIT(COL1 VARCHAR(2), COL2 VARCHAR(2),\n" +
" COL3 VARCHAR(2), COL4 VARCHAR(2), COL5 VARCHAR(2),\n" +
" COL6 VARCHAR(2), COL7 VARCHAR(2));\n" +
"\n" +
"CREATE TABLE WIDETABLE (WIDE VARCHAR(118));\n" +
"CREATE TABLE WIDETAB (WIDE1 VARCHAR(38), WIDE2 VARCHAR(38), WIDE3 VARCHAR(38));\n" +
"\n" +
"CREATE TABLE TEST_TRUNC (TEST_STRING VARCHAR (6));\n" +
"\n" +
"CREATE TABLE WARNING(TESTCHAR VARCHAR(6), TESTINT INTEGER);\n" +
"\n" +
"CREATE TABLE TV (dec3 DECIMAL(3), dec1514 DECIMAL(15,14),\n" +
" dec150 DECIMAL(15,0), dec1515 DECIMAL(15,15));\n" +
"\n" +
"CREATE TABLE TU (smint SMALLINT, dec1514 DECIMAL(15,14),\n" +
" integr INTEGER, dec1515 DECIMAL(15,15));\n" +
"\n" +
"CREATE TABLE STAFF\n" +
" (EMPNUM VARCHAR(3) NOT NULL UNIQUE,\n" +
" EMPNAME VARCHAR(20),\n" +
" GRADE DECIMAL(4),\n" +
" CITY VARCHAR(15));\n" +
"\n" +
"CREATE TABLE PROJ\n" +
" (PNUM VARCHAR(3) NOT NULL UNIQUE,\n" +
" PNAME VARCHAR(20),\n" +
" PTYPE VARCHAR(6),\n" +
" BUDGET DECIMAL(9),\n" +
" CITY VARCHAR(15));\n" +
"\n" +
"CREATE TABLE WORKS\n" +
" (EMPNUM VARCHAR(3) NOT NULL,\n" +
" PNUM VARCHAR(3) NOT NULL,\n" +
" HOURS DECIMAL(5),\n" +
" UNIQUE(EMPNUM,PNUM));\n" +
"\n" +
"CREATE TABLE INTS\n" +
" (INT1 SMALLINT NOT NULL,\n" +
" INT2 SMALLINT NOT NULL);\n" +
"CREATE PROCEDURE TestProcedure AS INSERT INTO AAA VALUES(?,?,?);\n" +
"CREATE PROCEDURE Insert AS INSERT into BLAH values (?, ?, ?);\n" +
"CREATE PROCEDURE InsertWithDate AS \n" +
" INSERT INTO BLAH VALUES (974599638818488300, '2011-06-24 10:30:26.002', 5);\n" +
"\n" +
"CREATE TABLE TS_CONSTRAINT_EXCEPTION\n" +
" (TS TIMESTAMP UNIQUE NOT NULL,\n" +
" COL1 VARCHAR(2048)); \n" +
"");
// add more partitioned and replicated tables, PARTED[1-3] and REPED[1-2]
AdHocQueryTester.setUpSchema(m_builder, pathToCatalog, pathToDeployment);
}
catch (Exception e) {
e.printStackTrace();
fail("Failed to set up schema");
}
m_cluster = new LocalCluster(pathToCatalog, siteCount, hostCount, kFactor,
BackendTarget.NATIVE_EE_JNI,
LocalCluster.FailureState.ALL_RUNNING,
m_debug);
m_cluster.setHasLocalServer(true);
boolean success = m_cluster.compile(m_builder);
assert(success);
try {
MiscUtils.copyFile(m_builder.getPathToDeployment(), pathToDeployment);
}
catch (Exception e) {
fail(String.format("Failed to copy \"%s\" to \"%s\"", m_builder.getPathToDeployment(), pathToDeployment));
}
}
void setUp() {
m_cluster.startUp();
try {
// do the test
m_client = ClientFactory.createClient();
m_client.createConnection("localhost", m_cluster.port(0));
}
catch (UnknownHostException e) {
e.printStackTrace();
fail(String.format("Failed to connect to localhost:%d", m_cluster.port(0)));
}
catch (IOException e) {
e.printStackTrace();
fail(String.format("Failed to connect to localhost:%d", m_cluster.port(0)));
}
}
void tearDown() {
if (m_client != null) {
try {
m_client.close();
} catch (InterruptedException e) {
e.printStackTrace();
fail("Failed to close client");
}
}
m_client = null;
if (m_cluster != null) {
try {
m_cluster.shutDown();
} catch (InterruptedException e) {
e.printStackTrace();
fail("Failed to shut down cluster");
}
}
m_cluster = null;
// no clue how helpful this is
System.gc();
}
}
}
|
package org.voltdb;
import java.io.File;
import java.io.IOException;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.junit.AfterClass;
import org.junit.Test;
import org.voltdb.TheHashinator.HashinatorType;
import org.voltdb.VoltDB.Configuration;
import org.voltdb.client.Client;
import org.voltdb.client.ClientFactory;
import org.voltdb.client.NoConnectionsException;
import org.voltdb.client.ProcCallException;
import org.voltdb.compiler.AsyncCompilerAgent;
import org.voltdb.compiler.VoltProjectBuilder;
import org.voltdb.regressionsuites.LocalCluster;
import org.voltdb.types.TimestampType;
import org.voltdb.utils.MiscUtils;
import org.voltdb.utils.VoltFile;
public class TestAdHocQueries extends AdHocQueryTester {
Client m_client;
private final static boolean m_debug = false;
public static final boolean retry_on_mismatch = true;
@AfterClass
public static void tearDownClass()
{
try {
VoltFile.recursivelyDelete(new File("/tmp/" + System.getProperty("user.name")));
}
catch (IOException e) {};
}
@Test
public void testProcedureAdhoc() throws Exception {
VoltDB.Configuration config = setUpSPDB();
ServerThread localServer = new ServerThread(config);
try {
localServer.start();
localServer.waitForInitialization();
// do the test
m_client = ClientFactory.createClient();
m_client.createConnection("localhost", config.m_port);
m_client.callProcedure("@AdHoc", "insert into PARTED1 values ( 23, 3 )");
// Test that a basic multipartition select works as well as a parameterized
// query (it's in the procedure)
VoltTable results[] = m_client.callProcedure(
"executeSQLSP",
23,
"select * from PARTED1").getResults();
assertTrue(
results[0].advanceRow());
assertTrue(results[1].advanceRow());
results = m_client.callProcedure(
"executeSQLMP",
23,
" select * from PARTED1").getResults();
assertTrue(
results[0].advanceRow());
assertTrue(results[1].advanceRow());
// Validate that doing an insert from a RO procedure fails
try {
m_client.callProcedure("executeSQLSP", 24, "insert into parted1 values (24,5)");
fail("Procedure call should not have succeded");
} catch (ProcCallException e) {}
try {
m_client.callProcedure("executeSQLMP", 24, "insert into parted1 values (24,5)");
fail("Procedure call should not have succeded");
} catch (ProcCallException e) {}
// Validate one sql statement per
try {
m_client.callProcedure("executeSQLSP", 24, "insert into parted1 values (24,5); select * from parted1;");
fail("Procedure call should not have succeded");
} catch (ProcCallException e) {}
try {
m_client.callProcedure("executeSQLSP", 24, "drop table parted1");
fail("Procedure call should not have succeded");
} catch (ProcCallException e) {}
// Validate that an insert does work from a write procedure
m_client.callProcedure("executeSQLSPWRITE", 24, "insert into parted1 values (24, 4);");
m_client.callProcedure("executeSQLMPWRITE", 25, "insert into parted1 values (25, 5);");
// Query the inserts and all the rest do it once for singe and once for multi
results = m_client.callProcedure("executeSQLMP", 24, "select * from parted1 order by partval").getResults();
assertEquals( 3, results[0].getRowCount());
for (int ii = 3; ii < 6; ii++) {
assertTrue(results[0].advanceRow());
assertEquals(20 + ii, results[0].getLong(0));
assertEquals(ii, results[0].getLong(1));
}
//Output from the first preplanned statement
assertEquals( 3, results[1].getRowCount());
assertTrue(results[1].advanceRow());
assertEquals( 23, results[1].getLong(0));
assertEquals( 3, results[1].getLong(1));
//Output from the second adhoc statement
assertEquals( 1, results[2].getRowCount());
assertTrue(results[2].advanceRow());
assertEquals( 24, results[2].getLong(0));
assertEquals( 4, results[2].getLong(1));
//Output from the second preplanned statement
assertEquals( 3, results[3].getRowCount());
assertTrue(results[3].advanceRow());
assertEquals( 23, results[3].getLong(0));
assertEquals( 3, results[3].getLong(1));
results = m_client.callProcedure("executeSQLSP", 24, "select * from parted1 order by partval").getResults();
if (TheHashinator.getConfiguredHashinatorType() == TheHashinator.HashinatorType.LEGACY) {
for (int ii = 0; ii < 4; ii++) {
assertEquals( 1, results[ii].getRowCount());
assertTrue(results[ii].advanceRow());
assertEquals(24, results[ii].getLong(0));
assertEquals( 4, results[ii].getLong(1));
}
} else {
//These constants break when partitioning changes
//Recently 23, 24, and 25, started hashing to the same place /facepalm
for (int ii = 0; ii < 4; ii++) {
//The third statement does an exact equality match
if (ii == 2) {
assertEquals( 1, results[ii].getRowCount());
assertTrue(results[ii].advanceRow());
assertEquals(24, results[ii].getLong(0));
assertEquals( 4, results[ii].getLong(1));
continue;
}
assertEquals( 3, results[ii].getRowCount());
assertTrue(results[ii].advanceRow());
assertEquals(23, results[ii].getLong(0));
assertEquals( 3, results[ii].getLong(1));
assertTrue(results[ii].advanceRow());
assertEquals(24, results[ii].getLong(0));
assertEquals( 4, results[ii].getLong(1));
assertTrue(results[ii].advanceRow());
assertEquals(25, results[ii].getLong(0));
assertEquals( 5, results[ii].getLong(1));
}
}
}
catch (Exception e) {
e.printStackTrace();
fail();
}
finally {
if (m_client != null) m_client.close();
m_client = null;
if (localServer != null) {
localServer.shutdown();
localServer.join();
}
localServer = null;
// no clue how helpful this is
System.gc();
}
}
@Test
public void testSP() throws Exception {
System.out.println("Starting testSP");
VoltDB.Configuration config = setUpSPDB();
ServerThread localServer = new ServerThread(config);
try {
localServer.start();
localServer.waitForInitialization();
// do the test
m_client = ClientFactory.createClient();
m_client.createConnection("localhost", config.m_port);
VoltTable modCount;
//Hashes to partition 0
int hashableA;
//Hashes to partition 1
int hashableB;
//Hashes to partition 0
int hashableC;
//Hashes to partition 1
int hashableD;
if (TheHashinator.getConfiguredHashinatorType() == HashinatorType.LEGACY) {
hashableA = 4;
hashableB = 1;
hashableC = 2;
hashableD = 3;
} else {
hashableA = 8;
hashableB = 2;
hashableC = 1;
hashableD = 4;
}
//If things break you can use this to find what hashes where and fix the constants
// for (int ii = 0; ii < 10; ii++) {
// System.out.println("Partition " + TheHashinator.getPartitionForParameter(VoltType.INTEGER.getValue(), ii) + " param " + ii);
// Unlike TestAdHocPlans, TestAdHocQueries runs the queries against actual (minimal) data.
// Load that, here.
modCount = m_client.callProcedure("@AdHoc", String.format("INSERT INTO PARTED1 VALUES (%d, %d);", hashableA, hashableA)).getResults()[0];
assertEquals(1, modCount.getRowCount());
assertEquals(1, modCount.asScalarLong());
modCount = m_client.callProcedure("@AdHoc", String.format("INSERT INTO PARTED1 VALUES (%d, %d);", hashableB, hashableB)).getResults()[0];
assertEquals(1, modCount.getRowCount());
assertEquals(1, modCount.asScalarLong());
modCount = m_client.callProcedure("@AdHoc", String.format("INSERT INTO PARTED2 VALUES (%d, %d);", hashableA, hashableA)).getResults()[0];
assertEquals(1, modCount.getRowCount());
assertEquals(1, modCount.asScalarLong());
modCount = m_client.callProcedure("@AdHoc", String.format("INSERT INTO PARTED2 VALUES (%d, %d);", hashableC, hashableC)).getResults()[0];
assertEquals(1, modCount.getRowCount());
assertEquals(1, modCount.asScalarLong());
modCount = m_client.callProcedure("@AdHoc", String.format("INSERT INTO PARTED3 VALUES (%d, %d);", hashableA, hashableA)).getResults()[0];
assertEquals(1, modCount.getRowCount());
assertEquals(1, modCount.asScalarLong());
modCount = m_client.callProcedure("@AdHoc", String.format("INSERT INTO PARTED3 VALUES (%d, %d);", hashableD, hashableD)).getResults()[0];
assertEquals(1, modCount.getRowCount());
assertEquals(1, modCount.asScalarLong());
modCount = m_client.callProcedure("@AdHoc", String.format("INSERT INTO REPPED1 VALUES (%d, %d);", hashableA, hashableA)).getResults()[0];
assertEquals(1, modCount.getRowCount());
assertEquals(1, modCount.asScalarLong());
modCount = m_client.callProcedure("@AdHoc", String.format("INSERT INTO REPPED1 VALUES (%d, %d);", hashableB, hashableB)).getResults()[0];
assertEquals(1, modCount.getRowCount());
assertEquals(1, modCount.asScalarLong());
modCount = m_client.callProcedure("@AdHoc", String.format("INSERT INTO REPPED2 VALUES (%d, %d);", hashableA, hashableA)).getResults()[0];
assertEquals(1, modCount.getRowCount());
assertEquals(1, modCount.asScalarLong());
modCount = m_client.callProcedure("@AdHoc", String.format("INSERT INTO REPPED2 VALUES (%d, %d);", hashableC, hashableC)).getResults()[0];
assertEquals(1, modCount.getRowCount());
assertEquals(1, modCount.asScalarLong());
// verify that inserts to a table partitioned on an integer get handled correctly - results not used later
for (int i = -7; i <= 7; i++) {
modCount = m_client.callProcedure("@AdHoc", String.format("INSERT INTO PARTED4 VALUES (%d, %d);", i, i)).getResults()[0];
assertEquals(1, modCount.getRowCount());
assertEquals(1, modCount.asScalarLong());
}
runAllAdHocSPtests(hashableA, hashableB, hashableC, hashableD);
}
finally {
if (m_client != null) m_client.close();
m_client = null;
if (localServer != null) {
localServer.shutdown();
localServer.join();
}
localServer = null;
// no clue how helpful this is
System.gc();
System.out.println("Ending testSP");
}
}
/**
* @param query
* @param hashable - used to pick a single partition for running the query
* @param spPartialSoFar - counts from prior SP queries to compensate for unpredictable hashing
* @param expected - expected value of MP query (and of SP query, adjusting by spPartialSoFar, and only if validatingSPresult).
* @param validatingSPresult - disables validation for non-deterministic SP results (so we don't have to second-guess the hashinator)
* @return
* @throws IOException
* @throws NoConnectionsException
* @throws ProcCallException
*/
@Override
public int runQueryTest(String query, int hashable, int spPartialSoFar, int expected, int validatingSPresult)
throws IOException, NoConnectionsException, ProcCallException {
VoltTable result;
result = m_client.callProcedure("@AdHoc", query).getResults()[0];
//System.out.println(result.toString());
assertEquals(expected, result.getRowCount());
result = m_client.callProcedure("@AdHocSpForTest", query, hashable).getResults()[0];
int spResult = result.getRowCount();
//System.out.println(result.toString());
if (validatingSPresult != 0) {
assertEquals(expected, spPartialSoFar + spResult);
}
return spResult;
}
public static String m_catalogJar = "adhoc.jar";
public static String m_pathToCatalog = Configuration.getPathToCatalogForTest(m_catalogJar);
public static String m_pathToDeployment = Configuration.getPathToCatalogForTest("adhoc.xml");
@Test
public void testSimple() throws Exception {
System.out.println("Starting testSimple");
TestEnv env = new TestEnv(m_catalogJar, m_pathToDeployment, 2, 2, 1);
try {
env.setUp();
VoltTable modCount = env.m_client.callProcedure("@AdHoc", "INSERT INTO BLAH VALUES (1, 1, 1);").getResults()[0];
assertEquals(1, modCount.getRowCount());
assertEquals(1, modCount.asScalarLong());
VoltTable result = env.m_client.callProcedure("@AdHoc", "SELECT * FROM BLAH;").getResults()[0];
assertEquals(1, result.getRowCount());
//System.out.println(result.toString());
// test single-partition stuff
// TODO: upgrade to use @GetPartitionKeys instead of TheHashinator interface
VoltTable result1 = env.m_client.callProcedure("@AdHocSpForTest", "SELECT * FROM BLAH;",
TheHashinator.getConfiguredHashinatorType() == TheHashinator.HashinatorType.LEGACY ?
0 : 2).getResults()[0];
//System.out.println(result1.toString());
VoltTable result2 = env.m_client.callProcedure("@AdHocSpForTest", "SELECT * FROM BLAH;",
TheHashinator.getConfiguredHashinatorType() == TheHashinator.HashinatorType.LEGACY ?
1 : 0).getResults()[0];
//System.out.println(result2.toString());
assertEquals(1, result1.getRowCount() + result2.getRowCount());
assertEquals(0, result1.getRowCount());
assertEquals(1, result2.getRowCount());
try {
env.m_client.callProcedure("@AdHocSpForTest", "INSERT INTO BLAH VALUES (0, 0, 0);",
TheHashinator.getConfiguredHashinatorType() == TheHashinator.HashinatorType.LEGACY ?
1 : 2);
fail("Badly partitioned insert failed to throw expected exception");
}
catch (Exception e) {}
try {
env.m_client.callProcedure("@AdHoc", "SLEECT * FROOM NEEEW_OOORDERERER;");
fail("Bad SQL failed to throw expected exception");
}
catch (Exception e) {}
// try a huge bigint literal
modCount = env.m_client.callProcedure("@AdHoc", "INSERT INTO BLAH VALUES (974599638818488300, '2011-06-24 10:30:26.123012', 5);").getResults()[0];
modCount = env.m_client.callProcedure("@AdHoc", "INSERT INTO BLAH VALUES (974599638818488301, '2011-06-24 10:30:28', 5);").getResults()[0];
assertEquals(1, modCount.getRowCount());
assertEquals(1, modCount.asScalarLong());
result = env.m_client.callProcedure("@AdHoc", "SELECT * FROM BLAH WHERE IVAL = 974599638818488300;").getResults()[0];
assertEquals(1, result.getRowCount());
//System.out.println(result.toString());
result = env.m_client.callProcedure("@AdHoc", "SELECT * FROM BLAH WHERE TVAL = '2011-06-24 10:30:26.123012';").getResults()[0];
assertEquals(1, result.getRowCount());
//System.out.println(result.toString());
result = env.m_client.callProcedure("@AdHoc", "SELECT * FROM BLAH WHERE TVAL > '2011-06-24 10:30:25';").getResults()[0];
assertEquals(2, result.getRowCount());
//System.out.println(result.toString());
result = env.m_client.callProcedure("@AdHoc", "SELECT * FROM BLAH WHERE TVAL < '2011-06-24 10:30:27';").getResults()[0];
//System.out.println(result.toString());
// We inserted a 1,1,1 row way earlier
assertEquals(2, result.getRowCount());
// try something like the queries in ENG-1242
try {
env.m_client.callProcedure("@AdHoc", "select * from blah; dfvsdfgvdf select * from blah WHERE IVAL = 1;");
fail("Bad SQL failed to throw expected exception");
}
catch (Exception e) {}
env.m_client.callProcedure("@AdHoc", "select\n* from blah;");
// try a decimal calculation (ENG-1093)
modCount = env.m_client.callProcedure("@AdHoc", "INSERT INTO BLAH VALUES (2, '2011-06-24 10:30:26', 1.12345*1);").getResults()[0];
assertEquals(1, modCount.getRowCount());
assertEquals(1, modCount.asScalarLong());
result = env.m_client.callProcedure("@AdHoc", "SELECT * FROM BLAH WHERE IVAL = 2;").getResults()[0];
assertEquals(1, result.getRowCount());
//System.out.println(result.toString());
// test wasNull asScalarLong
long value;
boolean wasNull;
result = env.m_client.callProcedure("@AdHoc", "select top 1 cast(null as tinyInt) from BLAH").getResults()[0];
value = result.asScalarLong();
wasNull = result.wasNull();
assertEquals(VoltType.NULL_TINYINT, value);
assertEquals(true, wasNull);
result = env.m_client.callProcedure("@AdHoc", "select top 1 cast(null as smallInt) from BLAH").getResults()[0];
value = result.asScalarLong();
wasNull = result.wasNull();
assertEquals(VoltType.NULL_SMALLINT, value);
assertEquals(true, wasNull);
result = env.m_client.callProcedure("@AdHoc", "select top 1 cast(null as integer) from BLAH").getResults()[0];
value = result.asScalarLong();
wasNull = result.wasNull();
assertEquals(VoltType.NULL_INTEGER, value);
assertEquals(true, wasNull);
result = env.m_client.callProcedure("@AdHoc", "select top 1 cast(null as bigint) from BLAH").getResults()[0];
value = result.asScalarLong();
wasNull = result.wasNull();
assertEquals(VoltType.NULL_BIGINT, value);
assertEquals(true, wasNull);
}
finally {
env.tearDown();
System.out.println("Ending testSimple");
}
}
@Test
public void testAdHocLengthLimit() throws Exception {
System.out.println("Starting testAdHocLengthLimit");
TestEnv env = new TestEnv(m_catalogJar, m_pathToDeployment, 2, 2, 1);
try {
env.setUp();
// by pass valgrind due to ENG-7843
if (env.isValgrind()) {
return;
}
StringBuffer adHocQueryTemp = new StringBuffer("SELECT * FROM VOTES WHERE PHONE_NUMBER IN (");
int i = 0;
while (adHocQueryTemp.length() <= Short.MAX_VALUE*10) {
String randPhone = RandomStringUtils.randomNumeric(10);
VoltTable result = env.m_client.callProcedure("@AdHoc", "INSERT INTO VOTES VALUES(?, ?, ?);", randPhone, "MA", i).getResults()[0];
assertEquals(1, result.getRowCount());
adHocQueryTemp.append(randPhone);
adHocQueryTemp.append(", ");
i++;
}
adHocQueryTemp.replace(adHocQueryTemp.length()-2, adHocQueryTemp.length(), ");");
// assure that adhoc query text can exceed 2^15 length, but the literals still cannot exceed 2^15
assert(adHocQueryTemp.length() > Short.MAX_VALUE);
assert(i < Short.MAX_VALUE);
VoltTable result = env.m_client.callProcedure("@AdHoc", adHocQueryTemp.toString()).getResults()[0];
assertEquals(i, result.getRowCount());
} catch (Exception e) {
e.printStackTrace();
fail("Adhoc SQL exceeding length limit, throw expected exception");
}
finally {
env.tearDown();
System.out.println("Ending testAdHocLengthLimit");
}
}
@Test
public void testAdHocWithParams() throws Exception {
System.out.println("Starting testAdHocWithParams");
TestEnv env = new TestEnv(m_catalogJar, m_pathToDeployment, 2, 2, 1);
try {
env.setUp();
VoltTable modCount = env.m_client.callProcedure("@AdHoc", "INSERT INTO BLAH VALUES (?, ?, ?);", 1, 1, 1).getResults()[0];
assertEquals(1, modCount.getRowCount());
assertEquals(1, modCount.asScalarLong());
VoltTable result;
result = env.m_client.callProcedure("@AdHoc", "SELECT * FROM BLAH WHERE IVAL = ?;", 1).getResults()[0];
assertEquals(1, result.getRowCount());
//System.out.println(result.toString());
result = env.m_client.callProcedure("@AdHoc", "SELECT * FROM BLAH WHERE IVAL = ?;", 2).getResults()[0];
assertEquals(0, result.getRowCount());
//System.out.println(result.toString());
// test single-partition stuff
// TODO: upgrade to use @GetPartitionKeys instead of TheHashinator interface
VoltTable result1 = env.m_client.callProcedure("@AdHocSpForTest", "SELECT * FROM BLAH WHERE IVAL = ?;",
(TheHashinator.getConfiguredHashinatorType() == TheHashinator.HashinatorType.LEGACY ?
0 : 2), 1).getResults()[0];
//System.out.println(result1.toString());
VoltTable result2 = env.m_client.callProcedure("@AdHocSpForTest", "SELECT * FROM BLAH WHERE IVAL = ?;",
(TheHashinator.getConfiguredHashinatorType() == TheHashinator.HashinatorType.LEGACY ?
1 : 0), 1).getResults()[0];
//System.out.println(result2.toString());
assertEquals(1, result1.getRowCount() + result2.getRowCount());
assertEquals(0, result1.getRowCount());
assertEquals(1, result2.getRowCount());
try {
env.m_client.callProcedure("@AdHocSpForTest", "INSERT INTO BLAH VALUES (?, ?, ?);",
(TheHashinator.getConfiguredHashinatorType() == TheHashinator.HashinatorType.LEGACY ?
1 : 2), 0, 0, 0);
fail("Badly partitioned insert failed to throw expected exception");
}
catch (Exception e) {}
try {
env.m_client.callProcedure("@AdHoc", "SLEECT * FROOM NEEEW_OOORDERERER WHERE NONESUCH = ?;", 1);
fail("Bad SQL failed to throw expected exception");
}
catch (Exception e) {}
// try a huge bigint literal
modCount = env.m_client.callProcedure("@AdHoc", "INSERT INTO BLAH VALUES (?, ?, ?)", 974599638818488300L, "2011-06-24 10:30:26.123000", 5).getResults()[0];
modCount = env.m_client.callProcedure("@AdHoc", "INSERT INTO BLAH VALUES (?, ?, ?)", 974599638818488301L, "2011-06-24 10:30:28.000000", 5).getResults()[0];
assertEquals(1, modCount.getRowCount());
assertEquals(1, modCount.asScalarLong());
result = env.m_client.callProcedure("@AdHoc", "SELECT * FROM BLAH WHERE IVAL = ?;", 974599638818488300L).getResults()[0];
assertEquals(1, result.getRowCount());
//System.out.println(result.toString());
result = env.m_client.callProcedure("@AdHoc", "SELECT * FROM BLAH WHERE IVAL = ?;", "974599638818488300").getResults()[0];
//System.out.println(result.toString());
assertEquals(1, result.getRowCount());
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
result = env.m_client.callProcedure("@AdHoc", "SELECT * FROM BLAH WHERE TVAL = ?;", dateFormat.parse("2011-06-24 10:30:26.123")).getResults()[0];
assertEquals(1, result.getRowCount());
//System.out.println(result.toString());
result = env.m_client.callProcedure("@AdHoc", "SELECT * FROM BLAH WHERE TVAL > ?;", dateFormat.parse("2011-06-24 10:30:25.000")).getResults()[0];
assertEquals(2, result.getRowCount());
//System.out.println(result.toString());
result = env.m_client.callProcedure("@AdHoc", "SELECT * FROM BLAH WHERE TVAL < ?;", dateFormat.parse("2011-06-24 10:30:27.000000")).getResults()[0];
//System.out.println(result.toString());
// We inserted a 1,1,1 row way earlier
assertEquals(2, result.getRowCount());
// try something like the queries in ENG-1242
try {
env.m_client.callProcedure("@AdHoc", "select * from blah; dfvsdfgvdf select * from blah WHERE IVAL = ?;", 1);
fail("Bad SQL failed to throw expected exception");
}
catch (Exception e) {}
env.m_client.callProcedure("@AdHoc", "select\n* from blah;");
// try a decimal calculation (ENG-1093)
modCount = env.m_client.callProcedure("@AdHoc", "INSERT INTO BLAH VALUES (?, ?, ?);", 2, "2011-06-24 10:30:26", 1.12345).getResults()[0];
assertEquals(1, modCount.getRowCount());
assertEquals(1, modCount.asScalarLong());
result = env.m_client.callProcedure("@AdHoc", "SELECT * FROM BLAH WHERE IVAL = ?;", 2).getResults()[0];
assertEquals(1, result.getRowCount());
//System.out.println(result.toString());
result = env.m_client.callProcedure("@AdHoc", "SELECT * FROM BLAH WHERE IVAL = ?;", "2").getResults()[0];
//System.out.println(result.toString());
assertEquals(1, result.getRowCount());
}
finally {
env.tearDown();
System.out.println("Ending testAdHocWithParams");
}
}
private void verifyIncorrectParameterMessage(TestEnv env, String adHocQuery, Object[] params) {
int expected = 0;
for (int i=0; i < adHocQuery.length(); i++ ) {
if (adHocQuery.charAt(i) == '?' ) {
expected++;
}
}
String errorMsg = String.format("Incorrect number of parameters passed: expected %d, passed %d",
expected, params.length);
try {
switch (params.length) {
case 1:
env.m_client.callProcedure("@AdHoc", adHocQuery, params[0]);
break;
case 2:
env.m_client.callProcedure("@AdHoc", adHocQuery, params[0], params[1]);
break;
case 3:
env.m_client.callProcedure("@AdHoc", adHocQuery, params[0], params[1], params[2]);
break;
case 4:
env.m_client.callProcedure("@AdHoc", adHocQuery, params[0], params[1], params[2], params[3]);
break;
case 5:
env.m_client.callProcedure("@AdHoc", adHocQuery, params[0], params[1], params[2], params[3], params[4]);
break;
default:
// guard against other number of parameters tests
fail("This test does not support other than 1-5 parameters!");
}
// expecting failure above
fail();
} catch(Exception ex) {
assertTrue(ex.getMessage().contains(errorMsg));
}
}
@Test
public void testAdHocWithParamsNegative() throws Exception {
System.out.println("Starting testAdHocWithParamsNegative cases");
TestEnv env = new TestEnv(m_catalogJar, m_pathToDeployment, 2, 2, 1);
String adHocQuery;
try {
env.setUp();
// no constants
adHocQuery = "SELECT * FROM AAA WHERE a1 = ? and a2 = ?;";
verifyIncorrectParameterMessage(env, adHocQuery, new Integer[]{1});
verifyIncorrectParameterMessage(env, adHocQuery, new Integer[]{1, 1, 1});
// mix question mark and constants
adHocQuery = "SELECT * FROM AAA WHERE a1 = ? and a2 = 'a2' and a3 = 'a3';";
verifyIncorrectParameterMessage(env, adHocQuery, new String[]{"a1", "a2"});
verifyIncorrectParameterMessage(env, adHocQuery, new String[]{"a1", "a2", "a3"});
// constants only
adHocQuery = "SELECT * FROM AAA WHERE a1 = 'a1';";
verifyIncorrectParameterMessage(env, adHocQuery, new String[]{"a2"});
verifyIncorrectParameterMessage(env, adHocQuery, new String[]{"a2", "a3"});
adHocQuery = "SELECT * FROM AAA WHERE a1 = 'a1' and a2 = 'a2';";
verifyIncorrectParameterMessage(env, adHocQuery, new String[]{"a1"});
verifyIncorrectParameterMessage(env, adHocQuery, new String[]{"a1", "a2"});
// test batch with extra parameter call
String errorMsg = AsyncCompilerAgent.AdHocErrorResponseMessage;
// test batch question mark parameter guards
adHocQuery = "SELECT * FROM AAA WHERE a1 = 'a1'; SELECT * FROM AAA WHERE a2 = 'a2';";
try {
env.m_client.callProcedure("@AdHoc", adHocQuery, "a2");
fail();
} catch (Exception ex) {
assertEquals(errorMsg, ex.getMessage());
}
adHocQuery = "SELECT * FROM AAA WHERE a1 = 'a1'; SELECT * FROM AAA WHERE a2 = ?;";
try {
env.m_client.callProcedure("@AdHoc", adHocQuery, "a2");
fail();
} catch (Exception ex) {
assertEquals(errorMsg, ex.getMessage());
}
}
finally {
env.tearDown();
System.out.println("Ending testAdHocWithParamsNegative cases");
}
}
@Test
public void testAdHocBatches() throws Exception {
TestEnv env = new TestEnv(m_catalogJar, m_pathToDeployment, 2, 1, 0);
try {
env.setUp();
Batcher batcher = new Batcher(env);
// a few inserts (with a couple of ignored blank statements)
batcher.add("INSERT INTO BLAH VALUES (100, '2012-05-21 12:00:00.000000', 1000)", 1);
batcher.add("", null);
batcher.add("INSERT INTO BLAH VALUES (101, '2012-05-21 12:01:00.000000', 1001)", 1);
batcher.add("", null);
batcher.add("INSERT INTO BLAH VALUES (102, '2012-05-21 12:02:00.000000', 1002)", 1);
batcher.add("INSERT INTO BLAH VALUES (103, '2012-05-21 12:03:00.000000', 1003)", 1);
batcher.add("INSERT INTO BLAH VALUES (104, '2012-05-21 12:04:00.000000', 1004)", 1);
batcher.run();
// a few selects using data inserted by previous batch
batcher.add("SELECT * FROM BLAH WHERE IVAL = 102", 1);
batcher.add("SELECT * FROM BLAH WHERE DVAL >= 1001 AND DVAL <= 1002", 2);
batcher.add("SELECT * FROM BLAH WHERE DVAL >= 1002 AND DVAL <= 1004", 3);
batcher.run();
// mixed reads and writes (start from a clean slate)
batcher.addUnchecked("DELETE FROM BLAH");
batcher.run();
System.out.println("Running problem batch");
batcher.add("INSERT INTO BLAH VALUES (100, '2012-05-21 12:00:00.000000', 1000)", 1);
batcher.add("INSERT INTO BLAH VALUES (101, '2012-05-21 12:00:00.000000', 1001)", 1);
batcher.add("INSERT INTO BLAH VALUES (102, '2012-05-21 12:00:00.000000', 1002)", 1);
batcher.add("DELETE FROM BLAH WHERE IVAL = 100", 1);
batcher.add("SELECT * FROM BLAH", 2);
batcher.add("DELETE FROM BLAH WHERE IVAL = 101", 1);
batcher.add("SELECT * FROM BLAH WHERE IVAL = 101", 0);
batcher.add("UPDATE BLAH SET DVAL = 0 WHERE IVAL = 102", 1);
batcher.run();
// mix replicated and partitioned
batcher.addUnchecked("DELETE FROM PARTED1");
batcher.addUnchecked("DELETE FROM REPPED1");
for (int i = 1; i <= 10; i++) {
batcher.add(String.format("INSERT INTO PARTED1 VALUES (%d, %d)", i, 100+i), 1);
batcher.add(String.format("INSERT INTO REPPED1 VALUES (%d, %d)", i, 100+i), 1);
}
batcher.run();
batcher.add("SELECT * FROM PARTED1", 10);
batcher.add("SELECT * FROM REPPED1", 10);
batcher.add("DELETE FROM PARTED1 WHERE PARTVAL > 5", 5);
batcher.add("DELETE FROM REPPED1 WHERE REPPEDVAL > 5", 5);
batcher.add("SELECT * FROM PARTED1", 5);
batcher.add("SELECT * FROM REPPED1", 5);
batcher.run();
// roll-back entire batch if one statement fails (start from a clean slate)
batcher.addUnchecked("DELETE FROM BLAH");
batcher.run();
batcher.add("INSERT INTO BLAH VALUES (100, '2012-05-21 12:00:00.000000', 1000)", 1);
batcher.run();
// this should succeed, but won't due to the failure below
batcher.add("INSERT INTO BLAH VALUES (101, '2012-05-21 12:00:00.000000', 1001)", 0);
// this will fail the batch due to a PK constraint violation
batcher.add("INSERT INTO BLAH VALUES (100, '2012-05-21 12:00:00.000000', 1000)", 0);
batcher.runWithException();
// expect 1 row, not 2.
batcher.add("SELECT * FROM BLAH", 1);
batcher.run();
}
finally {
env.tearDown();
}
}
@Test
public void testXopenSubSelectQueries() throws Exception {
TestEnv env = new TestEnv(m_catalogJar, m_pathToDeployment, 2, 1, 0);
String adHocQuery;
try {
env.setUp();
adHocQuery = " UPDATE STAFF \n" +
" SET GRADE=10*STAFF.GRADE \n" +
" WHERE STAFF.EMPNUM NOT IN \n" +
" (SELECT WORKS.EMPNUM \n" +
" FROM WORKS \n" +
" WHERE STAFF.EMPNUM = WORKS.EMPNUM);";
try {
env.m_client.callProcedure("@AdHoc", adHocQuery);
fail("did not fail on subquery In/Exists");
}
catch (ProcCallException pcex) {
assertTrue(pcex.getMessage().indexOf("Subquery expressions are only supported in SELECT statements") > 0);
}
adHocQuery = " SELECT 'ZZ', EMPNUM, EMPNAME, -99 \n" +
" FROM STAFF \n" +
" WHERE NOT EXISTS (SELECT * FROM WORKS \n" +
" WHERE WORKS.EMPNUM = STAFF.EMPNUM) \n" +
" ORDER BY EMPNUM;";
try {
env.m_client.callProcedure("@AdHoc", adHocQuery);
}
catch (Exception ex) {
fail("did fail on exists clause");
}
adHocQuery = " SELECT STAFF.EMPNAME \n" +
" FROM STAFF \n" +
" WHERE STAFF.EMPNUM IN \n" +
" (SELECT WORKS.EMPNUM \n" +
" FROM WORKS \n" +
" WHERE WORKS.PNUM IN \n" +
" (SELECT PROJ.PNUM \n" +
" FROM PROJ \n" +
" WHERE PROJ.CITY='Tampa')); \n" +
"";
try {
env.m_client.callProcedure("@AdHoc", adHocQuery);
}
catch (Exception ex) {
fail("did fail on subquery");
}
adHocQuery = "SELECT PNAME \n" +
" FROM PROJ \n" +
" WHERE 'Tampa' NOT BETWEEN CITY AND 'Vienna' \n" +
" AND PNUM > 'P2';";
try {
env.m_client.callProcedure("@AdHoc", adHocQuery);
fail("did not fail on static clause");
}
catch (ProcCallException pcex) {
assertTrue(pcex.getMessage().indexOf("does not support WHERE clauses containing only constants") > 0);
}
adHocQuery = "ROLLBACK;";
try {
env.m_client.callProcedure("@AdHoc", adHocQuery);
fail("did not fail on invalid SQL verb");
}
catch (ProcCallException pcex) {
assertTrue(pcex.getMessage().indexOf("this type of sql statement is not supported") > 0);
}
}
finally {
env.tearDown();
}
}
@Test
// ENG-4151 a bad string timestamp insert causes various errors when a constraint
// violation occurs because the bad timestamp column is serialized as a string
// instead of a timestamp. It was mis-handling the timestamp datatype during planning.
// Testing with ad hoc because that's how it was discovered.
public void testTimestampInsert() throws Exception {
TestEnv env = new TestEnv(m_catalogJar, m_pathToDeployment, 1, 1, 0);
try {
env.setUp();
// bad timestamp should result in a clean compiler error.
try {
String sql = "INSERT INTO TS_CONSTRAINT_EXCEPTION VALUES ('aaa','{}');";
env.m_client.callProcedure("@AdHoc", sql).getResults();
fail("Compilation should have failed.");
}
catch(ProcCallException e) {
assertTrue(e.getMessage().contains("Error compiling"));
}
String sql = String.format("INSERT INTO TS_CONSTRAINT_EXCEPTION VALUES ('%s','{}');",
new TimestampType().toString());
VoltTable modCount = env.m_client.callProcedure("@AdHoc", sql).getResults()[0];
assertEquals(1, modCount.getRowCount());
assertEquals(1, modCount.asScalarLong());
// double insert should cause a clean constraint violation, not a crash
try {
modCount = env.m_client.callProcedure("@AdHoc", sql).getResults()[0];
assertEquals(1, modCount.getRowCount());
assertEquals(1, modCount.asScalarLong());
}
catch(ProcCallException e) {
assertTrue(e.getMessage().contains("CONSTRAINT VIOLATION"));
}
}
finally {
env.tearDown();
}
}
/**
* Builds and validates query batch runs.
*/
private static class Batcher {
private final TestEnv m_env;
private final List<Integer> m_expectedCounts = new ArrayList<Integer>();
private final List<String> m_queries = new ArrayList<String>();
public Batcher(final TestEnv env) {
m_env = env;
}
void add(String query, Integer expectedCount) {
m_queries.add(query);
if (expectedCount != null) {
m_expectedCounts.add(expectedCount);
}
}
void addUnchecked(String query) {
m_queries.add(query);
m_expectedCounts.add(-1);
}
void run() throws Exception {
runAndCheck(false);
}
void runWithException() throws Exception {
runAndCheck(true);
}
private void runAndCheck(boolean expectException) throws Exception {
try {
VoltTable[] results = m_env.m_client.callProcedure("@AdHoc",
StringUtils.join(m_queries, "; ")).getResults();
int i = 0;
assertEquals(m_expectedCounts.size(), results.length);
for (String query : m_queries) {
int expectedCount = m_expectedCounts.get(i);
if (expectedCount >= 0) {
String s = query.toLowerCase().trim();
if (!s.isEmpty()) {
if ( s.startsWith("insert")
|| s.startsWith("update")
|| s.startsWith("delete")) {
assertEquals(String.format("%s (row count):",query),
1, results[i].getRowCount());
assertEquals(String.format("%s (result count):",query),
expectedCount, results[i].asScalarLong());
} else {
if (expectedCount != results[i].getRowCount()) {
System.out.println("Mismatched result from statement " + i + " expecting " + expectedCount + " rows and getting:\n" + results[i]);
}
assertEquals(String.format("%s (row count):",query),
expectedCount, results[i].getRowCount());
}
i++;
}
}
}
}
catch(ProcCallException e) {
assertTrue("Unexpected exception for batch: " + e.getMessage(), expectException);
}
finally {
m_queries.clear();
m_expectedCounts.clear();
}
}
}
/**
* Test environment with configured schema and server.
*/
public static class TestEnv {
final VoltProjectBuilder m_builder;
LocalCluster m_cluster;
Client m_client = null;
TestEnv(String pathToCatalog, String pathToDeployment,
int siteCount, int hostCount, int kFactor) {
// hack for no k-safety in community version
if (!MiscUtils.isPro()) {
kFactor = 0;
}
m_builder = new VoltProjectBuilder();
//Increase query tmeout as long literal queries taking long time.
m_builder.setQueryTimeout(60000);
try {
m_builder.addLiteralSchema("create table BLAH (" +
"IVAL bigint default 0 not null, " +
"TVAL timestamp default null," +
"DVAL decimal default null," +
"PRIMARY KEY(IVAL));\n" +
"PARTITION TABLE BLAH ON COLUMN IVAL;\n" +
"\n" +
"CREATE TABLE AAA (A1 VARCHAR(2), A2 VARCHAR(2), A3 VARCHAR(2));\n" +
"CREATE TABLE BBB (B1 VARCHAR(2), B2 VARCHAR(2), B3 VARCHAR(2) NOT NULL UNIQUE);\n" +
"CREATE TABLE CCC (C1 VARCHAR(2), C2 VARCHAR(2), C3 VARCHAR(2));\n" +
"\n" +
"CREATE TABLE CHAR_TEST (COL1 VARCHAR(254));\n" +
"CREATE TABLE INT_TEST (COL1 INTEGER);\n" +
"CREATE TABLE SMALL_TEST (COL1 SMALLINT);\n" +
"CREATE TABLE REAL_TEST (REF VARCHAR(1),COL1 REAL);\n" +
"CREATE TABLE REAL3_TEST (COL1 REAL,COL2 REAL,COL3 REAL);\n" +
"CREATE TABLE DOUB_TEST (REF VARCHAR(1),COL1 FLOAT);\n" +
"CREATE TABLE DOUB3_TEST (COL1 FLOAT,COL2 FLOAT\n" +
" PRECISION,COL3 FLOAT);\n" +
"\n" +
"-- Users may provide an explicit precision for FLOAT_TEST.COL1\n" +
"\n" +
"CREATE TABLE FLOAT_TEST (REF VARCHAR(1),COL1 FLOAT);\n" +
"\n" +
"CREATE TABLE INDEXLIMIT(COL1 VARCHAR(2), COL2 VARCHAR(2),\n" +
" COL3 VARCHAR(2), COL4 VARCHAR(2), COL5 VARCHAR(2),\n" +
" COL6 VARCHAR(2), COL7 VARCHAR(2));\n" +
"\n" +
"CREATE TABLE WIDETABLE (WIDE VARCHAR(118));\n" +
"CREATE TABLE WIDETAB (WIDE1 VARCHAR(38), WIDE2 VARCHAR(38), WIDE3 VARCHAR(38));\n" +
"\n" +
"CREATE TABLE TEST_TRUNC (TEST_STRING VARCHAR (6));\n" +
"\n" +
"CREATE TABLE WARNING(TESTCHAR VARCHAR(6), TESTINT INTEGER);\n" +
"\n" +
"CREATE TABLE TV (dec3 DECIMAL(3), dec1514 DECIMAL(15,14),\n" +
" dec150 DECIMAL(15,0), dec1515 DECIMAL(15,15));\n" +
"\n" +
"CREATE TABLE TU (smint SMALLINT, dec1514 DECIMAL(15,14),\n" +
" integr INTEGER, dec1515 DECIMAL(15,15));\n" +
"\n" +
"CREATE TABLE STAFF\n" +
" (EMPNUM VARCHAR(3) NOT NULL UNIQUE,\n" +
" EMPNAME VARCHAR(20),\n" +
" GRADE DECIMAL(4),\n" +
" CITY VARCHAR(15));\n" +
"\n" +
"CREATE TABLE PROJ\n" +
" (PNUM VARCHAR(3) NOT NULL UNIQUE,\n" +
" PNAME VARCHAR(20),\n" +
" PTYPE VARCHAR(6),\n" +
" BUDGET DECIMAL(9),\n" +
" CITY VARCHAR(15));\n" +
"\n" +
"CREATE TABLE WORKS\n" +
" (EMPNUM VARCHAR(3) NOT NULL,\n" +
" PNUM VARCHAR(3) NOT NULL,\n" +
" HOURS DECIMAL(5),\n" +
" UNIQUE(EMPNUM,PNUM));\n" +
"\n" +
"CREATE TABLE INTS\n" +
" (INT1 SMALLINT NOT NULL,\n" +
" INT2 SMALLINT NOT NULL);\n" +
"CREATE TABLE VOTES\n" +
" (PHONE_NUMBER BIGINT NOT NULL,\n" +
" STATE VARCHAR(2) NOT NULL,\n" +
" CONTESTANT_NUMBER INTEGER NOT NULL);\n" +
"\n" +
"CREATE PROCEDURE TestProcedure AS INSERT INTO AAA VALUES(?,?,?);\n" +
"CREATE PROCEDURE Insert AS INSERT into BLAH values (?, ?, ?);\n" +
"CREATE PROCEDURE InsertWithDate AS \n" +
" INSERT INTO BLAH VALUES (974599638818488300, '2011-06-24 10:30:26.002', 5);\n" +
"\n" +
"CREATE TABLE TS_CONSTRAINT_EXCEPTION\n" +
" (TS TIMESTAMP UNIQUE NOT NULL,\n" +
" COL1 VARCHAR(2048)); \n" +
"");
// add more partitioned and replicated tables, PARTED[1-3] and REPED[1-2]
AdHocQueryTester.setUpSchema(m_builder, pathToCatalog, pathToDeployment);
}
catch (Exception e) {
e.printStackTrace();
fail("Failed to set up schema");
}
m_cluster = new LocalCluster(pathToCatalog, siteCount, hostCount, kFactor,
BackendTarget.NATIVE_EE_JNI,
LocalCluster.FailureState.ALL_RUNNING,
m_debug);
m_cluster.setHasLocalServer(true);
boolean success = m_cluster.compile(m_builder);
assert(success);
try {
MiscUtils.copyFile(m_builder.getPathToDeployment(), pathToDeployment);
}
catch (Exception e) {
fail(String.format("Failed to copy \"%s\" to \"%s\"", m_builder.getPathToDeployment(), pathToDeployment));
}
}
void setUp() {
m_cluster.startUp();
try {
// do the test
m_client = ClientFactory.createClient();
m_client.createConnection("localhost", m_cluster.port(0));
}
catch (UnknownHostException e) {
e.printStackTrace();
fail(String.format("Failed to connect to localhost:%d", m_cluster.port(0)));
}
catch (IOException e) {
e.printStackTrace();
fail(String.format("Failed to connect to localhost:%d", m_cluster.port(0)));
}
}
void tearDown() {
if (m_client != null) {
try {
m_client.close();
} catch (InterruptedException e) {
e.printStackTrace();
fail("Failed to close client");
}
}
m_client = null;
if (m_cluster != null) {
try {
m_cluster.shutDown();
} catch (InterruptedException e) {
e.printStackTrace();
fail("Failed to shut down cluster");
}
}
m_cluster = null;
// no clue how helpful this is
System.gc();
}
boolean isValgrind() {
if (m_cluster != null)
return m_cluster.isValgrind();
return true;
}
}
}
|
package org.caleydo.view.domino.internal.dnd;
import gleem.linalg.Vec2f;
import org.caleydo.core.view.opengl.layout2.GLElement;
import org.caleydo.core.view.opengl.layout2.dnd.IUIDragInfo;
import org.caleydo.view.domino.internal.ui.prototype.INode;
/**
* @author Samuel Gratzl
*
*/
public class NodeDragInfo implements IUIDragInfo {
private final INode node;
private final Vec2f mousePos;
private Vec2f offset = new Vec2f(0, 0);
public NodeDragInfo(INode node, Vec2f mousePos) {
this.node = node;
this.mousePos = mousePos;
}
/**
* @param offset
* setter, see {@link offset}
*/
public void setOffset(Vec2f offset) {
this.offset = offset;
}
/**
* @return the offset, see {@link #offset}
*/
public Vec2f getOffset() {
return offset;
}
@Override
public String getLabel() {
return node.getLabel();
}
/**
* @return the offset, see {@link #mousePos}
*/
public Vec2f getMousePos() {
return mousePos;
}
@Override
public GLElement createUI() {
// DndNodeElement elem = new DndNodeElement(node);
// elem.setLocation(-offset.x(), -offset.y());
// elem.setVisibility(EVisibility.VISIBLE);
return null;
}
/**
* @return the node, see {@link #node}
*/
public INode getNode() {
return node;
}
}
|
package org.ccci.gto.android.common.api;
import static java.net.HttpURLConnection.HTTP_OK;
import static java.net.HttpURLConnection.HTTP_UNAUTHORIZED;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Build;
import android.util.Pair;
import org.ccci.gto.android.common.util.IOUtils;
import org.ccci.gto.android.common.util.UriUtils;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import me.thekey.android.TheKey;
import me.thekey.android.TheKeySocketException;
public abstract class AbstractGtoSmxApi {
private static final String PREF_SESSIONID = "session_id";
private static final String PARAM_APPVERSION = "_appVersion";
private static final int DEFAULT_ATTEMPTS = 3;
private static final Object LOCK_SESSION = new Object();
private final Executor asyncExecutor;
private final Context mContext;
private final TheKey mTheKey;
private final String prefFile;
private final String guid;
private final Uri apiUri;
private final String appVersion;
private boolean includeAppVersion = false;
private boolean allowGuest = false;
protected AbstractGtoSmxApi(final Context context, final TheKey thekey, final String prefFile,
final int apiUriResource) {
this(context, thekey, prefFile, apiUriResource, null);
}
protected AbstractGtoSmxApi(final Context context, final TheKey thekey, final String prefFile,
final int apiUriResource, final String guid) {
this(context, thekey, prefFile, context.getString(apiUriResource), guid);
}
protected AbstractGtoSmxApi(final Context context, final TheKey thekey, final String prefFile,
final String apiUri) {
this(context, thekey, prefFile, apiUri, null);
}
protected AbstractGtoSmxApi(final Context context, final TheKey thekey, final String prefFile,
final String apiUri, final String guid) {
this(context, thekey, prefFile, Uri.parse(apiUri.endsWith("/") ? apiUri : apiUri + "/"), guid);
}
protected AbstractGtoSmxApi(final Context context, final TheKey thekey, final String prefFile, final Uri apiUri,
final String guid) {
mContext = context;
mTheKey = thekey;
this.prefFile = prefFile;
this.guid = guid;
this.apiUri = apiUri;
this.asyncExecutor = Executors.newFixedThreadPool(1);
if (this.asyncExecutor instanceof ThreadPoolExecutor) {
((ThreadPoolExecutor) this.asyncExecutor).setKeepAliveTime(30, TimeUnit.SECONDS);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
((ThreadPoolExecutor) this.asyncExecutor).allowCoreThreadTimeOut(true);
}
}
// generate the app version string
final StringBuilder sb = new StringBuilder();
try {
sb.append(context.getPackageName());
sb.append("/");
sb.append(context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName);
} catch (final Exception e) {
// this isn't critical so suppress all exceptions
}
this.appVersion = sb.toString();
}
public void setIncludeAppVersion(final boolean includeAppVersion) {
this.includeAppVersion = includeAppVersion;
}
public void setAllowGuest(final boolean allowGuest) {
this.allowGuest = allowGuest;
}
private SharedPreferences getPrefs() {
return mContext.getSharedPreferences(this.prefFile, Context.MODE_PRIVATE);
}
private String getActiveGuid() {
String guid = this.guid;
if (guid == null) {
guid = mTheKey.getGuid();
if (guid == null && this.allowGuest) {
guid = "GUEST";
}
}
return guid;
}
private Session getSession(final String guid) {
assert guid != null;
// look up the session
final String name = PREF_SESSIONID + guid;
final SharedPreferences prefs = this.getPrefs();
synchronized (LOCK_SESSION) {
final Session session = new Session(guid, prefs.getString(name, null));
return session.id != null ? session : null;
}
}
@TargetApi(Build.VERSION_CODES.GINGERBREAD)
private void storeSession(final Session session) {
assert session != null;
final String name = PREF_SESSIONID + session.guid;
final SharedPreferences.Editor prefs = this.getPrefs().edit();
prefs.putString(name, session.id);
synchronized (LOCK_SESSION) {
// store updates
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
prefs.apply();
} else {
prefs.commit();
}
}
}
@TargetApi(Build.VERSION_CODES.GINGERBREAD)
private void removeSession(final Session session) {
assert session != null;
final String name = PREF_SESSIONID + session.guid;
final SharedPreferences.Editor prefs = this.getPrefs().edit();
prefs.remove(name);
synchronized (LOCK_SESSION) {
// store updates
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
prefs.apply();
} else {
prefs.commit();
}
}
}
private Session establishSession(final String guid) throws ApiSocketException {
assert guid != null;
// get the service to retrieve a ticket for
final String service = this.getService();
try {
// get a ticket for the specified service
final Pair<String, TheKey.Attributes> ticket = mTheKey.getTicketAndAttributes(service);
// short-circuit if we don't have a valid ticket
if (ticket == null || !guid.equals(ticket.second.getGuid())) {
return null;
}
// login to the hub
final Session session = new Session(ticket.second.getGuid(), this.login(ticket.first));
this.storeSession(session);
// return the newly established session
return session.id != null ? session : null;
} catch (final TheKeySocketException e) {
throw new ApiSocketException(e);
}
}
@Deprecated
protected final HttpURLConnection apiGetRequest(final String path)
throws ApiSocketException, InvalidSessionApiException {
return this.sendRequest(new Request(path));
}
@Deprecated
protected final HttpURLConnection apiGetRequest(final boolean useSession, final String path)
throws ApiSocketException, InvalidSessionApiException {
final Request request = new Request(path);
request.useSession = useSession;
return this.sendRequest(request);
}
@Deprecated
protected final HttpURLConnection apiGetRequest(final String path, final Collection<Pair<String, String>> params,
final boolean replaceParams)
throws ApiSocketException, InvalidSessionApiException {
final Request request = new Request(path);
request.params.addAll(params);
request.replaceParams = replaceParams;
return this.sendRequest(request);
}
@Deprecated
protected final HttpURLConnection apiGetRequest(final boolean useSession, final String path,
final Collection<Pair<String, String>> params,
final boolean replaceParams)
throws ApiSocketException, InvalidSessionApiException {
final Request request = new Request(path);
request.useSession = useSession;
request.params.addAll(params);
request.replaceParams = replaceParams;
return this.sendRequest(request);
}
protected final HttpURLConnection sendRequest(final Request request)
throws ApiSocketException, InvalidSessionApiException {
return this.sendRequest(request, DEFAULT_ATTEMPTS);
}
protected final HttpURLConnection sendRequest(final Request request, final int attempts)
throws ApiSocketException, InvalidSessionApiException {
try {
try {
// build the request uri
final Uri.Builder uri = this.apiUri.buildUpon();
final String guid = getActiveGuid();
Session session = null;
if (request.useSession) {
// short-circuit if we will be unable to get a valid session
if (guid == null) {
throw new InvalidSessionApiException();
}
// get the session, establish a session if one doesn't exist or if we have a stale session
synchronized (LOCK_SESSION) {
session = this.getSession(guid);
if (session == null) {
session = this.establishSession(guid);
}
}
// throw an InvalidSessionApiException if we don't have a valid session
if (session == null) {
throw new InvalidSessionApiException();
}
// use the current sessionId in the url
uri.appendPath(session.id);
}
uri.appendEncodedPath(request.path);
if(this.includeAppVersion) {
uri.appendQueryParameter(PARAM_APPVERSION, this.appVersion);
}
if (request.params.size() > 0) {
if (request.replaceParams) {
final List<String> keys = new ArrayList<String>();
for (final Pair<String, String> param : request.params) {
keys.add(param.first);
}
UriUtils.removeQueryParams(uri, keys.toArray(new String[keys.size()]));
}
for (final Pair<String, String> param : request.params) {
uri.appendQueryParameter(param.first, param.second);
}
}
// build base request object
final HttpURLConnection conn = (HttpURLConnection) new URL(uri.build().toString()).openConnection();
conn.setRequestMethod(request.method);
if (request.contentType != null) {
conn.addRequestProperty("Content-Type", request.contentType);
}
conn.setInstanceFollowRedirects(false);
// POST/PUT requests
if ("POST".equals(request.method) || "PUT".equals(request.method)) {
conn.setDoOutput(true);
final byte[] data = request.content != null ? request.content : new byte[0];
conn.setFixedLengthStreamingMode(data.length);
conn.setUseCaches(false);
OutputStream out = null;
try {
out = conn.getOutputStream();
out.write(data);
} finally {
if (out != null) {
out.close();
}
}
}
// no need to explicitly execute, accessing the response triggers the execute
// check for an expired session
if (request.useSession && conn.getResponseCode() == HTTP_UNAUTHORIZED) {
// determine the type of auth requested
String auth = conn.getHeaderField("WWW-Authenticate");
if (auth != null) {
auth = auth.trim();
int i = auth.indexOf(" ");
if (i != -1) {
auth = auth.substring(0, i);
}
auth = auth.toUpperCase(Locale.US);
} else {
// there isn't an auth header, so assume it is the CAS
// scheme
auth = "CAS";
}
// the 401 is requesting CAS auth, assume session is invalid
if ("CAS".equals(auth)) {
// reset the session
synchronized (LOCK_SESSION) {
// only reset if this is still the same session
assert session != null;
final Session current = this.getSession(guid);
if (current != null && session.id.equals(current.id)) {
this.removeSession(session);
}
}
// throw an invalid session exception
throw new InvalidSessionApiException();
}
}
// return the connection for method specific handling
return conn;
} catch (final MalformedURLException e) {
throw new RuntimeException("unexpected exception", e);
} catch (final IOException e) {
throw new ApiSocketException(e);
}
} catch (final InvalidSessionApiException e) {
// retry request on invalid session exceptions
if (attempts > 0) {
return this.sendRequest(request, attempts - 1);
}
// propagate the exception
throw e;
} catch (final ApiSocketException e) {
// retry request on socket exceptions (maybe spotty internet)
if (attempts > 0) {
return this.sendRequest(request, attempts - 1);
}
// propagate the exception
throw e;
}
}
public String getService() throws ApiSocketException {
final Request request = new Request("auth/service");
request.useSession = false;
HttpURLConnection conn = null;
try {
conn = this.sendRequest(request);
if (conn != null && conn.getResponseCode() == HTTP_OK) {
return IOUtils.readString(conn.getInputStream());
}
} catch (final InvalidSessionApiException e) {
throw new RuntimeException("unexpected exception", e);
} catch (final IOException e) {
throw new ApiSocketException(e);
} finally {
IOUtils.closeQuietly(conn);
}
return null;
}
public String login(final String ticket) throws ApiSocketException {
// don't attempt to login if we don't have a ticket
if (ticket == null) {
return null;
}
// build request
final Request request = new Request("auth/login");
request.useSession = false;
request.method = "POST";
try {
request.setContent("application/x-www-form-urlencoded",
("ticket=" + URLEncoder.encode(ticket, "UTF-8")).getBytes("UTF-8"));
} catch (final UnsupportedEncodingException e) {
throw new RuntimeException("unexpected error, UTF-8 encoding doesn't exist?", e);
}
// issue login request
HttpURLConnection conn = null;
try {
conn = this.sendRequest(request);
// was this a valid login
if (conn != null && conn.getResponseCode() == HTTP_OK) {
// the sessionId is returned as the body of the response
return IOUtils.readString(conn.getInputStream());
}
} catch (final InvalidSessionApiException ignored) {
} catch (final MalformedURLException e) {
throw new RuntimeException("unexpected exception", e);
} catch (final IOException e) {
throw new ApiSocketException(e);
} finally {
IOUtils.closeQuietly(conn);
}
return null;
}
public final void async(final Runnable task) {
this.asyncExecutor.execute(task);
}
private static final class Session {
private final String id;
private final String guid;
private Session(final String guid, final String id) {
assert guid != null;
this.guid = guid;
this.id = id;
}
}
/**
* class that represents a request being sent to the api
*/
protected static class Request {
public String method = "GET";
// uri attributes
public boolean useSession = true;
private final String path;
public final Collection<Pair<String, String>> params = new ArrayList<Pair<String, String>>();
public boolean replaceParams = false;
// POST/PUT data
private String contentType = null;
private byte[] content = null;
public Request(final String path) {
assert path != null : "request path cannot be null";
this.path = path;
}
protected void setContent(final String type, final byte[] data) {
this.contentType = type;
this.content = data;
}
protected void setContent(final String type, final String data) {
try {
this.setContent(type, data != null ? data.getBytes("UTF-8") : null);
} catch (final UnsupportedEncodingException e) {
throw new RuntimeException("unexpected error, UTF-8 encoding isn't present", e);
}
}
}
}
|
package org.dannil.httpdownloader.utility;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.ResourceBundle;
/**
* Class which handles operations on language bundles
*
* @author Daniel
*
*/
public final class LanguageUtility {
private static final Locale DEFAULT_LOCALE;
private static final List<Locale> availableLanguages;
static {
DEFAULT_LOCALE = new Locale("en", "US");
availableLanguages = new LinkedList<Locale>();
availableLanguages.add(new Locale("en", "US"));
availableLanguages.add(new Locale("sv", "SE"));
}
/**
* Private constructor to make the class a singleton.
*/
private LanguageUtility() {
throw new AssertionError();
}
/**
* Returns a bundle with the language which matches the users current display language.
*
* @return ResourceBundle with default language
*/
public static final ResourceBundle getLanguageBundle() {
return getLanguageBundle(Locale.getDefault());
}
/**
* Returns a bundle with the language which matches the inputed locale.
* If the language file doesn't exist, return a standard language (enUS).
*
* @param language
* - The language to load
*
* @return ResourceBundle with inputed locale
*/
public static final ResourceBundle getLanguageBundle(final Locale language) {
if (availableLanguages.contains(language)) {
return ResourceBundle.getBundle(PathUtility.LANGUAGE_PATH, language);
}
return ResourceBundle.getBundle(PathUtility.LANGUAGE_PATH, DEFAULT_LOCALE);
}
/**
* Convert a locale to its IETF BCP 47 string representation.
*
* @param language
* - The locale to be converted
*
* @return A String of the locale in IETF BCP 47 language tag representation
*/
public static final String toString(Locale language) {
return language.toLanguageTag();
}
/**
* Convert a language string in IETF BCP 47 representation to the correct corresponding locale.
*
* @param language
* - The string to be converted
*
* @return A Locale converted from the language string
*/
public static final Locale toLocale(String language) {
return Locale.forLanguageTag(language);
}
}
|
package org.testory;
import static java.util.Objects.deepEquals;
import static org.testory.TestoryAssertionError.assertionError;
import static org.testory.TestoryException.check;
import static org.testory.common.CharSequences.join;
import static org.testory.common.Classes.canReturn;
import static org.testory.common.Classes.canThrow;
import static org.testory.common.Classes.defaultValue;
import static org.testory.common.Classes.hasMethod;
import static org.testory.common.Classes.isFinal;
import static org.testory.common.Classes.isStatic;
import static org.testory.common.Classes.setAccessible;
import static org.testory.common.Effect.returned;
import static org.testory.common.Effect.returnedVoid;
import static org.testory.common.Effect.thrown;
import static org.testory.common.Matchers.asMatcher;
import static org.testory.common.Matchers.isMatcher;
import static org.testory.common.Objects.print;
import static org.testory.common.Samples.isSampleable;
import static org.testory.common.Samples.sample;
import static org.testory.common.Throwables.gently;
import static org.testory.common.Throwables.printStackTrace;
import static org.testory.plumbing.Anyvocation.anyvocation;
import static org.testory.plumbing.Anyvocation.matcherize;
import static org.testory.plumbing.Anyvocation.repair;
import static org.testory.plumbing.Calling.calling;
import static org.testory.plumbing.Calling.callings;
import static org.testory.plumbing.Capturing.capturedAnys;
import static org.testory.plumbing.Capturing.consumeAnys;
import static org.testory.plumbing.Capturing.CapturingAny.capturingAny;
import static org.testory.plumbing.History.add;
import static org.testory.plumbing.History.history;
import static org.testory.plumbing.Inspecting.findLastInspecting;
import static org.testory.plumbing.Inspecting.inspecting;
import static org.testory.plumbing.Mocking.mocking;
import static org.testory.plumbing.Mocking.nameMock;
import static org.testory.plumbing.Purging.mark;
import static org.testory.plumbing.Purging.purge;
import static org.testory.plumbing.Stubbing.findStubbing;
import static org.testory.plumbing.Stubbing.stubbing;
import static org.testory.plumbing.VerifyingInOrder.verifyInOrder;
import static org.testory.proxy.Invocation.invocation;
import static org.testory.proxy.Invocations.invoke;
import static org.testory.proxy.Proxies.isProxiable;
import static org.testory.proxy.Proxies.proxy;
import static org.testory.proxy.Typing.typing;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import org.testory.common.Any;
import org.testory.common.DiagnosticMatcher;
import org.testory.common.Effect;
import org.testory.common.Effect.Returned;
import org.testory.common.Effect.ReturnedObject;
import org.testory.common.Effect.Thrown;
import org.testory.common.Matcher;
import org.testory.common.Nullable;
import org.testory.common.Optional;
import org.testory.plumbing.Anyvocation;
import org.testory.plumbing.Calling;
import org.testory.plumbing.History;
import org.testory.plumbing.Inspecting;
import org.testory.plumbing.Mocking;
import org.testory.plumbing.Stubbing;
import org.testory.proxy.Handler;
import org.testory.proxy.Invocation;
import org.testory.proxy.InvocationMatcher;
import org.testory.proxy.Typing;
public class Testory {
private static ThreadLocal<History> localHistory = new ThreadLocal<History>() {
protected History initialValue() {
return history(new ArrayList<Object>());
}
};
private static History getHistory() {
return localHistory.get();
}
private static void setHistory(History history) {
localHistory.set(history);
}
public static void givenTest(Object test) {
setHistory(purge(mark(getHistory())));
try {
for (final Field field : test.getClass().getDeclaredFields()) {
if (!isStatic(field) && !isFinal(field)) {
setAccessible(field);
if (deepEquals(defaultValue(field.getType()), field.get(test))) {
check(canMockOrSample(field.getType()), "cannot inject field: " + field.getName());
field.set(test, mockOrSample(field.getType(), field.getName()));
}
}
}
} catch (ReflectiveOperationException e) {
throw new Error(e);
}
}
private static boolean canMockOrSample(Class<?> type) {
return isProxiable(type) || type.isArray() || isSampleable(type);
}
private static Object mockOrSample(Class<?> type, String name) {
if (isProxiable(type)) {
Object mock = rawMock(type);
log(mocking(mock, name));
stubNice(mock);
stubObject(mock, name);
return mock;
} else if (type.isArray()) {
Class<?> componentType = type.getComponentType();
Object array = Array.newInstance(componentType, 1);
Array.set(array, 0, mockOrSample(componentType, name + "[0]"));
return array;
} else if (isSampleable(type)) {
return sample(type, name);
} else {
throw new IllegalArgumentException("cannot mock or sample " + type.getName() + " " + name);
}
}
@Deprecated
public static Closure given(Closure closure) {
throw new TestoryException("\n\tgiven(Closure) is confusing, do not use it\n");
}
public static <T> T given(T object) {
return object;
}
public static void given(boolean primitive) {}
public static void given(double primitive) {}
public static <T> T givenTry(T object) {
check(object != null);
check(isProxiable(object.getClass()));
Handler handler = new Handler() {
public Object handle(Invocation invocation) {
try {
return invoke(invocation);
} catch (Throwable e) {
return null;
}
}
};
return proxyWrapping(object, handler);
}
public static void givenTimes(int number, Closure closure) {
check(number >= 0);
check(closure != null);
for (int i = 0; i < number; i++) {
try {
closure.invoke();
} catch (Throwable throwable) {
throw gently(throwable);
}
}
}
public static <T> T givenTimes(final int number, T object) {
check(number >= 0);
check(object != null);
check(isProxiable(object.getClass()));
Handler handler = new Handler() {
public Object handle(Invocation invocation) throws Throwable {
for (int i = 0; i < number; i++) {
invoke(invocation);
}
return null;
}
};
return proxyWrapping(object, handler);
}
public static <T> T mock(Class<T> type) {
check(type != null);
check(isProxiable(type));
final T mock = rawMock(type);
String name = nameMock(mock, getHistory());
log(mocking(mock, name));
stubNice(mock);
stubObject(mock, name);
return mock;
}
public static <T> T spy(T real) {
check(real != null);
Class<T> type = (Class<T>) real.getClass();
T mock = mock(type);
given(willSpy(real), onInstance(mock));
return mock;
}
private static <T> T rawMock(Class<T> type) {
check(isProxiable(type));
Typing typing = type.isInterface()
? typing(Object.class, new HashSet<Class<?>>(Arrays.asList(type)))
: typing(type, new HashSet<Class<?>>());
Handler handler = new Handler() {
public Object handle(Invocation invocation) throws Throwable {
check(isMock(invocation.instance));
check(isStubbed(invocation));
log(calling(invocation));
Stubbing stubbing = findStubbing(invocation, getHistory()).get();
return stubbing.handler.handle(invocation);
}
};
return (T) proxy(typing, compatible(handler));
}
private static Handler compatible(final Handler handler) {
return new Handler() {
public Object handle(Invocation invocation) throws Throwable {
Object returned;
try {
returned = handler.handle(invocation);
} catch (Throwable throwable) {
check(canThrow(throwable, invocation.method));
throw throwable;
}
check(canReturn(returned, invocation.method) || canReturnVoid(returned, invocation.method));
return returned;
}
private boolean canReturnVoid(Object returned, Method method) {
return method.getReturnType() == void.class && returned == null;
}
};
}
private static void stubNice(Object mock) {
given(new Handler() {
public Object handle(Invocation invocation) {
return defaultValue(invocation.method.getReturnType());
}
}, onInstance(mock));
}
private static void stubObject(final Object mock, final String name) {
final Object implementation = new Object() {
public String toString() {
return name;
}
public boolean equals(Object obj) {
return mock == obj;
}
public int hashCode() {
return name.hashCode();
}
};
given(willTarget(implementation), new InvocationMatcher() {
public boolean matches(Invocation invocation) {
return mock == invocation.instance
&& hasMethod(invocation.method.getName(), invocation.method.getParameterTypes(),
implementation.getClass());
}
});
}
public static <T> T given(final Handler will, T mock) {
check(will != null);
check(mock != null);
check(isMock(mock));
Handler handler = new Handler() {
public Object handle(Invocation invocation) {
log(stubbing(capture(invocation), will));
return null;
}
};
return proxyWrapping(mock, handler);
}
public static void given(Handler will, InvocationMatcher invocationMatcher) {
check(will != null);
check(invocationMatcher != null);
log(stubbing(invocationMatcher, will));
}
public static Handler willReturn(@Nullable final Object object) {
return new Handler() {
public Object handle(Invocation invocation) {
return object;
}
};
}
public static Handler willThrow(final Throwable throwable) {
check(throwable != null);
return new Handler() {
public Object handle(Invocation invocation) throws Throwable {
throw throwable.fillInStackTrace();
}
};
}
public static Handler willRethrow(final Throwable throwable) {
check(throwable != null);
return new Handler() {
public Object handle(Invocation invocation) throws Throwable {
throw throwable;
}
};
}
public static Handler willSpy(final Object real) {
check(real != null);
return new Handler() {
public Object handle(Invocation invocation) throws Throwable {
return invoke(invocation(invocation.method, real, invocation.arguments));
}
};
}
private static Handler willTarget(final Object target) {
return new Handler() {
public Object handle(Invocation invocation) throws Throwable {
String methodName = invocation.method.getName();
Class<?>[] parameters = invocation.method.getParameterTypes();
Method method = target.getClass().getDeclaredMethod(methodName, parameters);
return invoke(invocation(method, target, invocation.arguments));
}
};
}
public static <T> T any(Class<T> type) {
check(type != null);
return anyImpl(Any.any(type));
}
public static <T> T any(Class<T> type, Object matcher) {
check(matcher != null);
check(isMatcher(matcher));
return anyImpl(Any.any(type, asMatcher(matcher)));
}
public static boolean a(boolean value) {
return anyImpl(Any.a(value));
}
public static char a(char value) {
return anyImpl(Any.a(value));
}
public static byte a(byte value) {
return anyImpl(Any.a(value));
}
public static short a(short value) {
return anyImpl(Any.a(value));
}
public static int a(int value) {
return anyImpl(Any.a(value));
}
public static long a(long value) {
return anyImpl(Any.a(value));
}
public static float a(float value) {
return anyImpl(Any.a(value));
}
public static double a(double value) {
return anyImpl(Any.a(value));
}
public static <T> T a(T value) {
check(value != null);
return anyImpl(Any.a(value));
}
public static void the(boolean value) {
check(false);
}
public static void the(double value) {
check(false);
}
public static <T> T the(T instance) {
check(instance != null);
return anyImpl(Any.the(instance));
}
private static <T> T anyImpl(Any any) {
log(capturingAny(any));
return (T) any.token;
}
public static InvocationMatcher onInstance(final Object mock) {
check(mock != null);
check(isMock(mock));
return new InvocationMatcher() {
public boolean matches(Invocation invocation) {
return invocation.instance == mock;
}
public String toString() {
return "onInstance(" + mock + ")";
}
};
}
public static InvocationMatcher onReturn(final Class<?> type) {
check(type != null);
return new InvocationMatcher() {
public boolean matches(Invocation invocation) {
return type == invocation.method.getReturnType();
}
public String toString() {
return "onReturn(" + type.getName() + ")";
}
};
}
public static InvocationMatcher onRequest(final Class<?> type, final Object... arguments) {
check(type != null);
check(arguments != null);
return new InvocationMatcher() {
public boolean matches(Invocation invocation) {
return type == invocation.method.getReturnType()
&& deepEquals(arguments, invocation.arguments.toArray());
}
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("onRequest(").append(type.getName());
for (Object argument : arguments) {
builder.append(", ").append(argument);
}
builder.append(")");
return builder.toString();
}
};
}
public static <T> T when(T object) {
setHistory(mark(purge(getHistory())));
log(inspecting(returned(object)));
boolean isProxiable = object != null && isProxiable(object.getClass());
if (isProxiable) {
Handler handler = new Handler() {
public Object handle(Invocation invocation) {
log(inspecting(effectOfInvoke(invocation)));
setHistory(mark(getHistory()));
return null;
}
};
return proxyWrapping(object, handler);
} else {
return null;
}
}
public static void when(Closure closure) {
check(closure != null);
log(inspecting(effectOfInvoke(closure)));
setHistory(mark(purge(getHistory())));
}
private static Effect effectOfInvoke(Closure closure) {
Object object;
try {
object = closure.invoke();
} catch (Throwable throwable) {
return thrown(throwable);
}
return returned(object);
}
private static Effect effectOfInvoke(Invocation invocation) {
Object object;
try {
object = invoke(invocation);
} catch (Throwable throwable) {
return thrown(throwable);
}
return invocation.method.getReturnType() == void.class
? returnedVoid()
: returned(object);
}
public static void when(boolean value) {
when((Object) value);
}
public static void when(char value) {
when((Object) value);
}
public static void when(byte value) {
when((Object) value);
}
public static void when(short value) {
when((Object) value);
}
public static void when(int value) {
when((Object) value);
}
public static void when(long value) {
when((Object) value);
}
public static void when(float value) {
when((Object) value);
}
public static void when(double value) {
when((Object) value);
}
public static void thenReturned(@Nullable Object objectOrMatcher) {
Effect effect = getLastEffect();
boolean expected = effect instanceof ReturnedObject
&& (deepEquals(objectOrMatcher, ((ReturnedObject) effect).object) || objectOrMatcher != null
&& isMatcher(objectOrMatcher)
&& asMatcher(objectOrMatcher).matches(((ReturnedObject) effect).object));
if (!expected) {
String diagnosis = objectOrMatcher != null && isMatcher(objectOrMatcher)
&& effect instanceof ReturnedObject
? tryFormatDiagnosis(objectOrMatcher, ((ReturnedObject) effect).object)
: "";
throw assertionError("\n"
+ formatSection("expected returned", objectOrMatcher)
+ formatBut(effect)
+ diagnosis
);
}
}
public static void thenReturned(boolean value) {
thenReturned((Object) value);
}
public static void thenReturned(char value) {
thenReturned((Object) value);
}
public static void thenReturned(byte value) {
thenReturned((Object) value);
}
public static void thenReturned(short value) {
thenReturned((Object) value);
}
public static void thenReturned(int value) {
thenReturned((Object) value);
}
public static void thenReturned(long value) {
thenReturned((Object) value);
}
public static void thenReturned(float value) {
thenReturned((Object) value);
}
public static void thenReturned(double value) {
thenReturned((Object) value);
}
public static void thenReturned() {
Effect effect = getLastEffect();
boolean expected = effect instanceof Returned;
if (!expected) {
throw assertionError("\n"
+ formatSection("expected returned", "")
+ formatBut(effect));
}
}
public static void thenThrown(Object matcher) {
check(matcher != null);
check(isMatcher(matcher));
Effect effect = getLastEffect();
boolean expected = effect instanceof Thrown
&& asMatcher(matcher).matches(((Thrown) effect).throwable);
if (!expected) {
String diagnosis = effect instanceof Thrown
? tryFormatDiagnosis(matcher, ((Thrown) effect).throwable)
: "";
throw assertionError("\n"
+ formatSection("expected thrown", matcher)
+ formatBut(effect)
+ diagnosis
);
}
}
public static void thenThrown(Throwable throwable) {
check(throwable != null);
Effect effect = getLastEffect();
boolean expected = effect instanceof Thrown
&& deepEquals(throwable, ((Thrown) effect).throwable);
if (!expected) {
throw assertionError("\n"
+ formatSection("expected thrown", throwable)
+ formatBut(effect));
}
}
public static void thenThrown(Class<? extends Throwable> type) {
check(type != null);
Effect effect = getLastEffect();
boolean expected = effect instanceof Thrown && type.isInstance(((Thrown) effect).throwable);
if (!expected) {
throw assertionError("\n"
+ formatSection("expected thrown", type.getName())
+ formatBut(effect));
}
}
public static void thenThrown() {
Effect effect = getLastEffect();
boolean expected = effect instanceof Thrown;
if (!expected) {
throw assertionError("\n"
+ formatSection("expected thrown", "")
+ formatBut(effect));
}
}
private static Effect getLastEffect() {
Optional<Inspecting> inspecting = findLastInspecting(getHistory());
check(inspecting.isPresent());
return inspecting.get().effect;
}
private static String formatBut(Effect effect) {
return effect instanceof Returned
? effect instanceof ReturnedObject
? formatSection("but returned", ((ReturnedObject) effect).object)
: formatSection("but returned", "void")
: ""
+ formatSection("but thrown", ((Thrown) effect).throwable)
+ "\n"
+ printStackTrace(((Thrown) effect).throwable);
}
public static void then(boolean condition) {
if (!condition) {
throw assertionError("\n"
+ formatSection("expected", "true")
+ formatSection("but was", "false"));
}
}
public static void then(@Nullable Object object, Object matcher) {
check(matcher != null);
check(isMatcher(matcher));
if (!asMatcher(matcher).matches(object)) {
throw assertionError("\n"
+ formatSection("expected", matcher)
+ formatSection("but was", object)
+ tryFormatDiagnosis(matcher, object))
;
}
}
public static void thenEqual(@Nullable Object object, @Nullable Object expected) {
if (!deepEquals(object, expected)) {
throw assertionError("\n"
+ formatSection("expected", expected)
+ formatSection("but was", object));
}
}
public static <T> T thenCalled(T mock) {
check(mock != null);
check(isMock(mock));
return thenCalledTimes(exactly(1), mock);
}
public static void thenCalled(InvocationMatcher invocationMatcher) {
check(invocationMatcher != null);
thenCalledTimes(exactly(1), invocationMatcher);
}
public static <T> T thenCalledTimes(int number, T mock) {
check(number >= 0);
check(mock != null);
check(isMock(mock));
return thenCalledTimes(exactly(number), mock);
}
public static void thenCalledTimes(int number, InvocationMatcher invocationMatcher) {
check(number >= 0);
check(invocationMatcher != null);
thenCalledTimes(exactly(number), invocationMatcher);
}
public static <T> T thenCalledTimes(final Object numberMatcher, T mock) {
check(numberMatcher != null);
check(isMatcher(numberMatcher));
check(mock != null);
check(isMock(mock));
Handler handler = new Handler() {
public Object handle(Invocation invocation) {
thenCalledTimes(numberMatcher, capture(invocation));
return null;
}
};
return proxyWrapping(mock, handler);
}
public static void thenCalledTimes(Object numberMatcher, InvocationMatcher invocationMatcher) {
check(numberMatcher != null);
check(isMatcher(numberMatcher));
check(invocationMatcher != null);
int numberOfCalls = 0;
History history = getHistory();
for (Calling calling : callings(history)) {
if (invocationMatcher.matches(calling.invocation)) {
numberOfCalls++;
}
}
boolean expected = asMatcher(numberMatcher).matches(numberOfCalls);
if (!expected) {
throw assertionError("\n"
+ formatSection("expected called times " + numberMatcher, invocationMatcher)
+ formatSection("but called", "times " + numberOfCalls)
+ formatCallings(history))
;
}
}
public static <T> T thenCalledInOrder(T mock) {
check(mock != null);
check(isMock(mock));
Handler handler = new Handler() {
public Object handle(Invocation invocation) {
thenCalledInOrder(capture(invocation));
return null;
}
};
return proxyWrapping(mock, handler);
}
public static void thenCalledInOrder(InvocationMatcher invocationMatcher) {
check(invocationMatcher != null);
History history = getHistory();
Optional<History> verified = verifyInOrder(invocationMatcher, history);
if (verified.isPresent()) {
setHistory(verified.get());
} else {
throw assertionError("\n"
+ formatSection("expected called in order", invocationMatcher)
+ " but not called\n"
+ formatCallings(history))
;
}
}
private static Matcher exactly(final int number) {
return new Matcher() {
public boolean matches(Object item) {
return item.equals(number);
}
public String toString() {
return "" + number;
}
};
}
public static void log(Object event) {
setHistory(add(event, getHistory()));
}
private static <T> boolean isMock(T mock) {
return Mocking.isMock(mock, getHistory());
}
private static boolean isStubbed(Invocation invocation) {
return findStubbing(invocation, getHistory()).isPresent();
}
private static String formatSection(String caption, @Nullable Object content) {
return ""
+ " " + caption + "\n"
+ " " + print(content) + "\n";
}
private static String tryFormatDiagnosis(Object matcher, Object item) {
Matcher asMatcher = asMatcher(matcher);
return asMatcher instanceof DiagnosticMatcher
? formatSection("diagnosis", ((DiagnosticMatcher) asMatcher).diagnose(item))
: "";
}
private static String formatCallings(final History history) {
log(stubbing(new InvocationMatcher() {
public boolean matches(Invocation invocation) {
return invocation.method.getName().equals("toString")
&& invocation.method.getParameterTypes().length == 0;
}
}, new Handler() {
public Object handle(Invocation invocation) {
for (Object event : history.events) {
if (event instanceof Mocking) {
Mocking mocking = (Mocking) event;
if (mocking.mock == invocation.instance) {
return mocking.name;
}
}
}
return "unknownMock";
}
}));
StringBuilder builder = new StringBuilder();
for (Object event : history.events) {
if (event instanceof Calling) {
Calling calling = (Calling) event;
Invocation invocation = calling.invocation;
builder.append(" ").append(invocation.instance).append(".")
.append(invocation.method.getName()).append("(")
.append(join(",", invocation.arguments)).append(")").append("\n");
}
}
if (builder.length() > 0) {
builder.insert(0, " actual invocations\n");
} else {
builder.insert(0, " actual invocations\n none\n");
}
setHistory(history);
return builder.toString();
}
private static <T> T proxyWrapping(final T wrapped, final Handler handler) {
Typing typing = typing(wrapped.getClass(), new HashSet<Class<?>>());
return (T) proxy(typing, new Handler() {
public Object handle(Invocation invocation) throws Throwable {
handler.handle(invocation(invocation.method, wrapped, invocation.arguments));
return defaultValue(invocation.method.getReturnType());
}
});
}
private static InvocationMatcher capture(Invocation invocation) {
List<Any> anys = capturedAnys(getHistory());
setHistory(consumeAnys(getHistory()));
Anyvocation anyvocation = anyvocation(invocation.method, invocation.instance,
invocation.arguments, anys);
check(canRepair(anyvocation));
return convert(matcherize(repair(anyvocation).get()));
}
private static boolean canRepair(Anyvocation anyvocation) {
return repair(anyvocation).isPresent();
}
private static InvocationMatcher convert(final Matcher invocationMatcher) {
return new InvocationMatcher() {
public boolean matches(Invocation invocation) {
return invocationMatcher.matches(invocation);
}
public String toString() {
return invocationMatcher.toString();
}
};
}
}
|
package org.hazlewood.connor.bottema.emailaddress;
import org.jetbrains.annotations.NotNull;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;
import static java.lang.String.format;
/**
* MY DRAGONS WILL EAT YOUR DRAGONS
* <p/>
* Regular expressions based on given list of {@link EmailAddressCriteria}. Used in both validation ({@link EmailAddressValidator}) and email data extraction
* ({@link EmailAddressParser}).
*/
final class Dragons {
/**
* Java regex pattern for 2822 "mailbox" token; Not necessarily useful, but available in case.
*/
final Pattern MAILBOX_PATTERN;
/**
* Java regex pattern for 2822 "addr-spec" token; Not necessarily useful, but available in case.
*/
final Pattern ADDR_SPEC_PATTERN;
/**
* Java regex pattern for 2822 "mailbox-list" token; Not necessarily useful, but available in case.
*/
final Pattern MAILBOX_LIST_PATTERN;
// public static final Pattern ADDRESS_LIST_PATTERN = Pattern.compile(addressList);
/**
* Java regex pattern for 2822 "address" token; Not necessarily useful, but available in case.
*/
final Pattern ADDRESS_PATTERN;
/**
* Java regex pattern for 2822 "comment" token; Not necessarily useful, but available in case.
*/
final Pattern COMMENT_PATTERN;
final Pattern QUOTED_STRING_WO_CFWS_PATTERN;
final Pattern RETURN_PATH_PATTERN;
final Pattern GROUP_PREFIX_PATTERN;
final Pattern ESCAPED_QUOTE_PATTERN;
final Pattern ESCAPED_BSLASH_PATTERN;
/**
* Very simply cache to avoid recreating dragons all the time.
*/
private static final Map<EnumSet<EmailAddressCriteria>, Dragons> cache = new HashMap<>();
/**
* @return Dragons based on criteria, cached if the criteria have been used before
*/
@SuppressWarnings("WeakerAccess")
@NotNull
protected static Dragons fromCriteria(@NotNull final EnumSet<EmailAddressCriteria> criteria) {
if (!cache.containsKey(criteria)) {
cache.put(criteria, new Dragons(criteria));
}
return cache.get(criteria);
}
/**
* Hatch dragons...
*/
@NotNull
private Dragons(@NotNull final EnumSet<EmailAddressCriteria> criteria) {
// RFC 2822 2.2.2 Structured Header Field Bodies
final String crlf = "\\r\\n";
final String wsp = "[ \\t]"; //space or tab
final String fwsp = format("(?:%s*%s)?%s+", wsp, crlf, wsp);
//RFC 2822 3.2.1 Primitive tokens
final String dquote = "\"";
//ASCII Control characters excluding white space:
final String noWsCtl = "\\x01-\\x08\\x0B\\x0C\\x0E-\\x1F\\x7F";
//all ASCII characters except CR and LF:
final String asciiText = "[\\x01-\\x09\\x0B\\x0C\\x0E-\\x7F]";
// RFC 2822 3.2.2 Quoted characters:
//single backslash followed by a text char
final String quotedPair = format("(?:\\\\%s)", asciiText);
// RFC 2822 3.2.3 CFWS specification
// note: nesting should be permitted but is not by these rules given code limitations:
// rewritten to be shorter:
//final String ctext = "[" + noWsCtl + "\\x21-\\x27\\x2A-\\x5B\\x5D-\\x7E]";
final String ctext = format("[%s!-'*-\\[\\]-~]", noWsCtl);
final String ccontent = format("%s|%s", ctext, quotedPair); // + "|" + comment;
final String comment = format("\\((?:(?:%s)?%s)*(?:%s)?\\)", fwsp, ccontent, fwsp);
final String cfws = format("(?:(?:%s)?%s)*(?:(?:(?:%s)?%s)|(?:%s))", fwsp, comment, fwsp, comment, fwsp);
//RFC 2822 3.2.4 Atom:
final String atext = format("[a-zA-Z0-9!
criteria.contains(EmailAddressCriteria.ALLOW_DOT_IN_A_TEXT) ? "." : "",
criteria.contains(EmailAddressCriteria.ALLOW_SQUARE_BRACKETS_IN_A_TEXT) ? "\\[\\]" : "");
// regular atext is same as atext but has no . or [ or ] allowed, no matter the class prefs, to prevent
// long recursions on e.g. "a.b.c.d.e.f.g.h.i.j.k.l.m.n.o.p.q.r.s.t"
final String regularAtext = "[a-zA-Z0-9!
final String atom = format("(?:%s)?%s+(?:%s)?", cfws, atext, cfws);
final String dotAtomText = format("%s+(?:\\.%s+)*", regularAtext, regularAtext);
// final String dotAtom = format("(?:%s)?%s(?:%s)?", cfws, dotAtomText, cfws);
final String capDotAtomNoCFWS = format("(?:%s)?(%s)(?:%s)?", cfws, dotAtomText, cfws);
final String capDotAtomTrailingCFWS = format("(?:%s)?(%s)(%s)?", cfws, dotAtomText, cfws);
//RFC 2822 3.2.5 Quoted strings:
//noWsCtl and the rest of ASCII except the doublequote and backslash characters:
final String qtext = format("[%s!#-\\[\\]-~]", noWsCtl);
final String localPartqtext = format("[%s%s", noWsCtl,
criteria.contains(EmailAddressCriteria.ALLOW_PARENS_IN_LOCALPART) ? "!
final String qcontent = format("(?:%s|%s)", qtext, quotedPair);
final String localPartqcontent = format("(?>%s|%s)", localPartqtext, quotedPair);
final String quotedStringWOCFWS = format("%s(?>(?:%s)?%s)*(?:%s)?%s", dquote, fwsp, qcontent, fwsp, dquote);
final String quotedString = format("(?:%s)?%s(?:%s)?", cfws, quotedStringWOCFWS, cfws);
final String localPartQuotedString = format("(?:%s)?(%s(?:(?:%s)?%s)*(?:%s)?%s)(?:%s)?",
cfws, dquote, fwsp, localPartqcontent, fwsp, dquote, cfws);
//RFC 2822 3.2.6 Miscellaneous tokens
final String word = format("(?:(?:%s)|(?:%s))", atom, quotedString);
// by 2822: phrase = 1*word / obs-phrase
// implemented here as: phrase = word (FWS word)*
// so that aaaa can't be four words, which can cause tons of recursive backtracking
//final String phrase = "(?:" + word + "+?)"; //one or more words
final String phrase = format("%s(?:(?:%s)%s)*", word, fwsp, word);
//RFC 1035 tokens for domain names:
final String letter = "[a-zA-Z]";
final String letDig = "[a-zA-Z0-9]";
final String letDigHyp = "[a-zA-Z0-9-]";
final String rfcLabel = format("%s(?:%s{0,61}%s)?", letDig, letDigHyp, letDig);
final String rfc1035DomainName = format("%s(?:\\.%s)*\\.%s{2,26}", rfcLabel, rfcLabel, letter);
//RFC 2822 3.4 Address specification
//domain text - non white space controls and the rest of ASCII chars not
// including [, ], or \:
// rewritten to save space:
//final String dtext = "[" + noWsCtl + "\\x21-\\x5A\\x5E-\\x7E]";
final String dtext = format("[%s!-Z^-~]", noWsCtl);
final String dcontent = format("%s|%s", dtext, quotedPair);
final String capDomainLiteralNoCFWS =
format("(?:%s)?(\\[(?:(?:%s)?(?:%s)+)*(?:%s)?])(?:%s)?", cfws, fwsp, dcontent, fwsp, cfws);
final String capDomainLiteralTrailingCFWS =
format("(?:%s)?(\\[(?:(?:%s)?(?:%s)+)*(?:%s)?])(%s)?", cfws, fwsp, dcontent, fwsp, cfws);
final String rfc2822Domain = format("(?:%s|%s)", capDotAtomNoCFWS, capDomainLiteralNoCFWS);
final String capCFWSRfc2822Domain = format("(?:%s|%s)", capDotAtomTrailingCFWS, capDomainLiteralTrailingCFWS);
// Les chose to implement the more-strict 1035 instead of just relying on "dot-atom"
// as would be implied by 2822 without the domain-literal token. The issue is that 2822
// allows CFWS around the local part and the domain,
// strange though that may be (and you "SHOULD NOT" put it around the @). This version
// allows the cfws before and after.
// final String domain =
// ALLOW_DOMAIN_LITERALS ? rfc2822Domain : rfc1035DomainName;
final String domain = criteria.contains(EmailAddressCriteria.ALLOW_DOMAIN_LITERALS) ? rfc2822Domain : "(?:" + cfws + ")?(" + rfc1035DomainName + ")(?:" + cfws + ")?";
final String capCFWSDomain = criteria.contains(EmailAddressCriteria.ALLOW_DOMAIN_LITERALS)
? capCFWSRfc2822Domain
: format("(?:%s)?(%s)(%s)?", cfws, rfc1035DomainName, cfws);
final String localPart = format("(%s|%s)", capDotAtomNoCFWS, localPartQuotedString);
// uniqueAddrSpec exists so we can have a duplicate tree that has a capturing group
// instead of a non-capturing group for the trailing CFWS after the domain token
// that we wouldn't want if it was inside
// an angleAddr. The matching should be otherwise identical.
final String addrSpec = format("%s@%s", localPart, domain);
final String uniqueAddrSpec = localPart + "@" + capCFWSDomain;
final String angleAddr = format("(?:%s)?<%s>(%s)?", cfws, addrSpec, cfws);
// uses a reluctant quantifier to skip ahead and make sure there's actually an
// address in there somewhere... hmmm, maybe regex in java doesn't optimize that
// case by skipping over it at the start by default? Doesn't seem to solve the
// issue of recursion on long strings like [A-Za-z], but issue was solved by
// changing phrase definition (see above):
final String nameAddr = format("(%s)??(%s)", phrase, angleAddr);
final String mailboxName = criteria.contains(EmailAddressCriteria.ALLOW_QUOTED_IDENTIFIERS)
? format("(%s)|", nameAddr) : "";
final String mailbox = format("%s(%s)", mailboxName, uniqueAddrSpec);
final String returnPath = format("(?:(?:%s)?<((?:%s)?|%s)>(?:%s)?)", cfws, cfws, addrSpec, cfws);
final String mailboxList = format("(?:(?:%s)(?:,(?:%s))*)", mailbox, mailbox);
final String groupPostfix = format("(?:%s|(?:%s))?;(?:%s)?", cfws, mailboxList, cfws);
final String groupPrefix = phrase + ":";
final String group = groupPrefix + groupPostfix;
final String address = format("(?:(?:%s)|(?:%s))", mailbox, group);
// this string is too long, so must do it FSM style in isValidAddressList:
// private static final String addressList = address + "(?:," + address + ")*";
// That wasn't so hard...
// Group IDs:
// Capturing groups (works with (), ()?, but not ()* if it has nested
// groups). Many of these are provided for your convenience. As few as one
// or as many as four would be needed to reconstruct the address.
// If ALLOW_QUOTED_IDENTIFIERS and ALLOW_DOMAIN_LITERALS:
// 1: name-addr (inlc angle-addr only)
// 2: phrase (personal name) of said name-addr (1)
// 3: angle-addr of said name-addr (1)
// 4: local-part of said angle-addr (3)
// 5: non-cfws dot-atom local-part of said angle-addr (3)
// 6: non-cfws quoted-string local-part of said-angle-addr(3)
// 7: non-cfws dot-atom domain-part of said angle-addr (3)
// 8: non-cfws domain-literal domain-part of said angle-addr (3)
// 9: any CFWS that follows said angle-address (3)
// 10: addr-spec only
// 11: local-part of said addr-spec (10)
// 12: non-cfws dot-atom local-part of said addr-spec (10)
// 13: non-cfws quoted-string local-part of said addr-spec (10)
// 14: non-cfws dot-atom domain-part of said addr-spec (10)
// 15: non-cfws domain-literal domain-part of said addr-spec (10)
// 16: any CFWS that follows (14) or (15)
// if name-addr: addr w/o CFWS is part (5|6) + "@" + (7|8), personal name is part (2|9)
// if addr-spec: addr w/o CFWS is part (12|13) + "@" + (14|15), personal name is part (16)
// If ALLOW_QUOTED_IDENTIFIERS and !ALLOW_DOMAIN_LITERALS:
// 1: name-addr (inlc angle-addr only)
// 2: phrase (personal name) of said name-addr (1)
// 3: angle-addr of said name-addr (1)
// 4: local-part of said angle-addr (3)
// 5: non-cfws dot-atom local-part of said angle-addr (3)
// 6: non-cfws quoted-string local-part of said-angle-addr(3)
// 7: non-cfws domain-part (always dot-atom) of said angle-addr (3)
// 8: any CFWS that follows said angle-address (3)
// 9: addr-spec only
// 10: local-part of said addr-spec (9)
// 11: non-cfws dot-atom local-part of said addr-spec (9)
// 12: non-cfws quoted-string local-part of said addr-spec (9)
// 13: non-cfws domain-part of said addr-spec (9)
// 14: any CFWS that follows (12) or (13)
// if name-addr: addr w/o CFWS is part (5|6) + "@" + 7, personal name is part (2|8)
// if addr-spec: addr w/o CFWS is part (11|12) + "@" + 13, personal name is part (14)
// If !ALLOW_QUOTED_IDENTIFIERS and !ALLOW_DOMAIN_LITERALS:
// 1: addr-spec only
// 2: local-part of said addr-spec (1)
// 3: non-cfws dot-atom local-part of said addr-spec (1)
// 4: non-cfws quoted-string local-part of said addr-spec (1)
// 5: non-cfws domain-part (always dot-atom) of said addr-spec (1)
// 6: any CFWS that follows (5)
// addr w/o CFWS is part (3|4) + "@" + 5, personal name is (6)
// If !ALLOW_QUOTED_IDENTIFIERS and ALLOW_DOMAIN_LITERALS:
// 1: addr-spec only
// 2: local-part of said addr-spec (1)
// 3: non-cfws dot-atom local-part of said addr-spec (1)
// 4: non-cfws quoted-string local-part of said addr-spec (1)
// 5: non-cfws dot-atom domain-part of said addr-spec (1)
// 6: non-cfws domain-literal domain-part of said addr-spec (1)
// 7: any CFWS that follows (5) or (6)
// addr w/o CFWS is part (3|4) + "@" + (5|6), personal name is part (7)
// For RETURN_PATH_PATTERN, there is one matching group at the head of the
// group ID tree that matches the content inside the angle brackets (including
// CFWS, etc.: Group 1.
// optimize: could pre-make matchers as well and use reset(s) on them?
//compile patterns for efficient re-use:
/*
Java regex pattern for 2822 "mailbox" token; Not necessarily useful, but available in case.
*/
MAILBOX_PATTERN = Pattern.compile(mailbox);
/*
* Java regex pattern for 2822 "addr-spec" token; Not necessarily useful, but available in case.
*/
ADDR_SPEC_PATTERN = Pattern.compile(addrSpec);
/*
Java regex pattern for 2822 "mailbox-list" token; Not necessarily useful, but available in case.
*/
MAILBOX_LIST_PATTERN = Pattern.compile(mailboxList);
// public static final Pattern ADDRESS_LIST_PATTERN = Pattern.compile(addressList);
/*
Java regex pattern for 2822 "address" token; Not necessarily useful, but available in case.
*/
ADDRESS_PATTERN = Pattern.compile(address);
/*
* Java regex pattern for 2822 "comment" token; Not necessarily useful, but available in case.
*/
COMMENT_PATTERN = Pattern.compile(comment);
QUOTED_STRING_WO_CFWS_PATTERN = Pattern.compile(quotedStringWOCFWS);
RETURN_PATH_PATTERN = Pattern.compile(returnPath);
GROUP_PREFIX_PATTERN = Pattern.compile(groupPrefix);
// confused yet? Try this:
ESCAPED_QUOTE_PATTERN = Pattern.compile("\\\\\"");
ESCAPED_BSLASH_PATTERN = Pattern.compile("\\\\\\\\");
}
/* The current regex string for mailbox token, just for fun:
(((?:(?:(?:(?:(?:(?:[ \t]*\r\n)?[ \t]+)?\((?:(?:(?:[ \t]*\r\n)?[ \t]+)?[\x01-\x08\x0B\x0C\x0E-\x1F\x7F!-'*-\[\]-~]|(?:\\[\x01-\x09
\x0B\x0C\x0E-\x7F]))*(?:(?:[ \t]*\r\n)?[ \t]+)?\))*(?:(?:(?:(?:[ \t]*\r\n)?[ \t]+)?\((?:(?:(?:[ \t]*\r\n)?[ \t]+)?[\x01-\x08\x0B\x
0C\x0E-\x1F\x7F!-'*-\[\]-~]|(?:\\[\x01-\x09\x0B\x0C\x0E-\x7F]))*(?:(?:[ \t]*\r\n)?[ \t]+)?\))|(?:(?:[ \t]*\r\n)?[ \t]+)))?[a-zA-Z0
-9!#-'*+\-/=?^-`{-~.\[]]+(?:(?:(?:(?:[ \t]*\r\n)?[ \t]+)?\((?:(?:(?:[ \t]*\r\n)?[ \t]+)?[\x01-\x08\x0B\x0C\x0E-\x1F\x7F!-'*-\[\]-~
]|(?:\\[\x01-\x09\x0B\x0C\x0E-\x7F]))*(?:(?:[ \t]*\r\n)?[ \t]+)?\))*(?:(?:(?:(?:[ \t]*\r\n)?[ \t]+)?\((?:(?:(?:[ \t]*\r\n)?[ \t]+)
?[\x01-\x08\x0B\x0C\x0E-\x1F\x7F!-'*-\[\]-~]|(?:\\[\x01-\x09\x0B\x0C\x0E-\x7F]))*(?:(?:[ \t]*\r\n)?[ \t]+)?\))|(?:(?:[ \t]*\r\n)?[
\t]+)))?)|(?:(?:(?:(?:(?:[ \t]*\r\n)?[ \t]+)?\((?:(?:(?:[ \t]*\r\n)?[ \t]+)?[\x01-\x08\x0B\x0C\x0E-\x1F\x7F!-'*-\[\]-~]|(?:\\[\x0
1-\x09\x0B\x0C\x0E-\x7F]))*(?:(?:[ \t]*\r\n)?[ \t]+)?\))*(?:(?:(?:(?:[ \t]*\r\n)?[ \t]+)?\((?:(?:(?:[ \t]*\r\n)?[ \t]+)?[\x01-\x08
\x0B\x0C\x0E-\x1F\x7F!-'*-\[\]-~]|(?:\\[\x01-\x09\x0B\x0C\x0E-\x7F]))*(?:(?:[ \t]*\r\n)?[ \t]+)?\))|(?:(?:[ \t]*\r\n)?[ \t]+)))?"(
?>(?:(?:[ \t]*\r\n)?[ \t]+)?(?:[\x01-\x08\x0B\x0C\x0E-\x1F\x7F!#-\[\]-~]|(?:\\[\x01-\x09\x0B\x0C\x0E-\x7F])))*(?:(?:[ \t]*\r\n)?[
\t]+)?"(?:(?:(?:(?:[ \t]*\r\n)?[ \t]+)?\((?:(?:(?:[ \t]*\r\n)?[ \t]+)?[\x01-\x08\x0B\x0C\x0E-\x1F\x7F!-'*-\[\]-~]|(?:\\[\x01-\x09\
x0B\x0C\x0E-\x7F]))*(?:(?:[ \t]*\r\n)?[ \t]+)?\))*(?:(?:(?:(?:[ \t]*\r\n)?[ \t]+)?\((?:(?:(?:[ \t]*\r\n)?[ \t]+)?[\x01-\x08\x0B\x0
C\x0E-\x1F\x7F!-'*-\[\]-~]|(?:\\[\x01-\x09\x0B\x0C\x0E-\x7F]))*(?:(?:[ \t]*\r\n)?[ \t]+)?\))|(?:(?:[ \t]*\r\n)?[ \t]+)))?))(?:(?:(
?:[ \t]*\r\n)?[ \t]+)(?:(?:(?:(?:(?:(?:[ \t]*\r\n)?[ \t]+)?\((?:(?:(?:[ \t]*\r\n)?[ \t]+)?[\x01-\x08\x0B\x0C\x0E-\x1F\x7F!-'*-\[\]
-~]|(?:\\[\x01-\x09\x0B\x0C\x0E-\x7F]))*(?:(?:[ \t]*\r\n)?[ \t]+)?\))*(?:(?:(?:(?:[ \t]*\r\n)?[ \t]+)?\((?:(?:(?:[ \t]*\r\n)?[ \t]
+)?[\x01-\x08\x0B\x0C\x0E-\x1F\x7F!-'*-\[\]-~]|(?:\\[\x01-\x09\x0B\x0C\x0E-\x7F]))*(?:(?:[ \t]*\r\n)?[ \t]+)?\))|(?:(?:[ \t]*\r\n)
?[ \t]+)))?[a-zA-Z0-9!#-'*+\-/=?^-`{-~.\[]]+(?:(?:(?:(?:[ \t]*\r\n)?[ \t]+)?\((?:(?:(?:[ \t]*\r\n)?[ \t]+)?[\x01-\x08\x0B\x0C\x0E-
\x1F\x7F!-'*-\[\]-~]|(?:\\[\x01-\x09\x0B\x0C\x0E-\x7F]))*(?:(?:[ \t]*\r\n)?[ \t]+)?\))*(?:(?:(?:(?:[ \t]*\r\n)?[ \t]+)?\((?:(?:(?:
[ \t]*\r\n)?[ \t]+)?[\x01-\x08\x0B\x0C\x0E-\x1F\x7F!-'*-\[\]-~]|(?:\\[\x01-\x09\x0B\x0C\x0E-\x7F]))*(?:(?:[ \t]*\r\n)?[ \t]+)?\))|
(?:(?:[ \t]*\r\n)?[ \t]+)))?)|(?:(?:(?:(?:(?:[ \t]*\r\n)?[ \t]+)?\((?:(?:(?:[ \t]*\r\n)?[ \t]+)?[\x01-\x08\x0B\x0C\x0E-\x1F\x7F!-'
*-\[\]-~]|(?:\\[\x01-\x09\x0B\x0C\x0E-\x7F]))*(?:(?:[ \t]*\r\n)?[ \t]+)?\))*(?:(?:(?:(?:[ \t]*\r\n)?[ \t]+)?\((?:(?:(?:[ \t]*\r\n)
?[ \t]+)?[\x01-\x08\x0B\x0C\x0E-\x1F\x7F!-'*-\[\]-~]|(?:\\[\x01-\x09\x0B\x0C\x0E-\x7F]))*(?:(?:[ \t]*\r\n)?[ \t]+)?\))|(?:(?:[ \t]
*\r\n)?[ \t]+)))?"(?>(?:(?:[ \t]*\r\n)?[ \t]+)?(?:[\x01-\x08\x0B\x0C\x0E-\x1F\x7F!#-\[\]-~]|(?:\\[\x01-\x09\x0B\x0C\x0E-\x7F])))*(
?:(?:[ \t]*\r\n)?[ \t]+)?"(?:(?:(?:(?:[ \t]*\r\n)?[ \t]+)?\((?:(?:(?:[ \t]*\r\n)?[ \t]+)?[\x01-\x08\x0B\x0C\x0E-\x1F\x7F!-'*-\[\]-
~]|(?:\\[\x01-\x09\x0B\x0C\x0E-\x7F]))*(?:(?:[ \t]*\r\n)?[ \t]+)?\))*(?:(?:(?:(?:[ \t]*\r\n)?[ \t]+)?\((?:(?:(?:[ \t]*\r\n)?[ \t]+
)?[\x01-\x08\x0B\x0C\x0E-\x1F\x7F!-'*-\[\]-~]|(?:\\[\x01-\x09\x0B\x0C\x0E-\x7F]))*(?:(?:[ \t]*\r\n)?[ \t]+)?\))|(?:(?:[ \t]*\r\n)?
[ \t]+)))?)))*)??((?:(?:(?:(?:[ \t]*\r\n)?[ \t]+)?\((?:(?:(?:[ \t]*\r\n)?[ \t]+)?[\x01-\x08\x0B\x0C\x0E-\x1F\x7F!-'*-\[\]-~]|(?:\\
[\x01-\x09\x0B\x0C\x0E-\x7F]))*(?:(?:[ \t]*\r\n)?[ \t]+)?\))*(?:(?:(?:(?:[ \t]*\r\n)?[ \t]+)?\((?:(?:(?:[ \t]*\r\n)?[ \t]+)?[\x01-
\x08\x0B\x0C\x0E-\x1F\x7F!-'*-\[\]-~]|(?:\\[\x01-\x09\x0B\x0C\x0E-\x7F]))*(?:(?:[ \t]*\r\n)?[ \t]+)?\))|(?:(?:[ \t]*\r\n)?[ \t]+))
)?<((?:(?:(?:(?:[ \t]*\r\n)?[ \t]+)?\((?:(?:(?:[ \t]*\r\n)?[ \t]+)?[\x01-\x08\x0B\x0C\x0E-\x1F\x7F!-'*-\[\]-~]|(?:\\[\x01-\x09\x0B
\x0C\x0E-\x7F]))*(?:(?:[ \t]*\r\n)?[ \t]+)?\))*(?:(?:(?:(?:[ \t]*\r\n)?[ \t]+)?\((?:(?:(?:[ \t]*\r\n)?[ \t]+)?[\x01-\x08\x0B\x0C\x
0E-\x1F\x7F!-'*-\[\]-~]|(?:\\[\x01-\x09\x0B\x0C\x0E-\x7F]))*(?:(?:[ \t]*\r\n)?[ \t]+)?\))|(?:(?:[ \t]*\r\n)?[ \t]+)))?([a-zA-Z0-9!
#-'*+\-/=?^-`{-~]+(?:\.[a-zA-Z0-9!#-'*+\-/=?^-`{-~]+)*)(?:(?:(?:(?:[ \t]*\r\n)?[ \t]+)?\((?:(?:(?:[ \t]*\r\n)?[ \t]+)?[\x01-\x08\x
0B\x0C\x0E-\x1F\x7F!-'*-\[\]-~]|(?:\\[\x01-\x09\x0B\x0C\x0E-\x7F]))*(?:(?:[ \t]*\r\n)?[ \t]+)?\))*(?:(?:(?:(?:[ \t]*\r\n)?[ \t]+)?
\((?:(?:(?:[ \t]*\r\n)?[ \t]+)?[\x01-\x08\x0B\x0C\x0E-\x1F\x7F!-'*-\[\]-~]|(?:\\[\x01-\x09\x0B\x0C\x0E-\x7F]))*(?:(?:[ \t]*\r\n)?[
\t]+)?\))|(?:(?:[ \t]*\r\n)?[ \t]+)))?|(?:(?:(?:(?:[ \t]*\r\n)?[ \t]+)?\((?:(?:(?:[ \t]*\r\n)?[ \t]+)?[\x01-\x08\x0B\x0C\x0E-\x1F
\x7F!-'*-\[\]-~]|(?:\\[\x01-\x09\x0B\x0C\x0E-\x7F]))*(?:(?:[ \t]*\r\n)?[ \t]+)?\))*(?:(?:(?:(?:[ \t]*\r\n)?[ \t]+)?\((?:(?:(?:[ \t
]*\r\n)?[ \t]+)?[\x01-\x08\x0B\x0C\x0E-\x1F\x7F!-'*-\[\]-~]|(?:\\[\x01-\x09\x0B\x0C\x0E-\x7F]))*(?:(?:[ \t]*\r\n)?[ \t]+)?\))|(?:(
?:[ \t]*\r\n)?[ \t]+)))?("(?:(?:(?:[ \t]*\r\n)?[ \t]+)?(?>[\x01-\x08\x0B\x0C\x0E-\x1F\x7F!#-\[\]-~]|(?:\\[\x01-\x09\x0B\x0C\x0E-\x
7F])))*(?:(?:[ \t]*\r\n)?[ \t]+)?")(?:(?:(?:(?:[ \t]*\r\n)?[ \t]+)?\((?:(?:(?:[ \t]*\r\n)?[ \t]+)?[\x01-\x08\x0B\x0C\x0E-\x1F\x7F!
-'*-\[\]-~]|(?:\\[\x01-\x09\x0B\x0C\x0E-\x7F]))*(?:(?:[ \t]*\r\n)?[ \t]+)?\))*(?:(?:(?:(?:[ \t]*\r\n)?[ \t]+)?\((?:(?:(?:[ \t]*\r\
n)?[ \t]+)?[\x01-\x08\x0B\x0C\x0E-\x1F\x7F!-'*-\[\]-~]|(?:\\[\x01-\x09\x0B\x0C\x0E-\x7F]))*(?:(?:[ \t]*\r\n)?[ \t]+)?\))|(?:(?:[ \
t]*\r\n)?[ \t]+)))?)@(?:(?:(?:(?:(?:[ \t]*\r\n)?[ \t]+)?\((?:(?:(?:[ \t]*\r\n)?[ \t]+)?[\x01-\x08\x0B\x0C\x0E-\x1F\x7F!-'*-\[\]-~]
|(?:\\[\x01-\x09\x0B\x0C\x0E-\x7F]))*(?:(?:[ \t]*\r\n)?[ \t]+)?\))*(?:(?:(?:(?:[ \t]*\r\n)?[ \t]+)?\((?:(?:(?:[ \t]*\r\n)?[ \t]+)?
[\x01-\x08\x0B\x0C\x0E-\x1F\x7F!-'*-\[\]-~]|(?:\\[\x01-\x09\x0B\x0C\x0E-\x7F]))*(?:(?:[ \t]*\r\n)?[ \t]+)?\))|(?:(?:[ \t]*\r\n)?[
\t]+)))?([a-zA-Z0-9!#-'*+\-/=?^-`{-~]+(?:\.[a-zA-Z0-9!#-'*+\-/=?^-`{-~]+)*)(?:(?:(?:(?:[ \t]*\r\n)?[ \t]+)?\((?:(?:(?:[ \t]*\r\n)?
[ \t]+)?[\x01-\x08\x0B\x0C\x0E-\x1F\x7F!-'*-\[\]-~]|(?:\\[\x01-\x09\x0B\x0C\x0E-\x7F]))*(?:(?:[ \t]*\r\n)?[ \t]+)?\))*(?:(?:(?:(?:
[ \t]*\r\n)?[ \t]+)?\((?:(?:(?:[ \t]*\r\n)?[ \t]+)?[\x01-\x08\x0B\x0C\x0E-\x1F\x7F!-'*-\[\]-~]|(?:\\[\x01-\x09\x0B\x0C\x0E-\x7F]))
*(?:(?:[ \t]*\r\n)?[ \t]+)?\))|(?:(?:[ \t]*\r\n)?[ \t]+)))?|(?:(?:(?:(?:[ \t]*\r\n)?[ \t]+)?\((?:(?:(?:[ \t]*\r\n)?[ \t]+)?[\x01-\
x08\x0B\x0C\x0E-\x1F\x7F!-'*-\[\]-~]|(?:\\[\x01-\x09\x0B\x0C\x0E-\x7F]))*(?:(?:[ \t]*\r\n)?[ \t]+)?\))*(?:(?:(?:(?:[ \t]*\r\n)?[ \
t]+)?\((?:(?:(?:[ \t]*\r\n)?[ \t]+)?[\x01-\x08\x0B\x0C\x0E-\x1F\x7F!-'*-\[\]-~]|(?:\\[\x01-\x09\x0B\x0C\x0E-\x7F]))*(?:(?:[ \t]*\r
\n)?[ \t]+)?\))|(?:(?:[ \t]*\r\n)?[ \t]+)))?(\[(?:(?:(?:[ \t]*\r\n)?[ \t]+)?(?:[\x01-\x08\x0B\x0C\x0E-\x1F\x7F!-Z^-~]|(?:\\[\x01-\
x09\x0B\x0C\x0E-\x7F]))+)*(?:(?:[ \t]*\r\n)?[ \t]+)?])(?:(?:(?:(?:[ \t]*\r\n)?[ \t]+)?\((?:(?:(?:[ \t]*\r\n)?[ \t]+)?[\x01-\x08\x0
B\x0C\x0E-\x1F\x7F!-'*-\[\]-~]|(?:\\[\x01-\x09\x0B\x0C\x0E-\x7F]))*(?:(?:[ \t]*\r\n)?[ \t]+)?\))*(?:(?:(?:(?:[ \t]*\r\n)?[ \t]+)?\
((?:(?:(?:[ \t]*\r\n)?[ \t]+)?[\x01-\x08\x0B\x0C\x0E-\x1F\x7F!-'*-\[\]-~]|(?:\\[\x01-\x09\x0B\x0C\x0E-\x7F]))*(?:(?:[ \t]*\r\n)?[
\t]+)?\))|(?:(?:[ \t]*\r\n)?[ \t]+)))?)>((?:(?:(?:[ \t]*\r\n)?[ \t]+)?\((?:(?:(?:[ \t]*\r\n)?[ \t]+)?[\x01-\x08\x0B\x0C\x0E-\x1F\x
7F!-'*-\[\]-~]|(?:\\[\x01-\x09\x0B\x0C\x0E-\x7F]))*(?:(?:[ \t]*\r\n)?[ \t]+)?\))*(?:(?:(?:(?:[ \t]*\r\n)?[ \t]+)?\((?:(?:(?:[ \t]*
\r\n)?[ \t]+)?[\x01-\x08\x0B\x0C\x0E-\x1F\x7F!-'*-\[\]-~]|(?:\\[\x01-\x09\x0B\x0C\x0E-\x7F]))*(?:(?:[ \t]*\r\n)?[ \t]+)?\))|(?:(?:
[ \t]*\r\n)?[ \t]+)))?))|(((?:(?:(?:(?:[ \t]*\r\n)?[ \t]+)?\((?:(?:(?:[ \t]*\r\n)?[ \t]+)?[\x01-\x08\x0B\x0C\x0E-\x1F\x7F!-'*-\[\]
-~]|(?:\\[\x01-\x09\x0B\x0C\x0E-\x7F]))*(?:(?:[ \t]*\r\n)?[ \t]+)?\))*(?:(?:(?:(?:[ \t]*\r\n)?[ \t]+)?\((?:(?:(?:[ \t]*\r\n)?[ \t]
+)?[\x01-\x08\x0B\x0C\x0E-\x1F\x7F!-'*-\[\]-~]|(?:\\[\x01-\x09\x0B\x0C\x0E-\x7F]))*(?:(?:[ \t]*\r\n)?[ \t]+)?\))|(?:(?:[ \t]*\r\n)
?[ \t]+)))?([a-zA-Z0-9!#-'*+\-/=?^-`{-~]+(?:\.[a-zA-Z0-9!#-'*+\-/=?^-`{-~]+)*)(?:(?:(?:(?:[ \t]*\r\n)?[ \t]+)?\((?:(?:(?:[ \t]*\r\
n)?[ \t]+)?[\x01-\x08\x0B\x0C\x0E-\x1F\x7F!-'*-\[\]-~]|(?:\\[\x01-\x09\x0B\x0C\x0E-\x7F]))*(?:(?:[ \t]*\r\n)?[ \t]+)?\))*(?:(?:(?:
(?:[ \t]*\r\n)?[ \t]+)?\((?:(?:(?:[ \t]*\r\n)?[ \t]+)?[\x01-\x08\x0B\x0C\x0E-\x1F\x7F!-'*-\[\]-~]|(?:\\[\x01-\x09\x0B\x0C\x0E-\x7F
]))*(?:(?:[ \t]*\r\n)?[ \t]+)?\))|(?:(?:[ \t]*\r\n)?[ \t]+)))?|(?:(?:(?:(?:[ \t]*\r\n)?[ \t]+)?\((?:(?:(?:[ \t]*\r\n)?[ \t]+)?[\x0
1-\x08\x0B\x0C\x0E-\x1F\x7F!-'*-\[\]-~]|(?:\\[\x01-\x09\x0B\x0C\x0E-\x7F]))*(?:(?:[ \t]*\r\n)?[ \t]+)?\))*(?:(?:(?:(?:[ \t]*\r\n)?
[ \t]+)?\((?:(?:(?:[ \t]*\r\n)?[ \t]+)?[\x01-\x08\x0B\x0C\x0E-\x1F\x7F!-'*-\[\]-~]|(?:\\[\x01-\x09\x0B\x0C\x0E-\x7F]))*(?:(?:[ \t]
*\r\n)?[ \t]+)?\))|(?:(?:[ \t]*\r\n)?[ \t]+)))?("(?:(?:(?:[ \t]*\r\n)?[ \t]+)?(?>[\x01-\x08\x0B\x0C\x0E-\x1F\x7F!#-\[\]-~]|(?:\\[\
x01-\x09\x0B\x0C\x0E-\x7F])))*(?:(?:[ \t]*\r\n)?[ \t]+)?")(?:(?:(?:(?:[ \t]*\r\n)?[ \t]+)?\((?:(?:(?:[ \t]*\r\n)?[ \t]+)?[\x01-\x0
8\x0B\x0C\x0E-\x1F\x7F!-'*-\[\]-~]|(?:\\[\x01-\x09\x0B\x0C\x0E-\x7F]))*(?:(?:[ \t]*\r\n)?[ \t]+)?\))*(?:(?:(?:(?:[ \t]*\r\n)?[ \t]
+)?\((?:(?:(?:[ \t]*\r\n)?[ \t]+)?[\x01-\x08\x0B\x0C\x0E-\x1F\x7F!-'*-\[\]-~]|(?:\\[\x01-\x09\x0B\x0C\x0E-\x7F]))*(?:(?:[ \t]*\r\n
)?[ \t]+)?\))|(?:(?:[ \t]*\r\n)?[ \t]+)))?)@(?:(?:(?:(?:(?:[ \t]*\r\n)?[ \t]+)?\((?:(?:(?:[ \t]*\r\n)?[ \t]+)?[\x01-\x08\x0B\x0C\x
0E-\x1F\x7F!-'*-\[\]-~]|(?:\\[\x01-\x09\x0B\x0C\x0E-\x7F]))*(?:(?:[ \t]*\r\n)?[ \t]+)?\))*(?:(?:(?:(?:[ \t]*\r\n)?[ \t]+)?\((?:(?:
(?:[ \t]*\r\n)?[ \t]+)?[\x01-\x08\x0B\x0C\x0E-\x1F\x7F!-'*-\[\]-~]|(?:\\[\x01-\x09\x0B\x0C\x0E-\x7F]))*(?:(?:[ \t]*\r\n)?[ \t]+)?\
))|(?:(?:[ \t]*\r\n)?[ \t]+)))?([a-zA-Z0-9!#-'*+\-/=?^-`{-~]+(?:\.[a-zA-Z0-9!#-'*+\-/=?^-`{-~]+)*)((?:(?:(?:[ \t]*\r\n)?[ \t]+)?\(
(?:(?:(?:[ \t]*\r\n)?[ \t]+)?[\x01-\x08\x0B\x0C\x0E-\x1F\x7F!-'*-\[\]-~]|(?:\\[\x01-\x09\x0B\x0C\x0E-\x7F]))*(?:(?:[ \t]*\r\n)?[ \
t]+)?\))*(?:(?:(?:(?:[ \t]*\r\n)?[ \t]+)?\((?:(?:(?:[ \t]*\r\n)?[ \t]+)?[\x01-\x08\x0B\x0C\x0E-\x1F\x7F!-'*-\[\]-~]|(?:\\[\x01-\x0
9\x0B\x0C\x0E-\x7F]))*(?:(?:[ \t]*\r\n)?[ \t]+)?\))|(?:(?:[ \t]*\r\n)?[ \t]+)))?|(?:(?:(?:(?:[ \t]*\r\n)?[ \t]+)?\((?:(?:(?:[ \t]*
\r\n)?[ \t]+)?[\x01-\x08\x0B\x0C\x0E-\x1F\x7F!-'*-\[\]-~]|(?:\\[\x01-\x09\x0B\x0C\x0E-\x7F]))*(?:(?:[ \t]*\r\n)?[ \t]+)?\))*(?:(?:
(?:(?:[ \t]*\r\n)?[ \t]+)?\((?:(?:(?:[ \t]*\r\n)?[ \t]+)?[\x01-\x08\x0B\x0C\x0E-\x1F\x7F!-'*-\[\]-~]|(?:\\[\x01-\x09\x0B\x0C\x0E-\
x7F]))*(?:(?:[ \t]*\r\n)?[ \t]+)?\))|(?:(?:[ \t]*\r\n)?[ \t]+)))?(\[(?:(?:(?:[ \t]*\r\n)?[ \t]+)?(?:[\x01-\x08\x0B\x0C\x0E-\x1F\x7
F!-Z^-~]|(?:\\[\x01-\x09\x0B\x0C\x0E-\x7F]))+)*(?:(?:[ \t]*\r\n)?[ \t]+)?])((?:(?:(?:[ \t]*\r\n)?[ \t]+)?\((?:(?:(?:[ \t]*\r\n)?[
\t]+)?[\x01-\x08\x0B\x0C\x0E-\x1F\x7F!-'*-\[\]-~]|(?:\\[\x01-\x09\x0B\x0C\x0E-\x7F]))*(?:(?:[ \t]*\r\n)?[ \t]+)?\))*(?:(?:(?:(?:[
\t]*\r\n)?[ \t]+)?\((?:(?:(?:[ \t]*\r\n)?[ \t]+)?[\x01-\x08\x0B\x0C\x0E-\x1F\x7F!-'*-\[\]-~]|(?:\\[\x01-\x09\x0B\x0C\x0E-\x7F]))*(
?:(?:[ \t]*\r\n)?[ \t]+)?\))|(?:(?:[ \t]*\r\n)?[ \t]+)))?))
*/
}
|
package org.jenkinsci.remoting.engine;
import hudson.remoting.EngineListener;
import hudson.remoting.EngineListenerSplitter;
import java.util.Arrays;
import java.util.List;
/**
* Creates protocols to be used to initiate connection with master.
*
* The slave engine will call this factory once when it starts and try the
* protocols in the order they are returned.
*
* @author Akshay Dayal
*/
public class JnlpProtocolFactory {
/**
* Create the list of protocols the JNLP slave should attempt when
* connecting to the master.
*
* The protocols should be tried in the order they are given.
*
* @param slaveName The name of the registered slave.
* @param slaveSecret The secret associated with the slave.
* @param events The {@link EngineListener} that the protocl shall send events to.
*/
public static List<JnlpProtocol> createProtocols(String slaveName, String slaveSecret,
EngineListener events) {
return Arrays.asList(
new JnlpProtocol2(slaveName, slaveSecret, events),
new JnlpProtocol1(slaveName, slaveSecret, events)
);
}
/**
* @deprecated as of 2.51. Use {@link #createProtocols(String, String, EngineListener)}.
*/
public static List<JnlpProtocol> createProtocols(String slaveSecret, String slaveName) {
return createProtocols(slaveName,slaveSecret,new EngineListenerSplitter());
}
}
|
package org.kitteh.irc.client.library.command;
import org.kitteh.irc.client.library.ChannelModeType;
import org.kitteh.irc.client.library.Client;
import org.kitteh.irc.client.library.element.Channel;
import org.kitteh.irc.client.library.element.ChannelUserMode;
import org.kitteh.irc.client.library.element.User;
import org.kitteh.irc.client.library.util.Sanity;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.regex.Pattern;
/**
* Commands a la MODE.
*/
public class ModeCommand extends Command {
private class ModeChange {
private final Boolean add;
private final char mode;
private final String parameter;
private ModeChange(boolean add, char mode, String parameter) {
this.add = add;
this.mode = mode;
this.parameter = parameter;
}
private Boolean getAdd() {
return this.add;
}
private char getMode() {
return this.mode;
}
private String getParameter() {
return this.parameter;
}
}
private static final Pattern MASK_PATTERN = Pattern.compile("([^!@]+)!([^!@]+)@([^!@]+)");
private final List<ModeChange> changes = new ArrayList<>();
private final String channel;
/**
* Constructs a MODE command for a given channel.
*
* @param client the client on which this command is executing
* @param channel channel targeted
*/
public ModeCommand(Client client, Channel channel) {
super(client);
Sanity.nullCheck(channel, "Channel cannot be null");
Sanity.truthiness(channel.getClient() == client, "Channel comes from a different Client");
this.channel = channel.getName();
}
/**
* Constructs a MODE command for a given channel.
*
* @param client the client on which this command is executing
* @param channel channel targeted
*/
public ModeCommand(Client client, String channel) {
super(client);
Sanity.nullCheck(channel, "Channel cannot be null");
Sanity.nullCheck(client.getChannel(channel), "Invalid channel name '" + channel + "'");
this.channel = channel;
}
public ModeCommand addModeChange(boolean add, char mode) {
return this.addModeChange(add, mode, (String) null);
}
public ModeCommand addModeChange(boolean add, ChannelUserMode mode, String parameter) {
Sanity.nullCheck(mode, "Mode cannot be null");
Sanity.truthiness(mode.getClient() == this.getClient(), "Mode comes from a different Client");
return this.addModeChange(add, mode.getMode(), parameter);
}
public ModeCommand addModeChange(boolean add, char mode, User parameter) {
Sanity.nullCheck(parameter, "User cannot be null");
return this.addModeChange(add, mode, parameter.getNick());
}
public ModeCommand addModeChange(boolean add, ChannelUserMode mode, User parameter) {
Sanity.nullCheck(parameter, "User cannot be null");
return this.addModeChange(add, mode, parameter.getNick());
}
public synchronized ModeCommand addModeChange(boolean add, char mode, String parameter) {
ChannelModeType channelModeType = this.getChannelModeType(mode);
if (parameter != null) {
Sanity.safeMessageCheck(parameter);
}
boolean paramRequired = add ? channelModeType.isParameterRequiredOnSetting() : channelModeType.isParameterRequiredOnRemoval();
Sanity.truthiness(paramRequired && parameter == null, "Provided mode '" + mode + "' without parameter when one is required.");
Sanity.truthiness(!paramRequired && parameter != null, "Provided mode '" + mode + "' with parameter when one is not required.");
if (channelModeType == ChannelModeType.A_MASK) {
Sanity.truthiness(MASK_PATTERN.matcher(parameter).matches(), "Provided mode `" + mode + "' requires a mask parameter.");
}
this.changes.add(new ModeChange(add, mode, parameter));
return this;
}
@Override
public synchronized void execute() {
Queue<ModeChange> queue = new LinkedList<>();
for (ModeChange modeChange : this.changes) {
queue.offer(modeChange);
if (queue.size() == 3) {
this.send(queue);
}
}
if (!queue.isEmpty()) {
this.send(queue);
}
}
private ChannelModeType getChannelModeType(char mode) {
ChannelModeType type = this.getClient().getServerInfo().getChannelModes().get(mode);
if (type != null) {
return type;
}
for (ChannelUserMode prefix : this.getClient().getServerInfo().getChannelUserModes()) {
if (prefix.getMode() == mode) {
return ChannelModeType.B_PARAMETER_ALWAYS;
}
}
throw new IllegalArgumentException("Invalid mode '" + mode + "'");
}
private void send(Queue<ModeChange> queue) {
StringBuilder modes = new StringBuilder();
StringBuilder parameters = new StringBuilder();
ModeChange change;
Boolean add = null;
while ((change = queue.poll()) != null) {
if (add != change.getAdd()) {
add = change.getAdd();
modes.append(add ? '+' : '-');
}
modes.append(change.getMode());
if (change.getParameter() != null) {
parameters.append(' ').append(change.getParameter());
}
}
this.getClient().sendRawLine("MODE " + this.channel + " " + modes.toString() + parameters.toString());
}
}
|
package org.jfree.chart.axis.junit;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.GradientPaint;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.jfree.chart.axis.Axis;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.util.RectangleInsets;
/**
* Tests for the {@link Axis} class.
*/
public class AxisTests extends TestCase {
/**
* Returns the tests as a test suite.
*
* @return The test suite.
*/
public static Test suite() {
return new TestSuite(AxisTests.class);
}
/**
* Constructs a new set of tests.
*
* @param name the name of the tests.
*/
public AxisTests(String name) {
super(name);
}
/**
* Confirm that cloning works.
*/
public void testCloning() {
CategoryAxis a1 = new CategoryAxis("Test");
a1.setAxisLinePaint(Color.red);
CategoryAxis a2 = null;
try {
a2 = (CategoryAxis) a1.clone();
}
catch (CloneNotSupportedException e) {
e.printStackTrace();
}
assertTrue(a1 != a2);
assertTrue(a1.getClass() == a2.getClass());
assertTrue(a1.equals(a2));
}
/**
* Confirm that the equals method can distinguish all the required fields.
*/
public void testEquals() {
Axis a1 = new CategoryAxis("Test");
Axis a2 = new CategoryAxis("Test");
assertTrue(a1.equals(a2));
// visible flag...
a1.setVisible(false);
assertFalse(a1.equals(a2));
a2.setVisible(false);
assertTrue(a1.equals(a2));
// label...
a1.setLabel("New Label");
assertFalse(a1.equals(a2));
a2.setLabel("New Label");
assertTrue(a1.equals(a2));
// label font...
a1.setLabelFont(new Font("Dialog", Font.PLAIN, 8));
assertFalse(a1.equals(a2));
a2.setLabelFont(new Font("Dialog", Font.PLAIN, 8));
assertTrue(a1.equals(a2));
// label paint...
a1.setLabelPaint(new GradientPaint(1.0f, 2.0f, Color.white,
3.0f, 4.0f, Color.black));
assertFalse(a1.equals(a2));
a2.setLabelPaint(new GradientPaint(1.0f, 2.0f, Color.white,
3.0f, 4.0f, Color.black));
assertTrue(a1.equals(a2));
// label insets...
a1.setLabelInsets(new RectangleInsets(10.0, 10.0, 10.0, 10.0));
assertFalse(a1.equals(a2));
a2.setLabelInsets(new RectangleInsets(10.0, 10.0, 10.0, 10.0));
assertTrue(a1.equals(a2));
// label angle...
a1.setLabelAngle(1.23);
assertFalse(a1.equals(a2));
a2.setLabelAngle(1.23);
assertTrue(a1.equals(a2));
a1.setLabelToolTip("123");
assertFalse(a1.equals(a2));
a2.setLabelToolTip("123");
assertTrue(a1.equals(a2));
a1.setLabelURL("ABC");
assertFalse(a1.equals(a2));
a2.setLabelURL("ABC");
assertTrue(a1.equals(a2));
// axis line visible...
a1.setAxisLineVisible(false);
assertFalse(a1.equals(a2));
a2.setAxisLineVisible(false);
assertTrue(a1.equals(a2));
// axis line stroke...
BasicStroke s = new BasicStroke(1.1f);
a1.setAxisLineStroke(s);
assertFalse(a1.equals(a2));
a2.setAxisLineStroke(s);
assertTrue(a1.equals(a2));
// axis line paint...
a1.setAxisLinePaint(new GradientPaint(1.0f, 2.0f, Color.red,
3.0f, 4.0f, Color.black));
assertFalse(a1.equals(a2));
a2.setAxisLinePaint(new GradientPaint(1.0f, 2.0f, Color.red,
3.0f, 4.0f, Color.black));
assertTrue(a1.equals(a2));
// tick labels visible flag...
a1.setTickLabelsVisible(false);
assertFalse(a1.equals(a2));
a2.setTickLabelsVisible(false);
assertTrue(a1.equals(a2));
// tick label font...
a1.setTickLabelFont(new Font("Dialog", Font.PLAIN, 12));
assertFalse(a1.equals(a2));
a2.setTickLabelFont(new Font("Dialog", Font.PLAIN, 12));
assertTrue(a1.equals(a2));
// tick label paint...
a1.setTickLabelPaint(new GradientPaint(1.0f, 2.0f, Color.yellow,
3.0f, 4.0f, Color.black));
assertFalse(a1.equals(a2));
a2.setTickLabelPaint(new GradientPaint(1.0f, 2.0f, Color.yellow,
3.0f, 4.0f, Color.black));
assertTrue(a1.equals(a2));
// tick label insets...
a1.setTickLabelInsets(new RectangleInsets(10.0, 10.0, 10.0, 10.0));
assertFalse(a1.equals(a2));
a2.setTickLabelInsets(new RectangleInsets(10.0, 10.0, 10.0, 10.0));
assertTrue(a1.equals(a2));
// tick marks visible flag...
a1.setTickMarksVisible(!a1.isTickMarksVisible());
assertFalse(a1.equals(a2));
a2.setTickMarksVisible(a1.isTickMarksVisible());
assertTrue(a1.equals(a2));
// tick mark inside length...
a1.setTickMarkInsideLength(1.23f);
assertFalse(a1.equals(a2));
a2.setTickMarkInsideLength(1.23f);
assertTrue(a1.equals(a2));
// tick mark outside length...
a1.setTickMarkOutsideLength(1.23f);
assertFalse(a1.equals(a2));
a2.setTickMarkOutsideLength(1.23f);
assertTrue(a1.equals(a2));
// tick mark stroke...
a1.setTickMarkStroke(new BasicStroke(2.0f));
assertFalse(a1.equals(a2));
a2.setTickMarkStroke(new BasicStroke(2.0f));
assertTrue(a1.equals(a2));
// tick mark paint...
a1.setTickMarkPaint(new GradientPaint(1.0f, 2.0f, Color.cyan,
3.0f, 4.0f, Color.black));
assertFalse(a1.equals(a2));
a2.setTickMarkPaint(new GradientPaint(1.0f, 2.0f, Color.cyan,
3.0f, 4.0f, Color.black));
assertTrue(a1.equals(a2));
// tick mark outside length...
a1.setFixedDimension(3.21f);
assertFalse(a1.equals(a2));
a2.setFixedDimension(3.21f);
assertTrue(a1.equals(a2));
a1.setMinorTickMarksVisible(true);
assertFalse(a1.equals(a2));
a2.setMinorTickMarksVisible(true);
assertTrue(a1.equals(a2));
a1.setMinorTickMarkInsideLength(1.23f);
assertFalse(a1.equals(a2));
a2.setMinorTickMarkInsideLength(1.23f);
assertTrue(a1.equals(a2));
a1.setMinorTickMarkOutsideLength(3.21f);
assertFalse(a1.equals(a2));
a2.setMinorTickMarkOutsideLength(3.21f);
assertTrue(a1.equals(a2));
}
/**
* Two objects that are equal are required to return the same hashCode.
*/
public void testHashCode() {
Axis a1 = new CategoryAxis("Test");
Axis a2 = new CategoryAxis("Test");
assertTrue(a1.equals(a2));
int h1 = a1.hashCode();
int h2 = a2.hashCode();
assertEquals(h1, h2);
}
}
|
package org.lanternpowered.server.command;
import static org.lanternpowered.server.command.CommandHelper.getWorld;
import static org.lanternpowered.server.text.translation.TranslationHelper.t;
import com.google.common.collect.ImmutableList;
import org.lanternpowered.server.world.LanternWorldProperties;
import org.lanternpowered.server.world.rules.RuleDataTypes;
import org.lanternpowered.server.world.rules.RuleType;
import org.spongepowered.api.Sponge;
import org.spongepowered.api.command.CommandResult;
import org.spongepowered.api.command.CommandSource;
import org.spongepowered.api.command.args.ArgumentParseException;
import org.spongepowered.api.command.args.CommandArgs;
import org.spongepowered.api.command.args.CommandContext;
import org.spongepowered.api.command.args.CommandElement;
import org.spongepowered.api.command.args.GenericArguments;
import org.spongepowered.api.command.spec.CommandSpec;
import org.spongepowered.api.text.Text;
import org.spongepowered.api.util.GuavaCollectors;
import org.spongepowered.api.util.StartsWithPredicate;
import org.spongepowered.api.world.storage.WorldProperties;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import javax.annotation.Nullable;
@SuppressWarnings({ "rawtypes", "unchecked" })
public final class CommandGameRule extends CommandProvider {
public CommandGameRule() {
super(2, "gamerule", "rule");
}
@Override
public void completeSpec(CommandSpec.Builder specBuilder) {
final Collection<String> defaultRules = Sponge.getRegistry().getDefaultGameRules();
final ThreadLocal<RuleType<?>> currentRule = new ThreadLocal<>();
specBuilder
.arguments(
GenericArguments.flags()
.valueFlag(GenericArguments.world(Text.of("world")), "-world", "w")
.buildWith(GenericArguments.none()),
new CommandElement(Text.of("rule")) {
@Nullable
@Override
protected Object parseValue(CommandSource source, CommandArgs args) throws ArgumentParseException {
RuleType<?> ruleType = RuleType.getOrCreate(args.next(), RuleDataTypes.STRING, "");
currentRule.set(ruleType);
return ruleType;
}
@Override
public List<String> complete(CommandSource src, CommandArgs args, CommandContext context) {
final String prefix = args.nextIfPresent().orElse("");
return defaultRules.stream().filter(new StartsWithPredicate(prefix)).collect(GuavaCollectors.toImmutableList());
}
},
new CommandElement(Text.of("value")) {
private final List<String> booleanRuleSuggestions = ImmutableList.of("true", "false");
@Nullable
@Override
protected Object parseValue(CommandSource source, CommandArgs args) throws ArgumentParseException {
RuleType<?> ruleType = currentRule.get();
currentRule.remove();
try {
return ruleType.getDataType().parse(args.next());
} catch (IllegalArgumentException e) {
throw args.createError(t(e.getMessage()));
}
}
@Override
public List<String> complete(CommandSource src, CommandArgs args, CommandContext context) {
RuleType<?> ruleType = context.<RuleType<?>>getOne("rule").get();
if (ruleType.getDataType() == RuleDataTypes.BOOLEAN) {
// Just return the suggestions, there is no need to
// match the first part of the string
return this.booleanRuleSuggestions;
}
return Collections.emptyList();
}
}
)
.executor((src, args) -> {
WorldProperties world = getWorld(src, args);
Object value = args.getOne("value").get();
RuleType ruleType = args.<RuleType>getOne("rule").get();
((LanternWorldProperties) world).getRules()
.getOrCreateRule(ruleType)
.setValue(value);
src.sendMessage(t("commands.gamerule.success", ruleType.getName(), ruleType.getDataType().serialize(value)));
return CommandResult.success();
});
}
}
|
package org.nrvz.services.osgi.locator;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Dictionary;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleException;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.ServiceRegistration;
public class OSGiServiceLocator implements BundleActivator
{
/**
* static reference to this activator.
*/
private static volatile OSGiServiceLocator instance;
/**
* {@link BundleContext} injected from the {@link #start(BundleContext)} method.
*/
private BundleContext context;
@Override
public void start(final BundleContext context) throws Exception
{
this.context = context;
instance = this;
//Automatically start Equinox DS bundles if available
for (final Bundle bundle : context.getBundles())
{
if (bundle.getSymbolicName().equals("org.eclipse.equinox.ds") ||
bundle.getSymbolicName().equals("org.eclipse.equinox.common"))
{
if (bundle.getState() != Bundle.ACTIVE && bundle.getState() != Bundle.STARTING)
{
try
{
bundle.start();
}
catch (BundleException e)
{
throw new IllegalArgumentException(e);
}
}
}
}
}
@Override
public void stop(final BundleContext context) throws Exception
{
this.context = null;
instance = null;
}
/**
* Retrieve the running {@link BundleContext}
*
* @return {@link BundleContext}
*/
private BundleContext getBundleContext()
{
return context;
}
/**
* Retrieve the static instance
*
* @return {@link OSGiServiceLocator} instance
*/
private static OSGiServiceLocator getInstance()
{
return instance;
}
/**
* Retrieve a service by {@link Class} type
*
* @param clazz {@link Class} type
* @return discovered service, or <code>null</code>
*/
public static <S> S getService(final Class<S> clazz)
{
final BundleContext context = getInstance().getBundleContext();
if (context != null)
{
final ServiceReference<S> ref = context.getServiceReference(clazz);
if (ref != null)
{
return context.getService(ref);
}
}
return null;
}
/**
* Retrieves the first service found that matches the provided {@link Class} and filter.
*
* @param clazz {@link Class} of the service to lookup
* @param filter {@link String} LDAP style filter to apply for search
* @return instance that was discovered, or <code>null</code>
*/
public static <S> S getService(final Class<S> clazz, final String filter)
{
final Collection<S> services = getServices(clazz, filter);
if (!services.isEmpty())
{
return services.iterator().next();
}
return null;
}
/**
* Retrieve all service instances of the provided {@link Class} and filter.
*
* @param clazz {@link Class} of the service to lookup
* @param filter {@link String} LDAP style filter to apply for search
* @return {@link Collection} of the discovered services, might be <code>empty</code>
*/
public static <S> Collection<S> getServices(final Class<S> clazz, final String filter)
{
final Collection<S> services = new ArrayList<S>();
final BundleContext context = getInstance().getBundleContext();
if (context != null)
{
try
{
final Collection<ServiceReference<S>> refs = context.getServiceReferences(clazz, filter);
if (refs != null)
{
for (final ServiceReference<S> ref : refs)
{
final S service = context.getService(ref);
if (service != null)
{
services.add(service);
}
}
}
}
catch (final InvalidSyntaxException e)
{
throw new IllegalArgumentException(e);
}
}
return services;
}
/**
* Register a service with the running OSGi framework.
*
* @param clazz service {@link Class}
* @param service instance of the service
* @param properties any properties that identify the service
* @return {@link ServiceRegistration} reference
*/
public static <S> ServiceRegistration<S> registerService(final Class<S> clazz, final S service, final Dictionary<String, String> properties)
{
final BundleContext context = getInstance().getBundleContext();
if (context != null)
{
return context.registerService(clazz, service, properties);
}
return null;
}
}
|
package org.sagebionetworks.web.shared;
import org.sagebionetworks.schema.ObjectSchema;
import org.sagebionetworks.schema.adapter.JSONEntity;
import org.sagebionetworks.schema.adapter.JSONObjectAdapter;
import org.sagebionetworks.schema.adapter.JSONObjectAdapterException;
/**
* AccessTokenWrapper
*
* Holds an access token used for short-term authentication with Synapse
*
*/
public class AccessTokenWrapper implements JSONEntity {
// maintaining the "sessionToken" key to ease migration pain (production portals do not all need to update in order to use the init session servlet)
private final static String _KEY_TOKEN = "sessionToken";
private String token;
public AccessTokenWrapper() {
}
public AccessTokenWrapper(JSONObjectAdapter adapter) throws JSONObjectAdapterException {
super();
if (adapter == null) {
throw new IllegalArgumentException(ObjectSchema.OBJECT_ADAPTER_CANNOT_BE_NULL);
}
initializeFromJSONObject(adapter);
}
public String getToken() {
return token;
}
public AccessTokenWrapper setToken(String token) {
this.token = token;
return this;
}
@Override
public JSONObjectAdapter initializeFromJSONObject(JSONObjectAdapter adapter) throws JSONObjectAdapterException {
if (adapter == null) {
throw new IllegalArgumentException(ObjectSchema.OBJECT_ADAPTER_CANNOT_BE_NULL);
}
if (!adapter.isNull(_KEY_TOKEN)) {
token = adapter.getString(_KEY_TOKEN);
} else {
token = null;
}
return adapter;
}
@Override
public JSONObjectAdapter writeToJSONObject(JSONObjectAdapter adapter) throws JSONObjectAdapterException {
if (adapter == null) {
throw new IllegalArgumentException(ObjectSchema.OBJECT_ADAPTER_CANNOT_BE_NULL);
}
if (token != null) {
adapter.put(_KEY_TOKEN, token);
}
return adapter;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = ((prime * result) + ((token == null) ? 0 : token.hashCode()));
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (this.getClass() != obj.getClass()) {
return false;
}
AccessTokenWrapper other = ((AccessTokenWrapper) obj);
if (token == null) {
if (other.token != null) {
return false;
}
} else {
if (!token.equals(other.token)) {
return false;
}
}
return true;
}
@Override
public String toString() {
StringBuilder result;
result = new StringBuilder();
result.append("");
result.append("org.sagebionetworks.web.shared.AccessTokenWrapper");
result.append(" [");
result.append("sessionToken=");
result.append(token);
result.append(" ");
result.append("]");
return result.toString();
}
}
|
package org.synyx.urlaubsverwaltung.absence.web;
import java.time.LocalDate;
import java.util.Iterator;
import java.util.NoSuchElementException;
final class DateRange implements Iterable<LocalDate> {
private final LocalDate startDate;
private final LocalDate endDate;
DateRange(LocalDate startDate, LocalDate endDate) {
this.startDate = startDate;
this.endDate = endDate;
}
LocalDate getStartDate() {
return startDate;
}
LocalDate getEndDate() {
return endDate;
}
@Override
public Iterator<LocalDate> iterator() {
return new DateRangeIterator(startDate, endDate);
}
private static final class DateRangeIterator implements Iterator<LocalDate> {
private LocalDate cursor;
private final LocalDate endDate;
DateRangeIterator(LocalDate startDate, LocalDate endDate) {
this.cursor = startDate;
this.endDate = endDate;
}
@Override
public boolean hasNext() {
return cursor.isBefore(endDate) || cursor.isEqual(endDate);
}
@Override
public LocalDate next() {
if (cursor.isAfter(endDate)) {
throw new NoSuchElementException("next date is after endDate which is not in range anymore.");
}
final LocalDate current = cursor;
cursor = cursor.plusDays(1);
return current;
}
}
}
|
package org.team2471.frc.lib.motion_profiling;
import org.team2471.frc.lib.math.Vector2;
import static org.team2471.frc.lib.motion_profiling.Path2DPoint.SlopeMethod.SLOPE_MANUAL;
import static org.team2471.frc.lib.motion_profiling.Path2DPoint.SlopeMethod.SLOPE_SMOOTH;
public class Path2DPoint {
public static transient final int STEPS = 600;
private Vector2 m_position;
private Vector2 m_prevAngleAndMagnitude = new Vector2(0, 1.9);
private Vector2 m_nextAngleAndMagnitude = new Vector2(0, 1.9);
private Vector2 m_prevTangent = new Vector2(0, 0);
private Vector2 m_nextTangent = new Vector2(0, 0);
private SlopeMethod m_prevSlopeMethod = SlopeMethod.SLOPE_SMOOTH;
private SlopeMethod m_nextSlopeMethod = SlopeMethod.SLOPE_SMOOTH;
private Path2DPoint m_nextPoint = null;
private transient boolean m_bTangentsDirty = true;
private transient boolean m_bCoefficientsDirty = true;
private transient CubicCoefficients1D m_xCoeff;
private transient CubicCoefficients1D m_yCoeff;
private transient double m_segmentLength = 0;
private transient double partialLength = -1, prevPartialLength;
private transient Path2DCurve m_path2DCurve = null;
private transient Path2DPoint m_prevPoint = null;
public Path2DPoint(double x, double y) {
m_position = new Vector2(x, y);
}
public Path2DPoint() {
this(0, 0);
}
public void onPositionChanged() {
getPath2DCurve().onPositionChanged(); // tell the path too
setTangentsDirty(true);
setCoefficientsDirty(true);
if (getPrevPoint() != null) {
getPrevPoint().setTangentsDirty(true);
getPrevPoint().setCoefficientsDirty(true);
if (getNextPoint() == null && getPrevPoint().getPrevPoint() != null) {
getPrevPoint().getPrevPoint().setCoefficientsDirty(true); // coefficients two back need recalculated
}
}
if (getNextPoint() != null) {
getNextPoint().setTangentsDirty(true);
getNextPoint().setCoefficientsDirty(true);
}
}
public boolean areTangentsDirty() {
return m_bTangentsDirty;
}
public void setTangentsDirty(boolean bTangentsDirty) {
m_bTangentsDirty = bTangentsDirty;
}
public boolean areCoefficientsDirty() {
return m_bCoefficientsDirty;
}
public void setCoefficientsDirty(boolean bCoefficientsDirty) {
m_bCoefficientsDirty = bCoefficientsDirty;
}
public Vector2 getPosition() {
return m_position;
}
public void setPosition(Vector2 position) {
this.m_position = position;
onPositionChanged();
}
public Vector2 getPrevAngleAndMagnitude() {
return m_prevAngleAndMagnitude;
}
public void setPrevAngleAndMagnitude(Vector2 prevAngleAndMagnitude) {
m_prevAngleAndMagnitude = new Vector2(prevAngleAndMagnitude.getX(), prevAngleAndMagnitude.getY());
m_prevSlopeMethod = SLOPE_SMOOTH;
onPositionChanged();
}
public Vector2 getNextAngleAndMagnitude() {
return m_nextAngleAndMagnitude;
}
public void setNextAngleAndMagnitude(Vector2 nextAngleAndMagnitude) { // this one takes the angle in world space - stored as an offset
m_nextAngleAndMagnitude = new Vector2(nextAngleAndMagnitude.getX(), nextAngleAndMagnitude.getY());
m_prevSlopeMethod = SLOPE_SMOOTH;
onPositionChanged();
}
public Vector2 getPrevTangent() {
if (areTangentsDirty())
calculateTangents();
return m_prevTangent;
}
public void setPrevTangent(Vector2 prevTangent) {
if (m_prevPoint!=null) {
m_prevTangent = prevTangent;
calculatePrevAngleAndMagnitudeFromTangent();
}
onPositionChanged();
}
public Vector2 getNextTangent() {
if (areTangentsDirty())
calculateTangents();
return m_nextTangent;
}
public void setNextTangent(Vector2 nextTangent) {
if (m_nextPoint != null) {
m_nextTangent = nextTangent;
calculateNextAngleAndMagnitudeFromTangent();
}
onPositionChanged();
}
private void calculatePrevAngleAndMagnitudeFromTangent() {
Vector2 prevTangent = new Vector2(m_prevTangent.getX(), m_prevTangent.getY());
calculateDefaultTangents(true, false); // determine the default tangents
double defaultAngle = Math.toDegrees(Math.atan2(m_prevTangent.getY(), m_prevTangent.getX()));
double goalAngle = Math.toDegrees(Math.atan2(prevTangent.getY(), prevTangent.getX()));
double angle = goalAngle - defaultAngle;
double magnitude = prevTangent.getLength() / m_prevTangent.getLength();
m_prevAngleAndMagnitude = new Vector2(angle, magnitude);
m_prevTangent.set(prevTangent);
}
private void calculateNextAngleAndMagnitudeFromTangent() {
Vector2 nextTangent = new Vector2(m_nextTangent.getX(), m_nextTangent.getY());
calculateDefaultTangents(false, true); // determine the default tangents
double defaultAngle = Math.toDegrees(Math.atan2(m_nextTangent.getY(), m_nextTangent.getX()));
double goalAngle = Math.toDegrees(Math.atan2(nextTangent.getY(), nextTangent.getX()));
double angle = goalAngle - defaultAngle;
double magnitude = nextTangent.getLength() / m_nextTangent.getLength();
m_nextAngleAndMagnitude = new Vector2(angle, magnitude);
m_nextTangent.set(nextTangent);
}
public Path2DCurve getPath2DCurve() {
return m_path2DCurve;
}
public void setPath2DCurve(Path2DCurve path2DCurve) {
m_path2DCurve = path2DCurve;
}
public Path2DPoint getNextPoint() {
return m_nextPoint;
}
public void setNextPoint(Path2DPoint nextPoint) {
this.m_nextPoint = nextPoint;
}
public Path2DPoint getPrevPoint() {
return m_prevPoint;
}
public void setPrevPoint(Path2DPoint prevPoint) {
this.m_prevPoint = prevPoint;
}
public SlopeMethod getPrevSlopeMethod() {
return m_prevSlopeMethod;
}
public void setPrevSlopeMethod(SlopeMethod slopeMethod) {
m_prevSlopeMethod = slopeMethod;
m_bTangentsDirty = true;
}
public SlopeMethod getNextSlopeMethod() {
return m_nextSlopeMethod;
}
public void setNextSlopeMethod(SlopeMethod slopeMethod) {
m_prevSlopeMethod = slopeMethod;
m_bTangentsDirty = true;
}
public double getPrevAngle() {
return m_prevAngleAndMagnitude.getX();
}
public double getNextAngle() {
return m_nextAngleAndMagnitude.getX();
}
public double getPrevMagnitude() {
return m_prevAngleAndMagnitude.getY();
}
public double getNextMagnitude() {
return m_nextAngleAndMagnitude.getY();
}
void insertBefore(Path2DPoint newPoint) {
m_prevPoint = newPoint.m_prevPoint;
if (newPoint.m_prevPoint != null)
newPoint.m_prevPoint.m_nextPoint = this;
newPoint.m_prevPoint = this;
m_nextPoint = newPoint;
}
void insertAfter(Path2DPoint newPoint) {
m_nextPoint = newPoint.m_nextPoint;
if (newPoint.m_nextPoint != null)
newPoint.m_nextPoint.m_prevPoint = this;
newPoint.m_nextPoint = this;
m_prevPoint = newPoint;
}
private void calculateTangents() {
setTangentsDirty(false);
boolean bCalcSmoothPrev = false;
boolean bCalcSmoothNext = false;
switch (getPrevSlopeMethod()) {
case SLOPE_LINEAR:
if (m_prevPoint != null)
m_prevTangent = getPosition().minus(m_prevPoint.getPosition());
break;
case SLOPE_SMOOTH:
bCalcSmoothPrev = true;
break;
case SLOPE_MANUAL:
// todo: should actually compute the angle and magnitude from the vector here
break;
}
switch (getNextSlopeMethod()) {
case SLOPE_LINEAR:
if (m_nextPoint != null)
m_nextTangent = m_nextPoint.getPosition().minus(getPosition());
break;
case SLOPE_SMOOTH:
bCalcSmoothNext = true;
break;
case SLOPE_MANUAL:
// todo: should actually compute the angle and magnitude from the vector here
break;
}
if (bCalcSmoothPrev || bCalcSmoothNext) {
calculateDefaultTangents(bCalcSmoothPrev, bCalcSmoothNext);
m_prevTangent = m_prevTangent.times(getPrevMagnitude())
.rotateDegrees(getPrevAngle());
m_nextTangent = m_nextTangent.times(getNextMagnitude())
.rotateDegrees(getNextAngle());
}
}
private void calculateDefaultTangents(boolean bCalcSmoothPrev, boolean bCalcSmoothNext) {
if (m_prevPoint != null && m_nextPoint != null) {
Vector2 delta = m_nextPoint.getPosition().minus(m_prevPoint.getPosition());
//double weight = Math.abs(delta.x); // Bug for paths: just works for 2d channels I think
double weight = delta.getLength();
if (weight == 0) // if points are on top of one another (no tangents)
{
if (bCalcSmoothPrev)
m_prevTangent = new Vector2(0, 0);
if (bCalcSmoothNext)
m_nextTangent = new Vector2(0, 0);
} else {
delta = delta.div(weight);
if (bCalcSmoothPrev) {
double prevLength = (getPosition().minus(m_prevPoint.getPosition())).getLength();
m_prevTangent = delta.times(prevLength);
}
if (bCalcSmoothNext) {
double nextLength = (m_nextPoint.getPosition().minus(getPosition())).getLength();
m_nextTangent = delta.times(nextLength);
}
}
} else {
if (m_nextPoint != null) {
if (bCalcSmoothPrev) {
m_prevTangent = m_nextPoint.getPosition().minus(getPosition());
}
if (bCalcSmoothNext) {
m_nextTangent = m_nextPoint.getPosition().minus(getPosition());
}
}
if (m_prevPoint != null) {
if (bCalcSmoothPrev) {
m_prevTangent = getPosition().minus(m_prevPoint.getPosition());
}
if (bCalcSmoothNext) {
m_nextTangent = getPosition().minus(m_prevPoint.getPosition());
}
}
}
}
public CubicCoefficients1D getXCoefficients() {
if (areCoefficientsDirty()) {
calculateCoefficientsAndLength();
}
return m_xCoeff;
}
public CubicCoefficients1D getYCoefficients() {
if (areCoefficientsDirty()) {
calculateCoefficientsAndLength();
}
return m_yCoeff;
}
private void calculateCoefficientsAndLength() {
if (areTangentsDirty())
calculateTangents();
if (getNextPoint() != null && getNextPoint().areTangentsDirty())
getNextPoint().calculateTangents();
setCoefficientsDirty(false);
double pointax = getPosition().getX();
double pointbx = m_nextPoint.getPosition().getX();
double pointcx = getNextTangent().getX();
double pointdx = m_nextPoint.getPrevTangent().getX();
m_xCoeff = new CubicCoefficients1D(pointax, pointbx, pointcx, pointdx);
double pointay = getPosition().getY();
double pointby = m_nextPoint.getPosition().getY();
double pointcy = getNextTangent().getY();
double pointdy = m_nextPoint.getPrevTangent().getY();
m_yCoeff = new CubicCoefficients1D(pointay, pointby, pointcy, pointdy);
// calculate segment length
Vector2 pos = new Vector2(0, 0);
m_xCoeff.initFD(STEPS);
m_yCoeff.initFD(STEPS);
m_segmentLength = 0;
Vector2 prevPos = new Vector2(m_xCoeff.getFDValue(), m_yCoeff.getFDValue());
for (int i = 0; i < STEPS; i++) {
pos = new Vector2(m_xCoeff.bumpFDFaster(), m_yCoeff.bumpFDFaster());
m_segmentLength += pos.minus(prevPos).getLength();
prevPos = new Vector2(pos.getX(), pos.getY());
}
}
public double getSegmentLength() {
if (areCoefficientsDirty()) {
calculateCoefficientsAndLength();
}
return m_segmentLength;
}
public Vector2 getPositionAtDistance(double distance) {
Vector2 pos = new Vector2(0, 0);
Vector2 prevPos = new Vector2(0, 0);
if (partialLength < 0 || partialLength > distance) {
m_xCoeff.initFD(STEPS);
m_yCoeff.initFD(STEPS);
partialLength = 0;
}
while (partialLength <= distance) {
pos = new Vector2(m_xCoeff.bumpFD(), m_yCoeff.bumpFD());
prevPos = new Vector2(m_xCoeff.getFdPrevValue(), m_yCoeff.getFdPrevValue());
prevPartialLength = partialLength;
partialLength += pos.minus(prevPos).getLength();
}
double intoSegment = (distance - prevPartialLength) / (partialLength - prevPartialLength); // linearly interpolate t based on distance of the surrounding steps
return prevPos.times(1.0f - intoSegment).plus(pos.times(intoSegment));
}
public Vector2 getTangentAtDistance(double distance) {
Vector2 pos = new Vector2(0, 0);
Vector2 prevPos = new Vector2(0, 0);
if (partialLength < 0 || partialLength > distance) {
m_xCoeff.initFD(STEPS);
m_yCoeff.initFD(STEPS);
partialLength = 0;
}
while (partialLength <= distance) {
pos = new Vector2(m_xCoeff.bumpFD(), m_yCoeff.bumpFD());
prevPos = new Vector2(m_xCoeff.getFdPrevValue(), m_yCoeff.getFdPrevValue());
prevPartialLength = partialLength;
partialLength += pos.minus(prevPos).getLength();
}
return pos.minus(prevPos);
}
public String toString() {
String rValue = "";
rValue += m_position.toString();
rValue += m_prevAngleAndMagnitude.toString();
rValue += m_nextAngleAndMagnitude.toString();
rValue += m_prevTangent.toString();
rValue += m_nextTangent.toString();
rValue += m_prevSlopeMethod.toString();
rValue += m_nextSlopeMethod.toString();
return rValue;
}
public enum SlopeMethod {
SLOPE_SMOOTH, SLOPE_MANUAL, SLOPE_LINEAR
}
}
|
package org.threadly.concurrent;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.Delayed;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.LockSupport;
import org.threadly.concurrent.BlockingQueueConsumer.ConsumerAcceptor;
import org.threadly.concurrent.collections.DynamicDelayQueue;
import org.threadly.concurrent.collections.DynamicDelayedUpdater;
import org.threadly.concurrent.future.ListenableFuture;
import org.threadly.concurrent.future.ListenableFutureTask;
import org.threadly.concurrent.future.ListenableRunnableFuture;
import org.threadly.concurrent.limiter.PrioritySchedulerLimiter;
import org.threadly.util.Clock;
import org.threadly.util.ExceptionUtils;
/**
* <p>Executor to run tasks, schedule tasks.
* Unlike {@link java.util.concurrent.ScheduledThreadPoolExecutor}
* this scheduled executor's pool size can grow and shrink based off
* usage. It also has the benefit that you can provide "low priority"
* tasks which will attempt to use existing workers and not instantly
* create new threads on demand. Thus allowing you to better take
* the benefits of a thread pool for tasks which specific execution
* time is less important.</p>
*
* <p>Most tasks provided into this pool will likely want to be
* "high priority", to more closely match the behavior of other
* thread pools. That is why unless specified by the constructor,
* the default {@link TaskPriority} is High.</p>
*
* <p>When providing a "low priority" task, the task wont execute till
* one of the following is true. The pool is has low load, and there
* are available threads already to run on. The pool has no available
* threads, but is under it's max size and has waited the maximum wait
* time for a thread to be become available.</p>
*
* <p>In all conditions, "low priority" tasks will never be starved.
* They only attempt to allow "high priority" tasks the priority.
* This makes "low priority" tasks ideal which do regular cleanup, or
* in general anything that must run, but cares little if there is a
* 1, or 10 second gap in the execution time. That amount of tolerance
* for "low priority" tasks is adjustable by setting the
* maxWaitForLowPriorityInMs either in the constructor, or at runtime.</p>
*
* @author jent - Mike Jensen
* @since 1.0.0
*/
public class PriorityScheduledExecutor implements PrioritySchedulerInterface {
protected static final TaskPriority DEFAULT_PRIORITY = TaskPriority.High;
protected static final int DEFAULT_LOW_PRIORITY_MAX_WAIT_IN_MS = 500;
protected static final boolean DEFAULT_NEW_THREADS_DAEMON = true;
protected static final int WORKER_CONTENTION_LEVEL = 2; // level at which no worker contention is considered
protected static final int LOW_PRIORITY_WAIT_TOLLERANCE_IN_MS = 2;
protected static final String QUEUE_CONSUMER_THREAD_NAME_HIGH_PRIORITY;
protected static final String QUEUE_CONSUMER_THREAD_NAME_LOW_PRIORITY;
static {
String threadNameSuffix = "task consumer for " + PriorityScheduledExecutor.class.getSimpleName();
QUEUE_CONSUMER_THREAD_NAME_HIGH_PRIORITY = "high priority " + threadNameSuffix;
QUEUE_CONSUMER_THREAD_NAME_LOW_PRIORITY = "low priority " + threadNameSuffix;
}
protected final TaskPriority defaultPriority;
protected final Object highPriorityLock;
protected final Object lowPriorityLock;
protected final Object workersLock;
protected final Object poolSizeChangeLock;
protected final DynamicDelayQueue<TaskWrapper> highPriorityQueue;
protected final DynamicDelayQueue<TaskWrapper> lowPriorityQueue;
protected final Deque<Worker> availableWorkers; // is locked around workersLock
protected final ThreadFactory threadFactory;
protected final TaskConsumer highPriorityConsumer; // is locked around highPriorityLock
protected final TaskConsumer lowPriorityConsumer; // is locked around lowPriorityLock
private final AtomicBoolean shutdownStarted;
private volatile boolean shutdownFinishing; // once true, never goes to false
private volatile int corePoolSize; // can only be changed when poolSizeChangeLock locked
private volatile int maxPoolSize; // can only be changed when poolSizeChangeLock locked
private volatile long keepAliveTimeInMs;
private volatile long maxWaitForLowPriorityInMs;
private volatile boolean allowCorePoolTimeout;
private int waitingForWorkerCount; // is locked around workersLock
private int currentPoolSize; // is locked around workersLock
private long lastHighDelay; // is locked around workersLock
/**
* Constructs a new thread pool, though no threads will be started
* till it accepts it's first request. This constructs a default
* priority of high (which makes sense for most use cases).
* It also defaults low priority worker wait as 500ms. It also
* defaults to all newly created threads being daemon threads.
*
* @param corePoolSize pool size that should be maintained
* @param maxPoolSize maximum allowed thread count
* @param keepAliveTimeInMs time to wait for a given thread to be idle before killing
*/
public PriorityScheduledExecutor(int corePoolSize, int maxPoolSize,
long keepAliveTimeInMs) {
this(corePoolSize, maxPoolSize, keepAliveTimeInMs,
DEFAULT_PRIORITY, DEFAULT_LOW_PRIORITY_MAX_WAIT_IN_MS,
DEFAULT_NEW_THREADS_DAEMON);
}
/**
* Constructs a new thread pool, though no threads will be started
* till it accepts it's first request. This constructs a default
* priority of high (which makes sense for most use cases).
* It also defaults low priority worker wait as 500ms.
*
* @param corePoolSize pool size that should be maintained
* @param maxPoolSize maximum allowed thread count
* @param keepAliveTimeInMs time to wait for a given thread to be idle before killing
* @param useDaemonThreads boolean for if newly created threads should be daemon
*/
public PriorityScheduledExecutor(int corePoolSize, int maxPoolSize,
long keepAliveTimeInMs, boolean useDaemonThreads) {
this(corePoolSize, maxPoolSize, keepAliveTimeInMs,
DEFAULT_PRIORITY, DEFAULT_LOW_PRIORITY_MAX_WAIT_IN_MS,
useDaemonThreads);
}
/**
* Constructs a new thread pool, though no threads will be started
* till it accepts it's first request. This provides the extra
* parameters to tune what tasks submitted without a priority will be
* scheduled as. As well as the maximum wait for low priority tasks.
* The longer low priority tasks wait for a worker, the less chance they will
* have to make a thread. But it also makes low priority tasks execution time
* less predictable.
*
* @param corePoolSize pool size that should be maintained
* @param maxPoolSize maximum allowed thread count
* @param keepAliveTimeInMs time to wait for a given thread to be idle before killing
* @param defaultPriority priority to give tasks which do not specify it
* @param maxWaitForLowPriorityInMs time low priority tasks wait for a worker
*/
public PriorityScheduledExecutor(int corePoolSize, int maxPoolSize,
long keepAliveTimeInMs, TaskPriority defaultPriority,
long maxWaitForLowPriorityInMs) {
this(corePoolSize, maxPoolSize, keepAliveTimeInMs,
defaultPriority, maxWaitForLowPriorityInMs,
DEFAULT_NEW_THREADS_DAEMON);
}
/**
* Constructs a new thread pool, though no threads will be started
* till it accepts it's first request. This provides the extra
* parameters to tune what tasks submitted without a priority will be
* scheduled as. As well as the maximum wait for low priority tasks.
* The longer low priority tasks wait for a worker, the less chance they will
* have to make a thread. But it also makes low priority tasks execution time
* less predictable.
*
* @param corePoolSize pool size that should be maintained
* @param maxPoolSize maximum allowed thread count
* @param keepAliveTimeInMs time to wait for a given thread to be idle before killing
* @param defaultPriority priority to give tasks which do not specify it
* @param maxWaitForLowPriorityInMs time low priority tasks wait for a worker
* @param useDaemonThreads boolean for if newly created threads should be daemon
*/
public PriorityScheduledExecutor(int corePoolSize, int maxPoolSize,
long keepAliveTimeInMs, TaskPriority defaultPriority,
long maxWaitForLowPriorityInMs,
final boolean useDaemonThreads) {
this(corePoolSize, maxPoolSize, keepAliveTimeInMs,
defaultPriority, maxWaitForLowPriorityInMs,
new ThreadFactory() {
private final ThreadFactory defaultFactory = Executors.defaultThreadFactory();
@Override
public Thread newThread(Runnable runnable) {
Thread thread = defaultFactory.newThread(runnable);
thread.setDaemon(useDaemonThreads);
return thread;
}
});
}
/**
* Constructs a new thread pool, though no threads will be started
* till it accepts it's first request. This provides the extra
* parameters to tune what tasks submitted without a priority will be
* scheduled as. As well as the maximum wait for low priority tasks.
* The longer low priority tasks wait for a worker, the less chance they will
* have to make a thread. But it also makes low priority tasks execution time
* less predictable.
*
* @param corePoolSize pool size that should be maintained
* @param maxPoolSize maximum allowed thread count
* @param keepAliveTimeInMs time to wait for a given thread to be idle before killing
* @param defaultPriority priority to give tasks which do not specify it
* @param maxWaitForLowPriorityInMs time low priority tasks wait for a worker
* @param threadFactory thread factory for producing new threads within executor
*/
public PriorityScheduledExecutor(int corePoolSize, int maxPoolSize,
long keepAliveTimeInMs, TaskPriority defaultPriority,
long maxWaitForLowPriorityInMs, ThreadFactory threadFactory) {
if (corePoolSize < 1) {
throw new IllegalArgumentException("corePoolSize must be > 0");
} else if (maxPoolSize < corePoolSize) {
throw new IllegalArgumentException("maxPoolSize must be >= corePoolSize");
}
//calls to verify and set values
setKeepAliveTime(keepAliveTimeInMs);
setMaxWaitForLowPriority(maxWaitForLowPriorityInMs);
if (defaultPriority == null) {
defaultPriority = DEFAULT_PRIORITY;
}
if (threadFactory == null) {
threadFactory = Executors.defaultThreadFactory();
}
this.defaultPriority = defaultPriority;
highPriorityLock = new Object();
lowPriorityLock = new Object();
workersLock = new Object();
poolSizeChangeLock = new Object();
highPriorityQueue = new DynamicDelayQueue<TaskWrapper>(highPriorityLock);
lowPriorityQueue = new DynamicDelayQueue<TaskWrapper>(lowPriorityLock);
availableWorkers = new ArrayDeque<Worker>(maxPoolSize);
this.threadFactory = threadFactory;
highPriorityConsumer = new TaskConsumer(highPriorityQueue, highPriorityLock,
new ConsumerAcceptor<TaskWrapper>() {
@Override
public void acceptConsumedItem(TaskWrapper task) throws InterruptedException {
runHighPriorityTask(task);
}
});
lowPriorityConsumer = new TaskConsumer(lowPriorityQueue, lowPriorityLock,
new ConsumerAcceptor<TaskWrapper>() {
@Override
public void acceptConsumedItem(TaskWrapper task) throws InterruptedException {
runLowPriorityTask(task);
}
});
shutdownStarted = new AtomicBoolean(false);
shutdownFinishing = false;
this.corePoolSize = corePoolSize;
this.maxPoolSize = maxPoolSize;
this.allowCorePoolTimeout = false;
this.lastHighDelay = 0;
waitingForWorkerCount = 0;
currentPoolSize = 0;
}
/**
* If a section of code wants a different default priority, or wanting to provide
* a specific default priority in for {@link TaskExecutorDistributor},
* or {@link TaskSchedulerDistributor}.
*
* @param priority default priority for PrioritySchedulerInterface implementation
* @return a PrioritySchedulerInterface with the default priority specified
*/
public PrioritySchedulerInterface makeWithDefaultPriority(TaskPriority priority) {
if (priority == defaultPriority) {
return this;
} else {
return new PrioritySchedulerWrapper(this, priority);
}
}
@Override
public TaskPriority getDefaultPriority() {
return defaultPriority;
}
/**
* Getter for the current set core pool size.
*
* @return current core pool size
*/
public int getCorePoolSize() {
return corePoolSize;
}
/**
* Getter for the currently set max pool size.
*
* @return current max pool size
*/
public int getMaxPoolSize() {
return maxPoolSize;
}
/**
* Getter for the currently set keep alive time.
*
* @return current keep alive time
*/
public long getKeepAliveTime() {
return keepAliveTimeInMs;
}
/**
* Getter for the current qty of workers constructed (ether running or idle).
*
* @return current worker count
*/
public int getCurrentPoolSize() {
synchronized (workersLock) {
return currentPoolSize;
}
}
/**
* Call to check how many tasks are currently being executed
* in this thread pool.
*
* @return current number of running tasks
*/
public int getCurrentRunningCount() {
synchronized (workersLock) {
return currentPoolSize - availableWorkers.size();
}
}
/**
* Change the set core pool size. If the value is less than the current max
* pool size, the max pool size will also be updated to this value.
*
* If this was a reduction from the previous value, this call will examine idle workers
* to see if they should be expired. If this call reduced the max pool size, and the
* current running thread count is higher than the new max size, this call will NOT
* block till the pool is reduced. Instead as those workers complete, they will clean
* up on their own.
*
* @param corePoolSize New pool size. Must be at least one.
*/
public void setCorePoolSize(int corePoolSize) {
if (corePoolSize < 1) {
throw new IllegalArgumentException("corePoolSize must be > 0");
}
synchronized (poolSizeChangeLock) {
boolean lookForExpiredWorkers = this.corePoolSize > corePoolSize;
if (maxPoolSize < corePoolSize) {
setMaxPoolSize(corePoolSize);
}
this.corePoolSize = corePoolSize;
if (lookForExpiredWorkers) {
expireOldWorkers();
}
}
}
/**
* Change the set max pool size. If the value is less than the current core
* pool size, the core pool size will be reduced to match the new max pool size.
*
* If this was a reduction from the previous value, this call will examine idle workers
* to see if they should be expired. If the current running thread count is higher
* than the new max size, this call will NOT block till the pool is reduced.
* Instead as those workers complete, they will clean up on their own.
*
* @param maxPoolSize New max pool size. Must be at least one.
*/
public void setMaxPoolSize(int maxPoolSize) {
if (maxPoolSize < 1) {
throw new IllegalArgumentException("maxPoolSize must be > 0");
}
synchronized (poolSizeChangeLock) {
boolean poolSizeIncrease = maxPoolSize < this.maxPoolSize;
if (maxPoolSize < corePoolSize) {
this.corePoolSize = maxPoolSize;
}
this.maxPoolSize = maxPoolSize;
if (poolSizeIncrease) {
// now that pool size increased, start any workers we can for the waiting tasks
synchronized (workersLock) {
if (waitingForWorkerCount > 0) {
while (availableWorkers.size() < waitingForWorkerCount &&
currentPoolSize < this.maxPoolSize) {
availableWorkers.add(makeNewWorker());
}
workersLock.notifyAll();
}
}
} else {
expireOldWorkers();
}
}
}
/**
* Change the set idle thread keep alive time. If this is a reduction in the
* previously set keep alive time, this call will then check for expired worker
* threads.
*
* @param keepAliveTimeInMs New keep alive time in milliseconds. Must be at least zero.
*/
public void setKeepAliveTime(long keepAliveTimeInMs) {
if (keepAliveTimeInMs < 0) {
throw new IllegalArgumentException("keepAliveTimeInMs must be >= 0");
}
boolean checkForExpiredWorkers = this.keepAliveTimeInMs > keepAliveTimeInMs;
this.keepAliveTimeInMs = keepAliveTimeInMs;
if (checkForExpiredWorkers) {
expireOldWorkers();
}
}
/**
* Changes the max wait time for an idle worker for low priority tasks.
* Changing this will only take effect for future low priority tasks, it
* will have no impact for the current low priority task attempting to get
* a worker.
*
* @param maxWaitForLowPriorityInMs new time to wait for a thread in milliseconds. Must be at least zero.
*/
public void setMaxWaitForLowPriority(long maxWaitForLowPriorityInMs) {
if (maxWaitForLowPriorityInMs < 0) {
throw new IllegalArgumentException("maxWaitForLowPriorityInMs must be >= 0");
}
this.maxWaitForLowPriorityInMs = maxWaitForLowPriorityInMs;
}
/**
* Getter for the maximum amount of time a low priority task will
* wait for an available worker.
*
* @return currently set max wait for low priority task
*/
public long getMaxWaitForLowPriority() {
return maxWaitForLowPriorityInMs;
}
/**
* Returns how many tasks are either waiting to be executed,
* or are scheduled to be executed at a future point.
*
* @return qty of tasks waiting execution or scheduled to be executed later
*/
public int getScheduledTaskCount() {
return highPriorityQueue.size() + lowPriorityQueue.size();
}
/**
* Returns a count of how many tasks are either waiting to be executed,
* or are scheduled to be executed at a future point for a specific priority.
*
* @param priority priority for tasks to be counted
* @return qty of tasks waiting execution or scheduled to be executed later
*/
public int getScheduledTaskCount(TaskPriority priority) {
if (priority == null) {
return getScheduledTaskCount();
}
switch (priority) {
case High:
return highPriorityQueue.size();
case Low:
return lowPriorityQueue.size();
default:
throw new UnsupportedOperationException("Not implemented for priority: " + priority);
}
}
/**
* Prestarts all core threads. This will make new idle workers to accept future tasks.
*/
public void prestartAllCoreThreads() {
synchronized (workersLock) {
boolean startedThreads = false;
while (currentPoolSize < corePoolSize) {
availableWorkers.addFirst(makeNewWorker());
startedThreads = true;
}
if (startedThreads) {
workersLock.notifyAll();
}
}
}
/**
* Changes the setting weather core threads are allowed to be killed
* if they remain idle. If changing to allow core thread timeout,
* this call will then perform a check to look for expired workers.
*
* @param value true if core threads should be expired when idle.
*/
public void allowCoreThreadTimeOut(boolean value) {
boolean checkForExpiredWorkers = ! allowCorePoolTimeout && value;
allowCorePoolTimeout = value;
if (checkForExpiredWorkers) {
expireOldWorkers();
}
}
@Override
public boolean isShutdown() {
return shutdownStarted.get();
}
protected List<Runnable> clearTaskQueue() {
synchronized (highPriorityLock) {
synchronized (lowPriorityLock) {
highPriorityConsumer.stop();
lowPriorityConsumer.stop();
List<Runnable> removedTasks = new ArrayList<Runnable>(highPriorityQueue.size() +
lowPriorityQueue.size());
synchronized (highPriorityQueue.getLock()) {
Iterator<TaskWrapper> it = highPriorityQueue.iterator();
while (it.hasNext()) {
TaskWrapper tw = it.next();
tw.cancel();
removedTasks.add(tw.task);
}
lowPriorityQueue.clear();
}
synchronized (lowPriorityQueue.getLock()) {
Iterator<TaskWrapper> it = lowPriorityQueue.iterator();
while (it.hasNext()) {
TaskWrapper tw = it.next();
tw.cancel();
removedTasks.add(tw.task);
}
lowPriorityQueue.clear();
}
return removedTasks;
}
}
}
protected void shutdownAllWorkers() {
synchronized (workersLock) {
Iterator<Worker> it = availableWorkers.iterator();
while (it.hasNext()) {
Worker w = it.next();
it.remove();
killWorker(w);
}
}
}
/**
* Stops any new tasks from being submitted to the pool. But allows all currently scheduled
* tasks to be run. If scheduled tasks are present they will also be unable to reschedule.
*
* If you wish to not want to run any queued tasks you should use {#link shutdownNow()).
*/
public void shutdown() {
if (! shutdownStarted.getAndSet(true)) {
addToHighPriorityQueue(new OneTimeTaskWrapper(new ShutdownRunnable(),
TaskPriority.High, 1));
}
}
/**
* Stops any new tasks from being able to be executed and removes workers from the pool.
*
* This implementation refuses new submissions after this call. And will NOT interrupt any
* tasks which are currently running. But any tasks which are waiting in queue to be run
* (but have not started yet), will not be run. Those waiting tasks will be removed, and
* as workers finish with their current tasks the threads will be joined.
*
* @return List of runnables which were waiting to execute
*/
public List<Runnable> shutdownNow() {
shutdownStarted.set(true);
shutdownFinishing = true;
List<Runnable> awaitingTasks = clearTaskQueue();
shutdownAllWorkers();
return awaitingTasks;
}
protected void verifyNotShutdown() {
if (isShutdown()) {
throw new IllegalStateException("Thread pool shutdown");
}
}
/**
* Makes a new {@link PrioritySchedulerLimiter} that uses this pool as it's execution source.
*
* @param maxConcurrency maximum number of threads to run in parallel in sub pool
* @return newly created {@link PrioritySchedulerLimiter} that uses this pool as it's execution source
*/
public PrioritySchedulerInterface makeSubPool(int maxConcurrency) {
return makeSubPool(maxConcurrency, null);
}
/**
* Makes a new {@link PrioritySchedulerLimiter} that uses this pool as it's execution source.
*
* @param maxConcurrency maximum number of threads to run in parallel in sub pool
* @param subPoolName name to describe threads while running under this sub pool
* @return newly created {@link PrioritySchedulerLimiter} that uses this pool as it's execution source
*/
public PrioritySchedulerInterface makeSubPool(int maxConcurrency, String subPoolName) {
if (maxConcurrency > maxPoolSize) {
throw new IllegalArgumentException("A sub pool should be smaller than the parent pool");
}
return new PrioritySchedulerLimiter(this, maxConcurrency, subPoolName);
}
protected static boolean removeFromTaskQueue(DynamicDelayQueue<TaskWrapper> queue,
Runnable task) {
synchronized (queue.getLock()) {
Iterator<TaskWrapper> it = queue.iterator();
while (it.hasNext()) {
TaskWrapper tw = it.next();
if (ContainerHelper.isContained(tw.task, task)) {
tw.cancel();
it.remove();
return true;
}
}
}
return false;
}
protected static boolean removeFromTaskQueue(DynamicDelayQueue<TaskWrapper> queue,
Callable<?> task) {
synchronized (queue.getLock()) {
Iterator<TaskWrapper> it = queue.iterator();
while (it.hasNext()) {
TaskWrapper tw = it.next();
if (ContainerHelper.isContained(tw.task, task)) {
tw.cancel();
it.remove();
return true;
}
}
}
return false;
}
/**
* Removes the runnable task from the execution queue. It is possible
* for the task to still run until this call has returned.
*
* Note that this call has high guarantees on the ability to remove the task
* (as in a complete guarantee). But while this task is called, it will
* reduce the throughput of execution, so should not be used extremely
* frequently.
*
* @param task The original task provided to the executor
* @return true if the task was found and removed
*/
public boolean remove(Runnable task) {
return removeFromTaskQueue(highPriorityQueue, task) ||
removeFromTaskQueue(lowPriorityQueue, task);
}
/**
* Removes the callable task from the execution queue. It is
* possible for the callable to still run until this call has
* returned.
*
* Note that this call has high guarantees on the ability to remove the task
* (as in a complete guarantee). But while this task is called, it will
* reduce the throughput of execution, so should not be used extremely
* frequently.
*
* @param task The original callable provided to the executor
* @return true if the callable was found and removed
*/
public boolean remove(Callable<?> task) {
return removeFromTaskQueue(highPriorityQueue, task) ||
removeFromTaskQueue(lowPriorityQueue, task);
}
@Override
public void execute(Runnable task) {
schedule(task, 0, defaultPriority);
}
@Override
public void execute(Runnable task, TaskPriority priority) {
schedule(task, 0, priority);
}
@Override
public ListenableFuture<?> submit(Runnable task) {
return submitScheduled(task, null, 0, defaultPriority);
}
@Override
public <T> ListenableFuture<T> submit(Runnable task, T result) {
return submitScheduled(task, result, 0, defaultPriority);
}
@Override
public ListenableFuture<?> submit(Runnable task, TaskPriority priority) {
return submitScheduled(task, null, 0, priority);
}
@Override
public <T> ListenableFuture<T> submit(Runnable task, T result, TaskPriority priority) {
return submitScheduled(task, result, 0, priority);
}
@Override
public <T> ListenableFuture<T> submit(Callable<T> task) {
return submitScheduled(task, 0, defaultPriority);
}
@Override
public <T> ListenableFuture<T> submit(Callable<T> task, TaskPriority priority) {
return submitScheduled(task, 0, priority);
}
@Override
public void schedule(Runnable task, long delayInMs) {
schedule(task, delayInMs, defaultPriority);
}
@Override
public void schedule(Runnable task, long delayInMs,
TaskPriority priority) {
if (task == null) {
throw new IllegalArgumentException("Must provide a task");
} else if (delayInMs < 0) {
throw new IllegalArgumentException("delayInMs must be >= 0");
}
if (priority == null) {
priority = defaultPriority;
}
addToQueue(new OneTimeTaskWrapper(task, priority, delayInMs));
}
@Override
public ListenableFuture<?> submitScheduled(Runnable task, long delayInMs) {
return submitScheduled(task, delayInMs, defaultPriority);
}
@Override
public <T> ListenableFuture<T> submitScheduled(Runnable task, T result, long delayInMs) {
return submitScheduled(task, result, delayInMs, defaultPriority);
}
@Override
public ListenableFuture<?> submitScheduled(Runnable task, long delayInMs,
TaskPriority priority) {
return submitScheduled(task, null, delayInMs, priority);
}
@Override
public <T> ListenableFuture<T> submitScheduled(Runnable task, T result,
long delayInMs,
TaskPriority priority) {
if (task == null) {
throw new IllegalArgumentException("Must provide a task");
} else if (delayInMs < 0) {
throw new IllegalArgumentException("delayInMs must be >= 0");
}
if (priority == null) {
priority = defaultPriority;
}
ListenableRunnableFuture<T> rf = new ListenableFutureTask<T>(false, task, result);
addToQueue(new OneTimeTaskWrapper(rf, priority, delayInMs));
return rf;
}
@Override
public <T> ListenableFuture<T> submitScheduled(Callable<T> task, long delayInMs) {
return submitScheduled(task, delayInMs, defaultPriority);
}
@Override
public <T> ListenableFuture<T> submitScheduled(Callable<T> task, long delayInMs,
TaskPriority priority) {
if (task == null) {
throw new IllegalArgumentException("Must provide a task");
} else if (delayInMs < 0) {
throw new IllegalArgumentException("delayInMs must be >= 0");
}
if (priority == null) {
priority = defaultPriority;
}
ListenableRunnableFuture<T> rf = new ListenableFutureTask<T>(false, task);
addToQueue(new OneTimeTaskWrapper(rf, priority, delayInMs));
return rf;
}
@Override
public void scheduleWithFixedDelay(Runnable task, long initialDelay,
long recurringDelay) {
scheduleWithFixedDelay(task, initialDelay, recurringDelay,
defaultPriority);
}
@Override
public void scheduleWithFixedDelay(Runnable task, long initialDelay,
long recurringDelay, TaskPriority priority) {
if (task == null) {
throw new IllegalArgumentException("Must provide a task");
} else if (initialDelay < 0) {
throw new IllegalArgumentException("initialDelay must be >= 0");
} else if (recurringDelay < 0) {
throw new IllegalArgumentException("recurringDelay must be >= 0");
}
if (priority == null) {
priority = defaultPriority;
}
addToQueue(new RecurringTaskWrapper(task, priority, initialDelay, recurringDelay));
}
protected void addToQueue(TaskWrapper task) {
verifyNotShutdown();
switch (task.priority) {
case High:
addToHighPriorityQueue(task);
break;
case Low:
addToLowPriorityQueue(task);
break;
default:
throw new UnsupportedOperationException("Priority not implemented: " + task.priority);
}
}
private void addToHighPriorityQueue(TaskWrapper task) {
ClockWrapper.stopForcingUpdate();
try {
highPriorityQueue.add(task);
} finally {
ClockWrapper.resumeForcingUpdate();
}
highPriorityConsumer.maybeStart(threadFactory,
QUEUE_CONSUMER_THREAD_NAME_HIGH_PRIORITY);
}
private void addToLowPriorityQueue(TaskWrapper task) {
ClockWrapper.stopForcingUpdate();
try {
lowPriorityQueue.add(task);
} finally {
ClockWrapper.resumeForcingUpdate();
}
lowPriorityConsumer.maybeStart(threadFactory,
QUEUE_CONSUMER_THREAD_NAME_LOW_PRIORITY);
}
/**
* This function REQUIRES that workersLock is synchronized before calling.
*
* @param maxWaitTimeInMs time to wait for a worker to become available
* @return an available worker, or null if no worker became available within the maxWaitTimeInMs
* @throws InterruptedException Thrown if thread is interrupted while waiting for worker
*/
protected Worker getExistingWorker(long maxWaitTimeInMs) throws InterruptedException {
long startTime = Clock.accurateTime();
waitingForWorkerCount++;
try {
long waitTime = maxWaitTimeInMs;
while (availableWorkers.isEmpty() && waitTime > 0) {
if (waitTime == Long.MAX_VALUE) { // prevent overflow
workersLock.wait();
} else {
long elapsedTime = Clock.accurateTime() - startTime;
waitTime = maxWaitTimeInMs - elapsedTime;
if (waitTime > 0) {
workersLock.wait(waitTime);
}
}
}
if (availableWorkers.isEmpty()) {
return null; // we exceeded the wait time
} else {
// always remove from the front, to get the newest worker
return availableWorkers.removeFirst();
}
} finally {
waitingForWorkerCount
}
}
/**
* This function REQUIRES that workersLock is synchronized before calling.
*
* @return Newly created worker, started and ready to accept work
*/
protected Worker makeNewWorker() {
Worker w = new Worker();
currentPoolSize++;
w.start();
// will be added to available workers when done with first task
return w;
}
protected void runHighPriorityTask(TaskWrapper task) throws InterruptedException {
Worker w = null;
synchronized (workersLock) {
if (! shutdownFinishing) {
if (currentPoolSize >= maxPoolSize) {
lastHighDelay = task.getDelayEstimateInMillis();
// we can't make the pool any bigger
w = getExistingWorker(Long.MAX_VALUE);
} else {
lastHighDelay = 0;
if (availableWorkers.isEmpty()) {
w = makeNewWorker();
} else {
// always remove from the front, to get the newest worker
w = availableWorkers.removeFirst();
}
}
}
}
if (w != null) { // may be null if shutdown
w.nextTask(task);
}
}
protected void runLowPriorityTask(TaskWrapper task) throws InterruptedException {
Worker w = null;
synchronized (workersLock) {
if (! shutdownFinishing) {
// wait for high priority tasks that have been waiting longer than us if all workers are consumed
long waitAmount;
while (currentPoolSize >= maxPoolSize &&
availableWorkers.size() < WORKER_CONTENTION_LEVEL && // only care if there is worker contention
! shutdownFinishing &&
(waitAmount = task.getDelayEstimateInMillis() - lastHighDelay) > LOW_PRIORITY_WAIT_TOLLERANCE_IN_MS) {
if (highPriorityQueue.isEmpty()) {
lastHighDelay = 0; // no waiting high priority tasks, so no need to wait on low priority tasks
} else {
workersLock.wait(waitAmount);
Clock.accurateTime(); // update for getDelayEstimateInMillis
}
}
if (! shutdownFinishing) { // check again that we are still running
long waitTime;
if (currentPoolSize >= maxPoolSize) {
waitTime = Long.MAX_VALUE;
} else {
waitTime = maxWaitForLowPriorityInMs;
}
w = getExistingWorker(waitTime);
if (w == null) {
// this means we expired past our wait time, so create a worker if we can
if (currentPoolSize >= maxPoolSize) {
// more workers were created while waiting, now have reached our max
w = getExistingWorker(Long.MAX_VALUE);
} else {
w = makeNewWorker();
}
}
}
}
}
if (w != null) { // may be null if shutdown
w.nextTask(task);
}
}
protected void expireOldWorkers() {
synchronized (workersLock) {
long now = Clock.lastKnownTimeMillis();
// we search backwards because the oldest workers will be at the back of the stack
while ((currentPoolSize > corePoolSize || allowCorePoolTimeout) &&
! availableWorkers.isEmpty() &&
(now - availableWorkers.getLast().getLastRunTime() > keepAliveTimeInMs ||
currentPoolSize > maxPoolSize)) { // it does not matter how old it is, the max pool size has changed
Worker w = availableWorkers.removeLast();
killWorker(w);
}
}
}
private void killWorker(Worker w) {
synchronized (workersLock) {
/* we check running around workersLock since we want to make sure
* we don't decrement the pool size more than once for a single worker
*/
if (w.running) {
currentPoolSize
// it may not always be here, but it sometimes can (for example when a worker is interrupted)
availableWorkers.remove(w);
w.stop(); // will set running to false for worker
}
}
}
protected void workerDone(Worker worker) {
synchronized (workersLock) {
if (shutdownFinishing) {
killWorker(worker);
} else {
// always add to the front so older workers are at the back
availableWorkers.addFirst(worker);
expireOldWorkers();
workersLock.notify();
}
}
}
/**
* <p>Runnable which will consume tasks from the appropriate
* and given the provided implementation to get a worker
* and execute consumed tasks.</p>
*
* @author jent - Mike Jensen
*/
protected class TaskConsumer extends BlockingQueueConsumer<TaskWrapper> {
private final Object queueLock;
public TaskConsumer(DynamicDelayQueue<TaskWrapper> queue,
Object queueLock,
ConsumerAcceptor<TaskWrapper> taskAcceptor) {
super(queue, taskAcceptor);
this.queueLock = queueLock;
}
@Override
public TaskWrapper getNext() throws InterruptedException {
TaskWrapper task;
/* must lock as same lock for removal to
* ensure that task can be found for removal
*/
synchronized (queueLock) {
task = queue.take();
task.executing(); // for recurring tasks this will put them back into the queue
}
return task;
}
}
/**
* <p>Runnable which will run on pool threads. It
* accepts runnables to run, and tracks usage.</p>
*
* @author jent - Mike Jensen
*/
protected class Worker implements Runnable {
protected final Thread thread;
private volatile long lastRunTime;
private volatile boolean running;
private volatile TaskWrapper nextTask;
protected Worker() {
thread = threadFactory.newThread(this);
running = false;
lastRunTime = Clock.lastKnownTimeMillis();
nextTask = null;
}
// should only be called from killWorker
public void stop() {
if (! running) {
return;
} else {
running = false;
LockSupport.unpark(thread);
}
}
public void start() {
if (running) {
return;
} else {
running = true;
thread.start();
}
}
public void nextTask(TaskWrapper task) {
if (! running) {
throw new IllegalStateException();
} else if (nextTask != null) {
throw new IllegalStateException();
}
nextTask = task;
LockSupport.unpark(thread);
}
public void blockTillNextTask() {
boolean checkedInterrupted = false;
while (nextTask == null && running) {
LockSupport.park(this);
checkInterrupted();
checkedInterrupted = true;
}
if (! checkedInterrupted) {
// must verify thread is not in interrupted status before it runs a task
checkInterrupted();
}
}
private void checkInterrupted() {
if (Thread.interrupted()) { // check and clear interrupt
if (shutdownFinishing) {
/* If provided a new task, by the time killWorker returns we will still run that task
* before letting the thread return.
*/
killWorker(this);
}
}
}
@Override
public void run() {
while (running) {
try {
blockTillNextTask();
if (nextTask != null) {
nextTask.run();
}
} catch (Throwable t) {
ExceptionUtils.handleException(t);
} finally {
nextTask = null;
if (running) {
// only check if still running, otherwise worker has already been killed
if (Thread.interrupted() && // clear interrupt
shutdownFinishing) { // if shutting down kill worker
killWorker(this);
} else {
lastRunTime = Clock.lastKnownTimeMillis();
workerDone(this);
}
}
}
}
}
public long getLastRunTime() {
return lastRunTime;
}
}
/**
* <p>Behavior for task after it finishes completion.</p>
*
* @author jent - Mike Jensen
*/
protected enum TaskType { OneTime, Recurring };
/**
* <p>Abstract implementation for all tasks handled by this pool.</p>
*
* @author jent - Mike Jensen
*/
protected abstract static class TaskWrapper implements Delayed, Runnable {
public final TaskType taskType;
public final TaskPriority priority;
protected final Runnable task;
protected volatile boolean canceled;
public TaskWrapper(TaskType taskType,
Runnable task,
TaskPriority priority) {
this.taskType = taskType;
this.priority = priority;
this.task = task;
canceled = false;
}
public void cancel() {
canceled = true;
if (task instanceof Future<?>) {
((Future<?>)task).cancel(false);
}
}
public abstract void executing();
protected abstract long getDelayEstimateInMillis();
@Override
public int compareTo(Delayed o) {
if (this == o) {
return 0;
} else {
long thisDelay = this.getDelay(TimeUnit.MILLISECONDS);
long otherDelay = o.getDelay(TimeUnit.MILLISECONDS);
if (thisDelay == otherDelay) {
return 0;
} else if (thisDelay > otherDelay) {
return 1;
} else {
return -1;
}
}
}
@Override
public String toString() {
return task.toString();
}
}
/**
* <p>Wrapper for tasks which only executes once.</p>
*
* @author jent - Mike Jensen
*/
protected static class OneTimeTaskWrapper extends TaskWrapper {
private final long runTime;
protected OneTimeTaskWrapper(Runnable task, TaskPriority priority, long delay) {
super(TaskType.OneTime, task, priority);
runTime = Clock.accurateTime() + delay;
}
@Override
public long getDelay(TimeUnit unit) {
return unit.convert(runTime - ClockWrapper.getSemiAccurateTime(),
TimeUnit.MILLISECONDS);
}
@Override
protected long getDelayEstimateInMillis() {
return runTime - Clock.lastKnownTimeMillis();
}
@Override
public void executing() {
// ignored
}
@Override
public void run() {
if (! canceled) {
task.run();
}
}
}
/**
* <p>Wrapper for tasks which reschedule after completion.</p>
*
* @author jent - Mike Jensen
*/
protected class RecurringTaskWrapper extends TaskWrapper
implements DynamicDelayedUpdater {
private final long recurringDelay;
//private volatile long maxExpectedRuntime;
private volatile boolean executing;
private long nextRunTime;
protected RecurringTaskWrapper(Runnable task, TaskPriority priority,
long initialDelay, long recurringDelay) {
super(TaskType.Recurring, task, priority);
this.recurringDelay = recurringDelay;
//maxExpectedRuntime = -1;
executing = false;
this.nextRunTime = Clock.accurateTime() + initialDelay;
}
@Override
public long getDelay(TimeUnit unit) {
if (executing) {
return Long.MAX_VALUE;
} else {
return unit.convert(getNextDelayInMillis(),
TimeUnit.MILLISECONDS);
}
}
private long getNextDelayInMillis() {
return nextRunTime - ClockWrapper.getSemiAccurateTime();
}
@Override
protected long getDelayEstimateInMillis() {
return nextRunTime - Clock.lastKnownTimeMillis();
}
@Override
public void allowDelayUpdate() {
executing = false;
}
@Override
public void executing() {
if (canceled) {
return;
}
executing = true;
/* add to queue before started, so that it can be removed if necessary
* We add to the end because the task wont re-run till it has finished,
* so there is no reason to sort at this point
*/
switch (priority) {
case High:
highPriorityQueue.addLast(this);
break;
case Low:
lowPriorityQueue.addLast(this);
break;
default:
throw new UnsupportedOperationException("Not implemented for priority: " + priority);
}
}
private void reschedule() {
nextRunTime = Clock.accurateTime() + recurringDelay;
// now that nextRunTime has been set, resort the queue
switch (priority) {
case High:
synchronized (highPriorityLock) {
if (! shutdownStarted.get()) {
ClockWrapper.stopForcingUpdate();
try {
highPriorityQueue.reposition(this, getNextDelayInMillis(), this);
} finally {
ClockWrapper.resumeForcingUpdate();
}
}
}
break;
case Low:
synchronized (lowPriorityLock) {
if (! shutdownStarted.get()) {
ClockWrapper.stopForcingUpdate();
try {
lowPriorityQueue.reposition(this, getNextDelayInMillis(), this);
} finally {
ClockWrapper.resumeForcingUpdate();
}
}
}
break;
default:
throw new UnsupportedOperationException("Not implemented for priority: " + priority);
}
}
@Override
public void run() {
if (canceled) {
return;
}
try {
//long startTime = ClockWrapper.getLastKnownTime();
task.run();
/*long runTime = ClockWrapper.getLastKnownTime() - startTime;
if (runTime > maxExpectedRuntime) {
maxExpectedRuntime = runTime;
}*/
} finally {
if (! canceled) {
try {
reschedule();
} catch (java.util.NoSuchElementException e) {
if (canceled) {
/* this is a possible condition where shutting down
* the thread pool occurred while rescheduling the item.
*
* Since this is unlikely, we just swallow the exception here.
*/
} else {
/* This condition however would not be expected,
* so we should throw the exception.
*/
throw e;
}
}
}
}
}
}
/**
* <p>Runnable to be run after all current tasks to finish the shutdown sequence.</p>
*
* @author jent - Mike Jensen
*/
protected class ShutdownRunnable implements Runnable {
@Override
public void run() {
shutdownNow();
}
}
}
|
/*
* @MultiplePickerField.java 1.0 Jun 25, 2013 Sistema Integral de Gestion
* Hospitalaria
*/
package py.una.med.base.dynamic.forms;
import java.util.Collections;
import java.util.List;
import py.una.med.base.util.KarakuListHelperProvider;
import py.una.med.base.util.LabelProvider;
public class MultiplePickerField<T> extends LabelField {
public interface ItemKeyProvider<T> {
Object getKeyValue(T item);
}
public interface ValuesChangeListener<T> {
boolean onChange(Field source, List<T> values);
}
public interface PickerValidator<T> {
boolean validate(Field source, List<T> values);
}
public static final String TYPE = "py.una.med.base.dynamic.forms.MultiplePickerField";
private String popupID;
private String dataTableID;
private boolean buttonDisabled;
private List<T> values;
private LabelProvider<List<T>> valuesLabelProvider;
private KarakuListHelperProvider<T> listHelper;
private String urlColumns;
private ItemKeyProvider<T> itemKeyProvider;
private ValuesChangeListener<T> valuesChangeListener;
private PickerValidator<T> pickerValidator;
public MultiplePickerField() {
super();
popupID = getId() + "popup";
dataTableID = popupID + "datatable";
}
@Override
public String getType() {
return TYPE;
}
public String getPopUpClientID() {
return findComponent(getPopupID()).getClientId();
}
@Override
public boolean disable() {
setButtonDisabled(true);
return true;
}
@Override
public boolean enable() {
setButtonDisabled(false);
return true;
}
public String getPopupID() {
return popupID;
}
public void setPopupID(String id) {
popupID = id;
}
public boolean isButtonDisabled() {
return buttonDisabled;
}
public void setButtonDisabled(boolean buttonDisabled) {
this.buttonDisabled = buttonDisabled;
}
public List<T> getValues() {
if (values == null) {
return Collections.emptyList();
}
return values;
}
public void setValues(List<T> values) {
this.values = values;
}
public LabelProvider<List<T>> getValuesLabelProvider() {
return valuesLabelProvider;
}
public void setValuesLabelProvider(
LabelProvider<List<T>> valuesLabelProvider) {
this.valuesLabelProvider = valuesLabelProvider;
}
public String getFormatedSelectedOptions() {
return getFormatedSelectedOptions(values);
}
public String getFormatedSelectedOptions(List<T> options) {
if (options == null) {
return "";
}
if (valuesLabelProvider == null) {
return Integer.toString(options.size());
}
return valuesLabelProvider.getAsString(options);
}
public Object getItemKey(T item) {
if (itemKeyProvider == null) {
throw new IllegalArgumentException(
"itemKeyProvider no puede ser null");
}
return itemKeyProvider.getKeyValue(item);
}
/**
* Retorna la url donde se encuentran las columnas mostradas por el popup de
* seleccion
*
* @return urlColumns
*/
public String getUrlColumns() {
return urlColumns;
}
/**
* Configura el componente para mostrar las filas que se encuetnran en la
* url pasada como parametro
*
* @param urlColumns
* urlColumns para setear
*/
public void setUrlColumns(final String urlColumns) {
this.urlColumns = urlColumns;
}
/**
* Retorna el list helper, el cual se encarga de los filtros y de mostrar
* informacion
*
* @return ListHelper
*/
public KarakuListHelperProvider<T> getListHelper() {
return listHelper;
}
/**
* Setea el list helper que sera utilizado por el sistema
*
* @param listHelper
* listHelper para setear
*/
public void setListHelper(final KarakuListHelperProvider<T> listHelper) {
if (listHelper == null) {
throw new IllegalArgumentException("listHelper no puede ser null");
}
this.listHelper = listHelper;
}
public String getDataTableID() {
return dataTableID;
}
public void setDataTableID(String id) {
dataTableID = id;
}
public ItemKeyProvider<T> getItemKeyProvider() {
return itemKeyProvider;
}
public void setItemKeyProvider(ItemKeyProvider<T> itemKeyProvider) {
this.itemKeyProvider = itemKeyProvider;
}
/**
* Se encarga de llamar al metodo {@link ValueChangeListener#onChange }
* cuando existe un cambio en el valor asociado al {@link PickerField}
**/
public void changeValueListener() {
if (valuesChangeListener == null) {
return;
}
valuesChangeListener.onChange(this, getValues());
performValidation();
}
/**
* Setea el {@link ValuesChangeListener} cuando existe un cambio en el valor
* asociado al {@link PickerField}
**/
public void setValuesChangeListener(ValuesChangeListener<T> listener) {
this.valuesChangeListener = listener;
}
public void performValidation() {
if (pickerValidator == null) {
return;
}
pickerValidator.validate(this, getValues());
}
public void setPickerValidator(PickerValidator<T> validator) {
if (validator == null) {
throw new IllegalArgumentException("validator no puede ser null");
}
pickerValidator = validator;
}
public void clear() {
values = Collections.<T> emptyList();
}
}
|
package ru.VirtaMarketAnalyzer.parser;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.jsoup.nodes.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ru.VirtaMarketAnalyzer.data.*;
import ru.VirtaMarketAnalyzer.main.Utils;
import ru.VirtaMarketAnalyzer.main.Wizard;
import ru.VirtaMarketAnalyzer.scrapper.Downloader;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.*;
import java.util.stream.Collectors;
public final class ServiceAtCityParser {
private static final Logger logger = LoggerFactory.getLogger(ServiceAtCityParser.class);
private static ServiceSpecRetail addRetailStatByProduct(final String host, final String realm, final String productID, final City city) {
try {
final TradeAtCity tac = CityParser.get(Wizard.host, realm, city, ProductInitParser.getTradingProduct(host, realm, productID), null, null).build();
return new ServiceSpecRetail(tac.getLocalPrice(), tac.getLocalQuality(), tac.getShopPrice(), tac.getShopQuality());
} catch (final Exception e) {
logger.error("Ошибка: ", e);
}
return null;
}
private static Map<String, ServiceSpecRetail> getRetailStat(final String host, final String realm
, final UnitTypeSpec spec
, final City city
, final Set<String> tradingProductsId
) {
final Map<String, ServiceSpecRetail> stat = new HashMap<>();
if (tradingProductsId.contains(spec.getEquipment().getId())) {
stat.put(spec.getEquipment().getId(), addRetailStatByProduct(host, realm, spec.getEquipment().getId(), city));
}
spec.getRawMaterials()
.stream()
.forEach(mat -> {
if (tradingProductsId.contains(mat.getId())) {
stat.put(mat.getId(), addRetailStatByProduct(host, realm, mat.getId(), city));
} else {
stat.put(mat.getId(), new ServiceSpecRetail(0, 0, 0, 0));
}
});
return stat;
}
private static ServiceSpecRetail calcBySpec(final String realm, final UnitTypeSpec spec, final Map<String, ServiceSpecRetail> stat) {
try {
// logger.info("spec.getRawMaterials().size() = {}", spec.getRawMaterials().size());
// logger.info("stat.containsKey(spec.getEquipment()) = {}", stat.containsKey(spec.getEquipment().getId()));
if (spec.getRawMaterials().size() > 0) {
final double localPrice = spec.getRawMaterials()
.stream()
.mapToDouble(mat -> stat.get(mat.getId()).getLocalPrice() * mat.getQuantity())
.sum();
final double localQuality = spec.getRawMaterials()
.stream()
.mapToDouble(mat -> stat.get(mat.getId()).getLocalQuality())
.average().orElse(0);
final double shopPrice = spec.getRawMaterials()
.stream()
.mapToDouble(mat -> stat.get(mat.getId()).getShopPrice() * mat.getQuantity())
.sum();
final double shopQuality = spec.getRawMaterials()
.stream()
.mapToDouble(mat -> stat.get(mat.getId()).getShopQuality())
.average().orElse(0);
return new ServiceSpecRetail(localPrice, localQuality, shopPrice, shopQuality);
} else if (stat.containsKey(spec.getEquipment().getId())) {
final ServiceSpecRetail serviceSpecRetail = stat.get(spec.getEquipment().getId());
final double localPrice = serviceSpecRetail.getLocalPrice();
final double localQuality = serviceSpecRetail.getLocalQuality();
final double shopPrice = serviceSpecRetail.getShopPrice();
final double shopQuality = serviceSpecRetail.getShopQuality();
return new ServiceSpecRetail(localPrice, localQuality, shopPrice, shopQuality);
}
} catch (final Exception e) {
logger.error("stat.size() = " + stat.size());
for (final RawMaterial mat : spec.getRawMaterials()) {
logger.error("('" + mat.getCaption() + "', stat.containsKey('" + mat.getId() + "') = " + stat.containsKey(mat.getId()));
}
logger.error("spec.getCaption() = " + spec.getCaption() + ", spec.getRawMaterials().size() = " + spec.getRawMaterials().size() + ", realm = " + realm, e);
}
return new ServiceSpecRetail(0, 0, 0, 0);
}
public static ServiceAtCity get(
final String host
, final String realm
, final City city
, final UnitType service
, final List<Region> regions
, final Set<String> tradingProductsId
, final List<RentAtCity> rents
) throws IOException {
final ServiceMetrics serviceMetrics = getServiceMetrics(host, realm, city, service);
final Map<String, Double> percentBySpec = getPercentBySpec(host, realm, city, service);
final double incomeTaxRate = (regions == null) ? 0 : regions.stream().filter(r -> r.getId().equals(city.getRegionId())).findFirst().get().getIncomeTaxRate();
final Map<String, Map<String, ServiceSpecRetail>> retailBySpec = new HashMap<>();
final Map<String, ServiceSpecRetail> retailCalcBySpec = new HashMap<>();
service.getSpecializations().forEach(spec -> {
final Map<String, ServiceSpecRetail> stat = getRetailStat(host, realm, spec, city, tradingProductsId);
retailCalcBySpec.put(spec.getCaption(), calcBySpec(realm, spec, stat));
stat.remove(spec.getEquipment().getId());
retailBySpec.put(spec.getCaption(), stat);
});
final double areaRent = rents.stream()
.filter(r -> r.getCityId().equalsIgnoreCase(city.getId()))
.filter(r -> r.getUnitTypeImgSrc().equalsIgnoreCase(service.getUnitTypeImgSrc()))
.findAny()
.get()
.getAreaRent();
return new ServiceAtCity(city.getCountryId()
, city.getRegionId()
, city.getId()
, serviceMetrics.getSales()
, serviceMetrics.getPrice()
, serviceMetrics.getUnitCount()
, serviceMetrics.getCompanyCount()
, Utils.round2(serviceMetrics.getRevenuePerRetail() * 100.0)
, percentBySpec
, city.getWealthIndex()
, incomeTaxRate
, retailBySpec
, retailCalcBySpec
, areaRent
);
}
public static List<ServiceAtCity> get(
final String host
, final String realm
, final List<City> cities
, final UnitType service
, final List<Region> regions
, final List<RentAtCity> rents
) throws IOException {
final Set<String> tradingProductsId = ProductInitParser.getTradingProducts(host, realm).stream().map(Product::getId).collect(Collectors.toSet());
return cities.parallelStream().map(city -> {
try {
return get(host, realm, city, service, regions, tradingProductsId, rents);
} catch (final IOException e) {
logger.error(e.getLocalizedMessage(), e);
}
return null;
})
.filter(Objects::nonNull)
.collect(Collectors.toList());
}
private static ServiceMetrics getServiceMetrics(final String host, final String realm, final City city, final UnitType service) throws IOException {
//TODO: &produce_id=422835
final String url = host + "api/" + realm + "/main/marketing/report/service/metrics?geo=" + city.getGeo() + "&unit_type_id=" + service.getId();
try {
final Document doc = Downloader.getDoc(url, true);
final String json = doc.body().text();
final Gson gson = new Gson();
final Type mapType = new TypeToken<Map<String, Object>>() {
}.getType();
final Map<String, Object> mapOfMetrics = gson.fromJson(json, mapType);
final String turnId = mapOfMetrics.get("turn_id").toString();
final double price = Utils.toDouble(mapOfMetrics.get("price").toString());
final long sales = Utils.toLong(mapOfMetrics.get("sales").toString());
final int unitCount = Utils.toInt(mapOfMetrics.get("unit_count").toString());
final int companyCount = Utils.toInt(mapOfMetrics.get("company_count").toString());
final double revenuePerRetail = Utils.toDouble(mapOfMetrics.get("revenue_per_retail").toString());
final String name = mapOfMetrics.get("name").toString();
final String symbol = mapOfMetrics.get("symbol").toString();
final String specialization = mapOfMetrics.get("specialization").toString();
return new ServiceMetrics(turnId, price, sales, unitCount, companyCount, revenuePerRetail, name, symbol, specialization);
} catch (final Exception e) {
logger.error(url + "&format=debug");
throw e;
}
}
private static Map<String, Double> getPercentBySpec(final String host, final String realm, final City city, final UnitType service) throws IOException {
final Map<String, Double> percentBySpec = new HashMap<>();
//TODO: &produce_id=422835
final String url = host + "api/" + realm + "/main/marketing/report/service/specializations?geo=" + city.getGeo() + "&unit_type_id=" + service.getId();
try {
final Document doc = Downloader.getDoc(url, true);
final String json = doc.body().text();
final Gson gson = new Gson();
final Type mapType = new TypeToken<Map<String, Map<String, Object>>>() {
}.getType();
final Map<String, Map<String, Object>> mapOfMetrics = gson.fromJson(json, mapType);
for (final String idx : mapOfMetrics.keySet()) {
final Map<String, Object> metrics = mapOfMetrics.get(idx);
final String caption = metrics.get("name").toString();
final double marketPerc = Utils.toDouble(metrics.get("market_size").toString());
percentBySpec.put(caption, marketPerc);
}
} catch (final Exception e) {
logger.error(url + "&format=debug");
throw e;
}
return percentBySpec;
}
}
|
/*
* Author : Stephen Chong
* Created: Nov 24, 2003
*/
package polyglot.pth;
import java.io.*;
import java.util.List;
public class ScriptTestSuite extends TestSuite {
protected File scriptFile;
protected boolean saveProblem = false;
private boolean scriptLoaded = false;
public ScriptTestSuite(String scriptFilename) {
super(scriptFilename);
this.scriptFile = new File(scriptFilename);
this.loadResults();
}
public ScriptTestSuite(File scriptFile) {
super(scriptFile.getName());
this.scriptFile = scriptFile;
this.loadResults();
}
protected boolean loadScript() {
if (scriptLoaded) return true;
scriptLoaded = true;
if (!this.scriptFile.exists()) {
this.setFailureMessage("File " + scriptFile.getName() + " not found.");
return false;
}
else {
if (!parseScript()) {
return false;
}
}
return true;
}
protected boolean runTest() {
saveProblem = false;
if (!loadScript()) {
return false;
}
this.setOutputController(output);
return super.runTest();
}
protected void postIndividualTest() {
if (!saveProblem) {
this.saveProblem = !saveResults();
}
}
protected void postRun() {
super.postRun();
this.saveResults();
}
protected boolean parseScript() {
Grm grm = new Grm(this.scriptFile);
try {
this.tests = (List<Test>)grm.parse().value;
}
catch (Exception e) {
this.setFailureMessage("Parsing error: " + e.getMessage());
return false;
}
return true;
}
protected void loadResults() {
try {
ObjectInputStream ois =
new ObjectInputStream(
new FileInputStream(TestSuiteResult.getResultsFileName(this.scriptFile)));
TestResult tr = (TestResult)ois.readObject();
this.setTestResult(tr);
ois.close();
}
catch (FileNotFoundException e) {
// ignore, and fail silently
}
catch (ClassNotFoundException e) {
System.err.println("Unable to load results for test suite " + this.getName() + ": " + e.getMessage());
}
catch (IOException e) {
System.err.println("Unable to load results for test suite " + this.getName() + ": " + e.getMessage());
}
}
protected boolean saveResults() {
try {
ObjectOutputStream oos =
new ObjectOutputStream(
new FileOutputStream(TestSuiteResult.getResultsFileName(this.scriptFile)));
oos.writeObject(this.getTestSuiteResult());
oos.close();
}
catch (IOException e) {
System.err.println("Unable to save results for test suite " + this.getName());
return false;
}
return true;
}
public List<Test> getTests() {
this.loadScript();
return super.getTests();
}
}
|
package edu.umd.cs.findbugs.detect;
import java.util.*;
import org.apache.bcel.classfile.*;
import org.apache.bcel.generic.*;
import edu.umd.cs.findbugs.*;
import edu.umd.cs.daveho.ba.*;
import edu.umd.cs.daveho.ba.bcp.*;
/**
* A bug detector that uses a ByteCodePattern to find instances of
* the double check idiom. This class serves as a good example of
* how ByteCodePatterns can be used to simplify the task of implementing
* Detectors.
*
* @see ByteCodePattern
* @author David Hovemeyer
*/
public class BCPDoubleCheck extends ByteCodePatternDetector {
// FIXME: prescreen for the existence of
// MONITORENTER, GETFIELD/GETSTATIC, and PUTFIELD/PUTSTATIC
// to avoid scanning a lot of methods
private BugReporter bugReporter;
/**
* Default maximum number of "wildcard" instructions to accept between explicit
* pattern instructions.
*/
private static final int MAX_WILD = 8;
/**
* Maximum number of "wildcard" instructions to accept for object creation
* in the doublecheck. This needs to be a lot higher than MAX_WILD.
*/
private static final int CREATE_OBJ_WILD = 40;
/**
* Constructor.
* @param bugReporter
*/
public BCPDoubleCheck(BugReporter bugReporter) {
this.bugReporter = bugReporter;
}
/**
* The doublecheck pattern.
* The variable "h" represents the field.
* "x" and "y" are local values resulting from loading
* the field.
*/
private static final ByteCodePattern pattern = new ByteCodePattern();
static {
pattern
.setInterElementWild(MAX_WILD)
.add(new Load("h", "x"))
.add(new IfNull("x"))
.add(new Monitorenter(pattern.dummyVariable()))
.add(new Load("h", "y"))
.add(new IfNull("y"))
.addWild(CREATE_OBJ_WILD)
.add(new Store("h", pattern.dummyVariable()));
}
public ByteCodePattern getPattern() {
return pattern;
}
public void reportMatch(MethodGen methodGen, ByteCodePatternMatch match) {
BindingSet bindingSet = match.getBindingSet();
// Note that the lookup of "h" cannot fail, and
// it is guaranteed to be bound to a FieldVariable.
Binding binding = bindingSet.lookup("h");
FieldVariable field = (FieldVariable) binding.getVariable();
bugReporter.reportBug(new BugInstance("BCPDC_DOUBLECHECK", NORMAL_PRIORITY)
.addClass(methodGen.getClassName())
.addMethod(methodGen)
.addField(field.getClassName(), field.getFieldName(), field.getFieldSig(), field.isStatic()));
}
}
// vim:ts=4
|
package edu.umd.cs.findbugs.gui;
import java.awt.event.WindowEvent;
import javax.swing.*;
import edu.umd.cs.findbugs.FindBugsProgress;
/**
* A modal dialog to run the actual FindBugs analysis on a project.
* The analysis is done in a separate thread, so that the GUI can
* still stay current while the analysis is running. We provide support
* for reporting the progress of the analysis, and for asynchronously
* cancelling the analysis before it completes.
*
* @author David Hovemeyer
*/
public class RunAnalysisDialog extends javax.swing.JDialog {
private class RunAnalysisProgress implements FindBugsProgress {
private int goal, count;
private synchronized int getGoal() {
return goal;
}
private synchronized int getCount() {
return count;
}
public void reportNumberOfArchives(final int numArchives) {
beginStage(L10N.getLocalString("msg.scanningarchives_txt", "Scanning archives"), numArchives);
}
public void finishArchive() {
step();
}
public void startAnalysis(int numClasses) {
beginStage(L10N.getLocalString("msg.analysingclasses_txt", "Analyzing classes"), numClasses);
}
public void finishClass() {
step();
}
public void finishPerClassAnalysis() {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
stageNameLabel.setText(L10N.getLocalString("msg.finishedanalysis_txt", "Finishing analysis"));
}
});
}
private void beginStage(final String stageName, final int goal) {
synchronized (this) {
this.count = 0;
this.goal = goal;
}
SwingUtilities.invokeLater(new Runnable() {
public void run() {
int goal = getGoal();
stageNameLabel.setText(stageName);
countValueLabel.setText("0/" + goal);
progressBar.setMaximum(goal);
progressBar.setValue(0);
}
});
}
private void step() {
synchronized (this) {
count++;
}
SwingUtilities.invokeLater(new Runnable() {
public void run() {
int count = getCount();
int goal = getGoal();
countValueLabel.setText(count + "/" + goal);
progressBar.setValue(count);
}
});
}
}
private final AnalysisRun analysisRun;
private Thread analysisThread;
private boolean completed;
private Exception fatalException;
/**
* Creates new form RunAnalysisDialog
*/
public RunAnalysisDialog(java.awt.Frame parent, AnalysisRun analysisRun_) {
super(parent, true);
initComponents();
this.analysisRun = analysisRun_;
this.completed = false;
// Create a progress callback to give the user feedback
// about how far along we are.
final FindBugsProgress progress = new RunAnalysisProgress();
// This is the thread that will actually run the analysis.
this.analysisThread = new Thread() {
public void run() {
try {
analysisRun.execute(progress);
setCompleted(true);
} catch (java.io.IOException e) {
setException(e);
} catch (InterruptedException e) {
// We don't need to do anything here.
// The completed flag is not set, so the frame
// will know that the analysis did not complete.
} catch (Exception e) {
setException(e);
}
// Send a message to the dialog that it should close
// That way, it goes away without any need for user intervention
SwingUtilities.invokeLater(new Runnable() {
public void run() {
closeDialog(new WindowEvent(RunAnalysisDialog.this, WindowEvent.WINDOW_CLOSING));
}
});
}
};
}
public synchronized void setCompleted(boolean completed) {
this.completed = completed;
}
/**
* The creator of the dialog may call this method to find out whether
* or not the analysis completed normally.
*/
public synchronized boolean isCompleted() {
return completed;
}
public synchronized void setException(Exception e) {
fatalException = e;
}
/**
* Determine whether or not a fatal exception occurred
* during analysis.
*/
public synchronized boolean exceptionOccurred() {
return fatalException != null;
}
/**
* Get the exception that abnormally terminated the analysis.
*/
public synchronized Exception getException() {
return fatalException;
}
/**
* This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
private void initComponents() {//GEN-BEGIN:initComponents
java.awt.GridBagConstraints gridBagConstraints;
findBugsLabel = new javax.swing.JLabel();
countLabel = new javax.swing.JLabel();
progressLabel = new javax.swing.JLabel();
progressBar = new javax.swing.JProgressBar();
cancelButton = new javax.swing.JButton();
jSeparator1 = new javax.swing.JSeparator();
stageLabel = new javax.swing.JLabel();
stageNameLabel = new javax.swing.JLabel();
topVerticalFiller = new javax.swing.JLabel();
bottomVerticalFiller = new javax.swing.JLabel();
countValueLabel = new javax.swing.JLabel();
getContentPane().setLayout(new java.awt.GridBagLayout());
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
closeDialog(evt);
}
public void windowOpened(java.awt.event.WindowEvent evt) {
formWindowOpened(evt);
}
});
findBugsLabel.setBackground(new java.awt.Color(0, 0, 204));
findBugsLabel.setFont(new java.awt.Font("Dialog", 1, 24));
findBugsLabel.setForeground(new java.awt.Color(255, 255, 255));
findBugsLabel.setText("Find Bugs!");
findBugsLabel.setOpaque(true);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 3, 0);
getContentPane().add(findBugsLabel, gridBagConstraints);
countLabel.setFont(new java.awt.Font("Dialog", 0, 12));
countLabel.setText("Count:");
countLabel.setText(L10N.getLocalString("dlg.count_lbl", "Count:"));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 3;
gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
gridBagConstraints.insets = new java.awt.Insets(3, 3, 3, 3);
getContentPane().add(countLabel, gridBagConstraints);
progressLabel.setFont(new java.awt.Font("Dialog", 0, 12));
progressLabel.setText("Progress:");
progressLabel.setText(L10N.getLocalString("dlg.progress_lbl", "Progress:"));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 5;
gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
gridBagConstraints.insets = new java.awt.Insets(3, 3, 3, 3);
getContentPane().add(progressLabel, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 5;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.insets = new java.awt.Insets(0, 3, 0, 3);
getContentPane().add(progressBar, gridBagConstraints);
cancelButton.setFont(new java.awt.Font("Dialog", 0, 12));
cancelButton.setText("Cancel");
cancelButton.setText(L10N.getLocalString("dlg.cancel_btn", "Cancel"));
cancelButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cancelButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 8;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.insets = new java.awt.Insets(3, 0, 3, 0);
getContentPane().add(cancelButton, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 7;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
getContentPane().add(jSeparator1, gridBagConstraints);
stageLabel.setFont(new java.awt.Font("Dialog", 0, 12));
stageLabel.setText("Stage:");
stageLabel.setText(L10N.getLocalString("dlg.stage_lbl", "Stage:"));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
gridBagConstraints.insets = new java.awt.Insets(3, 3, 3, 3);
getContentPane().add(stageLabel, gridBagConstraints);
stageNameLabel.setFont(new java.awt.Font("Dialog", 0, 12));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
getContentPane().add(stageNameLabel, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 6;
gridBagConstraints.fill = java.awt.GridBagConstraints.VERTICAL;
gridBagConstraints.weighty = 0.5;
getContentPane().add(topVerticalFiller, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.VERTICAL;
gridBagConstraints.weighty = 0.5;
getContentPane().add(bottomVerticalFiller, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 3;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(0, 3, 0, 0);
getContentPane().add(countValueLabel, gridBagConstraints);
pack();
}//GEN-END:initComponents
private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
int option = JOptionPane.showConfirmDialog(this, L10N.getLocalString("msg.cancelanalysis_txt", "Cancel analysis?"), L10N.getLocalString("msg.analyze_txt", "Analysis"),
JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
if (option == JOptionPane.YES_OPTION) {
// All we need to do to cancel the analysis is to interrupt
// the analysis thread.
analysisThread.interrupt();
}
}//GEN-LAST:event_cancelButtonActionPerformed
private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
// Here is where we actually kick off the analysis thread.
analysisThread.start();
}//GEN-LAST:event_formWindowOpened
/**
* Closes the dialog
*/
private void closeDialog(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_closeDialog
setVisible(false);
dispose();
}//GEN-LAST:event_closeDialog
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel bottomVerticalFiller;
private javax.swing.JButton cancelButton;
private javax.swing.JLabel countLabel;
private javax.swing.JLabel countValueLabel;
private javax.swing.JLabel findBugsLabel;
private javax.swing.JSeparator jSeparator1;
private javax.swing.JProgressBar progressBar;
private javax.swing.JLabel progressLabel;
private javax.swing.JLabel stageLabel;
private javax.swing.JLabel stageNameLabel;
private javax.swing.JLabel topVerticalFiller;
// End of variables declaration//GEN-END:variables
}
|
package br.net.mirante.singular.form;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class SIList<E extends SInstance> extends SInstance implements Iterable<E>, ICompositeInstance {
private List<E> values;
private SType<E> elementsType;
public SIList() {
}
@SuppressWarnings("unchecked")
static <I extends SInstance> SIList<I> of(SType<I> elementsType) {
// MILista<I> lista = new MILista<>();
SIList<I> lista = (SIList<I>) elementsType.getDictionary().getType(STypeList.class).newInstance();
lista.setType(elementsType.getDictionary().getType(STypeList.class));
lista.elementsType = elementsType;
return lista;
}
@Override
public STypeList<?, ?> getType() {
return (STypeList<?, ?>) super.getType();
}
@SuppressWarnings("unchecked")
public SType<E> getElementsType() {
if (elementsType == null) {
elementsType = (SType<E>) getType().getElementsType();
}
return elementsType;
}
@Override
public List<Object> getValue() {
if (values == null) {
return Collections.emptyList();
}
return values.stream().map(SInstance::getValue).collect(Collectors.toList());
}
@Override
public void clearInstance() {
if (values != null) {
values.forEach(SInstance::internalOnRemove);
values.clear();
invokeUpdateListeners();
}
}
@Override
public void removeChildren() {
clearInstance();
}
@Override
public final <T> T getValue(String fieldPath, Class<T> resultClass) {
return getValue(new PathReader(fieldPath), resultClass);
}
@Override
public boolean isEmptyOfData() {
return isEmpty() || values.stream().allMatch(SInstance::isEmptyOfData);
}
public E addNew() {
E instance = getElementsType().newInstance(getDocument());
return addInternal(instance, true, -1);
}
public E addNew(Consumer<E> consumer) {
E instance = addNew();
consumer.accept(instance);
return instance;
}
@SuppressWarnings("unchecked")
public E addElement(E e) {
E instance = e;
instance.setDocument(getDocument());
return addInternal(instance, true, -1);
}
public E addElementAt(int index, E e) {
E instance = e;
instance.setDocument(getDocument());
return addInternal(instance, false, index);
}
public E addNewAt(int index) {
E instance = getElementsType().newInstance(getDocument());
return addInternal(instance, false, index);
}
public E addValue(Object value) {
E instance = addNew();
try {
instance.setValue(value);
} catch (RuntimeException e) {
values.remove(values.size() - 1);
throw e;
}
return instance;
}
public SIList<E> addValues(Collection<?> values) {
for (Object valor : values)
addValue(valor);
return this;
}
private E addInternal(E instance, boolean atEnd, int index) {
if (values == null) {
values = new ArrayList<>();
}
if (atEnd) {
values.add(instance);
} else {
values.add(index, instance);
}
instance.setParent(this);
instance.init();
return instance;
}
public E get(int index) {
return getChecking(index, null);
}
@Override
public SInstance getField(String path) {
return getField(new PathReader(path));
}
@Override
public Optional<SInstance> getFieldOpt(String path) {
return getFieldOpt(new PathReader(path));
}
@Override
final SInstance getFieldLocal(PathReader pathReader) {
SInstance instance = getChecking(pathReader);
if (instance == null) {
SFormUtil.resolveFieldType(getType(), pathReader);
}
return instance;
}
@Override
Optional<SInstance> getFieldLocalOpt(PathReader pathReader) {
int index = resolveIndex(pathReader);
if (values != null && index < values.size()) {
return Optional.ofNullable(values.get(index));
}
return Optional.empty();
}
@Override
final SInstance getFieldLocalWithoutCreating(PathReader pathReader) {
return getChecking(pathReader);
}
private E getChecking(PathReader pathReader) {
return getChecking(resolveIndex(pathReader), pathReader);
}
private E getChecking(int index, PathReader pathReader) {
if (index < 0 || index + 1 > size()) {
String msg = "índice inválido: " + index + ((index < 0) ? " < 0" : " > que a lista (size= " + size() + ")");
if (pathReader == null) {
throw new SingularFormException(msg, this);
}
throw new SingularFormException(pathReader.getErroMsg(this, msg));
}
return values.get(index);
}
private int resolveIndex(PathReader pathReader) {
if (!pathReader.isIndex()) {
throw new SingularFormException(pathReader.getErroMsg(this, "Era esperado um indice do elemento (exemplo field[1]), mas em vez disso foi solicitado '" + pathReader.getTrecho() + "'"));
}
int index = pathReader.getIndex();
if (index < 0) {
throw new SingularFormException(pathReader.getErroMsg(this, index + " é um valor inválido de índice"));
}
return index;
}
@Override
public void setValue(Object obj) {
if (obj instanceof SIList<?>) {
@SuppressWarnings("unchecked")
SIList<E> list = (SIList<E>) obj;
clearInstance();
Iterator<E> it = list.iterator();
while (it.hasNext()){
E o = it.next();
it.remove();
addElement(o);
}
elementsType = list.getElementsType();
list.getValue().clear();
} else if (obj instanceof List) {
clearInstance();
for (Object o : (List)obj){
addValue(o);
}
} else {
throw new SingularFormException("SList só suporta valores de mesmo tipo da lista", this);
}
}
@Override
public final void setValue(String fieldPath, Object value) {
setValue(new PathReader(fieldPath), value);
}
@Override
void setValue(PathReader pathReader, Object value) {
SInstance instance = getChecking(pathReader);
if (pathReader.isLast()) {
instance.setValue(value);
} else {
instance.setValue(pathReader.next(), value);
}
}
public E remove(int index) {
E e = getChecking(index, null);
values.remove(index);
return internalRemove(e);
}
private E internalRemove(E e){
e.internalOnRemove();
invokeUpdateListeners();
return e;
}
private void invokeUpdateListeners(){
for (SType type : this.getType().getDependentTypes()){
SInstance dependentInstance = (SInstance) this.findNearest(type).orElse(null);
if (dependentInstance != null && dependentInstance.asAtr().getUpdateListener() != null){
dependentInstance.asAtr().getUpdateListener().accept(this);
}
}
}
public Object getValueAt(int index) {
return get(index).getValue();
}
public int indexOf(SInstance supposedChild) {
for (int i = size() - 1; i != -1; i
if (values.get(i) == supposedChild) {
return i;
}
}
return -1;
}
public int size() {
return (values == null) ? 0 : values.size();
}
public boolean isEmpty() {
return (values == null) || values.isEmpty();
}
public List<E> getValues() {
return (values == null) ? Collections.emptyList() : values;
}
@Override
public List<E> getChildren() {
return getValues();
}
@Override
public Iterator<E> iterator() {
return (values == null) ? Collections.emptyIterator() : new Iterator<E>() {
Iterator<E> it = values.iterator();
E current;
@Override
public boolean hasNext() {
return it.hasNext();
}
@Override
public E next() {
return current = it.next();
}
@Override
public void remove() {
it.remove();
SIList.this.internalRemove(current);
}
};
}
@Override
public Stream<E> stream() {
return getValues().stream();
}
public String toDebug() {
return stream().map(SInstance::toStringDisplay).collect(Collectors.joining("; "));
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((elementsType == null) ? 0 : elementsType.hashCode());
for (E e : this)
result = prime * result + (e == null ? 0 : e.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
SIList<?> other = (SIList<?>) obj;
if (size() != other.size()) {
return false;
} else if (!getType().equals(other.getType())) {
return false;
} else if (!Objects.equals(getElementsType(), other.getElementsType()))
return false;
for (int i = size() - 1; i != -1; i
if (!Objects.equals(get(i), other.get(i))) {
return false;
}
}
return true;
}
@Override
public String toString() {
return String.format("%s(%s)", getClass().getSimpleName(), getAllChildren());
}
public E first() {
if (hasValues())
return values.get(0);
return null;
}
public boolean hasValues() {
return values != null && !values.isEmpty();
}
public E last() {
if (hasValues())
return values.get(values.size() - 1);
return null;
}
@SuppressWarnings("unchecked")
public E remove(E e) {
return (E) remove(values.indexOf(e));
}
}
|
package org.openhab.binding.homeconnect.internal.handler;
import static java.util.Collections.emptyList;
import static org.openhab.binding.homeconnect.internal.HomeConnectBindingConstants.*;
import static org.openhab.binding.homeconnect.internal.client.model.EventType.*;
import static org.openhab.core.library.unit.ImperialUnits.FAHRENHEIT;
import static org.openhab.core.library.unit.SIUnits.CELSIUS;
import static org.openhab.core.library.unit.Units.*;
import static org.openhab.core.thing.ThingStatus.*;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Function;
import java.util.stream.Collectors;
import javax.measure.UnconvertibleException;
import javax.measure.Unit;
import javax.measure.quantity.Temperature;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
import org.openhab.binding.homeconnect.internal.client.HomeConnectApiClient;
import org.openhab.binding.homeconnect.internal.client.HomeConnectEventSourceClient;
import org.openhab.binding.homeconnect.internal.client.exception.ApplianceOfflineException;
import org.openhab.binding.homeconnect.internal.client.exception.AuthorizationException;
import org.openhab.binding.homeconnect.internal.client.exception.CommunicationException;
import org.openhab.binding.homeconnect.internal.client.listener.HomeConnectEventListener;
import org.openhab.binding.homeconnect.internal.client.model.AvailableProgramOption;
import org.openhab.binding.homeconnect.internal.client.model.Data;
import org.openhab.binding.homeconnect.internal.client.model.Event;
import org.openhab.binding.homeconnect.internal.client.model.HomeAppliance;
import org.openhab.binding.homeconnect.internal.client.model.Option;
import org.openhab.binding.homeconnect.internal.client.model.Program;
import org.openhab.binding.homeconnect.internal.handler.cache.ExpiringStateMap;
import org.openhab.binding.homeconnect.internal.type.HomeConnectDynamicStateDescriptionProvider;
import org.openhab.core.auth.client.oauth2.OAuthException;
import org.openhab.core.library.types.DecimalType;
import org.openhab.core.library.types.HSBType;
import org.openhab.core.library.types.IncreaseDecreaseType;
import org.openhab.core.library.types.OnOffType;
import org.openhab.core.library.types.OpenClosedType;
import org.openhab.core.library.types.PercentType;
import org.openhab.core.library.types.QuantityType;
import org.openhab.core.library.types.StringType;
import org.openhab.core.library.unit.ImperialUnits;
import org.openhab.core.library.unit.SIUnits;
import org.openhab.core.thing.Bridge;
import org.openhab.core.thing.Channel;
import org.openhab.core.thing.ChannelUID;
import org.openhab.core.thing.Thing;
import org.openhab.core.thing.ThingStatusDetail;
import org.openhab.core.thing.ThingStatusInfo;
import org.openhab.core.thing.binding.BaseThingHandler;
import org.openhab.core.thing.binding.BridgeHandler;
import org.openhab.core.types.Command;
import org.openhab.core.types.RefreshType;
import org.openhab.core.types.StateOption;
import org.openhab.core.types.UnDefType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@NonNullByDefault
public abstract class AbstractHomeConnectThingHandler extends BaseThingHandler implements HomeConnectEventListener {
private static final int CACHE_TTL_SEC = 2;
private static final int OFFLINE_MONITOR_1_DELAY_MIN = 30;
private static final int OFFLINE_MONITOR_2_DELAY_MIN = 4;
private static final int EVENT_LISTENER_CONNECT_RETRY_DELAY_MIN = 10;
private @Nullable String operationState;
private @Nullable ScheduledFuture<?> reinitializationFuture1;
private @Nullable ScheduledFuture<?> reinitializationFuture2;
private @Nullable ScheduledFuture<?> reinitializationFuture3;
private boolean ignoreEventSourceClosedEvent;
private final ConcurrentHashMap<String, EventHandler> eventHandlers;
private final ConcurrentHashMap<String, ChannelUpdateHandler> channelUpdateHandlers;
private final HomeConnectDynamicStateDescriptionProvider dynamicStateDescriptionProvider;
private final ExpiringStateMap expiringStateMap;
private final AtomicBoolean accessible;
private final Logger logger = LoggerFactory.getLogger(AbstractHomeConnectThingHandler.class);
public AbstractHomeConnectThingHandler(Thing thing,
HomeConnectDynamicStateDescriptionProvider dynamicStateDescriptionProvider) {
super(thing);
eventHandlers = new ConcurrentHashMap<>();
channelUpdateHandlers = new ConcurrentHashMap<>();
this.dynamicStateDescriptionProvider = dynamicStateDescriptionProvider;
expiringStateMap = new ExpiringStateMap(Duration.ofSeconds(CACHE_TTL_SEC));
accessible = new AtomicBoolean(false);
configureEventHandlers(eventHandlers);
configureChannelUpdateHandlers(channelUpdateHandlers);
}
@Override
public void initialize() {
if (getBridgeHandler().isEmpty()) {
updateStatus(OFFLINE, ThingStatusDetail.BRIDGE_UNINITIALIZED);
accessible.set(false);
} else if (isBridgeOffline()) {
updateStatus(OFFLINE, ThingStatusDetail.BRIDGE_OFFLINE);
accessible.set(false);
} else {
updateStatus(UNKNOWN);
scheduler.submit(() -> {
refreshThingStatus(); // set ONLINE / OFFLINE
updateSelectedProgramStateDescription();
updateChannels();
registerEventListener();
scheduleOfflineMonitor1();
scheduleOfflineMonitor2();
});
}
}
@Override
public void dispose() {
stopRetryRegistering();
stopOfflineMonitor1();
stopOfflineMonitor2();
unregisterEventListener(true);
}
@Override
public void bridgeStatusChanged(ThingStatusInfo bridgeStatusInfo) {
logger.debug("Bridge status changed to {} ({}). haId={}", bridgeStatusInfo, getThingLabel(), getThingHaId());
reinitialize();
}
private void reinitialize() {
logger.debug("Reinitialize thing handler ({}). haId={}", getThingLabel(), getThingHaId());
stopRetryRegistering();
stopOfflineMonitor1();
stopOfflineMonitor2();
unregisterEventListener();
initialize();
}
/**
* Handles a command for a given channel.
* <p>
* This method is only called, if the thing has been initialized (status ONLINE/OFFLINE/UNKNOWN).
* <p>
*
* @param channelUID the {@link ChannelUID} of the channel to which the command was sent
* @param command the {@link Command}
* @param apiClient the {@link HomeConnectApiClient}
* @throws CommunicationException communication problem
* @throws AuthorizationException authorization problem
* @throws ApplianceOfflineException appliance offline
*/
protected void handleCommand(ChannelUID channelUID, Command command, HomeConnectApiClient apiClient)
throws CommunicationException, AuthorizationException, ApplianceOfflineException {
if (command instanceof RefreshType) {
updateChannel(channelUID);
} else if (command instanceof StringType && CHANNEL_BASIC_ACTIONS_STATE.equals(channelUID.getId())
&& getBridgeHandler().isPresent()) {
updateState(channelUID, new StringType(""));
if (COMMAND_START.equalsIgnoreCase(command.toFullString())) {
HomeConnectBridgeHandler homeConnectBridgeHandler = getBridgeHandler().get();
// workaround for api bug
// if simulator, program options have to be passed along with the desired program
// if non simulator, some options throw a "SDK.Error.UnsupportedOption" error
if (homeConnectBridgeHandler.getConfiguration().isSimulator()) {
apiClient.startSelectedProgram(getThingHaId());
} else {
Program selectedProgram = apiClient.getSelectedProgram(getThingHaId());
if (selectedProgram != null) {
apiClient.startProgram(getThingHaId(), selectedProgram.getKey());
}
}
} else if (COMMAND_STOP.equalsIgnoreCase(command.toFullString())) {
apiClient.stopProgram(getThingHaId());
} else if (COMMAND_SELECTED.equalsIgnoreCase(command.toFullString())) {
apiClient.getSelectedProgram(getThingHaId());
} else {
logger.debug("Start custom program. command={} haId={}", command.toFullString(), getThingHaId());
apiClient.startCustomProgram(getThingHaId(), command.toFullString());
}
} else if (command instanceof StringType && CHANNEL_SELECTED_PROGRAM_STATE.equals(channelUID.getId())) {
apiClient.setSelectedProgram(getThingHaId(), command.toFullString());
}
}
@Override
public final void handleCommand(ChannelUID channelUID, Command command) {
var apiClient = getApiClient();
if ((isThingReadyToHandleCommand() || (this instanceof HomeConnectHoodHandler && isBridgeOnline()
&& isThingAccessibleViaServerSentEvents())) && apiClient.isPresent()) {
logger.debug("Handle \"{}\" command ({}). haId={}", command, channelUID.getId(), getThingHaId());
try {
handleCommand(channelUID, command, apiClient.get());
} catch (ApplianceOfflineException e) {
logger.debug("Could not handle command {}. Appliance offline. thing={}, haId={}, error={}",
command.toFullString(), getThingLabel(), getThingHaId(), e.getMessage());
updateStatus(OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR);
resetChannelsOnOfflineEvent();
resetProgramStateChannels();
} catch (CommunicationException e) {
logger.debug("Could not handle command {}. API communication problem! error={}, haId={}",
command.toFullString(), e.getMessage(), getThingHaId());
} catch (AuthorizationException e) {
logger.debug("Could not handle command {}. Authorization problem! error={}, haId={}",
command.toFullString(), e.getMessage(), getThingHaId());
handleAuthenticationError(e);
}
}
}
@Override
public void onEvent(Event event) {
if (DISCONNECTED.equals(event.getType())) {
logger.debug("Received DISCONNECTED event. Set {} to OFFLINE. haId={}", getThing().getLabel(),
getThingHaId());
updateStatus(OFFLINE);
resetChannelsOnOfflineEvent();
resetProgramStateChannels();
} else if (isThingOnline() && CONNECTED.equals(event.getType())) {
logger.debug("Received CONNECTED event. Update power state channel. haId={}", getThingHaId());
getThingChannel(CHANNEL_POWER_STATE).ifPresent(c -> updateChannel(c.getUID()));
} else if (isThingOffline() && !KEEP_ALIVE.equals(event.getType())) {
updateStatus(ONLINE);
logger.debug("Set {} to ONLINE and update channels. haId={}", getThing().getLabel(), getThingHaId());
updateChannels();
}
String key = event.getKey();
if (EVENT_OPERATION_STATE.equals(key)) {
operationState = event.getValue() == null ? null : event.getValue();
}
if (key != null && eventHandlers.containsKey(key)) {
EventHandler eventHandler = eventHandlers.get(key);
if (eventHandler != null) {
eventHandler.handle(event);
}
}
accessible.set(true);
}
@Override
public void onClosed() {
if (ignoreEventSourceClosedEvent) {
logger.debug("Ignoring event source close event. thing={}, haId={}", getThing().getLabel(), getThingHaId());
} else {
unregisterEventListener();
refreshThingStatus();
registerEventListener();
}
}
@Override
public void onRateLimitReached() {
unregisterEventListener();
// retry registering
scheduleRetryRegistering();
}
/**
* Register event listener.
*/
protected void registerEventListener() {
if (isBridgeOnline() && isThingAccessibleViaServerSentEvents()) {
getEventSourceClient().ifPresent(client -> {
try {
ignoreEventSourceClosedEvent = false;
client.registerEventListener(getThingHaId(), this);
} catch (CommunicationException | AuthorizationException e) {
logger.warn("Could not open event source connection. thing={}, haId={}, error={}", getThingLabel(),
getThingHaId(), e.getMessage());
}
});
}
}
/**
* Unregister event listener.
*/
protected void unregisterEventListener() {
unregisterEventListener(false);
}
private void unregisterEventListener(boolean immediate) {
getEventSourceClient().ifPresent(client -> {
ignoreEventSourceClosedEvent = true;
client.unregisterEventListener(this, immediate, false);
});
}
/**
* Get {@link HomeConnectApiClient}.
*
* @return client instance
*/
protected Optional<HomeConnectApiClient> getApiClient() {
return getBridgeHandler().map(HomeConnectBridgeHandler::getApiClient);
}
/**
* Get {@link HomeConnectEventSourceClient}.
*
* @return client instance if present
*/
protected Optional<HomeConnectEventSourceClient> getEventSourceClient() {
return getBridgeHandler().map(HomeConnectBridgeHandler::getEventSourceClient);
}
/**
* Update state description of selected program (Fetch programs via API).
*/
protected void updateSelectedProgramStateDescription() {
if (isBridgeOffline() || isThingOffline()) {
return;
}
Optional<HomeConnectApiClient> apiClient = getApiClient();
if (apiClient.isPresent()) {
try {
List<StateOption> stateOptions = apiClient.get().getPrograms(getThingHaId()).stream()
.map(p -> new StateOption(p.getKey(), mapStringType(p.getKey()))).collect(Collectors.toList());
getThingChannel(CHANNEL_SELECTED_PROGRAM_STATE).ifPresent(
channel -> dynamicStateDescriptionProvider.setStateOptions(channel.getUID(), stateOptions));
} catch (CommunicationException | ApplianceOfflineException | AuthorizationException e) {
logger.debug("Could not fetch available programs. thing={}, haId={}, error={}", getThingLabel(),
getThingHaId(), e.getMessage());
removeSelectedProgramStateDescription();
}
} else {
removeSelectedProgramStateDescription();
}
}
/**
* Remove state description of selected program.
*/
protected void removeSelectedProgramStateDescription() {
getThingChannel(CHANNEL_SELECTED_PROGRAM_STATE)
.ifPresent(channel -> dynamicStateDescriptionProvider.setStateOptions(channel.getUID(), emptyList()));
}
/**
* Is thing ready to process commands. If bridge or thing itself is offline commands will be ignored.
*
* @return true if ready
*/
protected boolean isThingReadyToHandleCommand() {
if (isBridgeOffline()) {
logger.debug("Bridge is OFFLINE. Ignore command. thing={}, haId={}", getThingLabel(), getThingHaId());
return false;
}
if (isThingOffline()) {
logger.debug("{} is OFFLINE. Ignore command. haId={}", getThing().getLabel(), getThingHaId());
return false;
}
return true;
}
/**
* Checks if bridge is online and set.
*
* @return true if online
*/
protected boolean isBridgeOnline() {
Bridge bridge = getBridge();
return bridge != null && ONLINE.equals(bridge.getStatus());
}
/**
* Checks if bridge is offline or not set.
*
* @return true if offline
*/
protected boolean isBridgeOffline() {
return !isBridgeOnline();
}
/**
* Checks if thing is online.
*
* @return true if online
*/
protected boolean isThingOnline() {
return ONLINE.equals(getThing().getStatus());
}
/**
* Checks if thing is connected to the cloud and accessible via SSE.
*
* @return true if yes
*/
public boolean isThingAccessibleViaServerSentEvents() {
return accessible.get();
}
/**
* Checks if thing is offline.
*
* @return true if offline
*/
protected boolean isThingOffline() {
return !isThingOnline();
}
/**
* Get {@link HomeConnectBridgeHandler}.
*
* @return bridge handler
*/
protected Optional<HomeConnectBridgeHandler> getBridgeHandler() {
Bridge bridge = getBridge();
if (bridge != null) {
BridgeHandler bridgeHandler = bridge.getHandler();
if (bridgeHandler instanceof HomeConnectBridgeHandler) {
return Optional.of((HomeConnectBridgeHandler) bridgeHandler);
}
}
return Optional.empty();
}
/**
* Get thing channel by given channel id.
*
* @param channelId channel id
* @return channel
*/
protected Optional<Channel> getThingChannel(String channelId) {
Channel channel = getThing().getChannel(channelId);
if (channel == null) {
return Optional.empty();
} else {
return Optional.of(channel);
}
}
/**
* Configure channel update handlers. Classes which extend {@link AbstractHomeConnectThingHandler} must implement
* this class and add handlers.
*
* @param handlers channel update handlers
*/
protected abstract void configureChannelUpdateHandlers(final Map<String, ChannelUpdateHandler> handlers);
/**
* Configure event handlers. Classes which extend {@link AbstractHomeConnectThingHandler} must implement
* this class and add handlers.
*
* @param handlers Server-Sent-Event handlers
*/
protected abstract void configureEventHandlers(final Map<String, EventHandler> handlers);
/**
* Update all channels via API.
*
*/
protected void updateChannels() {
if (isBridgeOffline()) {
logger.debug("Bridge handler not found or offline. Stopping update of channels. thing={}, haId={}",
getThingLabel(), getThingHaId());
} else if (isThingOffline()) {
logger.debug("{} offline. Stopping update of channels. haId={}", getThing().getLabel(), getThingHaId());
} else {
List<Channel> channels = getThing().getChannels();
for (Channel channel : channels) {
updateChannel(channel.getUID());
}
}
}
/**
* Update Channel values via API.
*
* @param channelUID channel UID
*/
protected void updateChannel(ChannelUID channelUID) {
if (!getApiClient().isPresent()) {
logger.error("Cannot update channel. No instance of api client found! thing={}, haId={}", getThingLabel(),
getThingHaId());
return;
}
if (!isThingReadyToHandleCommand()) {
return;
}
if ((isLinked(channelUID) || CHANNEL_OPERATION_STATE.equals(channelUID.getId())) // always update operation
// state channel
&& channelUpdateHandlers.containsKey(channelUID.getId())) {
try {
ChannelUpdateHandler channelUpdateHandler = channelUpdateHandlers.get(channelUID.getId());
if (channelUpdateHandler != null) {
channelUpdateHandler.handle(channelUID, expiringStateMap);
}
} catch (ApplianceOfflineException e) {
logger.debug(
"API communication problem while trying to update! Appliance offline. thing={}, haId={}, error={}",
getThingLabel(), getThingHaId(), e.getMessage());
updateStatus(OFFLINE);
resetChannelsOnOfflineEvent();
resetProgramStateChannels();
} catch (CommunicationException e) {
logger.debug("API communication problem while trying to update! thing={}, haId={}, error={}",
getThingLabel(), getThingHaId(), e.getMessage());
} catch (AuthorizationException e) {
logger.debug("Authentication problem while trying to update! thing={}, haId={}", getThingLabel(),
getThingHaId(), e);
handleAuthenticationError(e);
}
}
}
/**
* Reset program related channels.
*/
protected void resetProgramStateChannels() {
logger.debug("Resetting active program channel states. thing={}, haId={}", getThingLabel(), getThingHaId());
}
/**
* Reset all channels on OFFLINE event.
*/
protected void resetChannelsOnOfflineEvent() {
logger.debug("Resetting channel states due to OFFLINE event. thing={}, haId={}", getThingLabel(),
getThingHaId());
getThingChannel(CHANNEL_POWER_STATE).ifPresent(channel -> updateState(channel.getUID(), OnOffType.OFF));
getThingChannel(CHANNEL_OPERATION_STATE).ifPresent(channel -> updateState(channel.getUID(), UnDefType.UNDEF));
getThingChannel(CHANNEL_DOOR_STATE).ifPresent(channel -> updateState(channel.getUID(), UnDefType.UNDEF));
getThingChannel(CHANNEL_LOCAL_CONTROL_ACTIVE_STATE)
.ifPresent(channel -> updateState(channel.getUID(), UnDefType.UNDEF));
getThingChannel(CHANNEL_REMOTE_CONTROL_ACTIVE_STATE)
.ifPresent(channel -> updateState(channel.getUID(), UnDefType.UNDEF));
getThingChannel(CHANNEL_REMOTE_START_ALLOWANCE_STATE)
.ifPresent(channel -> updateState(channel.getUID(), UnDefType.UNDEF));
getThingChannel(CHANNEL_SELECTED_PROGRAM_STATE)
.ifPresent(channel -> updateState(channel.getUID(), UnDefType.UNDEF));
}
/**
* Map Home Connect key and value names to label.
* e.g. Dishcare.Dishwasher.Program.Eco50 --> Eco50 or BSH.Common.EnumType.OperationState.DelayedStart --> Delayed
* Start
*
* @param type type
* @return human readable label
*/
protected String mapStringType(String type) {
int index = type.lastIndexOf(".");
if (index > 0 && type.length() > index) {
String sub = type.substring(index + 1);
StringBuilder sb = new StringBuilder();
for (String word : sub.split("(?<!(^|[A-Z]))(?=[A-Z])|(?<!^)(?=[A-Z][a-z])")) {
sb.append(" ");
sb.append(word);
}
return sb.toString().trim();
}
return type;
}
/**
* Map Home Connect stage value to label.
* e.g. Cooking.Hood.EnumType.IntensiveStage.IntensiveStage1 --> 1
*
* @param stage stage
* @return human readable label
*/
protected String mapStageStringType(String stage) {
switch (stage) {
case STAGE_FAN_OFF:
case STAGE_INTENSIVE_STAGE_OFF:
stage = "Off";
break;
case STAGE_FAN_STAGE_01:
case STAGE_INTENSIVE_STAGE_1:
stage = "1";
break;
case STAGE_FAN_STAGE_02:
case STAGE_INTENSIVE_STAGE_2:
stage = "2";
break;
case STAGE_FAN_STAGE_03:
stage = "3";
break;
case STAGE_FAN_STAGE_04:
stage = "4";
break;
case STAGE_FAN_STAGE_05:
stage = "5";
break;
default:
stage = mapStringType(stage);
}
return stage;
}
protected Unit<Temperature> mapTemperature(@Nullable String unit) {
if (unit == null) {
return CELSIUS;
} else if (unit.endsWith("C")) {
return CELSIUS;
} else {
return FAHRENHEIT;
}
}
/**
* Map hex representation of color to HSB type.
*
* @param colorCode color code e.g. #001122
* @return HSB type
*/
protected HSBType mapColor(String colorCode) {
HSBType color = HSBType.WHITE;
if (colorCode.length() == 7) {
int r = Integer.valueOf(colorCode.substring(1, 3), 16);
int g = Integer.valueOf(colorCode.substring(3, 5), 16);
int b = Integer.valueOf(colorCode.substring(5, 7), 16);
color = HSBType.fromRGB(r, g, b);
}
return color;
}
/**
* Map HSB color type to hex representation.
*
* @param color HSB color
* @return color code e.g. #001122
*/
protected String mapColor(HSBType color) {
String redValue = String.format("%02X", (int) (color.getRed().floatValue() * 2.55));
String greenValue = String.format("%02X", (int) (color.getGreen().floatValue() * 2.55));
String blueValue = String.format("%02X", (int) (color.getBlue().floatValue() * 2.55));
return "#" + redValue + greenValue + blueValue;
}
/**
* Check bridge status and refresh connection status of thing accordingly.
*/
protected void refreshThingStatus() {
Optional<HomeConnectApiClient> apiClient = getApiClient();
apiClient.ifPresent(client -> {
try {
HomeAppliance homeAppliance = client.getHomeAppliance(getThingHaId());
if (!homeAppliance.isConnected()) {
updateStatus(OFFLINE);
} else {
updateStatus(ONLINE);
}
accessible.set(true);
} catch (CommunicationException e) {
logger.debug(
"Update status to OFFLINE. Home Connect service is not reachable or a problem occurred! thing={}, haId={}, error={}.",
getThingLabel(), getThingHaId(), e.getMessage());
updateStatus(OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
"Home Connect service is not reachable or a problem occurred! (" + e.getMessage() + ").");
accessible.set(false);
} catch (AuthorizationException e) {
logger.debug(
"Update status to OFFLINE. Home Connect service is not reachable or a problem occurred! thing={}, haId={}, error={}",
getThingLabel(), getThingHaId(), e.getMessage());
updateStatus(OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
"Home Connect service is not reachable or a problem occurred! (" + e.getMessage() + ").");
accessible.set(false);
handleAuthenticationError(e);
}
});
if (apiClient.isEmpty()) {
updateStatus(OFFLINE, ThingStatusDetail.BRIDGE_UNINITIALIZED);
accessible.set(false);
}
}
/**
* Get home appliance id of Thing.
*
* @return home appliance id
*/
public String getThingHaId() {
return getThing().getConfiguration().get(HA_ID).toString();
}
/**
* Returns the human readable label for this thing.
*
* @return the human readable label
*/
protected @Nullable String getThingLabel() {
return getThing().getLabel();
}
/**
* Handle authentication exception.
*/
protected void handleAuthenticationError(AuthorizationException exception) {
if (isBridgeOnline()) {
logger.debug(
"Thing handler threw authentication exception --> clear credential storage thing={}, haId={} error={}",
getThingLabel(), getThingHaId(), exception.getMessage());
getBridgeHandler().ifPresent(homeConnectBridgeHandler -> {
try {
homeConnectBridgeHandler.getOAuthClientService().remove();
homeConnectBridgeHandler.reinitialize();
} catch (OAuthException e) {
// client is already closed --> we can ignore it
}
});
}
}
/**
* Get operation state of device.
*
* @return operation state string
*/
protected @Nullable String getOperationState() {
return operationState;
}
protected EventHandler defaultElapsedProgramTimeEventHandler() {
return event -> getThingChannel(CHANNEL_ELAPSED_PROGRAM_TIME)
.ifPresent(channel -> updateState(channel.getUID(), new QuantityType<>(event.getValueAsInt(), SECOND)));
}
protected EventHandler defaultPowerStateEventHandler() {
return event -> {
getThingChannel(CHANNEL_POWER_STATE).ifPresent(
channel -> updateState(channel.getUID(), OnOffType.from(STATE_POWER_ON.equals(event.getValue()))));
if (STATE_POWER_ON.equals(event.getValue())) {
getThingChannel(CHANNEL_SELECTED_PROGRAM_STATE).ifPresent(c -> updateChannel(c.getUID()));
} else {
resetProgramStateChannels();
getThingChannel(CHANNEL_SELECTED_PROGRAM_STATE)
.ifPresent(c -> updateState(c.getUID(), UnDefType.UNDEF));
}
};
}
protected EventHandler defaultDoorStateEventHandler() {
return event -> getThingChannel(CHANNEL_DOOR_STATE).ifPresent(channel -> updateState(channel.getUID(),
STATE_DOOR_OPEN.equals(event.getValue()) ? OpenClosedType.OPEN : OpenClosedType.CLOSED));
}
protected EventHandler defaultOperationStateEventHandler() {
return event -> {
String value = event.getValue();
getThingChannel(CHANNEL_OPERATION_STATE).ifPresent(channel -> updateState(channel.getUID(),
value == null ? UnDefType.UNDEF : new StringType(mapStringType(value))));
if (STATE_OPERATION_FINISHED.equals(event.getValue())) {
getThingChannel(CHANNEL_PROGRAM_PROGRESS_STATE)
.ifPresent(c -> updateState(c.getUID(), new QuantityType<>(100, PERCENT)));
getThingChannel(CHANNEL_REMAINING_PROGRAM_TIME_STATE)
.ifPresent(c -> updateState(c.getUID(), new QuantityType<>(0, SECOND)));
} else if (STATE_OPERATION_RUN.equals(event.getValue())) {
getThingChannel(CHANNEL_PROGRAM_PROGRESS_STATE)
.ifPresent(c -> updateState(c.getUID(), new QuantityType<>(0, PERCENT)));
getThingChannel(CHANNEL_ACTIVE_PROGRAM_STATE).ifPresent(c -> updateChannel(c.getUID()));
} else if (STATE_OPERATION_READY.equals(event.getValue())) {
resetProgramStateChannels();
}
};
}
protected EventHandler defaultActiveProgramEventHandler() {
return event -> {
String value = event.getValue();
getThingChannel(CHANNEL_ACTIVE_PROGRAM_STATE).ifPresent(channel -> updateState(channel.getUID(),
value == null ? UnDefType.UNDEF : new StringType(mapStringType(value))));
if (event.getValue() == null) {
resetProgramStateChannels();
}
};
}
protected EventHandler defaultEventPresentStateEventHandler(String channelId) {
return event -> getThingChannel(channelId).ifPresent(channel -> updateState(channel.getUID(),
OnOffType.from(!STATE_EVENT_PRESENT_STATE_OFF.equals(event.getValue()))));
}
protected EventHandler defaultBooleanEventHandler(String channelId) {
return event -> getThingChannel(channelId)
.ifPresent(channel -> updateState(channel.getUID(), OnOffType.from(event.getValueAsBoolean())));
}
protected EventHandler defaultRemainingProgramTimeEventHandler() {
return event -> getThingChannel(CHANNEL_REMAINING_PROGRAM_TIME_STATE)
.ifPresent(channel -> updateState(channel.getUID(), new QuantityType<>(event.getValueAsInt(), SECOND)));
}
protected EventHandler defaultSelectedProgramStateEventHandler() {
return event -> getThingChannel(CHANNEL_SELECTED_PROGRAM_STATE)
.ifPresent(channel -> updateState(channel.getUID(),
event.getValue() == null ? UnDefType.UNDEF : new StringType(event.getValue())));
}
protected EventHandler defaultAmbientLightColorStateEventHandler() {
return event -> getThingChannel(CHANNEL_AMBIENT_LIGHT_COLOR_STATE)
.ifPresent(channel -> updateState(channel.getUID(),
event.getValue() == null ? UnDefType.UNDEF : new StringType(event.getValue())));
}
protected EventHandler defaultAmbientLightCustomColorStateEventHandler() {
return event -> getThingChannel(CHANNEL_AMBIENT_LIGHT_CUSTOM_COLOR_STATE).ifPresent(channel -> {
String value = event.getValue();
if (value != null) {
updateState(channel.getUID(), mapColor(value));
} else {
updateState(channel.getUID(), UnDefType.UNDEF);
}
});
}
protected EventHandler updateProgramOptionsAndSelectedProgramStateEventHandler() {
return event -> {
defaultSelectedProgramStateEventHandler().handle(event);
// update available program options
try {
String programKey = event.getValue();
if (programKey != null) {
updateProgramOptionsStateDescriptions(programKey, null);
}
} catch (CommunicationException | ApplianceOfflineException | AuthorizationException e) {
logger.debug("Could not update program options. {}", e.getMessage());
}
};
}
protected EventHandler defaultPercentQuantityTypeEventHandler(String channelId) {
return event -> getThingChannel(channelId).ifPresent(
channel -> updateState(channel.getUID(), new QuantityType<>(event.getValueAsInt(), PERCENT)));
}
protected EventHandler defaultPercentHandler(String channelId) {
return event -> getThingChannel(channelId)
.ifPresent(channel -> updateState(channel.getUID(), new PercentType(event.getValueAsInt())));
}
protected ChannelUpdateHandler defaultDoorStateChannelUpdateHandler() {
return (channelUID, cache) -> updateState(channelUID, cache.putIfAbsentAndGet(channelUID, () -> {
Optional<HomeConnectApiClient> apiClient = getApiClient();
if (apiClient.isPresent()) {
Data data = apiClient.get().getDoorState(getThingHaId());
if (data.getValue() != null) {
return STATE_DOOR_OPEN.equals(data.getValue()) ? OpenClosedType.OPEN : OpenClosedType.CLOSED;
} else {
return UnDefType.UNDEF;
}
} else {
return UnDefType.UNDEF;
}
}));
}
protected ChannelUpdateHandler defaultPowerStateChannelUpdateHandler() {
return (channelUID, cache) -> updateState(channelUID, cache.putIfAbsentAndGet(channelUID, () -> {
Optional<HomeConnectApiClient> apiClient = getApiClient();
if (apiClient.isPresent()) {
Data data = apiClient.get().getPowerState(getThingHaId());
if (data.getValue() != null) {
return OnOffType.from(STATE_POWER_ON.equals(data.getValue()));
} else {
return UnDefType.UNDEF;
}
} else {
return UnDefType.UNDEF;
}
}));
}
protected ChannelUpdateHandler defaultAmbientLightChannelUpdateHandler() {
return (channelUID, cache) -> updateState(channelUID, cache.putIfAbsentAndGet(channelUID, () -> {
Optional<HomeConnectApiClient> apiClient = getApiClient();
if (apiClient.isPresent()) {
Data data = apiClient.get().getAmbientLightState(getThingHaId());
if (data.getValue() != null) {
boolean enabled = data.getValueAsBoolean();
if (enabled) {
// brightness
Data brightnessData = apiClient.get().getAmbientLightBrightnessState(getThingHaId());
getThingChannel(CHANNEL_AMBIENT_LIGHT_BRIGHTNESS_STATE)
.ifPresent(channel -> updateState(channel.getUID(),
new PercentType(brightnessData.getValueAsInt())));
// color
Data colorData = apiClient.get().getAmbientLightColorState(getThingHaId());
getThingChannel(CHANNEL_AMBIENT_LIGHT_COLOR_STATE).ifPresent(
channel -> updateState(channel.getUID(), new StringType(colorData.getValue())));
// custom color
Data customColorData = apiClient.get().getAmbientLightCustomColorState(getThingHaId());
getThingChannel(CHANNEL_AMBIENT_LIGHT_CUSTOM_COLOR_STATE).ifPresent(channel -> {
String value = customColorData.getValue();
if (value != null) {
updateState(channel.getUID(), mapColor(value));
} else {
updateState(channel.getUID(), UnDefType.UNDEF);
}
});
}
return OnOffType.from(enabled);
} else {
return UnDefType.UNDEF;
}
} else {
return UnDefType.UNDEF;
}
}));
}
protected ChannelUpdateHandler defaultNoOpUpdateHandler() {
return (channelUID, cache) -> updateState(channelUID, UnDefType.UNDEF);
}
protected ChannelUpdateHandler defaultOperationStateChannelUpdateHandler() {
return (channelUID, cache) -> updateState(channelUID, cache.putIfAbsentAndGet(channelUID, () -> {
Optional<HomeConnectApiClient> apiClient = getApiClient();
if (apiClient.isPresent()) {
Data data = apiClient.get().getOperationState(getThingHaId());
String value = data.getValue();
if (value != null) {
operationState = data.getValue();
return new StringType(mapStringType(value));
} else {
operationState = null;
return UnDefType.UNDEF;
}
} else {
return UnDefType.UNDEF;
}
}));
}
protected ChannelUpdateHandler defaultRemoteControlActiveStateChannelUpdateHandler() {
return (channelUID, cache) -> updateState(channelUID, cache.putIfAbsentAndGet(channelUID, () -> {
Optional<HomeConnectApiClient> apiClient = getApiClient();
if (apiClient.isPresent()) {
return OnOffType.from(apiClient.get().isRemoteControlActive(getThingHaId()));
}
return OnOffType.OFF;
}));
}
protected ChannelUpdateHandler defaultLocalControlActiveStateChannelUpdateHandler() {
return (channelUID, cache) -> updateState(channelUID, cache.putIfAbsentAndGet(channelUID, () -> {
Optional<HomeConnectApiClient> apiClient = getApiClient();
if (apiClient.isPresent()) {
return OnOffType.from(apiClient.get().isLocalControlActive(getThingHaId()));
}
return OnOffType.OFF;
}));
}
protected ChannelUpdateHandler defaultRemoteStartAllowanceChannelUpdateHandler() {
return (channelUID, cache) -> updateState(channelUID, cache.putIfAbsentAndGet(channelUID, () -> {
Optional<HomeConnectApiClient> apiClient = getApiClient();
if (apiClient.isPresent()) {
return OnOffType.from(apiClient.get().isRemoteControlStartAllowed(getThingHaId()));
}
return OnOffType.OFF;
}));
}
protected ChannelUpdateHandler defaultSelectedProgramStateUpdateHandler() {
return (channelUID, cache) -> updateState(channelUID, cache.putIfAbsentAndGet(channelUID, () -> {
Optional<HomeConnectApiClient> apiClient = getApiClient();
if (apiClient.isPresent()) {
Program program = apiClient.get().getSelectedProgram(getThingHaId());
if (program != null) {
processProgramOptions(program.getOptions());
return new StringType(program.getKey());
} else {
return UnDefType.UNDEF;
}
}
return UnDefType.UNDEF;
}));
}
protected ChannelUpdateHandler updateProgramOptionsStateDescriptionsAndSelectedProgramStateUpdateHandler() {
return (channelUID, cache) -> updateState(channelUID, cache.putIfAbsentAndGet(channelUID, () -> {
Optional<HomeConnectApiClient> apiClient = getApiClient();
if (apiClient.isPresent()) {
Program program = apiClient.get().getSelectedProgram(getThingHaId());
if (program != null) {
updateProgramOptionsStateDescriptions(program.getKey(), program.getOptions());
processProgramOptions(program.getOptions());
return new StringType(program.getKey());
} else {
return UnDefType.UNDEF;
}
}
return UnDefType.UNDEF;
}));
}
protected ChannelUpdateHandler defaultActiveProgramStateUpdateHandler() {
return (channelUID, cache) -> updateState(channelUID, cache.putIfAbsentAndGet(channelUID, () -> {
Optional<HomeConnectApiClient> apiClient = getApiClient();
if (apiClient.isPresent()) {
Program program = apiClient.get().getActiveProgram(getThingHaId());
if (program != null) {
processProgramOptions(program.getOptions());
return new StringType(mapStringType(program.getKey()));
} else {
resetProgramStateChannels();
return UnDefType.UNDEF;
}
}
return UnDefType.UNDEF;
}));
}
protected void handleTemperatureCommand(final ChannelUID channelUID, final Command command,
final HomeConnectApiClient apiClient)
throws CommunicationException, AuthorizationException, ApplianceOfflineException {
if (command instanceof QuantityType) {
QuantityType<?> quantity = (QuantityType<?>) command;
String value;
String unit;
try {
if (quantity.getUnit().equals(SIUnits.CELSIUS) || quantity.getUnit().equals(ImperialUnits.FAHRENHEIT)) {
unit = quantity.getUnit().toString();
value = String.valueOf(quantity.intValue());
} else {
logger.debug("Converting target temperature from {}{} to °C value. thing={}, haId={}",
quantity.intValue(), quantity.getUnit().toString(), getThingLabel(), getThingHaId());
unit = "°C";
var celsius = quantity.toUnit(SIUnits.CELSIUS);
if (celsius == null) {
logger.warn("Converting temperature to celsius failed! quantity={}", quantity);
value = null;
} else {
value = String.valueOf(celsius.intValue());
}
logger.debug("Converted value {}{}", value, unit);
}
if (value != null) {
logger.debug("Set temperature to {} {}. thing={}, haId={}", value, unit, getThingLabel(),
getThingHaId());
switch (channelUID.getId()) {
case CHANNEL_REFRIGERATOR_SETPOINT_TEMPERATURE:
apiClient.setFridgeSetpointTemperature(getThingHaId(), value, unit);
case CHANNEL_FREEZER_SETPOINT_TEMPERATURE:
apiClient.setFreezerSetpointTemperature(getThingHaId(), value, unit);
break;
case CHANNEL_SETPOINT_TEMPERATURE:
apiClient.setProgramOptions(getThingHaId(), OPTION_SETPOINT_TEMPERATURE, value, unit, true,
false);
break;
default:
logger.debug("Unknown channel! Cannot set temperature. channelUID={}", channelUID);
}
}
} catch (UnconvertibleException e) {
logger.warn("Could not set temperature! haId={}, error={}", getThingHaId(), e.getMessage());
}
}
}
protected void handleLightCommands(final ChannelUID channelUID, final Command command,
final HomeConnectApiClient apiClient)
throws CommunicationException, AuthorizationException, ApplianceOfflineException {
switch (channelUID.getId()) {
case CHANNEL_FUNCTIONAL_LIGHT_BRIGHTNESS_STATE:
case CHANNEL_AMBIENT_LIGHT_BRIGHTNESS_STATE:
// turn light on if turned off
turnLightOn(channelUID, apiClient);
int newBrightness = BRIGHTNESS_MIN;
if (command instanceof OnOffType) {
newBrightness = command == OnOffType.ON ? BRIGHTNESS_MAX : BRIGHTNESS_MIN;
} else if (command instanceof IncreaseDecreaseType) {
int currentBrightness = getCurrentBrightness(channelUID, apiClient);
if (command.equals(IncreaseDecreaseType.INCREASE)) {
newBrightness = currentBrightness + BRIGHTNESS_DIM_STEP;
} else {
newBrightness = currentBrightness - BRIGHTNESS_DIM_STEP;
}
} else if (command instanceof PercentType) {
newBrightness = (int) Math.floor(((PercentType) command).doubleValue());
} else if (command instanceof DecimalType) {
newBrightness = ((DecimalType) command).intValue();
}
// check in in range
newBrightness = Math.min(Math.max(newBrightness, BRIGHTNESS_MIN), BRIGHTNESS_MAX);
setLightBrightness(channelUID, apiClient, newBrightness);
break;
case CHANNEL_FUNCTIONAL_LIGHT_STATE:
if (command instanceof OnOffType) {
apiClient.setFunctionalLightState(getThingHaId(), OnOffType.ON.equals(command));
}
break;
case CHANNEL_AMBIENT_LIGHT_STATE:
if (command instanceof OnOffType) {
apiClient.setAmbientLightState(getThingHaId(), OnOffType.ON.equals(command));
}
break;
case CHANNEL_AMBIENT_LIGHT_COLOR_STATE:
if (command instanceof StringType) {
turnLightOn(channelUID, apiClient);
apiClient.setAmbientLightColorState(getThingHaId(), command.toFullString());
}
break;
case CHANNEL_AMBIENT_LIGHT_CUSTOM_COLOR_STATE:
turnLightOn(channelUID, apiClient);
// make sure 'custom color' is set as color
Data ambientLightColorState = apiClient.getAmbientLightColorState(getThingHaId());
if (!STATE_AMBIENT_LIGHT_COLOR_CUSTOM_COLOR.equals(ambientLightColorState.getValue())) {
apiClient.setAmbientLightColorState(getThingHaId(), STATE_AMBIENT_LIGHT_COLOR_CUSTOM_COLOR);
}
if (command instanceof HSBType) {
apiClient.setAmbientLightCustomColorState(getThingHaId(), mapColor((HSBType) command));
} else if (command instanceof StringType) {
apiClient.setAmbientLightCustomColorState(getThingHaId(), command.toFullString());
}
break;
}
}
protected void handlePowerCommand(final ChannelUID channelUID, final Command command,
final HomeConnectApiClient apiClient, String stateNotOn)
throws CommunicationException, AuthorizationException, ApplianceOfflineException {
if (command instanceof OnOffType && CHANNEL_POWER_STATE.equals(channelUID.getId())) {
apiClient.setPowerState(getThingHaId(), OnOffType.ON.equals(command) ? STATE_POWER_ON : stateNotOn);
}
}
private int getCurrentBrightness(final ChannelUID channelUID, final HomeConnectApiClient apiClient)
throws CommunicationException, AuthorizationException, ApplianceOfflineException {
String id = channelUID.getId();
if (CHANNEL_FUNCTIONAL_LIGHT_BRIGHTNESS_STATE.equals(id)) {
return apiClient.getFunctionalLightBrightnessState(getThingHaId()).getValueAsInt();
} else {
return apiClient.getAmbientLightBrightnessState(getThingHaId()).getValueAsInt();
}
}
private void setLightBrightness(final ChannelUID channelUID, final HomeConnectApiClient apiClient, int value)
throws CommunicationException, AuthorizationException, ApplianceOfflineException {
switch (channelUID.getId()) {
case CHANNEL_FUNCTIONAL_LIGHT_BRIGHTNESS_STATE:
apiClient.setFunctionalLightBrightnessState(getThingHaId(), value);
break;
case CHANNEL_AMBIENT_LIGHT_BRIGHTNESS_STATE:
apiClient.setAmbientLightBrightnessState(getThingHaId(), value);
break;
}
}
private void turnLightOn(final ChannelUID channelUID, final HomeConnectApiClient apiClient)
throws CommunicationException, AuthorizationException, ApplianceOfflineException {
switch (channelUID.getId()) {
case CHANNEL_FUNCTIONAL_LIGHT_BRIGHTNESS_STATE:
Data functionalLightState = apiClient.getFunctionalLightState(getThingHaId());
if (!functionalLightState.getValueAsBoolean()) {
apiClient.setFunctionalLightState(getThingHaId(), true);
}
break;
case CHANNEL_AMBIENT_LIGHT_CUSTOM_COLOR_STATE:
case CHANNEL_AMBIENT_LIGHT_COLOR_STATE:
case CHANNEL_AMBIENT_LIGHT_BRIGHTNESS_STATE:
Data ambientLightState = apiClient.getAmbientLightState(getThingHaId());
if (!ambientLightState.getValueAsBoolean()) {
apiClient.setAmbientLightState(getThingHaId(), true);
}
break;
}
}
protected void processProgramOptions(List<Option> options) {
options.forEach(option -> {
String key = option.getKey();
if (key != null) {
switch (key) {
case OPTION_WASHER_TEMPERATURE:
getThingChannel(CHANNEL_WASHER_TEMPERATURE)
.ifPresent(channel -> updateState(channel.getUID(), new StringType(option.getValue())));
break;
case OPTION_WASHER_SPIN_SPEED:
getThingChannel(CHANNEL_WASHER_SPIN_SPEED)
.ifPresent(channel -> updateState(channel.getUID(), new StringType(option.getValue())));
break;
case OPTION_WASHER_IDOS_1_DOSING_LEVEL:
getThingChannel(CHANNEL_WASHER_IDOS1)
.ifPresent(channel -> updateState(channel.getUID(), new StringType(option.getValue())));
break;
case OPTION_WASHER_IDOS_2_DOSING_LEVEL:
getThingChannel(CHANNEL_WASHER_IDOS2)
.ifPresent(channel -> updateState(channel.getUID(), new StringType(option.getValue())));
break;
case OPTION_DRYER_DRYING_TARGET:
getThingChannel(CHANNEL_DRYER_DRYING_TARGET)
.ifPresent(channel -> updateState(channel.getUID(), new StringType(option.getValue())));
break;
case OPTION_HOOD_INTENSIVE_LEVEL:
String hoodIntensiveLevelValue = option.getValue();
if (hoodIntensiveLevelValue != null) {
getThingChannel(CHANNEL_HOOD_INTENSIVE_LEVEL)
.ifPresent(channel -> updateState(channel.getUID(),
new StringType(mapStageStringType(hoodIntensiveLevelValue))));
}
break;
case OPTION_HOOD_VENTING_LEVEL:
String hoodVentingLevel = option.getValue();
if (hoodVentingLevel != null) {
getThingChannel(CHANNEL_HOOD_VENTING_LEVEL)
.ifPresent(channel -> updateState(channel.getUID(),
new StringType(mapStageStringType(hoodVentingLevel))));
}
break;
case OPTION_SETPOINT_TEMPERATURE:
getThingChannel(CHANNEL_SETPOINT_TEMPERATURE).ifPresent(channel -> updateState(channel.getUID(),
new QuantityType<>(option.getValueAsInt(), mapTemperature(option.getUnit()))));
break;
case OPTION_DURATION:
getThingChannel(CHANNEL_DURATION).ifPresent(channel -> updateState(channel.getUID(),
new QuantityType<>(option.getValueAsInt(), SECOND)));
break;
case OPTION_REMAINING_PROGRAM_TIME:
getThingChannel(CHANNEL_REMAINING_PROGRAM_TIME_STATE)
.ifPresent(channel -> updateState(channel.getUID(),
new QuantityType<>(option.getValueAsInt(), SECOND)));
break;
case OPTION_ELAPSED_PROGRAM_TIME:
getThingChannel(CHANNEL_ELAPSED_PROGRAM_TIME).ifPresent(channel -> updateState(channel.getUID(),
new QuantityType<>(option.getValueAsInt(), SECOND)));
break;
case OPTION_PROGRAM_PROGRESS:
getThingChannel(CHANNEL_PROGRAM_PROGRESS_STATE)
.ifPresent(channel -> updateState(channel.getUID(),
new QuantityType<>(option.getValueAsInt(), PERCENT)));
break;
}
}
});
}
protected String convertWasherTemperature(String value) {
if (value.startsWith("LaundryCare.Washer.EnumType.Temperature.GC")) {
return value.replace("LaundryCare.Washer.EnumType.Temperature.GC", "") + "°C";
}
if (value.startsWith("LaundryCare.Washer.EnumType.Temperature.Ul")) {
return mapStringType(value.replace("LaundryCare.Washer.EnumType.Temperature.Ul", ""));
}
return mapStringType(value);
}
protected String convertWasherSpinSpeed(String value) {
if (value.startsWith("LaundryCare.Washer.EnumType.SpinSpeed.RPM")) {
return value.replace("LaundryCare.Washer.EnumType.SpinSpeed.RPM", "") + " RPM";
}
if (value.startsWith("LaundryCare.Washer.EnumType.SpinSpeed.Ul")) {
return value.replace("LaundryCare.Washer.EnumType.SpinSpeed.Ul", "");
}
return mapStringType(value);
}
protected void updateProgramOptionsStateDescriptions(String programKey, @Nullable List<Option> optionsValues)
throws CommunicationException, AuthorizationException, ApplianceOfflineException {
Optional<HomeConnectApiClient> apiClient = getApiClient();
if (apiClient.isPresent()) {
List<AvailableProgramOption> availableProgramOptions = apiClient.get().getProgramOptions(getThingHaId(),
programKey);
Optional<Channel> channelSpinSpeed = getThingChannel(CHANNEL_WASHER_SPIN_SPEED);
Optional<Channel> channelTemperature = getThingChannel(CHANNEL_WASHER_TEMPERATURE);
Optional<Channel> channelDryingTarget = getThingChannel(CHANNEL_DRYER_DRYING_TARGET);
if (availableProgramOptions.isEmpty()) {
List<Option> options;
if (optionsValues != null) {
options = optionsValues;
} else if (channelSpinSpeed.isPresent() || channelTemperature.isPresent()
|| channelDryingTarget.isPresent()) {
Program program = apiClient.get().getSelectedProgram(getThingHaId());
options = program != null ? program.getOptions() : emptyList();
} else {
options = emptyList();
}
channelSpinSpeed.ifPresent(channel -> dynamicStateDescriptionProvider.setStateOptions(channel.getUID(),
options.stream()
.filter(option -> option.getKey() != null && option.getValue() != null
&& OPTION_WASHER_SPIN_SPEED.equals(option.getKey()))
.map(option -> option.getValue())
.map(value -> new StateOption(value == null ? "" : value,
convertWasherSpinSpeed(value == null ? "" : value)))
.collect(Collectors.toList())));
channelTemperature
.ifPresent(channel -> dynamicStateDescriptionProvider.setStateOptions(channel.getUID(),
options.stream()
.filter(option -> option.getKey() != null && option.getValue() != null
&& OPTION_WASHER_TEMPERATURE.equals(option.getKey()))
.map(option -> option.getValue())
.map(value -> new StateOption(value == null ? "" : value,
convertWasherTemperature(value == null ? "" : value)))
.collect(Collectors.toList())));
channelDryingTarget
.ifPresent(channel -> dynamicStateDescriptionProvider.setStateOptions(channel.getUID(),
options.stream()
.filter(option -> option.getKey() != null && option.getValue() != null
&& OPTION_DRYER_DRYING_TARGET.equals(option.getKey()))
.map(option -> option.getValue())
.map(value -> new StateOption(value == null ? "" : value,
mapStringType(value == null ? "" : value)))
.collect(Collectors.toList())));
}
availableProgramOptions.forEach(option -> {
switch (option.getKey()) {
case OPTION_WASHER_SPIN_SPEED: {
channelSpinSpeed
.ifPresent(channel -> dynamicStateDescriptionProvider.setStateOptions(channel.getUID(),
createStateOptions(option, this::convertWasherSpinSpeed)));
break;
}
case OPTION_WASHER_TEMPERATURE: {
channelTemperature
.ifPresent(channel -> dynamicStateDescriptionProvider.setStateOptions(channel.getUID(),
createStateOptions(option, this::convertWasherTemperature)));
break;
}
case OPTION_DRYER_DRYING_TARGET: {
channelDryingTarget.ifPresent(channel -> dynamicStateDescriptionProvider
.setStateOptions(channel.getUID(), createStateOptions(option, this::mapStringType)));
break;
}
}
});
}
}
protected HomeConnectDynamicStateDescriptionProvider getDynamicStateDescriptionProvider() {
return dynamicStateDescriptionProvider;
}
private List<StateOption> createStateOptions(AvailableProgramOption option,
Function<String, String> stateConverter) {
return option.getAllowedValues().stream().map(av -> new StateOption(av, stateConverter.apply(av)))
.collect(Collectors.toList());
}
private synchronized void scheduleOfflineMonitor1() {
this.reinitializationFuture1 = scheduler.schedule(() -> {
if (isBridgeOnline() && isThingOffline()) {
logger.debug("Offline monitor 1: Check if thing is ONLINE. thing={}, haId={}", getThingLabel(),
getThingHaId());
refreshThingStatus();
if (isThingOnline()) {
logger.debug("Offline monitor 1: Thing status changed to ONLINE. thing={}, haId={}",
getThingLabel(), getThingHaId());
reinitialize();
} else {
scheduleOfflineMonitor1();
}
} else {
scheduleOfflineMonitor1();
}
}, AbstractHomeConnectThingHandler.OFFLINE_MONITOR_1_DELAY_MIN, TimeUnit.MINUTES);
}
private synchronized void stopOfflineMonitor1() {
ScheduledFuture<?> reinitializationFuture = this.reinitializationFuture1;
if (reinitializationFuture != null) {
reinitializationFuture.cancel(false);
this.reinitializationFuture1 = null;
}
}
private synchronized void scheduleOfflineMonitor2() {
this.reinitializationFuture2 = scheduler.schedule(() -> {
if (isBridgeOnline() && !accessible.get()) {
logger.debug("Offline monitor 2: Check if thing is ONLINE. thing={}, haId={}", getThingLabel(),
getThingHaId());
refreshThingStatus();
if (isThingOnline()) {
logger.debug("Offline monitor 2: Thing status changed to ONLINE. thing={}, haId={}",
getThingLabel(), getThingHaId());
reinitialize();
} else {
scheduleOfflineMonitor2();
}
} else {
scheduleOfflineMonitor2();
}
}, AbstractHomeConnectThingHandler.OFFLINE_MONITOR_2_DELAY_MIN, TimeUnit.MINUTES);
}
private synchronized void stopOfflineMonitor2() {
ScheduledFuture<?> reinitializationFuture = this.reinitializationFuture2;
if (reinitializationFuture != null) {
reinitializationFuture.cancel(false);
this.reinitializationFuture2 = null;
}
}
private synchronized void scheduleRetryRegistering() {
this.reinitializationFuture3 = scheduler.schedule(() -> {
logger.debug("Try to register event listener again. haId={}", getThingHaId());
unregisterEventListener();
registerEventListener();
}, AbstractHomeConnectThingHandler.EVENT_LISTENER_CONNECT_RETRY_DELAY_MIN, TimeUnit.MINUTES);
}
private synchronized void stopRetryRegistering() {
ScheduledFuture<?> reinitializationFuture = this.reinitializationFuture3;
if (reinitializationFuture != null) {
reinitializationFuture.cancel(true);
this.reinitializationFuture3 = null;
}
}
}
|
package org.hyperic.sigar.cmd;
import java.io.File;
import java.io.PrintStream;
import java.net.InetAddress;
import java.net.UnknownHostException;
import org.hyperic.sigar.OperatingSystem;
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException;
import org.hyperic.sigar.SigarLoader;
import org.hyperic.sigar.win32.LocaleInfo;
/**
* Display Sigar, java and system version information.
*/
public class Version extends SigarCommandBase {
public Version(Shell shell) {
super(shell);
}
public Version() {
super();
}
public String getUsageShort() {
return "Display sigar and system version info";
}
private static String getHostName() {
try {
return InetAddress.getLocalHost().getHostName();
} catch (UnknownHostException e) {
return "unknown";
}
}
private static void printNativeInfo(PrintStream os) {
String version =
"java=" + Sigar.VERSION_STRING +
", native=" + Sigar.NATIVE_VERSION_STRING;
String build =
"java=" + Sigar.BUILD_DATE +
", native=" + Sigar.NATIVE_BUILD_DATE;
String scm =
"java=" + Sigar.SCM_REVISION +
", native=" + Sigar.NATIVE_SCM_REVISION;
String archlib =
SigarLoader.getNativeLibraryName();
os.println("Sigar version......." + version);
os.println("Build date.........." + build);
os.println("SCM rev............." + scm);
String host = getHostName();
String fqdn;
Sigar sigar = new Sigar();
try {
File lib = sigar.getNativeLibrary();
if (lib != null) {
archlib = lib.getName();
}
fqdn = sigar.getFQDN();
} catch (SigarException e) {
fqdn = "unknown";
} finally {
sigar.close();
}
os.println("Archlib............." + archlib);
os.println("Current fqdn........" + fqdn);
if (!fqdn.equals(host)) {
os.println("Hostname............" + host);
}
if (SigarLoader.IS_WIN32) {
LocaleInfo info = new LocaleInfo();
os.println("Language............" + info);
os.println("Perflib lang id....." +
info.getPerflibLangId());
}
}
public static void printInfo(PrintStream os) {
try {
printNativeInfo(os);
} catch (UnsatisfiedLinkError e) {
os.println("*******ERROR******* " + e);
}
os.println("Current user........" +
System.getProperty("user.name"));
os.println("");
OperatingSystem sys = OperatingSystem.getInstance();
os.println("OS description......" + sys.getDescription());
os.println("OS name............." + sys.getName());
os.println("OS arch............." + sys.getArch());
os.println("OS machine.........." + sys.getMachine());
os.println("OS version.........." + sys.getVersion());
os.println("OS patch level......" + sys.getPatchLevel());
os.println("OS vendor..........." + sys.getVendor());
os.println("OS vendor version..." + sys.getVendorVersion());
if (sys.getVendorCodeName() != null) {
os.println("OS code name........" + sys.getVendorCodeName());
}
os.println("OS data model......." + sys.getDataModel());
os.println("OS cpu endian......." + sys.getCpuEndian());
os.println("Java vm version....." +
System.getProperty("java.vm.version"));
os.println("Java vm vendor......" +
System.getProperty("java.vm.vendor"));
os.println("Java home..........." +
System.getProperty("java.home"));
}
public void output(String[] args) {
printInfo(this.out);
}
public static void main(String[] args) throws Exception {
new Version().processCommand(args);
}
}
|
package com.yahoo.document;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yahoo.compress.CompressionType;
import com.yahoo.document.datatypes.Array;
import com.yahoo.document.datatypes.ByteFieldValue;
import com.yahoo.document.datatypes.DoubleFieldValue;
import com.yahoo.document.datatypes.FieldPathIteratorHandler;
import com.yahoo.document.datatypes.FieldValue;
import com.yahoo.document.datatypes.FloatFieldValue;
import com.yahoo.document.datatypes.IntegerFieldValue;
import com.yahoo.document.datatypes.LongFieldValue;
import com.yahoo.document.datatypes.MapFieldValue;
import com.yahoo.document.datatypes.Raw;
import com.yahoo.document.datatypes.StringFieldValue;
import com.yahoo.document.datatypes.Struct;
import com.yahoo.document.datatypes.WeightedSet;
import com.yahoo.document.serialization.DocumentDeserializer;
import com.yahoo.document.serialization.DocumentDeserializerFactory;
import com.yahoo.document.serialization.DocumentReader;
import com.yahoo.document.serialization.DocumentSerializer;
import com.yahoo.document.serialization.DocumentSerializerFactory;
import com.yahoo.document.serialization.XmlDocumentWriter;
import com.yahoo.io.GrowableByteBuffer;
import com.yahoo.vespa.objects.BufferSerializer;
import org.junit.Test;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.util.Map;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.instanceOf;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* Test for Document and all its features, including (de)serialization.
*
* @author <a href="thomasg@yahoo-inc.com>Thomas Gundersen</a>
* @author bratseth
*/
public class DocumentTestCase extends DocumentTestCaseBase {
private static final String SERTEST_DOC_AS_XML_HEAD =
"<document documenttype=\"sertest\" documentid=\"doc:sertest:foobar\">\n" +
" <mailid>emailfromalicetobob&someone</mailid>\n" +
" <date>-2013512400</date>\n" +
" <attachmentcount>2</attachmentcount>\n" +
" <rawfield binaryencoding=\"base64\">AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4vMDEyMzQ1Njc4OTo7PD0+P0BBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWltcXV5fYGFiYw==</rawfield>\n";
private static final String SERTEST_DOC_AS_XML_WEIGHT1 =
" <weightedfield>\n" +
" <item weight=\"10\">this is another test, blah blah</item>\n" +
" <item weight=\"5\">this is a test</item>\n" +
" </weightedfield>\n";
private static final String SERTEST_DOC_AS_XML_WEIGHT2 =
" <weightedfield>\n" +
" <item weight=\"5\">this is a test</item>\n" +
" <item weight=\"10\">this is another test, blah blah</item>\n" +
" </weightedfield>\n";
private static final String SERTEST_DOC_AS_XML_SUNNYVALE =
" <myposfield>N37.374821;W122.057174</myposfield>\n";
private static final String SERTEST_DOC_AS_XML_FOOT =
" <docindoc documenttype=\"docindoc\" documentid=\"doc:sertest:inserted\">\n" +
" <tull>ball</tull>\n" +
" </docindoc>\n" +
" <mapfield>\n" +
" <item>\n" +
" <key>foo2</key>\n" +
" <value>bar2</value>\n" +
" </item>\n" +
" <item>\n" +
" <key>foo1</key>\n" +
" <value>bar1</value>\n" +
" </item>\n" +
" </mapfield>\n" +
SERTEST_DOC_AS_XML_SUNNYVALE +
"</document>\n";
static DocumentTypeManager setUpCppDocType() {
return setUpDocType("file:src/tests/data/crossplatform-java-cpp-document.cfg");
}
static DocumentTypeManager setUpDocType(String filename) {
DocumentTypeManager dcMan = new DocumentTypeManager();
DocumentTypeManagerConfigurer.configure(dcMan, filename);
return dcMan;
}
public void setUpSertestDocType() {
docMan = new DocumentTypeManager();
DocumentType docInDocType = new DocumentType("docindoc");
docInDocType.addField(new Field("tull", 2, docMan.getDataType(2), true));
docMan.registerDocumentType(docInDocType);
DocumentType sertestDocType = new DocumentType("sertest");
sertestDocType.addField(new Field("mailid", 2, docMan.getDataType(2), true));
sertestDocType.addField(new Field("date", 3, docMan.getDataType(0), true));
sertestDocType.addField(new Field("from", 4, docMan.getDataType(2), true));
sertestDocType.addField(new Field("to", 6, docMan.getDataType(2), true));
sertestDocType.addField(new Field("subject", 9, docMan.getDataType(2), true));
sertestDocType.addField(new Field("body", 10, docMan.getDataType(2), false));
sertestDocType.addField(new Field("attachmentcount", 11, docMan.getDataType(0), false));
sertestDocType.addField(new Field("attachments", 1081629685, DataType.getArray(docMan.getDataType(2)), false));
sertestDocType.addField(new Field("rawfield", 879, DataType.RAW, false));
sertestDocType.addField(new Field("weightedfield", 880, DataType.getWeightedSet(DataType.STRING), false));
sertestDocType.addField(new Field("weightedfieldCreate", 881, DataType.getWeightedSet(DataType.STRING, true, false), false));
sertestDocType.addField(new Field("docindoc", 882, docInDocType, false));
sertestDocType.addField(new Field("mapfield", 883, new MapDataType(DataType.STRING, DataType.STRING), false));
sertestDocType.addField(new Field("myposfield", 884, PositionDataType.INSTANCE, false));
docMan.registerDocumentType(sertestDocType);
}
static byte[] readFile(String filename) throws IOException {
FileInputStream fis = new FileInputStream(filename);
byte[] data = new byte[1000];
int tot = fis.read(data);
if (tot == -1) {
throw new IOException("Could not read from file " + filename);
}
return data;
}
private Document getSertestDocument() {
Document doc = new Document(docMan.getDocumentType("sertest"), new DocumentId("doc:sertest:foobar"));
doc.setFieldValue("mailid", "emailfromalicetobob");
doc.setFieldValue("date", -2013512400); // 03/13/06 11:00:00
doc.setFieldValue("attachmentcount", 2);
byte[] rawBytes = new byte[100];
for (int i = 0; i < rawBytes.length; i++) {
rawBytes[i] = (byte)i;
}
doc.setFieldValue("rawfield", new Raw(ByteBuffer.wrap(rawBytes)));
Document docInDoc = new Document(docMan.getDocumentType("docindoc"), new DocumentId("doc:sertest:inserted"));
docInDoc.setFieldValue("tull", "ball");
doc.setFieldValue("docindoc", docInDoc);
WeightedSet<StringFieldValue> wset = new WeightedSet<>(DataType.getWeightedSet(DataType.STRING));
wset.put(new StringFieldValue("this is a test"), 5);
wset.put(new StringFieldValue("this is another test, blah blah"), 10);
doc.setFieldValue("weightedfield", wset);
MapFieldValue<StringFieldValue, StringFieldValue> map = new MapFieldValue<>(new MapDataType(DataType.STRING, DataType.STRING));
map.put(new StringFieldValue("foo1"), new StringFieldValue("bar1"));
map.put(new StringFieldValue("foo2"), new StringFieldValue("bar2"));
doc.setFieldValue("mapfield", map);
return doc;
}
@Test
public void testTypeChecking() {
DocumentType type = new DocumentType("test");
type.addField(new Field("double", DataType.DOUBLE));
type.addField(new Field("float", DataType.FLOAT));
type.addField(new Field("int", DataType.INT));
type.addField(new Field("long", DataType.LONG));
type.addField(new Field("string", DataType.STRING));
Document doc = new Document(type, "doc:scheme:");
FieldValue stringVal = new StringFieldValue("69");
FieldValue doubleVal = new DoubleFieldValue(6.9);
FieldValue floatVal = new FloatFieldValue(6.9f);
FieldValue intVal = new IntegerFieldValue(69);
FieldValue longVal = new LongFieldValue(69L);
doc.setFieldValue("string", stringVal);
doc.setFieldValue("string", doubleVal);
doc.setFieldValue("string", floatVal);
doc.setFieldValue("string", intVal);
doc.setFieldValue("string", longVal);
doc.setFieldValue("double", stringVal);
doc.setFieldValue("double", doubleVal);
doc.setFieldValue("double", floatVal);
doc.setFieldValue("double", intVal);
doc.setFieldValue("double", longVal);
doc.setFieldValue("float", stringVal);
doc.setFieldValue("float", doubleVal);
doc.setFieldValue("float", floatVal);
doc.setFieldValue("float", intVal);
doc.setFieldValue("float", longVal);
doc.setFieldValue("int", stringVal);
doc.setFieldValue("int", doubleVal);
doc.setFieldValue("int", floatVal);
doc.setFieldValue("int", intVal);
doc.setFieldValue("int", longVal);
doc.setFieldValue("long", stringVal);
doc.setFieldValue("long", doubleVal);
doc.setFieldValue("long", floatVal);
doc.setFieldValue("long", intVal);
doc.setFieldValue("long", longVal);
}
class VariableIteratorHandler extends FieldPathIteratorHandler {
public String retVal = "";
@Override
public void onPrimitive(FieldValue fv) {
for (Map.Entry<String, IndexValue> entry : getVariables().entrySet()) {
retVal += entry.getKey() + ": " + entry.getValue() + ",";
}
retVal += " - " + fv + "\n";
}
}
@Test
public void testVariables() {
ArrayDataType iarr = new ArrayDataType(DataType.INT);
ArrayDataType iiarr = new ArrayDataType(iarr);
ArrayDataType iiiarr = new ArrayDataType(iiarr);
DocumentType type = new DocumentType("test");
type.addField(new Field("iiiarray", iiiarr));
Array<Array<Array<IntegerFieldValue>>> iiiaV = new Array<>(iiiarr);
for (int i = 1; i < 4; i++) {
Array<Array<IntegerFieldValue>> iiaV = new Array<>(iiarr);
for (int j = 1; j < 4; j++) {
Array<IntegerFieldValue> iaV = new Array<>(iarr);
for (int k = 1; k < 4; k++) {
iaV.add(new IntegerFieldValue(i * j * k));
}
iiaV.add(iaV);
}
iiiaV.add(iiaV);
}
Document doc = new Document(type, new DocumentId("doc:foo:testdoc"));
doc.setFieldValue("iiiarray", iiiaV);
{
VariableIteratorHandler handler = new VariableIteratorHandler();
FieldPath path = type.buildFieldPath("iiiarray[$x][$y][$z]");
doc.iterateNested(path, 0, handler);
String fasit =
"x: 0,y: 0,z: 0, - 1\n" +
"x: 0,y: 0,z: 1, - 2\n" +
"x: 0,y: 0,z: 2, - 3\n" +
"x: 0,y: 1,z: 0, - 2\n" +
"x: 0,y: 1,z: 1, - 4\n" +
"x: 0,y: 1,z: 2, - 6\n" +
"x: 0,y: 2,z: 0, - 3\n" +
"x: 0,y: 2,z: 1, - 6\n" +
"x: 0,y: 2,z: 2, - 9\n" +
"x: 1,y: 0,z: 0, - 2\n" +
"x: 1,y: 0,z: 1, - 4\n" +
"x: 1,y: 0,z: 2, - 6\n" +
"x: 1,y: 1,z: 0, - 4\n" +
"x: 1,y: 1,z: 1, - 8\n" +
"x: 1,y: 1,z: 2, - 12\n" +
"x: 1,y: 2,z: 0, - 6\n" +
"x: 1,y: 2,z: 1, - 12\n" +
"x: 1,y: 2,z: 2, - 18\n" +
"x: 2,y: 0,z: 0, - 3\n" +
"x: 2,y: 0,z: 1, - 6\n" +
"x: 2,y: 0,z: 2, - 9\n" +
"x: 2,y: 1,z: 0, - 6\n" +
"x: 2,y: 1,z: 1, - 12\n" +
"x: 2,y: 1,z: 2, - 18\n" +
"x: 2,y: 2,z: 0, - 9\n" +
"x: 2,y: 2,z: 1, - 18\n" +
"x: 2,y: 2,z: 2, - 27\n";
assertEquals(fasit, handler.retVal);
}
}
@Test
public void testGetRecursiveValue() {
Document doc = new Document(testDocType, new DocumentId("doc:ns:testdoc"));
doc.setFieldValue("primitive1", 1);
Struct l1s1 = new Struct(doc.getField("l1s1").getDataType());
l1s1.setFieldValue("primitive1", 2);
Struct l2s1 = new Struct(doc.getField("struct2").getDataType());
l2s1.setFieldValue("primitive1", 3);
l2s1.setFieldValue("primitive2", 4);
Array<IntegerFieldValue> iarr1 = new Array<>(l2s1.getField("iarray").getDataType());
iarr1.add(new IntegerFieldValue(11));
iarr1.add(new IntegerFieldValue(12));
iarr1.add(new IntegerFieldValue(13));
l2s1.setFieldValue("iarray", iarr1);
ArrayDataType dt = (ArrayDataType)l2s1.getField("sarray").getDataType();
Array<Struct> sarr1 = new Array<>(dt);
{
Struct l3s1 = new Struct(dt.getNestedType());
l3s1.setFieldValue("primitive1", 1);
l3s1.setFieldValue("primitive2", 2);
sarr1.add(l3s1);
}
{
Struct l3s1 = new Struct(dt.getNestedType());
l3s1.setFieldValue("primitive1", 1);
l3s1.setFieldValue("primitive2", 2);
sarr1.add(l3s1);
}
l2s1.setFieldValue("sarray", sarr1);
MapFieldValue<StringFieldValue, StringFieldValue> smap1 = new MapFieldValue<>((MapDataType)l2s1.getField("smap").getDataType());
smap1.put(new StringFieldValue("leonardo"), new StringFieldValue("dicaprio"));
smap1.put(new StringFieldValue("ellen"), new StringFieldValue("page"));
smap1.put(new StringFieldValue("joseph"), new StringFieldValue("gordon-levitt"));
l2s1.setFieldValue("smap", smap1);
l1s1.setFieldValue("ss", l2s1.clone());
MapFieldValue<StringFieldValue, Struct> structmap1 = new MapFieldValue<>((MapDataType)l1s1.getField("structmap").getDataType());
structmap1.put(new StringFieldValue("test"), l2s1.clone());
l1s1.setFieldValue("structmap", structmap1);
WeightedSet<StringFieldValue> wset1 = new WeightedSet<>(l1s1.getField("wset").getDataType());
wset1.add(new StringFieldValue("foo"));
wset1.add(new StringFieldValue("bar"));
wset1.add(new StringFieldValue("zoo"));
l1s1.setFieldValue("wset", wset1);
Struct l2s2 = new Struct(doc.getField("struct2").getDataType());
l2s2.setFieldValue("primitive1", 5);
l2s2.setFieldValue("primitive2", 6);
WeightedSet<Struct> wset2 = new WeightedSet<>(l1s1.getField("structwset").getDataType());
wset2.add(l2s1.clone());
wset2.add(l2s2.clone());
l1s1.setFieldValue("structwset", wset2);
doc.setFieldValue("l1s1", l1s1.clone());
{
FieldValue fv = doc.getRecursiveValue("l1s1");
assertEquals(l1s1, fv);
}
{
FieldValue fv = doc.getRecursiveValue("l1s1.primitive1");
assertEquals(new IntegerFieldValue(2), fv);
}
{
FieldValue fv = doc.getRecursiveValue("l1s1.ss");
assertEquals(l2s1, fv);
}
{
FieldValue fv = doc.getRecursiveValue("l1s1.ss.iarray");
assertEquals(iarr1, fv);
}
{
FieldValue fv = doc.getRecursiveValue("l1s1.ss.iarray[2]");
assertEquals(new IntegerFieldValue(13), fv);
}
{
FieldValue fv = doc.getRecursiveValue("l1s1.ss.iarray[3]");
assertNull(fv);
}
{
FieldValue fv = doc.getRecursiveValue("l1s1.ss.sarray[0].primitive1");
assertEquals(new IntegerFieldValue(1), fv);
}
{
FieldValue fv = doc.getRecursiveValue("l1s1.ss.smap{joseph}");
assertEquals(new StringFieldValue("gordon-levitt"), fv);
}
{
FieldValue fv = doc.getRecursiveValue("l1s1.ss.smap.key");
assertEquals(3, ((Array)fv).size());
}
{
FieldValue fv = doc.getRecursiveValue("l1s1.structmap{test}.primitive1");
assertEquals(new IntegerFieldValue(3), fv);
}
{
FieldValue fv = doc.getRecursiveValue("l1s1.structmap.value.primitive1");
assertEquals(new IntegerFieldValue(3), fv);
}
{
FieldValue fv = doc.getRecursiveValue("l1s1.wset{foo}");
assertEquals(new IntegerFieldValue(1), fv);
}
{
FieldValue fv = doc.getRecursiveValue("l1s1.wset.key");
assertEquals(3, ((Array)fv).size());
}
{
FieldValue fv = doc.getRecursiveValue("l1s1.structwset.key.primitive1");
assertEquals(DataType.INT, (((ArrayDataType)fv.getDataType()).getNestedType()));
assertEquals(2, ((Array)fv).size());
}
}
class ModifyIteratorHandler extends FieldPathIteratorHandler {
public ModificationStatus doModify(FieldValue fv) {
if (fv instanceof StringFieldValue) {
fv.assign("newvalue");
return ModificationStatus.MODIFIED;
}
return ModificationStatus.NOT_MODIFIED;
}
public boolean onComplex(FieldValue fv) {
return false;
}
}
class AddIteratorHandler extends FieldPathIteratorHandler {
@SuppressWarnings("unchecked")
public ModificationStatus doModify(FieldValue fv) {
if (fv instanceof Array) {
((Array)fv).add(new IntegerFieldValue(32));
return ModificationStatus.MODIFIED;
}
return ModificationStatus.NOT_MODIFIED;
}
public boolean onComplex(FieldValue fv) {
return false;
}
}
class RemoveIteratorHandler extends FieldPathIteratorHandler {
public ModificationStatus doModify(FieldValue fv) {
return ModificationStatus.REMOVED;
}
public boolean onComplex(FieldValue fv) {
return false;
}
}
@Test
public void testModifyDocument() {
Document doc = new Document(testDocType, new DocumentId("doc:ns:testdoc"));
doc.setFieldValue("primitive1", 1);
Struct l1s1 = new Struct(doc.getField("l1s1").getDataType());
l1s1.setFieldValue("primitive1", 2);
Struct l2s1 = new Struct(doc.getField("struct2").getDataType());
l2s1.setFieldValue("primitive1", 3);
l2s1.setFieldValue("primitive2", 4);
Array<IntegerFieldValue> iarr1 = new Array<>(l2s1.getField("iarray").getDataType());
iarr1.add(new IntegerFieldValue(11));
iarr1.add(new IntegerFieldValue(12));
iarr1.add(new IntegerFieldValue(13));
l2s1.setFieldValue("iarray", iarr1);
ArrayDataType dt = (ArrayDataType)l2s1.getField("sarray").getDataType();
Array<Struct> sarr1 = new Array<>(dt);
{
Struct l3s1 = new Struct(dt.getNestedType());
l3s1.setFieldValue("primitive1", 1);
l3s1.setFieldValue("primitive2", 2);
sarr1.add(l3s1);
}
{
Struct l3s1 = new Struct(dt.getNestedType());
l3s1.setFieldValue("primitive1", 1);
l3s1.setFieldValue("primitive2", 2);
sarr1.add(l3s1);
}
l2s1.setFieldValue("sarray", sarr1);
MapFieldValue<StringFieldValue, StringFieldValue> smap1 = new MapFieldValue<>((MapDataType)l2s1.getField("smap").getDataType());
smap1.put(new StringFieldValue("leonardo"), new StringFieldValue("dicaprio"));
smap1.put(new StringFieldValue("ellen"), new StringFieldValue("page"));
smap1.put(new StringFieldValue("joseph"), new StringFieldValue("gordon-levitt"));
l2s1.setFieldValue("smap", smap1);
l1s1.setFieldValue("ss", l2s1.clone());
MapFieldValue<StringFieldValue, Struct> structmap1 = new MapFieldValue<>((MapDataType)l1s1.getField("structmap").getDataType());
structmap1.put(new StringFieldValue("test"), l2s1.clone());
l1s1.setFieldValue("structmap", structmap1);
WeightedSet<StringFieldValue> wset1 = new WeightedSet<>(l1s1.getField("wset").getDataType());
wset1.add(new StringFieldValue("foo"));
wset1.add(new StringFieldValue("bar"));
wset1.add(new StringFieldValue("zoo"));
l1s1.setFieldValue("wset", wset1);
Struct l2s2 = new Struct(doc.getField("struct2").getDataType());
l2s2.setFieldValue("primitive1", 5);
l2s2.setFieldValue("primitive2", 6);
WeightedSet<Struct> wset2 = new WeightedSet<>(l1s1.getField("structwset").getDataType());
wset2.add(l2s1.clone());
wset2.add(l2s2.clone());
l1s1.setFieldValue("structwset", wset2);
doc.setFieldValue("l1s1", l1s1.clone());
{
ModifyIteratorHandler handler = new ModifyIteratorHandler();
FieldPath path = doc.getDataType().buildFieldPath("l1s1.structmap.value.smap{leonardo}");
doc.iterateNested(path, 0, handler);
FieldValue fv = doc.getRecursiveValue("l1s1.structmap.value.smap{leonardo}");
assertEquals(new StringFieldValue("newvalue"), fv);
}
{
AddIteratorHandler handler = new AddIteratorHandler();
FieldPath path = doc.getDataType().buildFieldPath("l1s1.ss.iarray");
doc.iterateNested(path, 0, handler);
FieldValue fv = doc.getRecursiveValue("l1s1.ss.iarray");
assertTrue(((Array)fv).contains(new IntegerFieldValue(32)));
assertEquals(4, ((Array)fv).size());
}
{
RemoveIteratorHandler handler = new RemoveIteratorHandler();
FieldPath path = doc.getDataType().buildFieldPath("l1s1.ss.iarray[1]");
doc.iterateNested(path, 0, handler);
FieldValue fv = doc.getRecursiveValue("l1s1.ss.iarray");
assertFalse(((Array)fv).contains(Integer.valueOf(12)));
assertEquals(3, ((Array)fv).size());
}
{
RemoveIteratorHandler handler = new RemoveIteratorHandler();
FieldPath path = doc.getDataType().buildFieldPath("l1s1.ss.iarray[$x]");
doc.iterateNested(path, 0, handler);
FieldValue fv = doc.getRecursiveValue("l1s1.ss.iarray");
assertEquals(0, ((Array)fv).size());
}
{
RemoveIteratorHandler handler = new RemoveIteratorHandler();
FieldPath path = doc.getDataType().buildFieldPath("l1s1.structmap.value.smap{leonardo}");
doc.iterateNested(path, 0, handler);
FieldValue fv = doc.getRecursiveValue("l1s1.structmap.value.smap");
assertFalse(((MapFieldValue)fv).contains(new StringFieldValue("leonardo")));
}
{
RemoveIteratorHandler handler = new RemoveIteratorHandler();
FieldPath path = doc.getDataType().buildFieldPath("l1s1.wset{foo}");
doc.iterateNested(path, 0, handler);
FieldValue fv = doc.getRecursiveValue("l1s1.wset");
assertFalse(((WeightedSet)fv).contains(new StringFieldValue("foo")));
}
}
@Test
public void testNoType() {
try {
new Document(null, new DocumentId("doc:null:URI"));
fail("Should have gotten an Exception");
} catch (NullPointerException | IllegalArgumentException e) {
// Success
}
}
@Test
public void testURI() {
String uri = "doc:testdoc:http:
DocumentType documentType = docMan.getDocumentType("testdoc");
assertNotNull(documentType);
Document doc = new Document(docMan.getDocumentType("testdoc"), new DocumentId(uri));
assertEquals(doc.getId().toString(), uri);
}
@Test
public void testSetGet() {
Document doc = new Document(docMan.getDocumentType("testdoc"), new DocumentId("doc:testdoc:test"));
Object val = doc.getFieldValue(minField.getName());
assertNull(val);
doc.setFieldValue(minField.getName(), 500);
val = doc.getFieldValue(minField.getName());
assertEquals(new IntegerFieldValue(500), val);
val = doc.getFieldValue(minField.getName());
assertEquals(new IntegerFieldValue(500), val);
doc.removeFieldValue(minField);
assertNull(doc.getFieldValue(minField.getName()));
assertNull(doc.getFieldValue("doesntexist"));
}
@Test
public void testGetField() {
Document doc = getTestDocument();
assertNull(doc.getFieldValue("doesntexist"));
assertNull(doc.getFieldValue("notintype"));
}
@Test
public void testCppDocCompressed() throws IOException {
docMan = setUpCppDocType();
byte[] data = readFile("src/test/document/serializecpp-lz4-level9.dat");
ByteBuffer buf = ByteBuffer.wrap(data);
Document doc = docMan.createDocument(new GrowableByteBuffer(buf));
validateCppDoc(doc);
}
@Test
public void testCppDoc() throws IOException {
docMan = setUpCppDocType();
byte[] data = readFile("src/test/document/serializecpp.dat");
ByteBuffer buf = ByteBuffer.wrap(data);
Document doc = docMan.createDocument(new GrowableByteBuffer(buf));
validateCppDoc(doc);
}
@Test
public void testV6Doc() throws IOException {
docMan = setUpCppDocType();
byte[] data = readFile("src/tests/data/serializev6.dat");
ByteBuffer buf = ByteBuffer.wrap(data);
Document doc = docMan.createDocument(new GrowableByteBuffer(buf));
validateCppDocNotMap(doc);
}
public void validateCppDoc(Document doc) throws IOException {
validateCppDocNotMap(doc);
MapFieldValue map = (MapFieldValue)doc.getFieldValue("mapfield");
assertEquals(map.get(new StringFieldValue("foo1")), new StringFieldValue("bar1"));
assertEquals(map.get(new StringFieldValue("foo2")), new StringFieldValue("bar2"));
}
@SuppressWarnings("unchecked")
public void validateCppDocNotMap(Document doc) throws IOException {
// in practice to validate v6 serialization
assertEquals("doc:serializetest:http://test.doc.id/", doc.getId().toString());
assertEquals(new IntegerFieldValue(5), doc.getFieldValue("intfield"));
assertEquals(new FloatFieldValue((float)-9.23), doc.getFieldValue("floatfield"));
assertEquals(new StringFieldValue("This is a string."), doc.getFieldValue("stringfield"));
assertEquals(new LongFieldValue(398420092938472983L), doc.getFieldValue("longfield"));
assertEquals(new DoubleFieldValue(98374532.398820d), doc.getFieldValue("doublefield"));
assertEquals(new StringFieldValue("http://this.is.a.test/"), doc.getFieldValue("urifield"));
//NOTE: The value really is unsigned 254, which becomes signed -2:
assertEquals(new ByteFieldValue(-2), doc.getFieldValue("bytefield"));
ByteBuffer raw = ByteBuffer.wrap("RAW DATA".getBytes());
assertEquals(new Raw(raw), doc.getFieldValue("rawfield"));
Document docindoc = (Document)doc.getFieldValue("docfield");
assertEquals(docMan.getDocumentType("docindoc"), docindoc.getDataType());
assertEquals(new DocumentId("doc:docindoc:http://embedded"), docindoc.getId());
Array<FloatFieldValue> array = (Array<FloatFieldValue>)doc.getFieldValue("arrayoffloatfield");
assertEquals(new FloatFieldValue(1.0f), array.get(0));
assertEquals(new FloatFieldValue(2.0f), array.get(1));
WeightedSet<StringFieldValue> wset = (WeightedSet<StringFieldValue>)doc.getFieldValue("wsfield");
assertEquals(Integer.valueOf(50), wset.get(new StringFieldValue("Weighted 0")));
assertEquals(Integer.valueOf(199), wset.get(new StringFieldValue("Weighted 1")));
}
@Test
public void testCppDocSplit() throws IOException {
docMan = setUpCppDocType();
byte[] headerData = readFile("src/test/document/serializecppsplit_header.dat");
byte[] bodyData = readFile("src/test/document/serializecppsplit_body.dat");
DocumentDeserializer header = DocumentDeserializerFactory.create42(docMan, GrowableByteBuffer.wrap(headerData),
GrowableByteBuffer.wrap(bodyData));
Document doc = new Document(header);
assertEquals("doc:serializetest:http://test.doc.id/", doc.getId().toString());
assertEquals(new IntegerFieldValue(5), doc.getFieldValue("intfield"));
assertEquals(new FloatFieldValue((float)-9.23), doc.getFieldValue("floatfield"));
assertEquals(new StringFieldValue("This is a string."), doc.getFieldValue("stringfield"));
assertEquals(new LongFieldValue(398420092938472983L), doc.getFieldValue("longfield"));
assertEquals(new DoubleFieldValue(98374532.398820d), doc.getFieldValue("doublefield"));
assertEquals(new StringFieldValue("http://this.is.a.test/"), doc.getFieldValue("urifield"));
//NOTE: The value really is unsigned 254, which becomes signed -2:
assertEquals(new ByteFieldValue((byte)-2), doc.getFieldValue("bytefield"));
ByteBuffer raw = ByteBuffer.wrap("RAW DATA".getBytes());
assertEquals(new Raw(raw), doc.getFieldValue("rawfield"));
Document docindoc = (Document)doc.getFieldValue("docfield");
assertEquals(docMan.getDocumentType("docindoc"), docindoc.getDataType());
assertEquals(new DocumentId("doc:docindoc:http://embedded"), docindoc.getId());
WeightedSet wset = (WeightedSet)doc.getFieldValue("wsfield");
assertEquals(Integer.valueOf(50), wset.get(new StringFieldValue("Weighted 0")));
assertEquals(Integer.valueOf(199), wset.get(new StringFieldValue("Weighted 1")));
}
@Test
public void testCppDocSplitNoBody() throws IOException {
docMan = setUpCppDocType();
byte[] headerData = readFile("src/test/document/serializecppsplit_header.dat");
DocumentDeserializer header = DocumentDeserializerFactory.create42(docMan, GrowableByteBuffer.wrap(headerData));
Document doc = new Document(header);
assertEquals("doc:serializetest:http://test.doc.id/", doc.getId().toString());
assertEquals(new FloatFieldValue((float)-9.23), doc.getFieldValue("floatfield"));
assertEquals(new StringFieldValue("This is a string."), doc.getFieldValue("stringfield"));
assertEquals(new LongFieldValue(398420092938472983L), doc.getFieldValue("longfield"));
assertEquals(new StringFieldValue("http://this.is.a.test/"), doc.getFieldValue("urifield"));
}
@Test
public void testGenerateSerializedFile() throws IOException {
docMan = setUpCppDocType();
Document doc = new Document(docMan.getDocumentType("serializetest"),
new DocumentId("doc:serializetest:http://test.doc.id/"));
Document docindoc = new Document(docMan.getDocumentType("docindoc"),
new DocumentId("doc:serializetest:http://doc.in.doc/"));
docindoc.setFieldValue("stringindocfield", "Elvis is dead");
doc.setFieldValue("docfield", docindoc);
Array<FloatFieldValue> l = new Array<>(doc.getField("arrayoffloatfield").getDataType());
l.add(new FloatFieldValue((float)1.0));
l.add(new FloatFieldValue((float)2.0));
doc.setFieldValue("arrayoffloatfield", l);
WeightedSet<StringFieldValue>
wset = new WeightedSet<>(doc.getDataType().getField("wsfield").getDataType());
wset.put(new StringFieldValue("Weighted 0"), 50);
wset.put(new StringFieldValue("Weighted 1"), 199);
doc.setFieldValue("wsfield", wset);
MapFieldValue<StringFieldValue, StringFieldValue> map =
new MapFieldValue<>(
(MapDataType)doc.getDataType().getField("mapfield").getDataType());
map.put(new StringFieldValue("foo1"), new StringFieldValue("bar1"));
map.put(new StringFieldValue("foo2"), new StringFieldValue("bar2"));
doc.setFieldValue("mapfield", map);
doc.setFieldValue("bytefield", new ByteFieldValue((byte)254));
doc.setFieldValue("rawfield", new Raw(ByteBuffer.wrap("RAW DATA".getBytes())));
doc.setFieldValue("intfield", new IntegerFieldValue(5));
doc.setFieldValue("floatfield", new FloatFieldValue(-9.23f));
doc.setFieldValue("stringfield", new StringFieldValue("This is a string."));
doc.setFieldValue("longfield", new LongFieldValue(398420092938472983L));
doc.setFieldValue("doublefield", new DoubleFieldValue(98374532.398820d));
doc.setFieldValue("urifield", new StringFieldValue("http://this.is.a.test/"));
int size = doc.getSerializedSize();
GrowableByteBuffer buf = new GrowableByteBuffer(size, 2.0f);
doc.serialize(buf);
assertEquals(size, buf.position());
buf.position(0);
FileOutputStream fos = new FileOutputStream("src/tests/data/serializejava.dat");
fos.write(buf.array(), 0, size);
fos.close();
CompressionConfig noncomp = new CompressionConfig();
CompressionConfig lz4comp = new CompressionConfig(CompressionType.LZ4);
doc.getDataType().getHeaderType().setCompressionConfig(lz4comp);
doc.getDataType().getBodyType().setCompressionConfig(lz4comp);
buf = new GrowableByteBuffer(size, 2.0f);
doc.serialize(buf);
doc.getDataType().getHeaderType().setCompressionConfig(noncomp);
doc.getDataType().getBodyType().setCompressionConfig(noncomp);
fos = new FileOutputStream("src/tests/data/serializejava-compressed.dat");
fos.write(buf.array(), 0, buf.position());
fos.close();
}
@Test
public void testSerializeDeserialize() {
setUpSertestDocType();
Document doc = getSertestDocument();
GrowableByteBuffer data = new GrowableByteBuffer();
doc.serialize(data);
int size = doc.getSerializedSize();
assertEquals(size, data.position());
data.flip();
try {
FileOutputStream fos = new FileOutputStream("src/test/files/testser.dat");
fos.write(data.array(), 0, data.remaining());
fos.close();
} catch (Exception e) {
}
Document doc2 = docMan.createDocument(data);
assertEquals(doc.getFieldValue("mailid"), doc2.getFieldValue("mailid"));
assertEquals(doc.getFieldValue("date"), doc2.getFieldValue("date"));
assertEquals(doc.getFieldValue("from"), doc2.getFieldValue("from"));
assertEquals(doc.getFieldValue("to"), doc2.getFieldValue("to"));
assertEquals(doc.getFieldValue("subject"), doc2.getFieldValue("subject"));
assertEquals(doc.getFieldValue("body"), doc2.getFieldValue("body"));
assertEquals(doc.getFieldValue("attachmentcount"), doc2.getFieldValue("attachmentcount"));
assertEquals(doc.getFieldValue("attachments"), doc2.getFieldValue("attachments"));
byte[] docRawBytes = ((Raw)doc.getFieldValue("rawfield")).getByteBuffer().array();
byte[] doc2RawBytes = ((Raw)doc2.getFieldValue("rawfield")).getByteBuffer().array();
assertEquals(docRawBytes.length, doc2RawBytes.length);
for (int i = 0; i < docRawBytes.length; i++) {
assertEquals(docRawBytes[i], doc2RawBytes[i]);
}
assertEquals(doc.getFieldValue("weightedfield"), doc2.getFieldValue("weightedfield"));
assertEquals(doc.getFieldValue("mapfield"), doc2.getFieldValue("mapfield"));
// Do the same thing, splitting document in two
DocumentSerializer header = DocumentSerializerFactory.create42(new GrowableByteBuffer(), true);
DocumentSerializer body = DocumentSerializerFactory.create42(new GrowableByteBuffer());
doc.serializeHeader(header);
doc.serializeBody(body);
header.getBuf().flip();
body.getBuf().flip();
try {
FileOutputStream fos = new FileOutputStream("src/test/files/testser-split.header.dat");
fos.write(header.getBuf().array(), 0, header.getBuf().remaining());
fos.close();
fos = new FileOutputStream("src/test/files/testser-split.body.dat");
fos.write(body.getBuf().array(), 0, body.getBuf().remaining());
fos.close();
} catch (Exception e) {
}
DocumentDeserializer deser = DocumentDeserializerFactory.create42(docMan, header.getBuf(), body.getBuf());
doc2 = new Document(deser);
assertEquals(doc.getFieldValue("mailid"), doc2.getFieldValue("mailid"));
assertEquals(doc.getFieldValue("date"), doc2.getFieldValue("date"));
assertEquals(doc.getFieldValue("from"), doc2.getFieldValue("from"));
assertEquals(doc.getFieldValue("to"), doc2.getFieldValue("to"));
assertEquals(doc.getFieldValue("subject"), doc2.getFieldValue("subject"));
assertEquals(doc.getFieldValue("body"), doc2.getFieldValue("body"));
assertEquals(doc.getFieldValue("attachmentcount"), doc2.getFieldValue("attachmentcount"));
assertEquals(doc.getFieldValue("attachments"), doc2.getFieldValue("attachments"));
docRawBytes = ((Raw)doc.getFieldValue("rawfield")).getByteBuffer().array();
doc2RawBytes = ((Raw)doc2.getFieldValue("rawfield")).getByteBuffer().array();
assertEquals(docRawBytes.length, doc2RawBytes.length);
for (int i = 0; i < docRawBytes.length; i++) {
assertEquals(docRawBytes[i], doc2RawBytes[i]);
}
assertEquals(doc.getFieldValue("weightedfield"), doc2.getFieldValue("weightedfield"));
assertEquals(doc.getFieldValue("mapfield"), doc2.getFieldValue("mapfield"));
Document docInDoc = (Document)doc.getFieldValue("docindoc");
assert (docInDoc != null);
assertEquals(new StringFieldValue("ball"), docInDoc.getFieldValue("tull"));
}
@Test
public void testSerializeDeserializeCompressed() {
setUpSertestDocType();
Document doc = getSertestDocument();
CompressionConfig noncomp = new CompressionConfig();
CompressionConfig lz4comp = new CompressionConfig(CompressionType.LZ4);
doc.getDataType().getHeaderType().setCompressionConfig(lz4comp);
doc.getDataType().getBodyType().setCompressionConfig(lz4comp);
GrowableByteBuffer data = new GrowableByteBuffer();
doc.serialize(data);
int size = doc.getSerializedSize();
doc.getDataType().getHeaderType().setCompressionConfig(noncomp);
doc.getDataType().getBodyType().setCompressionConfig(noncomp);
assertEquals(size, data.position());
data.flip();
try {
FileOutputStream fos = new FileOutputStream("src/test/files/testser.dat");
fos.write(data.array(), 0, data.remaining());
fos.close();
} catch (Exception e) {
}
Document doc2 = docMan.createDocument(data);
assertEquals(doc.getFieldValue("mailid"), doc2.getFieldValue("mailid"));
assertEquals(doc.getFieldValue("date"), doc2.getFieldValue("date"));
assertEquals(doc.getFieldValue("from"), doc2.getFieldValue("from"));
assertEquals(doc.getFieldValue("to"), doc2.getFieldValue("to"));
assertEquals(doc.getFieldValue("subject"), doc2.getFieldValue("subject"));
assertEquals(doc.getFieldValue("body"), doc2.getFieldValue("body"));
assertEquals(doc.getFieldValue("attachmentcount"), doc2.getFieldValue("attachmentcount"));
assertEquals(doc.getFieldValue("attachments"), doc2.getFieldValue("attachments"));
byte[] docRawBytes = ((Raw)doc.getFieldValue("rawfield")).getByteBuffer().array();
byte[] doc2RawBytes = ((Raw)doc2.getFieldValue("rawfield")).getByteBuffer().array();
assertEquals(docRawBytes.length, doc2RawBytes.length);
for (int i = 0; i < docRawBytes.length; i++) {
assertEquals(docRawBytes[i], doc2RawBytes[i]);
}
assertEquals(doc.getFieldValue("weightedfield"), doc2.getFieldValue("weightedfield"));
assertEquals(doc.getFieldValue("mapfield"), doc2.getFieldValue("mapfield"));
// Do the same thing, splitting document in two
BufferSerializer header = new BufferSerializer(new GrowableByteBuffer());
BufferSerializer body = new BufferSerializer(new GrowableByteBuffer());
doc.serializeHeader(header);
doc.serializeBody(body);
header.getBuf().flip();
body.getBuf().flip();
try {
FileOutputStream fos = new FileOutputStream("src/test/files/testser-split.header.dat");
fos.write(header.getBuf().array(), 0, header.getBuf().remaining());
fos.close();
fos = new FileOutputStream("src/test/files/testser-split.body.dat");
fos.write(body.getBuf().array(), 0, body.getBuf().remaining());
fos.close();
} catch (Exception e) {
}
DocumentDeserializer deser = DocumentDeserializerFactory.create42(docMan, header.getBuf(), body.getBuf());
doc2 = new Document(deser);
assertEquals(doc.getFieldValue("mailid"), doc2.getFieldValue("mailid"));
assertEquals(doc.getFieldValue("date"), doc2.getFieldValue("date"));
assertEquals(doc.getFieldValue("from"), doc2.getFieldValue("from"));
assertEquals(doc.getFieldValue("to"), doc2.getFieldValue("to"));
assertEquals(doc.getFieldValue("subject"), doc2.getFieldValue("subject"));
assertEquals(doc.getFieldValue("body"), doc2.getFieldValue("body"));
assertEquals(doc.getFieldValue("attachmentcount"), doc2.getFieldValue("attachmentcount"));
assertEquals(doc.getFieldValue("attachments"), doc2.getFieldValue("attachments"));
docRawBytes = ((Raw)doc.getFieldValue("rawfield")).getByteBuffer().array();
doc2RawBytes = ((Raw)doc2.getFieldValue("rawfield")).getByteBuffer().array();
assertEquals(docRawBytes.length, doc2RawBytes.length);
for (int i = 0; i < docRawBytes.length; i++) {
assertEquals(docRawBytes[i], doc2RawBytes[i]);
}
assertEquals(doc.getFieldValue("weightedfield"), doc2.getFieldValue("weightedfield"));
assertEquals(doc.getFieldValue("mapfield"), doc2.getFieldValue("mapfield"));
}
@Test
public void testDeserialize() {
setUpSertestDocType();
BufferSerializer buf = new BufferSerializer();
try {
new Document(DocumentDeserializerFactory.create42(docMan, buf.getBuf()));
assertTrue(false);
} catch (Exception e) {
assertTrue(true);
}
buf = BufferSerializer.wrap("Hello world".getBytes());
try {
new Document(DocumentDeserializerFactory.create42(docMan, buf.getBuf()));
assertTrue(false);
} catch (Exception e) {
assertTrue(true);
}
}
@Test
public void testInheritance() {
// Create types that inherit each other.. And test that it works..
DocumentType parentType = new DocumentType("parent");
parentType.addField(new Field("parentbodyint", DataType.INT, false));
parentType.addField(new Field("parentheaderint", DataType.INT, true));
parentType.addField(new Field("overwritten", DataType.INT, true));
DocumentType childType = new DocumentType("child");
childType.addField(new Field("childbodyint", DataType.INT, false));
childType.addField(new Field("childheaderint", DataType.INT, true));
childType.addField(new Field("overwritten", DataType.INT, true));
childType.inherit(parentType);
DocumentTypeManager manager = new DocumentTypeManager();
manager.register(childType);
Document child = new Document(childType, new DocumentId("doc:what:test"));
child.setFieldValue(childType.getField("parentbodyint"), new IntegerFieldValue(4));
child.setFieldValue("parentheaderint", 6);
child.setFieldValue("overwritten", 7);
child.setFieldValue("childbodyint", 14);
GrowableByteBuffer buffer = new GrowableByteBuffer(1024, 2f);
child.serialize(buffer);
buffer.flip();
Document childCopy = manager.createDocument(buffer);
// Test various ways of retrieving values
assertEquals(new IntegerFieldValue(4), childCopy.getFieldValue(childType.getField("parentbodyint")));
assertEquals(new IntegerFieldValue(6), childCopy.getFieldValue("parentheaderint"));
assertEquals(new IntegerFieldValue(7), childCopy.getFieldValue("overwritten"));
assertEquals(child, childCopy);
}
@Test
public void testInheritanceTypeMismatch() {
DocumentType parentType = new DocumentType("parent");
parentType.addField(new Field("parentbodyint", DataType.INT, false));
parentType.addField(new Field("parentheaderint", DataType.INT, true));
parentType.addField(new Field("overwritten", DataType.STRING, true));
DocumentType childType = new DocumentType("child");
childType.addField(new Field("childbodyint", DataType.INT, false));
childType.addField(new Field("childheaderint", DataType.INT, true));
childType.addField(new Field("overwritten", DataType.INT, true));
try {
childType.inherit(parentType);
fail("Inheritance with conflicting types worked.");
} catch (IllegalArgumentException e) {
assertEquals(e.getMessage(),
"Inheritance type mismatch: field \"overwritten\" in datatype \"child\" must have same datatype as in parent document type \"parent\"");
}
}
@Test
public void testFieldValueImplementations() {
docMan = new DocumentTypeManager();
DocumentType docType = new DocumentType("impl");
docType.addField(new Field("something", DataType.getArray(DataType.STRING), false));
docMan.register(docType);
//just checks that isAssignableFrom() in Document.setFieldValue() goes the right way
Document doc = new Document(docMan.getDocumentType("impl"), new DocumentId("doc:doctest:fooooobardoc"));
Array<StringFieldValue> testlist = new Array<>(doc.getField("something").getDataType());
doc.setFieldValue("something", testlist);
}
@Test
public void testCompressionConfigured() {
int size_uncompressed;
{
DocumentTypeManager docMan = new DocumentTypeManager();
docMan.configure("file:src/tests/data/cppdocument.cfg");
Document doc = new Document(docMan.getDocumentType("serializetest"), new DocumentId("doc:test:test"));
doc.setFieldValue("stringfield",
"compress me compress me compress me compress me compress me compress me compress me compress me compress me compress me compress me compress me compress me compress me compress me compress me compress me compress me compress me compress me compress me compress me compress me compress me ");
GrowableByteBuffer data = new GrowableByteBuffer();
doc.serialize(data);
size_uncompressed = data.position();
}
DocumentTypeManager docMan = new DocumentTypeManager();
docMan.configure("file:src/tests/data/compressed.cfg");
Document doc = new Document(docMan.getDocumentType("serializetest"), new DocumentId("doc:test:test"));
doc.setFieldValue("stringfield",
"compress me compress me compress me compress me compress me compress me compress me compress me compress me compress me compress me compress me compress me compress me compress me compress me compress me compress me compress me compress me compress me compress me compress me compress me ");
GrowableByteBuffer data = new GrowableByteBuffer();
doc.serialize(data);
int size_compressed = data.position();
assertTrue(size_compressed + " < " + size_uncompressed, size_compressed < size_uncompressed);
}
@Test
public void testDocumentDataType() {
//use documenttypemanagerconfigurer to read config
docMan = new DocumentTypeManager();
DocumentTypeManagerConfigurer.configure(docMan, "file:src/test/document/docindoc.cfg");
//get a document type
docMan.getDocumentType("outerdoc");
//create document and necessary structures
Document outerdoc = new Document(docMan.getDocumentType("outerdoc"), new DocumentId("doc:recursion:outerdoc"));
Document innerdoc = new Document(docMan.getDocumentType("innerdoc"), new DocumentId("doc:recursion:innerdoc"));
innerdoc.setFieldValue("intfield", 55);
outerdoc.setFieldValue("stringfield", "boooo");
outerdoc.setFieldValue("docfield", innerdoc);
//serialize document
int size = outerdoc.getSerializedSize();
GrowableByteBuffer buf = new GrowableByteBuffer(size, 2.0f);
outerdoc.serialize(buf);
assertEquals(size, buf.position());
//deserialize document
buf.position(0);
Document outerdoc2 = docMan.createDocument(buf);
//compare values
assertEquals(outerdoc, outerdoc2);
}
@Test
public void testTimestamp() {
Document doc = new Document(docMan.getDocumentType("testdoc"), new DocumentId("doc:testdoc:timetest"));
assertNull(doc.getLastModified());
doc.setLastModified(4350129845023985L);
assertEquals(Long.valueOf(4350129845023985L), doc.getLastModified());
doc.setLastModified(null);
assertNull(doc.getLastModified());
Long timestamp = System.currentTimeMillis();
doc.setLastModified(timestamp);
assertEquals(timestamp, doc.getLastModified());
GrowableByteBuffer buf = new GrowableByteBuffer();
doc.getSerializedSize();
doc.serialize(buf);
buf.position(0);
Document doc2 = docMan.createDocument(buf);
assertNull(doc2.getLastModified());
}
@Test
public void testToXml() {
setUpSertestDocType();
Document doc = getSertestDocument();
doc.setFieldValue("mailid", "emailfromalicetobob&someone");
// Pizza Hut Sunnyvale: x="-122057174" y="37374821" latlong="N37.374821;W122.057174"
doc.setFieldValue("myposfield", PositionDataType.valueOf(-122057174, 37374821));
String xml = doc.toXML(" ");
System.out.println(xml);
assertTrue(xml.contains(SERTEST_DOC_AS_XML_HEAD));
assertTrue(xml.contains(SERTEST_DOC_AS_XML_FOOT));
assertTrue(xml.contains(SERTEST_DOC_AS_XML_WEIGHT1) || xml.contains(SERTEST_DOC_AS_XML_WEIGHT2));
assertTrue(xml.contains(SERTEST_DOC_AS_XML_SUNNYVALE));
}
@Test
public void testXmlSerializer() {
setUpSertestDocType();
Document doc = getSertestDocument();
doc.setFieldValue("mailid", "emailfromalicetobob&someone");
doc.setFieldValue("myposfield", PositionDataType.valueOf(-122057174, 37374821));
String xml = doc.toXML(" ");
XmlDocumentWriter w = XmlDocumentWriter.createWriter(" ");
w.write(doc);
String otherXml = doc.toXML(" ");
assertEquals(xml, otherXml);
}
@Test
public void testSingleFieldToXml() {
Document doc = new Document(docMan.getDocumentType("testdoc"), new DocumentId("doc:testdoc:xmltest"));
doc.setFieldValue("stringattr", new StringFieldValue("hello world"));
assertEquals("<value>hello world</value>\n", doc.getFieldValue("stringattr").toXml());
}
@Test
public void testDelegatedDocumentToXml() {
Document doc = new Document(docMan.getDocumentType("testdoc"), new DocumentId("doc:testdoc:xmltest"));
doc.setFieldValue("stringattr", new StringFieldValue("hello universe"));
// Should just delegate to toXML
assertEquals(
"<document documenttype=\"testdoc\" documentid=\"doc:testdoc:xmltest\">\n" +
" <stringattr>hello universe</stringattr>\n" +
"</document>\n",
doc.toXml());
}
@Test
public void testSerializationToJson() throws Exception {
setUpSertestDocType();
Document doc = getSertestDocument();
String json = doc.toJson();
Map<String, Object> parsed = new ObjectMapper().readValue(json, new TypeReference<Map<String, Object>>() {
});
assertEquals(parsed.get("id"), "doc:sertest:foobar");
assertThat(parsed.get("fields"), instanceOf(Map.class));
Object fieldMap = parsed.get("fields");
if (fieldMap instanceof Map) {
Map<?, ?> fields = (Map<?, ?>) fieldMap;
assertEquals(fields.get("mailid"), "emailfromalicetobob");
assertEquals(fields.get("date"), -2013512400);
assertThat(fields.get("docindoc"), instanceOf(Map.class));
assertThat(fields.keySet(),
containsInAnyOrder("mailid", "date", "attachmentcount", "rawfield", "weightedfield", "docindoc", "mapfield"));
}
}
@Test
public void testEmptyStringsSerialization() {
docMan = new DocumentTypeManager();
DocumentType docType = new DocumentType("emptystrings");
docType.addField(new Field("emptystring", DataType.STRING));
docType.addField(new Field("nullstring", DataType.STRING));
docType.addField(new Field("spacestring", DataType.STRING));
docType.addField(new Field("astring", DataType.STRING));
docMan.registerDocumentType(docType);
GrowableByteBuffer grbuf = new GrowableByteBuffer();
{
Document doc = new Document(docType, new DocumentId("doc:a:b:emptystrings"));
doc.setFieldValue("emptystring", "");
doc.removeFieldValue("nullstring");
doc.setFieldValue("spacestring", " ");
doc.setFieldValue("astring", "a");
assertEquals(new StringFieldValue(""), doc.getFieldValue("emptystring"));
assertNull(doc.getFieldValue("nullstring"));
assertEquals(new StringFieldValue(" "), doc.getFieldValue("spacestring"));
assertEquals(new StringFieldValue("a"), doc.getFieldValue("astring"));
doc.getSerializedSize();
doc.serialize(grbuf);
grbuf.flip();
}
{
Document doc2 = docMan.createDocument(grbuf);
assertEquals(new StringFieldValue(""), doc2.getFieldValue("emptystring"));
assertNull(doc2.getFieldValue("nullstring"));
assertEquals(new StringFieldValue(" "), doc2.getFieldValue("spacestring"));
assertEquals(new StringFieldValue("a"), doc2.getFieldValue("astring"));
}
}
@Test
public void testBug2354045() {
DocumentTypeManager docMan = new DocumentTypeManager();
DocumentType docType = new DocumentType("bug2354045");
docType.addField(new Field("string", DataType.STRING));
docMan.register(docType);
GrowableByteBuffer grbuf = new GrowableByteBuffer();
Document doc = new Document(docType, new DocumentId("doc:a:b:strings"));
doc.removeFieldValue("string");
assertNull(doc.getFieldValue("string"));
doc.getSerializedSize();
doc.serialize(grbuf);
grbuf.flip();
Document doc2 = docMan.createDocument(grbuf);
assertNull(doc2.getFieldValue("string"));
assertEquals(doc, doc2);
}
@Test
public void testUnknownFieldsDeserialization() {
DocumentTypeManager docTypeManasjer = new DocumentTypeManager();
GrowableByteBuffer buf = new GrowableByteBuffer();
{
DocumentType typeWithDinner = new DocumentType("elvis");
typeWithDinner.addField("breakfast", DataType.STRING);
typeWithDinner.addField("lunch", DataType.INT);
typeWithDinner.addField("dinner", DataType.DOUBLE);
docTypeManasjer.registerDocumentType(typeWithDinner);
Document docWithDinner = new Document(typeWithDinner, "doc:elvis:has:left:the:building");
docWithDinner.setFieldValue("breakfast", "peanut butter");
docWithDinner.setFieldValue("lunch", 14);
docWithDinner.setFieldValue("dinner", 5.43d);
docWithDinner.serialize(buf);
buf.flip();
docTypeManasjer.clear();
}
{
DocumentType typeWithoutDinner = new DocumentType("elvis");
typeWithoutDinner.addField("breakfast", DataType.STRING);
typeWithoutDinner.addField("lunch", DataType.INT);
//no dinner
docTypeManasjer.registerDocumentType(typeWithoutDinner);
Document docWithoutDinner = docTypeManasjer.createDocument(buf);
assertEquals(new StringFieldValue("peanut butter"), docWithoutDinner.getFieldValue("breakfast"));
assertEquals(new IntegerFieldValue(14), docWithoutDinner.getFieldValue("lunch"));
assertNull(docWithoutDinner.getFieldValue("dinner"));
}
}
@Test
public void testBug3233988() {
DocumentType type = new DocumentType("foo");
Field field = new Field("productdesc", DataType.STRING);
type.addField(field);
Document doc;
doc = new Document(type, "doc:foo:bar:bar");
doc.removeFieldValue("productdesc");
assertNull(doc.getFieldValue("productdesc"));
doc = new Document(type, "doc:foo:bar:bar");
assertNull(doc.getFieldValue("productdesc"));
}
@Test
public void testRequireThatDocumentWithIdSchemaIdChecksType() {
DocumentType docType = new DocumentType("mytype");
try {
new Document(docType, "id:namespace:mytype::foo");
} catch (Exception e) {
fail();
}
try {
new Document(docType, "id:namespace:wrong-type::foo");
fail();
} catch (IllegalArgumentException e) {
}
}
private class MyDocumentReader implements DocumentReader {
@Override
public void read(Document document) {
}
@Override
public DocumentId readDocumentId() {
return null;
}
@Override
public DocumentType readDocumentType() {
return null;
}
}
@Test
public void testRequireThatChangingDocumentTypeChecksId() {
MyDocumentReader reader = new MyDocumentReader();
Document doc = new Document(reader);
doc.setId(new DocumentId("id:namespace:mytype::foo"));
DocumentType docType = new DocumentType("mytype");
try {
doc.setDataType(docType);
} catch (Exception e) {
fail();
}
doc = new Document(reader);
doc.setId(new DocumentId("id:namespace:mytype::foo"));
DocumentType wrongType = new DocumentType("wrongtype");
try {
doc.setDataType(wrongType);
fail();
} catch (IllegalArgumentException e) {
}
}
@Test
public void testDocumentComparisonDoesNotCorruptStateBug6394548() {
DocumentTypeManager docMan = new DocumentTypeManager();
DocumentType docType = new DocumentType("bug2354045");
docType.addField(new Field("string", 2, DataType.STRING, true));
docType.addField(new Field("int", 1, DataType.INT, true));
docType.addField(new Field("float", 0, DataType.FLOAT, true));
docMan.register(docType);
Document doc1 = new Document(docType, new DocumentId("doc:a:b:bug6394548"));
doc1.setFieldValue("string", new StringFieldValue("hello world"));
doc1.setFieldValue("int", new IntegerFieldValue(1234));
doc1.setFieldValue("float", new FloatFieldValue(5.5f));
String doc1Before = doc1.toXml();
Document doc2 = new Document(docType, new DocumentId("doc:a:b:bug6394548"));
doc2.setFieldValue("string", new StringFieldValue("aardvark"));
doc2.setFieldValue("int", new IntegerFieldValue(90909));
doc2.setFieldValue("float", new FloatFieldValue(777.15f));
String doc2Before = doc2.toXml();
doc1.compareTo(doc2);
String doc1After = doc1.toXml();
String doc2After = doc2.toXml();
assertEquals(doc1Before, doc1After);
assertEquals(doc2Before, doc2After);
}
private static class DocumentIdFixture {
private final DocumentTypeManager docMan = new DocumentTypeManager();
private final DocumentType docType = new DocumentType("b");
private final GrowableByteBuffer buffer = new GrowableByteBuffer();
public DocumentIdFixture() {
docMan.register(docType);
}
public void serialize(String docId) {
new Document(docType, DocumentId.createFromSerialized(docId))
.serialize(DocumentSerializerFactory.createHead(buffer));
buffer.flip();
}
public Document deserialize() {
return new Document(DocumentDeserializerFactory.createHead(docMan, buffer));
}
}
@Test
public void testDocumentIdWithNonTextCharacterCanBeDeserialized() throws UnsupportedEncodingException {
DocumentIdFixture f = new DocumentIdFixture();
// Document id = "id:a:b::0x7c"
String docId = new String(new byte[]{105, 100, 58, 97, 58, 98, 58, 58, 7, 99}, "UTF-8");
f.serialize(docId);
Document result = f.deserialize();
assertEquals(docId, result.getId().toString());
}
}
|
package org.openhealthtools.mdht.uml.cda.ccd.operations;
import static org.junit.Assert.assertTrue;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.eclipse.emf.common.util.BasicDiagnostic;
import org.eclipse.emf.common.util.Enumerator;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.util.Diagnostician;
import org.junit.Test;
import org.openhealthtools.mdht.uml.cda.ccd.CCDFactory;
import org.openhealthtools.mdht.uml.cda.ccd.CoverageActivity;
import org.openhealthtools.mdht.uml.hl7.vocab.x_ActClassDocumentEntryAct;
import org.openhealthtools.mdht.uml.hl7.vocab.x_DocumentActMood;
/**
* This class is a JUnit4 test case.
*/
@SuppressWarnings({ "nls", "serial" })
public class CoverageActivityOperationsTest extends
StructuralAttributeValidationTest {
protected static final String COVERAGE_ACTIVITY_TEMPLATE_ID = "2.16.840.1.113883.10.20.1.20";
protected static final HashMap<String, Enumerator> VALID_STRUCTURAL_ATTRIBUTE_NAME_VALUE_MAP = new HashMap<String, Enumerator>() {
{
put(CLASS_CODE_ATTRIBUTE_NAME, x_ActClassDocumentEntryAct.ACT);
put(MOOD_CODE_ATTRIBUTE_NAME, x_DocumentActMood.DEF);
}
};
protected static final String STATUS_CODE = "completed";
protected static final String STATUS_CODE_CODE_SYSTEM = "2.16.840.1.113883.5.14";
private static final CDATestCase TEST_CASE_ARRAY[] = {
// Template ID
new TemplateIDValidationTest(COVERAGE_ACTIVITY_TEMPLATE_ID) {
@Override
protected boolean validate(final EObject objectToTest,
final BasicDiagnostic diagnostician,
final Map<Object, Object> map) {
return CoverageActivityOperations
.validateCoverageActivityTemplateId(
(CoverageActivity) objectToTest,
diagnostician, map);
}
},
new IDCCDValidationTest() {
@Override
protected boolean validate(final EObject objectToTest,
final BasicDiagnostic diagnostician,
final Map<Object, Object> map) {
return CoverageActivityOperations
.validateCoverageActivityId(
(CoverageActivity) objectToTest,
diagnostician, map);
}
},
// Status Code
new StatusCodeCCDValidationTest(STATUS_CODE,
STATUS_CODE_CODE_SYSTEM) {
@Override
protected boolean validate(final EObject objectToTest,
final BasicDiagnostic diagnostician,
final Map<Object, Object> map) {
return CoverageActivityOperations
.validateCoverageActivityStatusCode(
(CoverageActivity) objectToTest,
diagnostician, map);
}
}
}; // TEST_CASE_ARRAY
@Override
protected List<CDATestCase> getTestCases() {
// Return a new List because the one returned by Arrays.asList is
// unmodifiable so a sub-class can't append their test cases.
final List<CDATestCase> retValue = super.getTestCases();
retValue.addAll(Arrays.asList(TEST_CASE_ARRAY));
return retValue;
}
@Override
protected EObject getObjectToTest() {
return CCDFactory.eINSTANCE.createCoverageActivity();
}
@Override
protected EObject getObjectInitToTest() {
return CCDFactory.eINSTANCE.createCoverageActivity().init();
}
@Override
protected Enumerator doGetValidStructuralAttributeValue(
final String structuralAttributeName) {
return VALID_STRUCTURAL_ATTRIBUTE_NAME_VALUE_MAP
.get(structuralAttributeName);
}
@Override
protected boolean doValidateStructuralAttributeValues(
final EObject eObjectToValidate,
final BasicDiagnostic diagnostician, final Map<Object, Object> map) {
return CoverageActivityOperations.validateCoverageActivityClassCode(
(CoverageActivity) eObjectToValidate, diagnostician, map)
&& CoverageActivityOperations.validateCoverageActivityMoodCode(
(CoverageActivity) eObjectToValidate, diagnostician,
map);
}
@Test
public void testValidateCoverageActivitySequenceNumber() {
// This is not fully implemented.
final CoverageActivity ca = (CoverageActivity) getObjectToTest();
final BasicDiagnostic diagnostician = Diagnostician.INSTANCE
.createDefaultDiagnostic(ca);
boolean isValid = CoverageActivityOperations
.validateCoverageActivitySequenceNumber(ca, diagnostician, map);
assertTrue(createAssertionFailureMessage(diagnostician), !isValid);
}
@Test
public void testValidateCoverageActivityPolicyActivity() {
// This is not fully implemented.
final CoverageActivity ca = (CoverageActivity) getObjectToTest();
final BasicDiagnostic diagnostician = Diagnostician.INSTANCE
.createDefaultDiagnostic(ca);
boolean isValid = CoverageActivityOperations
.validateCoverageActivityPolicyActivity(ca, diagnostician, map);
assertTrue(createAssertionFailureMessage(diagnostician), !isValid);
}
@Test
public void testValidateCoverageActivityInformationSource() {
// This is not fully implemented.
final CoverageActivity ca = (CoverageActivity) getObjectToTest();
final BasicDiagnostic diagnostician = Diagnostician.INSTANCE
.createDefaultDiagnostic(ca);
boolean isValid = CoverageActivityOperations
.validateCoverageActivityInformationSource(ca, diagnostician,
map);
assertTrue(createAssertionFailureMessage(diagnostician), !isValid);
}
@Test
public void testValidateCoverageActivityCode() {
// This is not fully implemented.
final CoverageActivity ca = (CoverageActivity) getObjectToTest();
final BasicDiagnostic diagnostician = Diagnostician.INSTANCE
.createDefaultDiagnostic(ca);
boolean isValid = CoverageActivityOperations
.validateCoverageActivityCode(ca, diagnostician, map);
assertTrue(createAssertionFailureMessage(diagnostician), !isValid);
}
} // CoverageActivityOperationsTest
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.