answer
stringlengths
17
10.2M
package io.javalin; import org.apache.velocity.app.VelocityEngine; import org.junit.BeforeClass; import org.junit.Test; import io.javalin.translator.json.Jackson; import io.javalin.translator.template.TemplateUtil; import io.javalin.translator.template.Velocity; import io.javalin.util.CustomMapper; import io.javalin.util.TestObject_NonSerializable; import io.javalin.util.TestObject_Serializable; import com.mashape.unirest.http.HttpMethod; import com.mashape.unirest.http.HttpResponse; import com.mashape.unirest.http.Unirest; import static org.hamcrest.MatcherAssert.*; import static org.hamcrest.Matchers.*; public class TestTranslators extends _UnirestBaseTest { @BeforeClass public static void setObjectMapper() { Jackson.INSTANCE.configure(new CustomMapper()); } @Test public void test_json_jacksonMapsObjectToJson() throws Exception { app.get("/hello", ctx -> ctx.status(200).json(new TestObject_Serializable())); String expected = new CustomMapper().writeValueAsString(new TestObject_Serializable()); assertThat(GET_body("/hello"), is(expected)); } @Test public void test_json_jacksonMapsStringsToJson() throws Exception { app.get("/hello", ctx -> ctx.status(200).json("\"ok\"")); assertThat(GET_body("/hello"), is("\"\\\"ok\\\"\"")); } @Test public void test_json_customMapper_works() throws Exception { app.get("/hello", ctx -> ctx.status(200).json(new TestObject_Serializable())); assertThat(GET_body("/hello").split("\r\n|\r|\n").length, is(4)); } @Test public void test_json_jackson_throwsForBadObject() throws Exception { app.get("/hello", ctx -> ctx.status(200).json(new TestObject_NonSerializable())); HttpResponse<String> response = call(HttpMethod.GET, "/hello"); assertThat(response.getStatus(), is(500)); assertThat(response.getBody(), is("Internal server error")); } @Test public void test_json_jacksonMapsJsonToObject() throws Exception { app.post("/hello", ctx -> { Object o = ctx.bodyAsClass(TestObject_Serializable.class); if (o instanceof TestObject_Serializable) { ctx.result("success"); } }); HttpResponse<String> response = Unirest.post(origin + "/hello").body(new CustomMapper().writeValueAsString(new TestObject_Serializable())).asString(); assertThat(response.getBody(), is("success")); } @Test public void test_json_jacksonMapsJsonToObject_throwsForBadObject() throws Exception { app.get("/hello", ctx -> ctx.json(ctx.bodyAsClass(TestObject_NonSerializable.class).getClass().getSimpleName())); HttpResponse<String> response = call(HttpMethod.GET, "/hello"); assertThat(response.getStatus(), is(500)); assertThat(response.getBody(), is("Internal server error")); } @Test public void test_renderVelocity_works() throws Exception { app.get("/hello", ctx -> ctx.renderVelocity("/templates/velocity/test.vm", TemplateUtil.INSTANCE.model("message", "Hello Velocity!"))); assertThat(GET_body("/hello"), is("<h1>Hello Velocity!</h1>")); } @Test public void test_customVelocityEngine_works() throws Exception { app.get("/hello", ctx -> ctx.renderVelocity("/templates/velocity/test.vm", TemplateUtil.INSTANCE.model())); assertThat(GET_body("/hello"), is("<h1>$message</h1>")); Velocity.INSTANCE.configure(strictVelocityEngine()); assertThat(GET_body("/hello"), is("Internal server error")); } private static VelocityEngine strictVelocityEngine() { VelocityEngine strictEngine = new VelocityEngine(); strictEngine.setProperty("runtime.references.strict", true); strictEngine.setProperty("resource.loader", "class"); strictEngine.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); return strictEngine; } @Test public void test_renderFreemarker_works() throws Exception { app.get("/hello", ctx -> ctx.renderFreemarker("/templates/freemarker/test.ftl", TemplateUtil.INSTANCE.model("message", "Hello Freemarker!"))); assertThat(GET_body("/hello"), is("<h1>Hello Freemarker!</h1>")); } @Test public void test_renderThymeleaf_works() throws Exception { app.get("/hello", ctx -> ctx.renderThymeleaf("/templates/thymeleaf/test.html", TemplateUtil.INSTANCE.model("message", "Hello Thymeleaf!"))); assertThat(GET_body("/hello"), is("<h1>Hello Thymeleaf!</h1>")); } @Test public void test_renderMustache_works() throws Exception { app.get("/hello", ctx -> ctx.renderMustache("/templates/mustache/test.mustache", TemplateUtil.INSTANCE.model("message", "Hello Mustache!"))); assertThat(GET_body("/hello"), is("<h1>Hello Mustache!</h1>")); } }
package test.java.latexee.docast; import java.util.ArrayList; import java.util.Arrays; import main.java.latexee.declareast.DeclareNode; import main.java.latexee.docast.DeclareStatement; import main.java.latexee.docast.FormulaStatement; import main.java.latexee.docast.IncludeStatement; import main.java.latexee.docast.LemmaStatement; import main.java.latexee.docast.ParsedStatement; import main.java.latexee.docast.ProofStatement; import main.java.latexee.docast.TheoremStatement; import main.java.latexee.utils.DeclarationParser; import main.java.latexee.utils.DocumentParser; import main.java.latexee.utils.GrammarGenerator; import org.junit.Test; import fr.inria.openmath.omapi.TreePrinter; import fr.inria.openmath.omapi.implementation.TreePrinterImpl; import static org.junit.Assert.*; public class GrammarTest { @Test public void Parsing1Test(){ DeclareNode.identifier = 0; ParsedStatement tree = DocumentParser.parse("src/test/antlr/parsing1.tex"); DeclarationParser.declarationFinder(tree); ArrayList<DeclareNode> nodes = GrammarGenerator.getDeclareNodes(tree, new ArrayList<DeclareNode>()); String generatedGrammar = GrammarGenerator.createGrammar(nodes); generatedGrammar = generatedGrammar.replaceAll(" ", ""); generatedGrammar = generatedGrammar.replaceAll("\n", ""); String grammar = "grammarRuntimeGrammar;"+ "highestLevel:highestNumber#DEFAULT0;"+ "highestNumber:level100#DEFAULT1;" + "level100:level100level101#INVISIBLETIMES" + "|level101#DEFAULT2;" + "level101:lowestLevel#DEFAULT3;" + "lowestLevel:'{'highestLevel'}'#BRACES" + "|'('highestLevel')'#PARENS" + "|LEXERRULE#DEFAULT4;" + "LEXERRULE:[0-9]+|[a-z];"; grammar = grammar.replaceAll(" ", ""); grammar = grammar.replaceAll("\n", ""); assertTrue(generatedGrammar.equals(grammar)); } @Test public void Parsing8Test(){ DeclareNode.identifier = 0; ParsedStatement tree = DocumentParser.parse("src/test/antlr/parsing8.tex"); DeclarationParser.declarationFinder(tree); ArrayList<DeclareNode> nodes = GrammarGenerator.getDeclareNodes(tree, new ArrayList<DeclareNode>()); String generatedGrammar = GrammarGenerator.createGrammar(nodes); generatedGrammar = generatedGrammar.replaceAll(" ", ""); generatedGrammar = generatedGrammar.replaceAll("\n", ""); String grammar = "grammarRuntimeGrammar;" + "highestLevel : highestNumber #DEFAULT0;" + "highestNumber : level7 #DEFAULT1;" + "level7 : level7'/'level100 #Op0" + "|level7'/'level100 #Op1" + "|level100 #DEFAULT2;" + "level100 : level100 level101 #INVISIBLETIMES" + "|level101 #DEFAULT3;" + "level101 : lowestLevel #DEFAULT4;" + "lowestLevel:'{'highestLevel'}'#BRACES" + "|'('highestLevel')'#PARENS" + "|LEXERRULE #DEFAULT5;" + "LEXERRULE : [0-9]+|[a-z];"; grammar = grammar.replaceAll(" ", ""); grammar = grammar.replaceAll("\n", ""); assertTrue(generatedGrammar.equals(grammar)); } @Test public void Parsing9Test(){ DeclareNode.identifier = 0; ParsedStatement tree = DocumentParser.parse("src/test/antlr/parsing9.tex"); DeclarationParser.declarationFinder(tree); ArrayList<DeclareNode> nodes = GrammarGenerator.getDeclareNodes(tree, new ArrayList<DeclareNode>()); String generatedGrammar = GrammarGenerator.createGrammar(nodes); generatedGrammar = generatedGrammar.replaceAll(" ", ""); generatedGrammar = generatedGrammar.replaceAll("\n", ""); String grammar = "grammarRuntimeGrammar;" + "highestLevel : highestNumber #DEFAULT0;" + "highestNumber : level100 #DEFAULT1;" + "level100 : level100 level101 #INVISIBLETIMES" + "|level101 #DEFAULT2;" + "level101 : lowestLevel #DEFAULT3;" + "lowestLevel:'{'highestLevel'}'#BRACES" + "|'('highestLevel')'#PARENS" + "|LEXERRULE #DEFAULT4;" + "LEXERRULE : [0-9]+|[a-z];"; grammar = grammar.replaceAll(" ", ""); grammar = grammar.replaceAll("\n", ""); assertTrue(generatedGrammar.equals(grammar)); } @Test public void BasicWithAllDeclaresTest(){ DeclareNode.identifier = 0; ParsedStatement tree = DocumentParser.parse("src/test/antlr/basic_with_all_declares.tex"); DeclarationParser.declarationFinder(tree); ArrayList<DeclareNode> nodes = GrammarGenerator.getDeclareNodes(tree, new ArrayList<DeclareNode>()); String generatedGrammar = GrammarGenerator.createGrammar(nodes); generatedGrammar = generatedGrammar.replaceAll(" ", ""); generatedGrammar = generatedGrammar.replaceAll("\n", ""); String grammar = "grammarRuntimeGrammar;" + "highestLevel : highestNumber #DEFAULT0;" + "highestNumber : level5 #DEFAULT1;" + "level5 : level5'+'level7 #Op1" + "|level5'-'level7 #Op2" + "|level7 #DEFAULT2;" + "level7:level7'/'level100 #Op0" + "|level7'*'level100 #Op3" + "|level100 #DEFAULT3;" + "level100:level100 level101 #INVISIBLETIMES" + "|level101 #DEFAULT4;" + "level101 : lowestLevel #DEFAULT5;" + "lowestLevel:'{'highestLevel'}'#BRACES" + "|'('highestLevel')'#PARENS" + "|'\\\\gcd''{'highestLevel'}''{'highestLevel'}' #MACRO4" + "|LEXERRULE#DEFAULT6;" + "LEXERRULE:[0-9]+|[a-z];"; grammar = grammar.replaceAll(" ", ""); grammar = grammar.replaceAll("\n", ""); assertTrue(generatedGrammar.equals(grammar)); } @Test public void BasicWithNonsemanticTest(){ DeclareNode.identifier = 0; ParsedStatement tree = DocumentParser.parse("src/test/antlr/basic_with_nonsemantic.tex"); DeclarationParser.declarationFinder(tree); ArrayList<DeclareNode> nodes = GrammarGenerator.getDeclareNodes(tree, new ArrayList<DeclareNode>()); String generatedGrammar = GrammarGenerator.createGrammar(nodes); generatedGrammar = generatedGrammar.replaceAll(" ", ""); generatedGrammar = generatedGrammar.replaceAll("\n", ""); String grammar = "grammarRuntimeGrammar;" + "highestLevel : highestNumber #DEFAULT0;" + "highestNumber : level99 #DEFAULT1;" + "level99 : level99'+'level100 #Op0" + "|level99'-'level100 #Op2" + "|level100 #DEFAULT2;" + "level100 : level100 level101 #INVISIBLETIMES" + "|level100'/'level101 #Op1" + "|level100'*'level10 1#Op3" + "|level101 #DEFAULT3" + ";level101 : lowestLevel #DEFAULT4;" + "lowestLevel:'{'highestLevel'}'#BRACES" + "|'('highestLevel')'#PARENS" + "|'\\\\gcd''{'highestLevel'}''{'highestLevel'}' #MACRO4" + "|'\\\\gcd2''{'highestLevel'}''{'highestLevel'}' #MACRO5" + "|LEXERRULE #DEFAULT5;" + "LEXERRULE:[0-9]+|[a-z];"; grammar = grammar.replaceAll(" ", ""); grammar = grammar.replaceAll("\n", ""); assertTrue(generatedGrammar.equals(grammar)); } @Test public void BasicWithScopingTest(){ DeclareNode.identifier = 0; ParsedStatement tree = DocumentParser.parse("src/test/antlr/basic_with_scoping.tex"); DeclarationParser.declarationFinder(tree); ArrayList<DeclareNode> nodes = GrammarGenerator.getDeclareNodes(tree, new ArrayList<DeclareNode>()); String generatedGrammar = GrammarGenerator.createGrammar(nodes); generatedGrammar = generatedGrammar.replaceAll(" ", ""); generatedGrammar = generatedGrammar.replaceAll("\n", ""); String grammar = "grammarRuntimeGrammar;" + "highestLevel : highestNumber #DEFAULT0;" + "highestNumber : level5 #DEFAULT1;" + "level5 : level5'+'level7 #Op0" + "|level5'-'level7 #Op2" + "|level7 #DEFAULT2;" + "level7 : level7'/'level100 #Op1" + "|level7'*'level100 #Op3" + "|level100 #DEFAULT3;" + "level100 : level100 level101 #INVISIBLETIMES" + "|level101 #DEFAULT4;" + "level101 : lowestLevel #DEFAULT5;" + "lowestLevel:'{'highestLevel'}'#BRACES" + "|'('highestLevel')'#PARENS" + "|'\\\\gcd''{'highestLevel'}''{'highestLevel'}' #MACRO4" + "|'\\\\gcd2''{'highestLevel'}''{'highestLevel'}' #MACRO5" + "|LEXERRULE#DEFAULT6;" + "LEXERRULE:[0-9]+|[a-z];"; grammar = grammar.replaceAll(" ", ""); grammar = grammar.replaceAll("\n", ""); assertTrue(generatedGrammar.equals(grammar)); } @Test public void GrammarGeneratorTest(){ DeclareNode.identifier = 0; ParsedStatement tree = DocumentParser.parse("src/test/antlr/grammar_generator.tex"); DeclarationParser.declarationFinder(tree); ArrayList<DeclareNode> nodes = GrammarGenerator.getDeclareNodes(tree, new ArrayList<DeclareNode>()); String generatedGrammar = GrammarGenerator.createGrammar(nodes); System.out.println(generatedGrammar); generatedGrammar = generatedGrammar.replaceAll(" ", ""); generatedGrammar = generatedGrammar.replaceAll("\n", ""); String grammar = "grammarRuntimeGrammar;" + "highestLevel : highestNumber #DEFAULT0;" + "highestNumber : level7 #DEFAULT1;" + "level7 : level7'*'level100 #Op3" + "|level100 #DEFAULT2;" + "level100 : level100 level101 #INVISIBLETIMES" + "|level100'+'level101 #Op0" + "|level100'-'level101 #Op2" + "|level101 #DEFAULT3;" + "level101 : level101'/'level102 #Op1" + "|level102 #DEFAULT4;" + "level102 : lowestLevel #DEFAULT5;" + "lowestLevel:'{'highestLevel'}'#BRACES" + "|'('highestLevel')'#PARENS" + "|'\\\\gcd''{'highestLevel'}''{'highestLevel'}' #MACRO4" + "|'\\\\gcd2''{'highestLevel'}''{'highestLevel'}' #MACRO5" + "|LEXERRULE #DEFAULT6;" + "LEXERRULE:[0-9]+|[a-z];"; grammar = grammar.replaceAll(" ", ""); grammar = grammar.replaceAll("\n", ""); assertTrue(generatedGrammar.equals(grammar)); } }
package net.sf.jabref; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.TreeMap; import net.sf.jabref.logic.exporter.MetaDataSerializer; import net.sf.jabref.logic.formatter.casechanger.LowerCaseFormatter; import net.sf.jabref.logic.util.OS; import net.sf.jabref.model.bibtexkeypattern.AbstractBibtexKeyPattern; import net.sf.jabref.model.bibtexkeypattern.GlobalBibtexKeyPattern; import net.sf.jabref.model.cleanup.FieldFormatterCleanup; import net.sf.jabref.model.cleanup.FieldFormatterCleanups; import net.sf.jabref.model.metadata.ContentSelector; import net.sf.jabref.model.metadata.MetaData; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; public class MetaDataTest { private MetaData metaData; private GlobalBibtexKeyPattern pattern; @Before public void setUp() { metaData = new MetaData(); pattern = new GlobalBibtexKeyPattern(AbstractBibtexKeyPattern.split("[auth][year]")); } @Test public void serializeNewMetadataReturnsEmptyMap() throws Exception { assertEquals(Collections.emptyMap(), MetaDataSerializer.getSerializedStringMap(metaData, pattern)); } @Test public void serializeSingleSaveAction() { FieldFormatterCleanups saveActions = new FieldFormatterCleanups(true, Collections.singletonList(new FieldFormatterCleanup("title", new LowerCaseFormatter()))); metaData.setSaveActions(saveActions); Map<String, String> expectedSerialization = new TreeMap<>(); expectedSerialization.put("saveActions", "enabled;" + OS.NEWLINE + "title[lower_case]" + OS.NEWLINE + ";"); assertEquals(expectedSerialization, MetaDataSerializer.getSerializedStringMap(metaData, pattern)); } @Test public void serializeSingleContentSelectors() { List<String> values = new ArrayList(4); values.add("approved"); values.add("captured"); values.add("received"); values.add("status"); metaData.addContentSelector(new ContentSelector("status", values)); Map<String, String> expectedSerialization = new TreeMap<>(); expectedSerialization.put(MetaData.SELECTOR_META_PREFIX + "status", "approved;captured;received;status;"); assertEquals(expectedSerialization, MetaDataSerializer.getSerializedStringMap(metaData, pattern)); } @Test public void emptyGroupsIfNotSet() { assertEquals(Optional.empty(), metaData.getGroups()); } }
package com.xpn.xwiki.test; import org.xwiki.component.manager.ComponentManager; import org.xwiki.plexus.manager.PlexusComponentManager; import org.xwiki.context.Execution; import org.xwiki.context.ExecutionContext; import org.xwiki.context.ExecutionContextManager; import org.codehaus.plexus.DefaultContainerConfiguration; import org.codehaus.plexus.DefaultPlexusContainer; public class XWikiComponentInitializer { private ComponentManager componentManager; public void initialize() throws Exception { // Initialize the Execution Context ExecutionContextManager ecm = (ExecutionContextManager) getComponentManager().lookup(ExecutionContextManager.ROLE); Execution execution = (Execution) getComponentManager().lookup(Execution.ROLE); ExecutionContext ec = new ExecutionContext(); // Make sure we push this empty context in the Execution component before we call the initialization // so that we don't get any NPE if some initializer code asks to get the Execution Context. This // happens for example with the Velocity Execution Context initializer which in turns calls the Velocity // Context initializers and some of them look inside the Execution Context. execution.setContext(ec); ecm.initialize(ec); } public void shutdown() throws Exception { Execution execution = (Execution) getComponentManager().lookup(Execution.ROLE); execution.removeContext(); // Make sure we mark the component manager for garbage collection as otherwise each JUnit test will // have an instance of the Component Manager (will all the components it's holding), leading to // out of memory errors when there are lots of tests... this.componentManager = null; } /** * @return a configured Component Manager (which uses the plexus.xml file in the test resources directory) * which can then be put in the XWiki Context for testing. */ public ComponentManager getComponentManager() throws Exception { if (this.componentManager == null) { DefaultContainerConfiguration configuration = new DefaultContainerConfiguration(); configuration.setContainerConfiguration("/plexus.xml"); DefaultPlexusContainer container = new DefaultPlexusContainer(configuration); this.componentManager = new PlexusComponentManager(container); } return this.componentManager; } }
// M a i n // // <editor-fold defaultstate="collapsed" desc="hdr"> // This program is free software: you can redistribute it and/or modify it under the terms of the // </editor-fold> package org.audiveris.omr; import org.audiveris.omr.CLI.CliTask; import org.audiveris.omr.classifier.SampleRepository; import org.audiveris.omr.constant.Constant; import org.audiveris.omr.constant.ConstantManager; import org.audiveris.omr.constant.ConstantSet; import org.audiveris.omr.log.LogUtil; import org.audiveris.omr.sheet.BookManager; import org.audiveris.omr.text.tesseract.TesseractOCR; import org.audiveris.omr.ui.MainGui; import org.audiveris.omr.ui.symbol.MusicFont; import org.audiveris.omr.util.OmrExecutors; import org.jdesktop.application.Application; import org.kohsuke.args4j.CmdLineException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.List; import java.util.Locale; import java.util.concurrent.Callable; import java.util.concurrent.Future; public class Main { static { // We need class WellKnowns to be elaborated before anything else WellKnowns.ensureLoaded(); } private static final Logger logger = LoggerFactory.getLogger(Main.class); private static final Constants constants = new Constants(); /** CLI parameters. */ private static CLI cli; private Main () { } // getCli // /** * Points to the command line interface parameters * * @return CLI instance */ public static CLI getCli () { return cli; } // getSheetStepTimeOut // /** * Report the timeout value for any step on a sheet. * * @return the timeout value (in seconds) */ public static int getSheetStepTimeOut () { return constants.sheetStepTimeOut.getValue(); } // main // /** * Specific starting method for the application. * * @param args command line parameters * @see org.audiveris.omr.CLI the possible command line parameters */ public static void main (String[] args) { // Process CLI parameters processCli(args); // Initialize tool parameters initialize(); // Locale to be used in the whole application? checkLocale(); // Environment showEnvironment(); // Native libs //loadNativeLibraries(); // Engine OMR.engine = BookManager.getInstance(); if (!cli.isBatchMode()) { // Here we are in interactive mode logger.debug("Main. Launching MainGui"); Application.launch(MainGui.class, args); } else { // Here we are in batch mode // Check MusicFont is loaded MusicFont.checkMusicFont(); // Run the required tasks, if any (and remember if at least one task failed) boolean failure = runBatchTasks(); // At this point all tasks have completed (except timeout...) // So shutdown gracefully the executors boolean timeout = !OmrExecutors.shutdown(); // Save global sample repository if modified if (SampleRepository.hasInstance()) { SampleRepository repository = SampleRepository.getGlobalInstance(false); if (repository.isModified()) { repository.storeRepository(); } } // Store latest constant values on disk? if (constants.persistBatchCliConstants.getValue()) { ConstantManager.getInstance().storeResource(); } // Force JVM exit? if (failure || timeout) { String msg = "Exit forced."; int status = 0; if (failure) { status -= 1; msg += " Failure"; } if (timeout) { status -= 2; msg += " Timeout"; } logger.warn(msg); System.exit(status); } } } // processSystemsInParallel // public static boolean processSystemsInParallel () { return constants.processSystemsInParallel.isSet(); } // saveSheetOnEveryStep // public static boolean saveSheetOnEveryStep () { return constants.saveSheetOnEveryStep.isSet(); } // checkLocale // private static void checkLocale () { final String localeStr = constants.locale.getValue().trim(); if (!localeStr.isEmpty()) { for (Locale locale : Locale.getAvailableLocales()) { if (locale.toString().equalsIgnoreCase(localeStr)) { Locale.setDefault(locale); logger.debug("Locale set to {}", locale); return; } } logger.warn("Cannot set locale to {}", localeStr); } } // initialize // private static void initialize () { // (re) Open the executor services OmrExecutors.restart(); } // logTasks // private static void logTasks (List<CliTask> tasks, boolean inParallel) { StringBuilder sb = new StringBuilder(); sb.append("Submitting ").append(tasks.size()).append(" task(s) in "); sb.append(inParallel ? "parallel:" : "sequence:"); for (Callable task : tasks) { sb.append("\n ").append(task); } logger.info(sb.toString()); } // processCli // private static void processCli (String[] args) { try { // First get the provided parameters if any cli = new CLI(WellKnowns.TOOL_NAME); cli.getParameters(args); // Interactive or Batch mode ? if (cli.isBatchMode()) { logger.info("Running in batch mode"); ///System.setProperty("java.awt.headless", "true"); //TODO: Useful? } else { logger.debug("Running in interactive mode"); LogUtil.addGuiAppender(); } } catch (CmdLineException ex) { logger.warn("Error in command line: {}", ex.getLocalizedMessage(), ex); logger.warn("Exiting ..."); // Stop the JVM, with failure status (1) Runtime.getRuntime().exit(1); } } // runBatchTasks // private static boolean runBatchTasks () { boolean failure = false; final List<CliTask> tasks = cli.getCliTasks(); if (!tasks.isEmpty()) { // Run all tasks in parallel? (or one task at a time) if (constants.runBatchTasksInParallel.isSet()) { try { logTasks(tasks, true); List<Future<Void>> futures = OmrExecutors.getCachedLowExecutor().invokeAll( tasks); logger.info("Checking {} task(s)", tasks.size()); // Check for time-out for (Future<Void> future : futures) { try { future.get(); } catch (Exception ex) { CliTask task = tasks.get(futures.indexOf(future)); final String radix = task.getRadix(); logger.warn("Future exception on {}, {}", radix, ex.toString(), ex); failure = true; } } } catch (Exception ex) { logger.warn("Error in processing tasks", ex); failure = true; } } else { logTasks(tasks, false); for (CliTask task : tasks) { try { task.call(); } catch (Exception ex) { final String radix = task.getRadix(); logger.warn("Exception on {}, {}", radix, ex.toString(), ex); failure = true; } } } } return failure; } // showEnvironment // /** * Show the application environment to the user. */ private static void showEnvironment () { if (constants.showEnvironment.isSet()) { logger.info( "Environment:\n" + "- Audiveris: {}\n" + "- OS: {}\n" + "- Architecture: {}\n" + "- Java VM: {}\n" + "- OCR Engine: {}", WellKnowns.TOOL_REF + ":" + WellKnowns.TOOL_BUILD, System.getProperty("os.name") + " " + System.getProperty("os.version"), System.getProperty("os.arch"), System.getProperty("java.vm.name") + " (build " + System.getProperty("java.vm.version") + ", " + System.getProperty("java.vm.info") + ")", TesseractOCR.getInstance().identify()); } } // Constants // private static final class Constants extends ConstantSet { private final Constant.Boolean showEnvironment = new Constant.Boolean( true, "Should we show environment?"); private final Constant.Boolean showNatives = new Constant.Boolean( true, "Should we show loading of native libraries?"); private final Constant.String locale = new Constant.String( "en", "Locale language to be used in the whole application (en, fr)"); private final Constant.Boolean persistBatchCliConstants = new Constant.Boolean( false, "Should we persist CLI-defined constants when running in batch?"); private final Constant.Boolean runBatchTasksInParallel = new Constant.Boolean( false, "Should we process all tasks in parallel when running in batch?"); private final Constant.Boolean processSystemsInParallel = new Constant.Boolean( false, "Should we process all systems in parallel in a sheet?"); private final Constant.Boolean saveSheetOnEveryStep = new Constant.Boolean( true, "Should we save sheet after every successful step?"); private final Constant.Integer sheetStepTimeOut = new Constant.Integer( "Seconds", 120, "Time-out for one step on a sheet, specified in seconds"); private final Constant.Boolean closeBookOnEnd = new Constant.Boolean( true, "Should we close a book when it has been processed in batch?"); } }
package ch.puzzle.itc.mobiliar.business.property.entity; import ch.puzzle.itc.mobiliar.business.database.control.Constants; import ch.puzzle.itc.mobiliar.business.foreignable.entity.Foreignable; import ch.puzzle.itc.mobiliar.business.foreignable.entity.ForeignableOwner; import ch.puzzle.itc.mobiliar.business.resourcegroup.control.CopyUnit; import ch.puzzle.itc.mobiliar.business.utils.Auditable; import ch.puzzle.itc.mobiliar.business.utils.CopyHelper; import ch.puzzle.itc.mobiliar.business.utils.Copyable; import ch.puzzle.itc.mobiliar.business.utils.Identifiable; import lombok.Getter; import lombok.Setter; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.builder.HashCodeBuilder; import org.hibernate.envers.Audited; import javax.persistence.*; import java.io.Serializable; import java.util.*; import static javax.persistence.CascadeType.ALL; import static javax.persistence.CascadeType.PERSIST; /** * Entity implementation class for Entity: PropertyDescriptor */ @Entity @Audited @Table(name = "TAMW_propertyDescriptor") public class PropertyDescriptorEntity implements Identifiable, Serializable, PropertyTagEntityHolder, Foreignable<PropertyDescriptorEntity>, Copyable<PropertyDescriptorEntity>, Auditable { // IMPORTANT! Whenever a new field (not relation to other entity) is added then this field must be added to foreignableFieldEquals method!!! @Getter @Setter @TableGenerator(name = "propertyDescriptorIdGen", table = Constants.GENERATORTABLE, pkColumnName = Constants.GENERATORPKCOLUMNNAME, valueColumnName = Constants.GENERATORVALUECOLUMNNAME, pkColumnValue = "propertyDescriptorId") @GeneratedValue(strategy = GenerationType.TABLE, generator = "propertyDescriptorIdGen") @Id @Column(unique = true, nullable = false) private Integer id; @Setter @Getter @Column(nullable = false) private boolean encrypt; /** * The propertyName represents the technical Key TODO: rename */ @Getter @Column private String propertyName; @Setter @Getter @Column(nullable = false) // TODO: Rename to valueOptional private boolean nullable; @Getter @Setter @Column(nullable = false) private boolean testing; @Setter private String validationLogic; @Getter @Setter @Column(length = 65536) @Lob private String propertyComment; @Getter @Setter private Integer cardinalityProperty; @Getter @Setter @ManyToOne private PropertyTypeEntity propertyTypeEntity; public Set<PropertyEntity> getProperties() { if (properties == null){ properties = new HashSet<>(); } return properties; } @Setter @OneToMany(mappedBy = "descriptor", cascade = ALL, orphanRemoval = true) private Set<PropertyEntity> properties; @Getter @Version private long v; @Getter @Lob private String defaultValue; @Getter @Lob private String exampleValue; @Getter @Setter private String machineInterpretationKey; @Getter @Setter // TODO: Rename to keyOptional private boolean optional; @Setter @ManyToMany(cascade = PERSIST) @JoinTable( name = "TAMW_propDesc_propTag", joinColumns = { @JoinColumn(name = "PROPERTYDESCRIPTOR_ID", referencedColumnName = "ID") }, inverseJoinColumns = { @JoinColumn(name = "PROPERTYTAG_ID", referencedColumnName = "ID") }) private List<PropertyTagEntity> propertyTags; @Getter @Setter private String displayName; private static final long serialVersionUID = 1L; @Enumerated(EnumType.STRING) private ForeignableOwner fcOwner; private String fcExternalKey; private String fcExternalLink; /** * Creates new entity object with default system owner */ public PropertyDescriptorEntity() { this(ForeignableOwner.getSystemOwner()); } public PropertyDescriptorEntity(ForeignableOwner owner) { this.fcOwner = Objects.requireNonNull(owner, "Owner must not be null"); } public List<PropertyTagEntity> getPropertyTags() { return propertyTags == null ? new ArrayList<PropertyTagEntity>() : propertyTags; } @Override public Set<String> getPropertyTagsNameSet() { Set<String> tagNames = new HashSet<>(); for (PropertyTagEntity propertyTagEntity : getPropertyTags()) { tagNames.add(propertyTagEntity.getName()); } return tagNames; } public void removeProperty(PropertyEntity p) { if (properties != null) { properties.remove(p); } } public void setPropertyName(String propertyName) { if (propertyName != null) { this.propertyName = propertyName.trim(); } } public void addProperty(PropertyEntity property) { if (properties == null) { properties = new HashSet<>(); } properties.add(property); } public void setDefaultValue(String value) { if (value != null) { defaultValue = removeLineBreaks(value); } } public void setExampleValue(String value) { if (value != null) { exampleValue = removeLineBreaks(value); } } @Override public String toString() { return "PropertyDescriptorEntity [id=" + id + ", propertyName=" + propertyName + "]"; } @Transient protected static final String DEFAULTVALIDATIONEXPRESSION = ".*"; /** * The validation logic can either be defined in the property validation logic or as a regex of the * property type. This method distincts between those different possibility and returns the actual * validation pattern. * * @return */ public String getValidationLogic() { String result = null; if (isCustomType()) { result = this.validationLogic == null ? DEFAULTVALIDATIONEXPRESSION : this.validationLogic; } else { result = this.validationLogic == null ? getPropertyTypeValidationRegex() : this.validationLogic; } return result; } private String getPropertyTypeValidationRegex(){ return propertyTypeEntity != null ? propertyTypeEntity.getValidationRegex() : null; } public boolean isCustomType() { boolean isCustomType = false; if (getPropertyTypeEntity() == null || getPropertyTypeEntity().getId() == null) { isCustomType = true; } return isCustomType; } @Transient public static final Comparator<PropertyDescriptorEntity> CARDINALITY_AND_NAME_COMPARATOR = new Comparator<PropertyDescriptorEntity>() { @Override public int compare(PropertyDescriptorEntity o1, PropertyDescriptorEntity o2) { Integer cardinality = o2.getCardinalityProperty(); if (cardinality == null) { cardinality = Integer.MAX_VALUE; } Integer myCardinality = o1.getCardinalityProperty(); if (myCardinality == null) { myCardinality = Integer.MAX_VALUE; } if (!myCardinality.equals(cardinality)) { return myCardinality - cardinality; } return NAME_SORTING_COMPARATOR.compare(o1, o2); } }; @Transient public static final Comparator<PropertyDescriptorEntity> NAME_SORTING_COMPARATOR = new Comparator<PropertyDescriptorEntity>() { @Override public int compare(PropertyDescriptorEntity o1, PropertyDescriptorEntity o2) { if (o1 == null || o1.getPropertyName() == null) { if (o2 == null || o2.getPropertyName() == null) { return 0; } else { return -1; } } else { if (o2 == null) { return 1; } else { return o1.getPropertyName().compareTo(o2.getPropertyName()); } } } }; @Override public void addPropertyTag(PropertyTagEntity propertyTagEntity) { if (propertyTags == null) { propertyTags = new ArrayList<>(); } if (!hasTagWithName(propertyTagEntity)) { propertyTags.add(propertyTagEntity); } } private boolean hasTagWithName(PropertyTagEntity newTagEntity) { for (PropertyTagEntity tag : propertyTags) { if (newTagEntity != null && newTagEntity.getName().equals(tag.getName())) { return true; } } return false; } @Override public void removePropertyTag(PropertyTagEntity propertyTagEntity) { if (propertyTags != null) { propertyTags.remove(propertyTagEntity); } } private String removeLineBreaks(String input) { return input.replaceAll("\\r\\n|\\r|\\n", " "); } /** * @return the techkey if displayName is empty */ public String getPropertyDescriptorDisplayName() { if (this.displayName == null || this.displayName.isEmpty()) { return this.propertyName; } return displayName; } @Override public ForeignableOwner getOwner() { return fcOwner; } @Override public void setOwner(ForeignableOwner owner) { this.fcOwner = owner; } @Override public String getExternalLink() { return fcExternalLink; } @Override public void setExternalLink(String externalLink) { this.fcExternalLink = externalLink; } @Override public String getExternalKey() { return fcExternalKey; } @Override public void setExternalKey(String externalKey) { this.fcExternalKey = externalKey; } @Override public String getForeignableObjectName() { return this.getClass().getSimpleName(); } @Override public PropertyDescriptorEntity getCopy(PropertyDescriptorEntity target, CopyUnit copyUnit) { if (target == null) { target = new PropertyDescriptorEntity(); } // properties will be added in when copying PropertyEntity target.setEncrypt(isEncrypt()); target.setPropertyName(getPropertyName()); target.setNullable(isNullable()); target.setTesting(isTesting()); target.setValidationLogic(getValidationLogic()); target.setPropertyComment(getPropertyComment()); target.setCardinalityProperty(getCardinalityProperty()); target.setPropertyTypeEntity(getPropertyTypeEntity()); target.setDefaultValue(getDefaultValue()); target.setExampleValue(getExampleValue()); target.setMachineInterpretationKey(getMachineInterpretationKey()); target.setOptional(isOptional()); target.setDisplayName(getDisplayName()); CopyHelper.copyForeignable(target, this, copyUnit); return target; } @Override public int foreignableFieldHashCode() { HashCodeBuilder eb = new HashCodeBuilder(); eb.append(this.id); eb.append(this.displayName); eb.append(this.fcOwner); eb.append(this.fcExternalKey); eb.append(this.fcExternalLink); eb.append(this.defaultValue); eb.append(this.exampleValue); eb.append(this.machineInterpretationKey); eb.append(this.optional); eb.append(this.encrypt); eb.append(this.propertyName); eb.append(this.nullable); eb.append(this.testing); eb.append(this.validationLogic); eb.append(this.propertyComment); eb.append(this.cardinalityProperty); eb.append(this.propertyTypeEntity != null ? this.propertyTypeEntity.getId() : null); return eb.toHashCode(); } @Override public String getNewValueForAuditLog() { return String.format( "Technichal Key: %s, " + "PropertyType: %s, " + "MIK: %s, " + "Default Value: %s", this.propertyName, this.propertyTypeEntity == null ? StringUtils.EMPTY : this.propertyTypeEntity.getPropertyTypeName(), this.machineInterpretationKey, this.defaultValue); } @Override public String getType() { return Auditable.TYPE_PROPERTY_DESCRIPTOR; } @Override public String getNameForAuditLog() { return this.propertyName; } }
package com.navigation.reactnative; import static com.google.android.material.navigation.NavigationBarView.LABEL_VISIBILITY_AUTO; import static com.google.android.material.navigation.NavigationBarView.LABEL_VISIBILITY_LABELED; import static com.google.android.material.navigation.NavigationBarView.LABEL_VISIBILITY_SELECTED; import static com.google.android.material.navigation.NavigationBarView.LABEL_VISIBILITY_UNLABELED; import android.content.res.ColorStateList; import androidx.annotation.Nullable; import com.facebook.react.common.MapBuilder; import com.facebook.react.uimanager.ThemedReactContext; import com.facebook.react.uimanager.ViewGroupManager; import com.facebook.react.uimanager.ViewManagerDelegate; import com.facebook.react.uimanager.annotations.ReactProp; import com.facebook.react.viewmanagers.NVTabNavigationManagerDelegate; import com.facebook.react.viewmanagers.NVTabNavigationManagerInterface; import java.util.Map; import javax.annotation.Nonnull; public class TabNavigationViewManager extends ViewGroupManager<TabNavigationView> implements NVTabNavigationManagerInterface<TabNavigationView> { private final ViewManagerDelegate<TabNavigationView> delegate; public TabNavigationViewManager() { delegate = new NVTabNavigationManagerDelegate<>(this); } @Nullable @Override protected ViewManagerDelegate<TabNavigationView> getDelegate() { return delegate; } @Nonnull @Override public String getName() { return "NVTabNavigation"; } @ReactProp(name = "bottomTabs") public void setBottomTabs(TabNavigationView view, boolean bottomTabs) { view.bottomTabs = bottomTabs; } @ReactProp(name = "labelVisibilityMode", defaultInt = LABEL_VISIBILITY_AUTO) public void setLabelVisibilityMode(TabNavigationView view, int labelVisibilityMode) { view.setLabelVisibilityMode(labelVisibilityMode); } @Override @ReactProp(name = "itemHorizontalTranslation") public void setItemHorizontalTranslation(TabNavigationView view, boolean itemHorizontalTranslation) { view.setItemHorizontalTranslationEnabled(itemHorizontalTranslation); } @Override @ReactProp(name = "selectedTintColor", customType = "Color") public void setSelectedTintColor(TabNavigationView view, @Nullable Integer selectedTintColor) { view.selectedTintColor = selectedTintColor != null ? selectedTintColor : view.defaultTextColor; view.setItemTextColor(new ColorStateList( new int[][]{ new int[]{-android.R.attr.state_checked}, new int[]{android.R.attr.state_checked }}, new int[]{ view.unselectedTintColor, view.selectedTintColor } )); view.setItemIconTintList(view.getItemTextColor()); } @Override @ReactProp(name = "unselectedTintColor", customType = "Color") public void setUnselectedTintColor(TabNavigationView view, @Nullable Integer unselectedTintColor) { view.unselectedTintColor = unselectedTintColor != null ? unselectedTintColor : view.defaultTextColor; view.setItemTextColor(new ColorStateList( new int[][]{ new int[]{-android.R.attr.state_checked}, new int[]{android.R.attr.state_checked }}, new int[]{ view.unselectedTintColor, view.selectedTintColor } )); view.setItemIconTintList(view.getItemTextColor()); } @Override public Map<String, Object> getExportedViewConstants() { return MapBuilder.<String, Object>of( "LabelVisibility", MapBuilder.of( "auto", LABEL_VISIBILITY_AUTO, "labeled", LABEL_VISIBILITY_LABELED, "unlabeled", LABEL_VISIBILITY_UNLABELED, "selected", LABEL_VISIBILITY_SELECTED)); } @Nonnull @Override protected TabNavigationView createViewInstance(@Nonnull ThemedReactContext reactContext) { return new TabNavigationView(reactContext); } }
package org.opensim.view.motions; import java.awt.Color; import java.util.AbstractList; import java.util.ArrayList; import java.util.Collection; import java.util.Enumeration; import java.util.HashMap; import java.util.Hashtable; import java.util.LinkedHashMap; import java.util.Map; import java.util.UUID; import java.util.Vector; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.opensim.logger.OpenSimLogger; import org.opensim.modeling.ArrayDouble; import org.opensim.modeling.ArrayStr; import org.opensim.modeling.Body; import org.opensim.modeling.BodySet; import org.opensim.modeling.Component; import org.opensim.modeling.Coordinate; import org.opensim.modeling.CoordinateSet; import org.opensim.modeling.ForceSet; import org.opensim.modeling.Ground; import org.opensim.modeling.Marker; import org.opensim.modeling.MarkerSet; import org.opensim.modeling.Model; import org.opensim.modeling.OpenSimContext; import org.opensim.modeling.OpenSimObject; import org.opensim.modeling.PhysicalFrame; import org.opensim.modeling.SimbodyEngine; import org.opensim.modeling.StateVector; import org.opensim.modeling.Storage; import org.opensim.modeling.Transform; import org.opensim.modeling.TransformAxis; import org.opensim.modeling.UnitVec3; import org.opensim.modeling.Vec3; import org.opensim.threejs.JSONUtilities; import org.opensim.threejs.ModelVisualizationJson; import org.opensim.view.MuscleColoringFunction; import org.opensim.view.OpenSimvtkGlyphCloud; import org.opensim.view.SelectedGlyphUserObject; import org.opensim.view.SelectionListener; import org.opensim.view.SingleModelVisuals; import org.opensim.view.experimentaldata.AnnotatedMotion; import org.opensim.view.experimentaldata.ExperimentalDataItemType; import org.opensim.view.experimentaldata.ExperimentalDataObject; import org.opensim.view.experimentaldata.ExperimentalMarker; import org.opensim.view.experimentaldata.ModelForExperimentalData; import org.opensim.view.experimentaldata.MotionObjectBodyPoint; import org.opensim.view.experimentaldata.MotionObjectPointForce; import org.opensim.view.pub.OpenSimDB; import org.opensim.view.pub.ViewDB; import vtk.vtkActor; import vtk.vtkAppendPolyData; import vtk.vtkAssemblyNode; import vtk.vtkAssemblyPath; import vtk.vtkLineSource; import vtk.vtkPolyDataMapper; import vtk.vtkProp; /** * * * * @author Ayman. This class is used to preprocess motion files (Storage or similar) so that * 1. Mapping column indices to markersRep, gcs, ... is done only once. * 2. If additional objects need to be created for force or other markersRep they are maintained here. * 3. This isolates the display code from the specifics of Storage so that OpenSim proper creatures can be used. */ public class MotionDisplayer implements SelectionListener { double[] defaultExperimentalMarkerColor = new double[]{0.0, 0.35, 0.65}; private double[] defaultForceColor = new double[]{0., 1.0, 0.}; private Vec3 defaultForceColorVec3 = new Vec3(0., 1.0, 0.); private MuscleColoringFunction mcf=null; // Create JSONs for geometry and material and use them for all objects of this type so that they all change together private JSONObject experimenalMarkerGeometryJson=null; private JSONObject experimenalMarkerMaterialJson=null; private Vec3 defaultMarkerColor = new Vec3(0., 0., 1.); private ModelVisualizationJson modelVisJson=null; JSONObject motionObjectsRoot=null; private final HashMap<UUID, Component> mapUUIDToComponent = new HashMap<UUID, Component>(); private final HashMap<OpenSimObject, ArrayList<UUID>> mapComponentToUUID = new HashMap<OpenSimObject, ArrayList<UUID>>(); /** * @return the associatedMotions */ public ArrayList<MotionDisplayer> getAssociatedMotions() { return associatedMotions; } private void maskForceComponent(double[] vectorGlobal, String forceComponent) { if (forceComponent.equals("All")) return; if (forceComponent.equals("x")) {vectorGlobal[1]=0.0; vectorGlobal[2]=0.0; return;}; if (forceComponent.equals("y")) {vectorGlobal[0]=0.0; vectorGlobal[2]=0.0; return;}; if (forceComponent.equals("z")) {vectorGlobal[0]=0.0; vectorGlobal[1]=0.0; return;}; } /** * @return the groundForcesRep */ public OpenSimvtkGlyphCloud getGroundForcesRep() { return groundForcesRep; } /** * @return the markersRep */ public OpenSimvtkGlyphCloud getMarkersRep() { return markersRep; } /** * @return the currentForceShape */ public String getCurrentForceShape() { return currentForceShape; } /** * @param currentForceShape the currentForceShape to set */ public void setCurrentForceShape(String currentForceShape) { this.currentForceShape = currentForceShape; } /** * @return the defaultForceColor */ public Color getDefaultForceColor() { return new Color((float)defaultForceColor[0], (float)defaultForceColor[1], (float)defaultForceColor[2]); } /** * @param defaultForceColor the defaultForceColor to set */ public void setDefaultForceColor(Color defaultForceColor) { float[] colorFloat = new float[3]; defaultForceColor.getColorComponents(colorFloat); for (int i=0;i<3;i++) this.defaultForceColor[i] = (double) colorFloat[i]; getGroundForcesRep().setColor(defaultForceColor); } public void setMuscleColoringFunction(MuscleColoringFunction mcbya) { mcf = mcbya; // Push it down to muscle displayers if (ViewDB.isVtkGraphicsAvailable()){ SingleModelVisuals vis = ViewDB.getInstance().getModelVisuals(model); vis.setMuscleColoringFunction(mcf); } } public void addMotionObjectsToFrame(JSONArray transforms_json) { if (!(simmMotionData instanceof AnnotatedMotion)) return; AnnotatedMotion mot = (AnnotatedMotion)simmMotionData; Vector<ExperimentalDataObject> objects=mot.getClassified(); Vec3 unitScale = new Vec3(1., 1., 1.); for (ExperimentalDataObject nextObject : objects) { //if (!nextObject.isDisplayed()) // continue; JSONObject motionObjectTransform = new JSONObject(); Transform xform = new Transform(); if (nextObject instanceof ExperimentalMarker) { double[] point = ((ExperimentalMarker) nextObject).getPoint(); xform.setP(new Vec3(point[0], point[1], point[2])); motionObjectTransform.put("uuid", nextObject.getDataObjectUUID().toString()); motionObjectTransform.put("matrix", JSONUtilities.createMatrixFromTransform(xform, unitScale, modelVisJson.getVisScaleFactor())); transforms_json.add(motionObjectTransform); } else if (nextObject instanceof MotionObjectPointForce) { double[] point = ((MotionObjectPointForce) nextObject).getPoint(); Vec3 dir = ((MotionObjectPointForce) nextObject).getDirection(); double length = Math.sqrt(Math.pow(dir.get(0),2)+Math.pow(dir.get(1),2)+Math.pow(dir.get(2),2))/1000; UnitVec3 dirNorm = new UnitVec3(dir); xform.setP(new Vec3(point[0], point[1], point[2])); for (int i=0; i<3; i++) xform.R().set(i, 1, dirNorm.get(i)); motionObjectTransform.put("uuid", nextObject.getDataObjectUUID().toString()); motionObjectTransform.put("matrix", JSONUtilities.createMatrixFromTransform(xform, new Vec3(1, length ,1), modelVisJson.getVisScaleFactor())); transforms_json.add(motionObjectTransform); } } } public boolean hasMotionObjects() { return (simmMotionData instanceof AnnotatedMotion); } public void createMotionObjectsGroupJson() { // Create aan objects under gnd/children to serve as top node for motion objects // all will be in ground frame. if (motionObjectsRoot==null) { motionObjectsRoot = new JSONObject(); motionObjectsRoot.put("parent", modelVisJson.getModelUUID().toString()); motionObjectsRoot.put("uuid", UUID.randomUUID().toString()); motionObjectsRoot.put("type", "Group"); motionObjectsRoot.put("opensimType", "MotionObjects"); motionObjectsRoot.put("name", simmMotionData.getName().concat("_Objects")); motionObjectsRoot.put("userData", "NonEditable"); motionObjectsRoot.put("children", new JSONArray()); motionObjectsRoot.put("matrix", JSONUtilities.createMatrixFromTransform(new Transform(), new Vec3(1.), 1.0)); } } private JSONObject createJsonForMotionObjects() { JSONObject topJson = new JSONObject(); JSONArray jsonGeomArray = new JSONArray(); jsonGeomArray.add(getExperimenalMarkerGeometryJson()); JSONArray jsonMatArray = new JSONArray(); jsonMatArray.add(getExperimenalMarkerMaterialJson()); topJson.put("geometries", jsonGeomArray); topJson.put("materials", jsonMatArray); topJson.put("object", motionObjectsRoot); return topJson; } /** * @return the experimenalMarkerGeometryJson */ public JSONObject getExperimenalMarkerGeometryJson() { return experimenalMarkerGeometryJson; } /** * @return the experimenalMarkerMaterialJson */ public JSONObject getExperimenalMarkerMaterialJson() { return experimenalMarkerMaterialJson; } /** * @return the defaultForceColorVec3 */ public Vec3 getDefaultForceColorVec3() { return defaultForceColorVec3; } public enum ObjectTypesInMotionFiles{GenCoord, GenCoord_Velocity, GenCoord_Force, State, Marker, Segment, Segment_marker_p1, Segment_marker_p2, Segment_marker_p3, Segment_force_p1, Segment_force_p2, Segment_force_p3, Segment_force_p4, Segment_force_p5, Segment_force_p6, Segment_torque_p1, Segment_torque_p2, Segment_torque_p3, UNKNOWN}; Hashtable<Integer, ObjectTypesInMotionFiles> mapIndicesToObjectTypes=new Hashtable<Integer, ObjectTypesInMotionFiles>(40); Hashtable<Integer, Object> mapIndicesToObjects=new Hashtable<Integer, Object>(40); private OpenSimvtkGlyphCloud groundForcesRep = null; OpenSimvtkGlyphCloud bodyForcesRep = null; OpenSimvtkGlyphCloud generalizedForcesRep = null; private OpenSimvtkGlyphCloud markersRep = null; private Storage simmMotionData; private Model model; OpenSimContext dContext; ArrayStr stateNames; private double[] statesBuffer; private boolean renderMuscleActivations=false; double DEFAULT_FACTOR_SCALE_FACTOR=.001; double currentScaleFactor; String DEFAULT_FORCE_SHAPE="arrow"; private String currentForceShape; // For columns that start with a body name, this is the map from column index to body reference. // The map is currently used only for body forces and generalized forces. private Hashtable<Integer, Body> mapIndicesToBodies = new Hashtable<Integer, Body>(10); // For generalized forces, this is the map from column index to DOF reference. private Hashtable<Integer, TransformAxis> mapIndicesToDofs = new Hashtable<Integer, TransformAxis>(10); protected Hashtable<ExperimentalDataObject, vtkActor> objectTrails = new Hashtable<ExperimentalDataObject, vtkActor>(); private ArrayList<MotionDisplayer> associatedMotions = new ArrayList<MotionDisplayer>(); private ArrayStr colNames; // Will cache in labels and construct map to states for quick setting public class ObjectIndexPair { public Object object; public int stateVectorIndex; // Actual (0-based) index into state vector public ObjectIndexPair(Object obj, int idx) { this.object = obj; this.stateVectorIndex = idx; } } // For faster access to gencoords/markers/forces to update in applyFrameToModel ArrayList<ObjectIndexPair> genCoordColumns=null; ArrayList<ObjectIndexPair> genCoordForceColumns=null; ArrayList<ObjectIndexPair> segmentMarkerColumns=null; // state vector index of the first of three (x y z) coordinates for a marker ArrayList<ObjectIndexPair> segmentForceColumns=null; // state vector index of the first of six (px py pz vx vy vz) coordinates for a force vector ArrayList<ObjectIndexPair> anyStateColumns=null; // state vector index of muscle excitations and other generic states ArrayList<String> canonicalStateNames = new ArrayList<String>(); ArrayDouble interpolatedStates = null; boolean statesFile = false; // special type of file that contains full state vectors // A local copy of motionObjects so that different motions have different motion objects //Hashtable<String, vtkActor> motionObjectInstances =new Hashtable<String, vtkActor>(10); /** Creates a new instance of MotionDisplayer */ public MotionDisplayer(Storage motionData, Model model) { this.model = model; dContext= OpenSimDB.getInstance().getContext(model); simmMotionData = motionData; currentScaleFactor = DEFAULT_FACTOR_SCALE_FACTOR; currentForceShape = DEFAULT_FORCE_SHAPE; modelVisJson = ViewDB.getInstance().getModelVisualizationJson(model); setupMotionDisplay(); // create a buffer to be used for comuptation of constrained states //statesBuffer = new double[model.getNumStateVariables()]; modelVisJson.addMotionDisplayer(this); if (model instanceof ModelForExperimentalData) return; if (ViewDB.isVtkGraphicsAvailable()){ SingleModelVisuals vis = ViewDB.getInstance().getModelVisuals(model); if(vis!=null) vis.setApplyMuscleColors(isRenderMuscleActivations()); } } public void setupMotionDisplay() { if (simmMotionData == null) return; colNames = simmMotionData.getColumnLabels(); int numColumnsIncludingTime = colNames.getSize(); //for(int i=0; i< numColumnsIncludingTime; i++ ) // System.out.print(" "+colNames.get(i)); //System.out.println(""); interpolatedStates = new ArrayDouble(0.0, numColumnsIncludingTime-1); AddMotionObjectsRep(model); if (simmMotionData instanceof AnnotatedMotion){ // Add place hoders for markers AnnotatedMotion mot= (AnnotatedMotion) simmMotionData; Vector<ExperimentalDataObject> objects=mot.getClassified(); mot.setMotionDisplayer(this); createMotionObjectsGroupJson(); addExperimentalDataObjectsToJson(objects); for(ExperimentalDataObject nextObject:objects){ if (nextObject.getObjectType()==ExperimentalDataItemType.MarkerData){ bindMarkerToVisualizerObjectKeepHandle(nextObject); } else if (nextObject.getObjectType()==ExperimentalDataItemType.PointForceData){ bindForceVisualizerObjectKeepHandle(nextObject); } } // create objects and cache their uuids //createTrails(model); ViewDB.getInstance().addVisualizerObject(createJsonForMotionObjects()); return; } mapIndicesToBodies.clear(); mapIndicesToDofs.clear(); stateNames = model.getStateVariableNames(); stateNames.insert(0, "time"); if(colNames.arrayEquals(stateNames)) { // This is a states file statesFile = true; if (ViewDB.isVtkGraphicsAvailable()){ SingleModelVisuals vis = ViewDB.getInstance().getModelVisuals(model); if(vis!=null) vis.setApplyMuscleColors(true); } setRenderMuscleActivations(true); } else { // We should build sorted lists of object names so that we can find them easily for(int i=0; i < numColumnsIncludingTime; i++){ String columnName = colNames.getitem(i); // Time is included in labels int numClassified = classifyColumn(model, i, columnName); // find out if column is gencord/muscle/segment/...etc. ObjectTypesInMotionFiles cType = mapIndicesToObjectTypes.get(i); //System.out.println("Classified "+columnName+" as "+cType); if (numClassified>1) // If we did a group then skip the group i += (numClassified-1); } genCoordColumns = new ArrayList<ObjectIndexPair>(numColumnsIncludingTime); genCoordForceColumns = new ArrayList<ObjectIndexPair>(numColumnsIncludingTime); segmentMarkerColumns = new ArrayList<ObjectIndexPair>(numColumnsIncludingTime); segmentForceColumns = new ArrayList<ObjectIndexPair>(numColumnsIncludingTime); anyStateColumns = new ArrayList<ObjectIndexPair>(numColumnsIncludingTime); for (int i = 1; i< numColumnsIncludingTime; i++){ ObjectTypesInMotionFiles cType = mapIndicesToObjectTypes.get(i); Object o=mapIndicesToObjects.get(i); if (cType==null) continue; ObjectIndexPair newPair = new ObjectIndexPair(o,i-1); // -1 to account for time switch(cType){ case GenCoord: genCoordColumns.add(newPair); break; case GenCoord_Force: genCoordForceColumns.add(newPair); break; case State: anyStateColumns.add(newPair); break; case Segment_marker_p1: segmentMarkerColumns.add(newPair); break; case Segment_force_p1: segmentForceColumns.add(newPair); break; } } } } private void bindForceVisualizerObjectKeepHandle(ExperimentalDataObject nextObject) { if (ViewDB.isVtkGraphicsAvailable()){ int glyphIndex=groundForcesRep.addLocation(nextObject); nextObject.setGlyphInfo(glyphIndex, groundForcesRep); } nextObject.setDataObjectUUID(findUUIDForObject(nextObject).get(0)); } private void bindMarkerToVisualizerObjectKeepHandle(ExperimentalDataObject nextObject) { if (ViewDB.isVtkGraphicsAvailable()){ int glyphIndex=markersRep.addLocation(nextObject); nextObject.setGlyphInfo(glyphIndex, markersRep); } nextObject.setDataObjectUUID(findUUIDForObject(nextObject).get(0)); } private void AddMotionObjectsRep(final Model model) { if (ViewDB.isVtkGraphicsAvailable()){ if (groundForcesRep != null) ViewDB.getInstance().removeUserObjectFromModel(model, groundForcesRep.getVtkActor()); if (bodyForcesRep != null) ViewDB.getInstance().removeUserObjectFromModel(model, bodyForcesRep.getVtkActor()); if (generalizedForcesRep != null) ViewDB.getInstance().removeUserObjectFromModel(model, generalizedForcesRep.getVtkActor()); if (markersRep != null) ViewDB.getInstance().removeUserObjectFromModel(model, markersRep.getVtkActor()); groundForcesRep = new OpenSimvtkGlyphCloud(true); groundForcesRep.setName("GRF"); bodyForcesRep = new OpenSimvtkGlyphCloud(true); bodyForcesRep.setName("BodyForce"); generalizedForcesRep = new OpenSimvtkGlyphCloud(true); bodyForcesRep.setName("JointForce"); markersRep = new OpenSimvtkGlyphCloud(false); bodyForcesRep.setName("Exp. Markers"); groundForcesRep.setShapeName(currentForceShape); groundForcesRep.setColor(defaultForceColor); groundForcesRep.setColorRange(defaultForceColor, defaultForceColor); groundForcesRep.setOpacity(0.7); groundForcesRep.setScaleFactor(currentScaleFactor); groundForcesRep.orientByNormalAndScaleByVector(); bodyForcesRep.setShapeName("arrow"); bodyForcesRep.setColor(new double[]{0., 0., 1.0}); bodyForcesRep.setOpacity(0.7); bodyForcesRep.setScaleFactor(currentScaleFactor); bodyForcesRep.orientByNormalAndScaleByVector(); generalizedForcesRep.setShapeName("arrow"); generalizedForcesRep.setColor(new double[]{0., 1.0, 1.0}); generalizedForcesRep.setOpacity(0.7); generalizedForcesRep.setScaleFactor(currentScaleFactor); generalizedForcesRep.orientByNormalAndScaleByVector(); markersRep.setShapeName("marker"); markersRep.setColor(defaultExperimentalMarkerColor); //Scale , scaleBy markersRep.setColorRange(defaultExperimentalMarkerColor, defaultExperimentalMarkerColor); markersRep.scaleByVectorComponents(); markersRep.setScaleFactor(ViewDB.getInstance().getExperimentalMarkerDisplayScale()); ViewDB.getInstance().addUserObjectToModel(model, groundForcesRep.getVtkActor()); ViewDB.getInstance().addUserObjectToModel(model, bodyForcesRep.getVtkActor()); ViewDB.getInstance().addUserObjectToModel(model, generalizedForcesRep.getVtkActor()); ViewDB.getInstance().addUserObjectToModel(model, markersRep.getVtkActor()); } // should send new objects to visualizer ViewDB.getInstance().addSelectionListener(this); } //interface applyValue // public void apply(double val); /* * Check what kind of data is at columnIndex, and add object of relevance * to the map "mapIndicesToObjects" for quick access during animation * * returns the number of columns that has been classified since _px may lead to _py, _pz * so we don't want to start name searching from scratch. * A side effect is the creation of motion object instances and adding them to the model **/ private int classifyColumn(Model model, int columnIndex, String columnName) { ObjectTypesInMotionFiles retType = ObjectTypesInMotionFiles.UNKNOWN; if (model instanceof ModelForExperimentalData) { return 0; } int newIndex = simmMotionData.getStateIndex(columnName); if (newIndex ==-1) return 0; String canonicalCcolumnName = columnName.replace('.', '/'); CoordinateSet coords = model.getCoordinateSet(); for (int i = 0; i<coords.getSize(); i++){ Coordinate co = coords.get(i); // GenCoord String cName = co.getName(); if (cName.equals(columnName)||cName.equals(co.getRelativePathName(model))){ mapIndicesToObjectTypes.put(columnIndex, ObjectTypesInMotionFiles.GenCoord); mapIndicesToObjects.put(columnIndex, co); //co.setValue(); return 1; } // GenCoord_Velocity if (columnName.endsWith("_vel")|| columnName.endsWith("_u")){ if (columnName.equals(cName+"_vel")|| columnName.equals(cName+"_u")) mapIndicesToObjectTypes.put(columnIndex, ObjectTypesInMotionFiles.GenCoord_Velocity); mapIndicesToObjects.put(columnIndex, co); return 1; } // GenCoord_Force if (columnName.endsWith("_torque") || columnName.endsWith("_force")){ if (columnName.equals(cName+"_torque") || columnName.equals(cName+"_force")) { mapIndicesToObjectTypes.put(columnIndex, ObjectTypesInMotionFiles.GenCoord_Force); //mapIndicesToObjects.put(columnIndex, co); //Joint joint = null; //TransformAxis unconstrainedDof = model.getSimbodyEngine().findUnconstrainedDof(co, joint); //Body body = unconstrainedDof.getJoint().getBody(); //mapIndicesToBodies.put(columnIndex, body); //mapIndicesToDofs.put(columnIndex, unconstrainedDof); //int index = generalizedForcesRep.addLocation(0., 0., 0.); //mapIndicesToObjects.put(columnIndex, new Integer(index)); return 1; } } } // Allow "/" instead of in addition to "." // Add method to convert column labels to state names so it's centralized if (columnName.contains("excitation") || columnName.contains("activation")){ setRenderMuscleActivations(true); } ForceSet acts = model.getForceSet(); for (int i=0; i< acts.getSize(); i++) if (columnName.startsWith(acts.get(i).getName())){ // Make sure it's a muscle state' // Any other state int stateIndex=stateNames.findIndex(canonicalCcolumnName); // includes time so 0 is time if (stateIndex>0){ int stateIndexMinusTime = stateIndex-1; mapIndicesToObjectTypes.put(columnIndex, ObjectTypesInMotionFiles.State); mapIndicesToObjects.put(columnIndex, new Integer(stateIndexMinusTime)); canonicalStateNames.add(canonicalCcolumnName); return 1; } } MarkerSet markers = model.getMarkerSet(); for (int i = 0; i<markers.getSize(); i++){ Marker marker = markers.get(i); String cName = marker.getName(); if (columnName.startsWith(cName+"_")){ mapIndicesToObjectTypes.put(columnIndex, ObjectTypesInMotionFiles.Segment_marker_p1); mapIndicesToObjectTypes.put(columnIndex+1, ObjectTypesInMotionFiles.Segment_marker_p2); mapIndicesToObjectTypes.put(columnIndex+2, ObjectTypesInMotionFiles.Segment_marker_p3); int index= markersRep.addLocation(0., 0., 0.); mapIndicesToObjects.put(columnIndex, new Integer(index)); mapIndicesToObjects.put(columnIndex+1, new Integer(index)); mapIndicesToObjects.put(columnIndex+2, new Integer(index)); return 3; } } // Body segment since experimental markersRep are in ground frame as ground_marker_?? BodySet bodySet = model.getBodySet(); String[] motionObjectNames=MotionObjectsDB.getInstance().getAvailableNames(); for (int i = 0; i<bodySet.getSize(); i++){ Body bdy = bodySet.get(i); String bName = bdy.getName(); if (columnName.startsWith(bName+"_")){ if (columnName.startsWith(bName+"_marker_")){ if (columnName.equals(bName+"_marker_px")){ mapIndicesToObjectTypes.put(columnIndex, ObjectTypesInMotionFiles.Segment_marker_p1); mapIndicesToObjectTypes.put(columnIndex+1, ObjectTypesInMotionFiles.Segment_marker_p2); mapIndicesToObjectTypes.put(columnIndex+2, ObjectTypesInMotionFiles.Segment_marker_p3); int index= markersRep.addLocation(0., 0., 0.); mapIndicesToObjects.put(columnIndex, new Integer(index)); mapIndicesToObjects.put(columnIndex+1, new Integer(index)); mapIndicesToObjects.put(columnIndex+2, new Integer(index)); return 3; } else { mapIndicesToObjectTypes.put(columnIndex, ObjectTypesInMotionFiles.UNKNOWN); return 0; // Something else } } int numColumnsIncludingTime = simmMotionData.getColumnLabels().getSize(); if (columnName.startsWith(bName) && columnName.contains("force")){ if (columnName.startsWith(bName) && columnName.endsWith("_vx")){ // Make sure we're not going outside # columns due to assumption about column ordering' if ((columnIndex+5) > numColumnsIncludingTime){ OpenSimLogger.logMessage("Unexpected column headers for forces at column "+columnIndex+" will be ignored", OpenSimLogger.INFO); continue; } mapIndicesToObjectTypes.put(columnIndex, ObjectTypesInMotionFiles.Segment_force_p1); mapIndicesToObjectTypes.put(columnIndex+1, ObjectTypesInMotionFiles.Segment_force_p2); mapIndicesToObjectTypes.put(columnIndex+2, ObjectTypesInMotionFiles.Segment_force_p3); mapIndicesToObjectTypes.put(columnIndex+3, ObjectTypesInMotionFiles.Segment_force_p4); mapIndicesToObjectTypes.put(columnIndex+4, ObjectTypesInMotionFiles.Segment_force_p5); mapIndicesToObjectTypes.put(columnIndex+5, ObjectTypesInMotionFiles.Segment_force_p6); int index = 0; if (bName.equalsIgnoreCase("ground")) index = groundForcesRep.addLocation(0., 0., 0.); else index = bodyForcesRep.addLocation(0., 0., 0.); mapIndicesToObjects.put(columnIndex, new Integer(index)); mapIndicesToObjects.put(columnIndex+1, new Integer(index)); mapIndicesToObjects.put(columnIndex+2, new Integer(index)); mapIndicesToObjects.put(columnIndex+3, new Integer(index)); mapIndicesToObjects.put(columnIndex+4, new Integer(index)); mapIndicesToObjects.put(columnIndex+5, new Integer(index)); mapIndicesToBodies.put(columnIndex, bdy); return 6; } else{ mapIndicesToObjectTypes.put(columnIndex, ObjectTypesInMotionFiles.UNKNOWN); return 0; // Something else, maybe a velocity component } } mapIndicesToObjectTypes.put(columnIndex, ObjectTypesInMotionFiles.Segment); mapIndicesToObjects.put(columnIndex, bdy); return 1; } } mapIndicesToObjectTypes.put(columnIndex, ObjectTypesInMotionFiles.UNKNOWN); return 0; } void applyFrameToModel(int currentFrame) { boolean profile=(OpenSimObject.getDebugLevel()>=2); long before = 0, after=0; if (profile) before =System.nanoTime(); StateVector states=simmMotionData.getStateVector(currentFrame); applyStatesToModel(states.getData()); ViewDB.getInstance().updateAnnotationAnchors(); if (profile) { after=System.nanoTime(); System.out.println("applyFrameToModel time: "+1e-6*(after-before)+" ms"); } } public void applyTimeToModel(double currentTime) { //TODO: Option to snap to nearest valid storage time rather than interpolate... // Better clamp the time otherwise we'll get linear extrapolation outside the valid time range (we might get out-of-range times // if we're playing this motion synced with another motion) double clampedTime = (currentTime < simmMotionData.getFirstTime()) ? simmMotionData.getFirstTime() : (currentTime > simmMotionData.getLastTime()) ? simmMotionData.getLastTime() : currentTime; //OpenSimDB.getInstance().getContext(model).getCurrentStateRef().setTime(clampedTime); simmMotionData.getDataAtTime(clampedTime, interpolatedStates.getSize(), interpolatedStates); applyStatesToModel(interpolatedStates); // Repeat for associated motions for (MotionDisplayer assocMotion:associatedMotions){ assocMotion.applyTimeToModel(currentTime); } } private void applyStatesToModel(ArrayDouble states) { boolean profile=false;//(OpenSimObject.getDebugLevel()>=2); long before = 0, after=0; if (profile) before =System.nanoTime(); if (simmMotionData instanceof AnnotatedMotion){ int dataSize = states.getSize(); AnnotatedMotion mot = (AnnotatedMotion)simmMotionData; Vector<ExperimentalDataObject> objects=mot.getClassified(); boolean markersModified=false; boolean forcesModified=false; mot.updateDecorations(interpolatedStates); if (ViewDB.isVtkGraphicsAvailable()){ SingleModelVisuals vis = ViewDB.getInstance().getModelVisuals(model); for(ExperimentalDataObject nextObject:objects){ if (!nextObject.isDisplayed()) continue; vis.upateDisplay(nextObject); // The following blocks need to be moved inside updateDecorations if (nextObject.getObjectType()==ExperimentalDataItemType.MarkerData){ int startIndex = nextObject.getStartIndexInFileNotIncludingTime(); /* markersRep.setLocation(nextObject.getGlyphIndex(), states.getitem(startIndex)/mot.getUnitConversion(), states.getitem(startIndex+1)/mot.getUnitConversion(), states.getitem(startIndex+2)/mot.getUnitConversion()); markersModified = true;*/ } else if (nextObject.getObjectType()==ExperimentalDataItemType.PointForceData){ String pointId = ((MotionObjectPointForce)nextObject).getPointIdentifier(); String forceId = ((MotionObjectPointForce)nextObject).getForceIdentifier(); String bodyId = ((MotionObjectPointForce)nextObject).getPointExpressedInBody(); Body b = model.getBodySet().get(bodyId); int startPointIndex = simmMotionData.getColumnIndicesForIdentifier(pointId).getitem(0)-1; double[] locationLocal = new double[]{states.getitem(startPointIndex), states.getitem(startPointIndex+1), states.getitem(startPointIndex+2)}; double[] locationGlobal = new double[3]; // Transform to ground from body frame dContext.transformPosition(b, locationLocal, locationGlobal); groundForcesRep.setLocation(nextObject.getGlyphIndex(), locationGlobal[0], locationGlobal[1], locationGlobal[2]); int startForceIndex = simmMotionData.getColumnIndicesForIdentifier(forceId).getitem(0)-1; double[] forceLocal = new double[]{states.getitem(startForceIndex), states.getitem(startForceIndex+1), states.getitem(startForceIndex+2)}; maskForceComponent(forceLocal, ((MotionObjectPointForce)nextObject).getForceComponent()); double[] forceGlobal = new double[3]; dContext.transform(b, forceLocal, model.get_ground(), forceGlobal); groundForcesRep.setNormalAtLocation(nextObject.getGlyphIndex(), forceGlobal[0], forceGlobal[1], forceGlobal[2]); forcesModified=true; } else if (nextObject.getObjectType()==ExperimentalDataItemType.BodyForceData){ int startIndex = nextObject.getStartIndexInFileNotIncludingTime(); MotionObjectBodyPoint bodyPointObject = (MotionObjectBodyPoint)nextObject; double[] bodyPoint =bodyPointObject.getPoint(); PhysicalFrame b = model.getBodySet().get(bodyPointObject.getPointExpressedInBody()); double[] bodyPointGlobal = new double[3]; // Transform to ground from body frame dContext.transformPosition(b, bodyPoint, bodyPointGlobal); groundForcesRep.setLocation(nextObject.getGlyphIndex(), bodyPointGlobal[0], bodyPointGlobal[1], bodyPointGlobal[2]); double[] vectorGlobal = new double[]{states.getitem(startIndex), states.getitem(startIndex+1), states.getitem(startIndex+2)}; if (b==model.get_ground()) maskForceComponent(vectorGlobal, ((MotionObjectPointForce)nextObject).getForceComponent()); else{ double[] vectorLocal = new double[]{ states.getitem(startIndex), states.getitem(startIndex+1), states.getitem(startIndex+2) }; maskForceComponent(vectorLocal, ((MotionObjectPointForce)nextObject).getForceComponent()); // Transform to ground from body frame dContext.transform(b, vectorLocal, model.get_ground(), vectorGlobal); } groundForcesRep.setNormalAtLocation(nextObject.getGlyphIndex(), vectorGlobal[0], vectorGlobal[1], vectorGlobal[2]); forcesModified=true; } if (forcesModified) groundForcesRep.setModified(); if (markersModified) markersRep.setModified(); } } // Create one frame and send to Visualizer this would have: // updated positions for markers, // updated transforms for forces //groundForcesRep.hide(0); return; } OpenSimContext context = OpenSimDB.getInstance().getContext(model); if(statesFile) { // FIX40 speed this up by using map or YIndex for (int i=0; i<states.getSize();i++){ String nmForIndex = colNames.get(i+1); double val = states.get(i); //System.out.print(nmForIndex+"="+val+","); model.setStateVariableValue(context.getCurrentStateRef(), nmForIndex, val); } } else { boolean realize=false; int which=-1; for(int i=0; i<genCoordColumns.size(); i++) { Coordinate coord=(Coordinate)(genCoordColumns.get(i).object); if(!context.getLocked(coord)) { int index = genCoordColumns.get(i).stateVectorIndex; context.setValue(coord, states.getitem(index), false); realize=true; which=i; } // Make sure we realize once IF a coordinate has bben set if (i==genCoordColumns.size()-1 && realize){ coord=(Coordinate)(genCoordColumns.get(which).object); int index = genCoordColumns.get(which).stateVectorIndex; context.setValue(coord, states.getitem(index), true); } } // update states to make sure constraints are valid //context.getStates(statesBuffer); //OpenSim20 model.getDynamicsEngine().computeConstrainedCoordinates(statesBuffer); // Any other states including muscles for(int i=0; i<anyStateColumns.size(); i++) { int index = anyStateColumns.get(i).stateVectorIndex; double newValue=states.getitem(index); // Set value in statesBuffer //Object o=mapIndicesToObjects.get(index+1); //int bufferIndex = ((Integer)o).intValue(); model.setStateVariableValue(context.getCurrentStateRef(), canonicalStateNames.get(i), newValue); //statesBuffer[bufferIndex]=newValue; } for(int i=0; i<segmentMarkerColumns.size(); i++) { int markerIndex = ((Integer)(segmentMarkerColumns.get(i).object)).intValue(); int index = segmentMarkerColumns.get(i).stateVectorIndex; markersRep.setLocation(markerIndex, states.getitem(index), states.getitem(index+1), states.getitem(index+2)); } if(segmentMarkerColumns.size()>0) markersRep.setModified(); Ground gnd = model.getGround(); for(int i=0; i<genCoordForceColumns.size(); i++) { int forceIndex = ((Integer)(genCoordForceColumns.get(i).object)).intValue(); int index = genCoordForceColumns.get(i).stateVectorIndex; SimbodyEngine de = model.getSimbodyEngine(); Body body = mapIndicesToBodies.get(index+1); TransformAxis dof = mapIndicesToDofs.get(index+1); Vec3 vOffset = new Vec3(); double[] offset = new double[3]; double[] gOffset = new double[3]; dof.getAxis(vOffset); // in parent frame, right? double magnitude = states.getitem(index); for (int j=0; j<3; j++) offset[j] = vOffset.get(j) * magnitude * 10.0; // * 10.0 because test data is small context.transform(body, offset, gnd, gOffset); generalizedForcesRep.setNormalAtLocation(forceIndex, gOffset[0], gOffset[1], gOffset[2]); ///vOffset = dof.getJoint().getLocationInChild(); for (int ix=0; ix<3; ix++) offset[ix]=vOffset.get(ix); context.transformPosition(body, offset, gOffset); generalizedForcesRep.setLocation(forceIndex, gOffset[0], gOffset[1], gOffset[2]); } if(genCoordForceColumns.size()>0) { generalizedForcesRep.setModified(); } for(int i=0; i<segmentForceColumns.size(); i++) { int forceIndex = ((Integer)(segmentForceColumns.get(i).object)).intValue(); int index = segmentForceColumns.get(i).stateVectorIndex; Body body = mapIndicesToBodies.get(index+1); double[] offset = new double[3]; double[] gOffset = new double[3]; for (int j=0; j<3; j++) offset[j] = states.getitem(index+j); if (body.equals(gnd)) { groundForcesRep.setNormalAtLocation(forceIndex, offset[0], offset[1], offset[2]); } else { context.transform(body, offset, gnd, gOffset); bodyForcesRep.setNormalAtLocation(forceIndex, gOffset[0], gOffset[1], gOffset[2]); } for (int j=0; j<3; j++) offset[j] = states.getitem(index+j+3); if (body.equals(gnd)) { groundForcesRep.setLocation(forceIndex, offset[0], offset[1], offset[2]); } else { context.transformPosition(body, offset, gOffset); bodyForcesRep.setLocation(forceIndex, gOffset[0], gOffset[1], gOffset[2]); } } if(segmentForceColumns.size()>0) { groundForcesRep.setModified(); bodyForcesRep.setModified(); } } if (profile) { after=System.nanoTime(); OpenSimLogger.logMessage("applyFrameToModel time: "+1e-6*(after-before)+" ms.\n", OpenSimLogger.INFO); } context.realizeVelocity(); } /* * cleanupDisplay is called when the motion is mode non-current either explicitly by the user or by selecting * another motion for the same model and making it current */ void cleanupDisplay() { if (ViewDB.isVtkGraphicsAvailable()){ if (groundForcesRep != null) { ViewDB.getInstance().removeUserObjectFromModel(model, groundForcesRep.getVtkActor()); } if (bodyForcesRep != null) { ViewDB.getInstance().removeUserObjectFromModel(model, bodyForcesRep.getVtkActor()); } if (generalizedForcesRep != null) { ViewDB.getInstance().removeUserObjectFromModel(model, generalizedForcesRep.getVtkActor()); } if (markersRep != null) { ViewDB.getInstance().removeUserObjectFromModel(model, markersRep.getVtkActor()); } // Don't attempt to change muscle activation color if we're here because // the model is closing... check this by checking model is still in models list // This may help fix a crash that Sam got when he closed a model that had a MotionDisplayer // associated with it. It may be because setRenderMuscleActivations ends up updating the actuator // geometry, and if the model is closing it may be that it was in the process of being deleted when // those actuators were referred to... So we avoid all that with this if statement. if (OpenSimDB.getInstance().hasModel(model) && renderMuscleActivations) { SingleModelVisuals vis = ViewDB.getInstance().getModelVisuals(model); if (vis != null) { vis.setApplyMuscleColors(false); } } // If trails are shown, hide them too Enumeration<vtkActor> trailActors = objectTrails.elements(); while (trailActors.hasMoreElements()) { ViewDB.getInstance().removeUserObjectFromModel(model, trailActors.nextElement()); } for (MotionDisplayer assocMotion : associatedMotions) { assocMotion.cleanupDisplay(); } setMuscleColoringFunction(null); } if (motionObjectsRoot!=null) { ViewDB.getInstance().RemoveVisualizerObject(motionObjectsRoot, modelVisJson.getModelUUID().toString()); } // Recursively cleanup ArrayList<MotionDisplayer> associatedDisplayers = getAssociatedMotions(); for (MotionDisplayer assoc:associatedDisplayers){ assoc.cleanupDisplay(); } } public Storage getSimmMotionData() { return simmMotionData; } public Model getModel() { return model; } public boolean isRenderMuscleActivations() { return renderMuscleActivations; } public void setRenderMuscleActivations(boolean renderMuscleActivations) { this.renderMuscleActivations = renderMuscleActivations; } public void toggleTrail(ExperimentalDataObject aExperimentalDataObject) { vtkActor prop=objectTrails.get(aExperimentalDataObject); if (prop!=null){ // Created visuals already at some point prop.Modified(); prop.SetVisibility(1-prop.GetVisibility()); return; } // Else recreate prop = createTrail(aExperimentalDataObject); ViewDB.getInstance().addUserObjectToModel(model, prop); prop.Modified(); } // This method precreates the Trails for motion objects regardless. // user uses commands to add or remove them from the scene. private vtkActor createTrail(ExperimentalDataObject object) { AnnotatedMotion mot= (AnnotatedMotion) simmMotionData; ArrayDouble xCoord = new ArrayDouble(); ArrayDouble yCoord = new ArrayDouble(); ArrayDouble zCoord = new ArrayDouble(); double scale = 1.0; if (object.getObjectType()==ExperimentalDataItemType.MarkerData){ int startIndex = object.getStartIndexInFileNotIncludingTime(); mot.getDataColumn(startIndex, xCoord); mot.getDataColumn(startIndex+1, yCoord); mot.getDataColumn(startIndex+2, zCoord); scale = mot.getUnitConversion(); } else if (object.getObjectType()==ExperimentalDataItemType.PointForceData){ int startIndex = object.getStartIndexInFileNotIncludingTime(); mot.getDataColumn(startIndex+2, xCoord); mot.getDataColumn(startIndex+3, yCoord); mot.getDataColumn(startIndex+4, zCoord); } else return null; vtkAppendPolyData traceLinePolyData = new vtkAppendPolyData(); int numPoints = xCoord.getSize(); for(int i=0;i<numPoints-1;i++){ vtkLineSource nextLine = new vtkLineSource(); double vals[] = new double[]{xCoord.getitem(i), yCoord.getitem(i), zCoord.getitem(i)}; double valsp1[] = new double[]{xCoord.getitem(i+1), yCoord.getitem(i+1), zCoord.getitem(i+1)}; nextLine.SetPoint1(xCoord.getitem(i)/scale, yCoord.getitem(i)/scale, zCoord.getitem(i)/scale); nextLine.SetPoint2(xCoord.getitem(i+1)/scale, yCoord.getitem(i+1)/scale, zCoord.getitem(i+1)/scale); if (Double.isNaN(xCoord.getitem(i))||Double.isNaN(xCoord.getitem(i+1))) continue; // Gap in data /*System.out.println("Line ("+nextLine.GetPoint1()[0]+", "+ nextLine.GetPoint1()[1]+", "+nextLine.GetPoint1()[2]+")- to "+nextLine.GetPoint2()[0]+ nextLine.GetPoint2()[1]+", "+nextLine.GetPoint2()[2]);*/ traceLinePolyData.AddInput(nextLine.GetOutput()); } vtkPolyDataMapper traceLineMapper = new vtkPolyDataMapper(); traceLineMapper.SetInput(traceLinePolyData.GetOutput()); vtkActor traceLineActor = new vtkActor(); traceLineActor.SetMapper(traceLineMapper); objectTrails.put(object, traceLineActor); return traceLineActor; } public Vector<vtkActor> getActors() { Vector<vtkActor> dActors = new Vector<vtkActor>(4); if (groundForcesRep != null) dActors.add(groundForcesRep.getVtkActor()); if (bodyForcesRep != null) dActors.add(bodyForcesRep.getVtkActor()); if (generalizedForcesRep != null) dActors.add(generalizedForcesRep.getVtkActor()); if (markersRep != null) dActors.add(markersRep.getVtkActor()); Collection<vtkActor> trails = objectTrails.values(); for(vtkActor nextActor:trails) dActors.add(nextActor); return dActors; } public void pickUserObject(vtkAssemblyPath asmPath, int cellId) { if (asmPath != null) { vtkAssemblyNode pickedAsm = asmPath.GetLastNode(); vtkProp dProp = pickedAsm.GetViewProp(); int index=getActors().indexOf(dProp); if (index >=0){ vtkActor dActor=getActors().get(index); if (dProp==groundForcesRep.getVtkActor()) handleSelection(groundForcesRep, cellId); else if(dProp==bodyForcesRep.getVtkActor()) handleSelection(bodyForcesRep, cellId); else if (dProp==generalizedForcesRep.getVtkActor()) handleSelection(generalizedForcesRep, cellId); else if (dProp==markersRep.getVtkActor()){ handleSelection(markersRep, cellId); } else System.out.println("Unknown user object "); } return; } } private void handleSelection(final OpenSimvtkGlyphCloud glyphRep, final int cellId) { final OpenSimObject obj = glyphRep.getPickedObject(cellId); if (obj!=null) // SelectedGlyphUserObject provies the bbox, name, other attributes needed for selection mgmt ViewDB.getInstance().markSelected(new SelectedGlyphUserObject(obj, model, glyphRep), true, false, true); } public void updateMotionObjects(){ if (simmMotionData instanceof AnnotatedMotion){ // Add place hoders for markers AnnotatedMotion mot= (AnnotatedMotion) simmMotionData; currentScaleFactor = mot.getDisplayForceScale(); currentForceShape = mot.getDisplayForceShape(); AddMotionObjectsRep(model); Vector<ExperimentalDataObject> objects=mot.getClassified(); mot.setMotionDisplayer(this); for(ExperimentalDataObject nextObject:objects){ if (nextObject.getObjectType()==ExperimentalDataItemType.MarkerData){ bindMarkerToVisualizerObjectKeepHandle(nextObject); } else if (nextObject.getObjectType()==ExperimentalDataItemType.PointForceData){ bindForceVisualizerObjectKeepHandle(nextObject); } else if (nextObject.getObjectType()==ExperimentalDataItemType.BodyForceData){ bindForceVisualizerObjectKeepHandle(nextObject); } } //createTrails(model); return; } } private void createDefaultMotionObjects() { if (getExperimenalMarkerGeometryJson() == null) { experimenalMarkerGeometryJson = new JSONObject(); UUID uuidForMarkerGeometry = UUID.randomUUID(); getExperimenalMarkerGeometryJson().put("uuid", uuidForMarkerGeometry.toString()); getExperimenalMarkerGeometryJson().put("type", "BoxGeometry"); getExperimenalMarkerGeometryJson().put("width", 8); getExperimenalMarkerGeometryJson().put("height", 8); getExperimenalMarkerGeometryJson().put("depth", 8); getExperimenalMarkerGeometryJson().put("name", "DefaultExperimentalMarker"); JSONArray json_geometries = (JSONArray) modelVisJson.get("geometries"); json_geometries.add(getExperimenalMarkerGeometryJson()); experimenalMarkerMaterialJson = new JSONObject(); UUID uuidForMarkerMaterial = UUID.randomUUID(); getExperimenalMarkerMaterialJson().put("uuid", uuidForMarkerMaterial.toString()); String colorString = JSONUtilities.mapColorToRGBA(defaultMarkerColor); getExperimenalMarkerMaterialJson().put("type", "MeshPhongMaterial"); getExperimenalMarkerMaterialJson().put("shininess", 30); getExperimenalMarkerMaterialJson().put("transparent", true); getExperimenalMarkerMaterialJson().put("emissive", JSONUtilities.mapColorToRGBA(new Vec3(0., 0., 0.))); getExperimenalMarkerMaterialJson().put("specular", JSONUtilities.mapColorToRGBA(new Vec3(0., 0., 0.))); getExperimenalMarkerMaterialJson().put("side", 2); getExperimenalMarkerMaterialJson().put("wireframe", false); getExperimenalMarkerMaterialJson().put("color", colorString); JSONArray json_materials = (JSONArray) modelVisJson.get("materials"); json_materials.add(getExperimenalMarkerMaterialJson()); } } public void addExperimentalDataObjectsToJson(AbstractList<ExperimentalDataObject> expObjects) { // Make sure this createDefaultMotionObjects(); // create default top Group for motion JSONObject topJson = motionObjectsRoot; if (topJson.get("children") == null) { topJson.put("children", new JSONArray()); } JSONArray motObjectsChildren = (JSONArray) topJson.get("children"); for (ExperimentalDataObject nextExpObject : expObjects) { if (mapComponentToUUID.get(nextExpObject)!= null) continue; ArrayList<UUID> comp_uuids = new ArrayList<UUID>(); motObjectsChildren.add(nextExpObject.createDecorationJson(comp_uuids, this)); mapComponentToUUID.put(nextExpObject, comp_uuids); } } public OpenSimObject findObjectForUUID(String uuidString) { return mapUUIDToComponent.get(UUID.fromString(uuidString)); } public ArrayList<UUID> findUUIDForObject(OpenSimObject obj) { return mapComponentToUUID.get(obj); } }
package org.xins.tests.server; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.xins.server.API; /** * Tests for class <code>API</code>. * * @version $Revision$ $Date$ * @author Ernst de Haan (<a href="mailto:ernst.dehaan@nl.wanadoo.com">ernst.dehaan@nl.wanadoo.com</a>) */ public class APITests extends TestCase { // Class functions /** * Returns a test suite with all test cases defined by this class. * * @return * the test suite, never <code>null</code>. */ public static Test suite() { return new TestSuite(APITests.class); } // Class fields // Constructor /** * Constructs a new <code>APITests</code> test suite with * the specified name. The name will be passed to the superconstructor. * * @param name * the name for this test suite. */ public APITests(String name) { super(name); } // Fields // Methods /** * Performs setup for the tests. */ protected void setUp() { // empty } public void testAPI() throws Throwable { try { new TestAPI(null); fail("Expected API(null) to throw an IllegalArgumentException."); } catch (IllegalArgumentException exception) { // as expected } try { new TestAPI(""); } catch (IllegalArgumentException exception) { fail("Expected API(\"\") to throw an IllegalArgumentException."); } } // Inner classes private class TestAPI extends API { TestAPI(String name) { super(name); } } }
package org.eclipse.birt.report.designer.internal.ui.util; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.eclipse.birt.report.designer.core.model.SessionHandleAdapter; import org.eclipse.birt.report.designer.core.runtime.GUIException; import org.eclipse.birt.report.designer.internal.ui.dialogs.ImportLibraryDialog; import org.eclipse.birt.report.designer.internal.ui.editors.IReportEditor; import org.eclipse.birt.report.designer.internal.ui.editors.parts.DeferredGraphicalViewer; import org.eclipse.birt.report.designer.internal.ui.editors.parts.GraphicalEditorWithFlyoutPalette; import org.eclipse.birt.report.designer.internal.ui.editors.schematic.editparts.DummyEditpart; import org.eclipse.birt.report.designer.internal.ui.editors.schematic.editparts.GridEditPart; import org.eclipse.birt.report.designer.internal.ui.editors.schematic.editparts.ListBandEditPart; import org.eclipse.birt.report.designer.internal.ui.editors.schematic.editparts.ListEditPart; import org.eclipse.birt.report.designer.internal.ui.editors.schematic.editparts.TableCellEditPart; import org.eclipse.birt.report.designer.internal.ui.editors.schematic.editparts.TableEditPart; import org.eclipse.birt.report.designer.nls.Messages; import org.eclipse.birt.report.designer.ui.ReportPlugin; import org.eclipse.birt.report.designer.ui.dialogs.GroupDialog; import org.eclipse.birt.report.designer.ui.editors.AbstractMultiPageEditor; import org.eclipse.birt.report.designer.ui.newelement.DesignElementFactory; import org.eclipse.birt.report.designer.util.DEUtil; import org.eclipse.birt.report.model.api.DesignElementHandle; import org.eclipse.birt.report.model.api.DesignFileException; import org.eclipse.birt.report.model.api.ElementFactory; import org.eclipse.birt.report.model.api.GroupHandle; import org.eclipse.birt.report.model.api.LibraryHandle; import org.eclipse.birt.report.model.api.ListHandle; import org.eclipse.birt.report.model.api.ModuleHandle; import org.eclipse.birt.report.model.api.ReportElementHandle; import org.eclipse.birt.report.model.api.SlotHandle; import org.eclipse.birt.report.model.api.TableHandle; import org.eclipse.birt.report.model.api.ThemeHandle; import org.eclipse.birt.report.model.api.activity.SemanticException; import org.eclipse.core.resources.IFolder; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IResourceStatus; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.OperationCanceledException; import org.eclipse.core.runtime.Platform; import org.eclipse.core.runtime.SubProgressMonitor; import org.eclipse.gef.EditPart; import org.eclipse.gef.EditPartViewer; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.util.Assert; import org.eclipse.jface.viewers.AbstractTreeViewer; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.ITreeContentProvider; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.window.Window; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.ScrolledComposite; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Layout; import org.eclipse.swt.widgets.ScrollBar; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.forms.editor.FormEditor; import org.eclipse.ui.forms.widgets.ColumnLayout; import org.eclipse.ui.forms.widgets.ILayoutExtension; import org.osgi.framework.Bundle; /** * Utility class for UI related routines. */ public class UIUtil { private static final String MSG_DIALOG_TITLE = Messages.getString( "ImportLibraryAction.Title.ImportSuccessfully" ); //$NON-NLS-1$ private static final String MSG_DIALOG_MSG = Messages.getString( "ImportLibraryAction.Message.ImportSuccessfully" ); //$NON-NLS-1$ /** * Returns if current active editor is reportEditor. * * @return true if current active editor is reportEditor, or false else. */ public static boolean isReportEditorActivated( ) { return getActiveReportEditor( ) != null; } /** * Returns the current active report editor. The same as getActiveEditor( * true ). * * @return the current active report editor, or null if no report editor is * active. */ public static FormEditor getActiveReportEditor( ) { return getActiveReportEditor( true ); } /** * Returns the current active report editor in current active page or * current active workbench. * * @param activePageOnly * If this is true, only search the current active page, or will * search all pages in current workbench, returns the first * active report or null if not found. * @return the current active report editor, or null if no report editor is * active. */ public static FormEditor getActiveReportEditor( boolean activePageOnly ) { IWorkbenchWindow window = PlatformUI.getWorkbench( ) .getActiveWorkbenchWindow( ); if ( window != null ) { if ( activePageOnly ) { IWorkbenchPage pg = window.getActivePage( ); if ( pg != null ) { IEditorPart editor = pg.getActiveEditor( ); if ( editor != null ) { if ( editor instanceof IReportEditor ) { IEditorPart part = ( (IReportEditor) editor ).getEditorPart( ); if ( part instanceof FormEditor ) { return (FormEditor) part; } } else if ( editor instanceof FormEditor ) { return (FormEditor) editor; } } } } else { IWorkbenchPage[] pgs = window.getPages( ); for ( int i = 0; i < pgs.length; i++ ) { IWorkbenchPage pg = pgs[i]; if ( pg != null ) { IEditorPart editor = pg.getActiveEditor( ); if ( editor instanceof IReportEditor ) { IEditorPart part = ( (IReportEditor) editor ).getEditorPart( ); if ( part instanceof FormEditor ) { return (FormEditor) part; } } else if ( editor instanceof FormEditor ) { return (FormEditor) editor; } } } } } return null; } /** * Returns the current active editor part in current active page or current * active workbench. * * @param activePageOnly * If this is true, only search the current active page, or will * search all pages in current workbench, returns the first * active editor part or null if not found. * @return the current active editor part, or null if no editor part is * active. */ public static IEditorPart getActiveEditor( boolean activePageOnly ) { IWorkbenchWindow window = PlatformUI.getWorkbench( ) .getActiveWorkbenchWindow( ); if ( window != null ) { if ( activePageOnly ) { IWorkbenchPage pg = window.getActivePage( ); if ( pg != null ) { return pg.getActiveEditor( ); } } else { IWorkbenchPage[] pgs = window.getPages( ); for ( int i = 0; i < pgs.length; i++ ) { IWorkbenchPage pg = pgs[i]; if ( pg != null ) { IEditorPart editor = pg.getActiveEditor( ); if ( editor != null ) { return editor; } } } } } return null; } /** * Returns current project according to current selection. 1. If current * selection is editPart, get editor input and return associated project. 2. * If current selection is not ediPart, use first selected element, query * from its IAdaptable interface to get associated project. 3. If the above * is not working, get the first accessible project in the current workspace * and return it. 4. If none is accessible, returns null. * * @return the default project according to current selection. */ public static IProject getDefaultProject( ) { IWorkbenchWindow benchWindow = PlatformUI.getWorkbench( ) .getActiveWorkbenchWindow( ); IWorkbenchPart part = benchWindow.getPartService( ).getActivePart( ); Object selection = null; if ( part instanceof IEditorPart ) { selection = ( (IEditorPart) part ).getEditorInput( ); } else { ISelection sel = benchWindow.getSelectionService( ).getSelection( ); if ( ( sel != null ) && ( sel instanceof IStructuredSelection ) ) { selection = ( (IStructuredSelection) sel ).getFirstElement( ); } } if ( selection instanceof IAdaptable ) { IResource resource = (IResource) ( (IAdaptable) selection ).getAdapter( IResource.class ); if ( resource != null && resource.getProject( ) != null && resource.getProject( ).isAccessible( ) ) { return resource.getProject( ); } } IProject[] pjs = ResourcesPlugin.getWorkspace( ) .getRoot( ) .getProjects( ); for ( int i = 0; i < pjs.length; i++ ) { if ( pjs[i].isAccessible( ) ) { return pjs[i]; } } return null; } /** * Returns the default shell used by dialogs * * @return the active shell of the current display */ public static Shell getDefaultShell( ) { Shell shell = null; try { shell = PlatformUI.getWorkbench( ).getDisplay( ).getActiveShell( ); if ( shell == null ) { shell = Display.getCurrent( ).getActiveShell( ); } if ( shell == null ) { shell = PlatformUI.getWorkbench( ) .getActiveWorkbenchWindow( ) .getShell( ); } } catch ( Exception e ) { } if ( shell == null ) { return new Shell( ); } return shell; } public static ElementFactory getElementFactory( ) { return SessionHandleAdapter.getInstance( ) .getReportDesignHandle( ) .getElementFactory( ); } /** * Creates a new group under the given parent * * @param parent * The parent of the new group, it should be a table or a list * and should not be null. * @return true if the group created successfully, false if the creation is * cancelled or some error occurred. */ public static boolean createGroup( DesignElementHandle parent ) { Assert.isNotNull( parent ); try { return addGroup( parent, -1 ); } catch ( SemanticException e ) { ExceptionHandler.handle( e ); return false; } } /** * Creates a new group in the position under the given parent * * @param parent * The parent of the new group, it should be a table or a list * and should not be null. * @param position * insert position * @return true if the group created successfully, false if the creation is * cancelled or some error occurred. */ public static boolean createGroup( DesignElementHandle parent, int position ) { Assert.isNotNull( parent ); try { return addGroup( parent, position ); } catch ( SemanticException e ) { ExceptionHandler.handle( e ); return false; } } private static boolean addGroup( DesignElementHandle parent, int position ) throws SemanticException { GroupHandle groupHandle = null; SlotHandle slotHandle = null; // ElementFactory factory = parent.getElementFactory( ); DesignElementFactory factory = DesignElementFactory.getInstance( parent.getModuleHandle( ) ); if ( parent instanceof TableHandle ) { groupHandle = factory.newTableGroup( ); slotHandle = ( (TableHandle) parent ).getGroups( ); int columnCount = ( (TableHandle) parent ).getColumnCount( ); groupHandle.getHeader( ).add( factory.newTableRow( columnCount ) ); groupHandle.getFooter( ).add( factory.newTableRow( columnCount ) ); } else if ( parent instanceof ListHandle ) { groupHandle = factory.newListGroup( ); slotHandle = ( (ListHandle) parent ).getGroups( ); } if ( groupHandle != null && slotHandle != null ) { slotHandle.add( groupHandle, position ); // if ( !DEUtil.getDataSetList( parent ).isEmpty( ) ) {// If data set can be found or a blank group will be inserted. GroupDialog dialog = new GroupDialog( getDefaultShell( ), GroupDialog.GROUP_DLG_TITLE_NEW ); dialog.setDataSetList( DEUtil.getDataSetList( parent ) ); dialog.setInput( groupHandle ); if ( dialog.open( ) == Window.CANCEL ) {// Cancel the action return false; } } return true; } return false; } /** * Gets the first selected edit part in layout editor. Whenever the user has * deselected all edit parts, the contents edit part should be returned. * * @return the first selected EditPart or root edit part */ public static EditPart getCurrentEditPart( ) { EditPartViewer viewer = getLayoutEditPartViewer( ); if ( viewer == null ) return null; IStructuredSelection targets = (IStructuredSelection) viewer.getSelection( ); if ( targets.isEmpty( ) ) return null; return (EditPart) targets.getFirstElement( ); } /** * Gets EditPartViewer in layout editor. * * @return the EditPartViewer in layout editor, or null if not found. */ public static EditPartViewer getLayoutEditPartViewer( ) { IEditorPart part = PlatformUI.getWorkbench( ) .getActiveWorkbenchWindow( ) .getActivePage( ) .getActiveEditor( ); AbstractMultiPageEditor reportEditor = null; if ( part instanceof AbstractMultiPageEditor ) { reportEditor = (AbstractMultiPageEditor)part; } else if ( part instanceof IReportEditor ) { IEditorPart activeEditor = ( (IReportEditor) part ).getEditorPart( ); if ( activeEditor instanceof AbstractMultiPageEditor ) { reportEditor = (AbstractMultiPageEditor) activeEditor; } } if ( reportEditor == null || !( reportEditor.getActivePageInstance( ) instanceof GraphicalEditorWithFlyoutPalette ) ) { return null; } return ( (GraphicalEditorWithFlyoutPalette) reportEditor.getActivePageInstance( ) ).getGraphicalViewer( ); } /** * Creates a new grid layout without margins by default * * @return the layout created */ public static GridLayout createGridLayoutWithoutMargin( ) { GridLayout layout = new GridLayout( ); layout.marginHeight = layout.marginWidth = 0; return layout; } /** * Creates a new grid layout without margins with given the number of * columns, and whether or not the columns should be forced to have the same * width * * @param numsColumn * the number of columns in the grid * @param makeColumnsEqualWidth * whether or not the columns will have equal width * * @return the layout created */ public static GridLayout createGridLayoutWithoutMargin( int numsColumn, boolean makeColumnsEqualWidth ) { GridLayout layout = new GridLayout( numsColumn, makeColumnsEqualWidth ); layout.marginHeight = layout.marginWidth = 0; return layout; } /** * Convert the give string to GUI style, which cannot be null * * @param string * the string to convert * @return the string, or an empty string for null */ public static String convertToGUIString( String string ) { if ( string == null ) { string = ""; //$NON-NLS-1$ } return string; } /** * Convert the give string to Model style * * @param string * the string to convert * @param trim * specify if the string needs to be trimmed * @return the string, or null for an empty string */ public static String convertToModelString( String string, boolean trim ) { if ( string == null ) { return null; } if ( trim ) { string = string.trim( ); } if ( string.length( ) == 0 ) { string = null; //$NON-NLS-1$ } return string; } /** * Returns the width hint for the given control. * * @param wHint * the width hint * @param c * the control * * @return the width hint */ public static int getWidthHint( int wHint, Control c ) { boolean wrap = isWrapControl( c ); return wrap ? wHint : SWT.DEFAULT; } /** * Returns the height hint for the given control. * * @param hHint * the width hint * @param c * the control * * @return the height hint */ public static int getHeightHint( int hHint, Control c ) { if ( c instanceof Composite ) { Layout layout = ( (Composite) c ).getLayout( ); if ( layout instanceof ColumnLayout ) return hHint; } return SWT.DEFAULT; } /** * Updates the page scroll increment for given composite. * * @param scomp */ public static void updatePageIncrement( ScrolledComposite scomp ) { ScrollBar vbar = scomp.getVerticalBar( ); if ( vbar != null ) { Rectangle clientArea = scomp.getClientArea( ); int increment = clientArea.height - 5; vbar.setPageIncrement( increment ); } } private static boolean isWrapControl( Control c ) { if ( c instanceof Composite ) { return ( (Composite) c ).getLayout( ) instanceof ILayoutExtension; } return ( c.getStyle( ) & SWT.WRAP ) != 0; } /** * Returns table editpart. * * @param editParts * a list of editpart * @return the current selected table editpart, null if no table editpart, * more than one table, or other non-table editpart. Cell editpart * is also a type of table editpart. */ public static TableEditPart getTableEditPart( List editParts ) { if ( editParts == null || editParts.isEmpty( ) ) return null; int size = editParts.size( ); TableEditPart part = null; for ( int i = 0; i < size; i++ ) { Object obj = editParts.get( i ); TableEditPart currentEditPart = null; if ( obj instanceof TableEditPart ) { currentEditPart = (TableEditPart) obj; } else if ( obj instanceof TableCellEditPart ) { currentEditPart = (TableEditPart) ( (TableCellEditPart) obj ).getParent( ); } else if ( obj instanceof DummyEditpart ) { continue; } if ( part == null ) { part = currentEditPart; } // Check if select only one table if ( currentEditPart == null || currentEditPart != null && part != currentEditPart ) { return null; } } // Only table permitted if ( part instanceof GridEditPart ) return null; return part; } /** * Returns list editpart. * * @param editParts * a list of editpart * @return the current selected list editpart, null if no list editpart, * more than one list, or other list editpart. List band editpart is * also a type of list editpart. */ public static ListEditPart getListEditPart( List editParts ) { if ( editParts == null || editParts.isEmpty( ) ) return null; int size = editParts.size( ); ListEditPart part = null; for ( int i = 0; i < size; i++ ) { Object obj = editParts.get( i ); ListEditPart currentEditPart = null; if ( obj instanceof ListEditPart ) { currentEditPart = (ListEditPart) obj; } else if ( obj instanceof ListBandEditPart ) { currentEditPart = (ListEditPart) ( (ListBandEditPart) obj ).getParent( ); } if ( part == null ) { part = currentEditPart; } // Check if select only one list if ( currentEditPart == null || currentEditPart != null && part != currentEditPart ) { return null; } } return part; } /** * Tests if the specified element is on the given tree viewer * * @param treeViewer * the tree viewer * @param element * the element * * @return true if the element is on the tree, or false else. */ public static boolean containElement( AbstractTreeViewer treeViewer, Object element ) { ITreeContentProvider provider = (ITreeContentProvider) treeViewer.getContentProvider( ); Object input = treeViewer.getInput( ); if ( input instanceof Object[] ) { Object[] inputs = (Object[]) input; for ( int i = 0; i < inputs.length; i++ ) { if ( containElement( inputs[i], provider, element ) ) { return true; } } return false; } return containElement( input, provider, element ); } private static boolean containElement( Object parent, ITreeContentProvider provider, Object element ) { if ( parent == null ) { return false; } if ( parent == element || parent.equals( element ) ) { return true; } if ( provider == null ) { return false; } Object[] children = provider.getChildren( parent ); for ( int i = 0; i < children.length; i++ ) { if ( containElement( children[i], provider, element ) ) { return true; } } return false; } /** * Returns the plug-in provider * * @param pluginId * the identify of the plugin * * @return the plug-in provider, or null if the plug-in is not found */ public static String getPluginProvider( String pluginId ) { return getBundleValue( pluginId, org.osgi.framework.Constants.BUNDLE_VENDOR ); } /** * Returns the plug-in name * * @param pluginId * the identify of the plugin * * @return the plug-in name, or null if the plug-in is not found */ public static String getPluginName( String pluginId ) { return getBundleValue( pluginId, org.osgi.framework.Constants.BUNDLE_NAME ); } /** * Returns the plug-in version * * @param pluginId * the identify of the plugin * * @return the plug-in version, or null if the plug-in is not found */ public static String getPluginVersion( String pluginId ) { return getBundleValue( pluginId, org.osgi.framework.Constants.BUNDLE_VERSION ); } private static String getBundleValue( String pluginId, String key ) { Assert.isNotNull( pluginId ); Bundle bundle = Platform.getBundle( pluginId ); if ( bundle != null ) { return (String) bundle.getHeaders( ).get( key ); } return null; } public static void resetViewSelection( final EditPartViewer viewer, final boolean notofyToMedia ) { final List list = new ArrayList( ( (StructuredSelection) viewer.getSelection( ) ).toList( ) ); boolean hasColumnOrRow = false; for ( int i = 0; i < list.size( ); i++ ) { if ( list.get( i ) instanceof TableEditPart.DummyRowEditPart || list.get( i ) instanceof TableEditPart.DummyColumnEditPart ) { hasColumnOrRow = true; break; } } if ( hasColumnOrRow ) { int selectionType = 0;// 0 select row 1select colum TableEditPart part = null; int[] selectContents = new int[0]; for ( int i = 0; i < list.size( ); i++ ) { Object obj = list.get( i ); int number = -1; if ( obj instanceof TableEditPart.DummyRowEditPart ) { selectionType = 0;// select row number = ( (TableEditPart.DummyRowEditPart) obj ).getRowNumber( ); } else if ( obj instanceof TableEditPart.DummyColumnEditPart ) { selectionType = 1;// select column number = ( (TableEditPart.DummyColumnEditPart) obj ).getColumnNumber( ); } else if ( obj instanceof TableCellEditPart ) { part = (TableEditPart) ( (TableCellEditPart) obj ).getParent( ); } if ( number != -1 ) { int lenegth = selectContents.length; int[] temp = new int[lenegth + 1]; System.arraycopy( selectContents, 0, temp, 0, lenegth ); temp[lenegth] = number; selectContents = temp; } } if ( part == null || selectContents.length == 0 || !viewer.getControl( ).isVisible( ) ) { return; } if ( selectionType == 0 ) { part.selectRow( selectContents ); } else if ( selectionType == 1 ) { part.selectColumn( selectContents ); } } else { if ( viewer.getControl( ).isVisible( ) ) { if ( viewer instanceof DeferredGraphicalViewer ) ( (DeferredGraphicalViewer) viewer ).setSelection( new StructuredSelection( list ), notofyToMedia ); } } } /** * Creates a folder resource given the folder handle. * * @param folderHandle * the folder handle to create a folder resource for * @param monitor * the progress monitor to show visual progress with * @exception CoreException * if the operation fails * @exception OperationCanceledException * if the operation is canceled */ public static void createFolder( IFolder folderHandle, IProgressMonitor monitor ) throws CoreException { try { // Create the folder resource in the workspace // already if ( !folderHandle.exists( ) ) { IPath path = folderHandle.getFullPath( ); IWorkspaceRoot root = ResourcesPlugin.getWorkspace( ).getRoot( ); int numSegments = path.segmentCount( ); if ( numSegments > 2 && !root.getFolder( path.removeLastSegments( 1 ) ) .exists( ) ) { // If the direct parent of the path doesn't exist, try // to create the // necessary directories. for ( int i = numSegments - 2; i > 0; i { IFolder folder = root.getFolder( path.removeLastSegments( i ) ); if ( !folder.exists( ) ) { folder.create( false, true, monitor ); } } } folderHandle.create( false, true, monitor ); } } catch ( CoreException e ) { // If the folder already existed locally, just refresh to get // contents if ( e.getStatus( ).getCode( ) == IResourceStatus.PATH_OCCUPIED ) folderHandle.refreshLocal( IResource.DEPTH_INFINITE, new SubProgressMonitor( monitor, 500 ) ); else throw e; } if ( monitor.isCanceled( ) ) throw new OperationCanceledException( ); } /** * @return Report Designer UI plugin installation directory as OS string. */ public static String getHomeDirectory( ) { URL url = ReportPlugin.getDefault( ).getBundle( ).getEntry( "/" ); String home = null; try { home = Platform.resolve( url ).getPath( ); } catch ( IOException e ) { e.printStackTrace( ); } return home; } /** * Creates a blank label under the given parent. * * @return the label created */ public static Label createBlankLabel( Composite parent ) { Label label = new Label( parent, SWT.NONE ); label.setVisible( false ); return label; } /** * Includes the library into within the given module. * * @param moduleHandle * the handle module * @param libraryPath * the full path of the library * @return true if it included successfully, or false if the operation * failed. */ public static boolean includeLibrary( ModuleHandle moduleHandle, String libraryPath ) throws DesignFileException, SemanticException { String namespace = getLibraryNamespace( moduleHandle, libraryPath ); if ( namespace != null ) { moduleHandle.includeLibrary( DEUtil.getRelativedPath( moduleHandle.getFileName( ), libraryPath ), namespace ); // ExceptionHandler.openMessageBox( MSG_DIALOG_TITLE, // MessageFormat.format( MSG_DIALOG_MSG, new String[]{ // libraryPath // SWT.ICON_INFORMATION ); return true; } return false; } /** * Includes the library into within the given module. * * @param moduleHandle * the handle module * @param libraryHandle * the library to include. * @return true if it included successfully, or false if the operation * failed. */ public static boolean includeLibrary( ModuleHandle moduleHandle, LibraryHandle libraryHandle ) throws DesignFileException, SemanticException { if ( moduleHandle != libraryHandle && !moduleHandle.isInclude( libraryHandle ) ) { return includeLibrary( moduleHandle, libraryHandle.getFileName( ) ); } return true; } /** * Includes the library into within the current module. * * @param libraryHandle * the library to include. * @return true if it included successfully, or false if the operation * failed. */ public static boolean includeLibrary( LibraryHandle libraryHandle ) throws DesignFileException, SemanticException { return includeLibrary( SessionHandleAdapter.getInstance( ) .getReportDesignHandle( ), libraryHandle ); } /** * Returns the name for the file * * @param filePath * the full path of the file * @return Returns the name of the file */ public static String getSimpleFileName( String filePath ) { return new File( filePath ).getName( ); } /** * Returns the namespace of the library for inculde * * @param handle * the module handle to include the library * @param libraryPath * the full path of the library file to include * @return the namespace used to include, or null if the user cancels this * operator */ private static String getLibraryNamespace( ModuleHandle handle, String libraryPath ) { String namespace = getSimpleFileName( libraryPath ).split( "\\." )[0]; if ( handle.getLibrary( namespace ) != null ) { ImportLibraryDialog dialog = new ImportLibraryDialog( namespace ); if ( dialog.open( ) == Dialog.OK ) { namespace = (String) dialog.getResult( ); } else { namespace = null; } } return namespace; } public static ThemeHandle themeInModuleHandle(ThemeHandle handle, ModuleHandle moduleHandle) { String themeName = handle.getName( ).trim( ); String themeFileName = handle.getModuleHandle( ).getFileName( ); LibraryHandle libHandle = moduleHandle.findLibrary(themeFileName); if(libHandle == null) { return null; } Iterator iterator = moduleHandle.getAllThemes( ).iterator( ); if ( iterator != null ) { while ( iterator.hasNext( ) ) { ReportElementHandle elementHandle = (ReportElementHandle) iterator.next( ); if(elementHandle.getName( ).trim( ).equals( themeName ) && elementHandle.getRoot( ) == libHandle) { return (ThemeHandle)elementHandle; } } } return null; } public static ThemeHandle applyTheme(ThemeHandle handle, ModuleHandle moduleHandle, LibraryHandle library) { if(handle.getRoot( ) == moduleHandle) { try { moduleHandle.setTheme( handle ); } catch ( SemanticException e ) { // TODO Auto-generated catch block e.printStackTrace(); } return handle; } ThemeHandle applyThemeHandle = themeInModuleHandle(handle,moduleHandle); if(applyThemeHandle != null) { try { moduleHandle.setTheme( applyThemeHandle ); } catch ( SemanticException e ) { GUIException exception = GUIException.createGUIException( ReportPlugin.REPORT_UI, e, "Library.DND.messages.cannotApplyTheme" );//$NON-NLS-1$ ExceptionHandler.handle( exception ); e.printStackTrace(); } } return applyThemeHandle; } }
package com.elmakers.mine.bukkit.magic; import javax.annotation.Nonnull; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.entity.Creature; import org.bukkit.entity.Entity; import com.elmakers.mine.bukkit.api.magic.Mage; import com.elmakers.mine.bukkit.api.magic.MageController; public class MobTrigger extends CustomTrigger { boolean requiresTarget = false; public MobTrigger(@Nonnull MageController controller, @Nonnull String key, @Nonnull ConfigurationSection configuration) { super(controller, key, configuration); requiresTarget = configuration.getBoolean("requires_target"); } @Override public boolean isValid(Mage mage) { if (!super.isValid(mage)) return false; if (requiresTarget) { Entity entity = mage.getEntity(); if (entity instanceof Creature) { return ((Creature)entity).getTarget() != null; } } return true; } }
package com.elmakers.mine.bukkit.utility; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.elmakers.mine.bukkit.block.MaterialAndData; import com.elmakers.mine.bukkit.integration.VaultController; import org.apache.commons.lang.StringEscapeUtils; import org.bukkit.ChatColor; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.BookMeta; import org.bukkit.inventory.meta.ItemMeta; public class Messages implements com.elmakers.mine.bukkit.api.magic.Messages { private static String PARAMETER_PATTERN_STRING = "\\$([a-zA-Z0-9]+)"; private static Pattern PARAMETER_PATTERN = Pattern.compile(PARAMETER_PATTERN_STRING); private static Random random = new Random(); private Map<String, String> messageMap = new HashMap<>(); private Map<String, List<String>> randomized = new HashMap<>(); private ConfigurationSection configuration = null; public Messages() { } public void load(ConfigurationSection messages) { configuration = messages; Collection<String> keys = messages.getKeys(true); for (String key : keys) { if (key.equals("randomized")) { ConfigurationSection randomSection = messages.getConfigurationSection(key); Set<String> randomKeys = randomSection.getKeys(false); for (String randomKey : randomKeys) { randomized.put(randomKey, randomSection.getStringList(randomKey)); } } else if (messages.isString(key)) { String value = messages.getString(key); value = ChatColor.translateAlternateColorCodes('&', StringEscapeUtils.unescapeHtml(value)); messageMap.put(key, value); } } } @Override public List<String> getAll(String path) { if (configuration == null) return new ArrayList<>(); return configuration.getStringList(path); } public void reset() { messageMap.clear(); } @Override public boolean containsKey(String key) { return messageMap.containsKey(key); } @Override public String get(String key, String defaultValue) { if (messageMap.containsKey(key)) { return messageMap.get(key); } if (defaultValue == null) { return ""; } return ChatColor.translateAlternateColorCodes('&', defaultValue); } @Override public String get(String key) { return get(key, key); } @Override public String getParameterized(String key, String paramName, String paramValue) { return get(key, key).replace(paramName, paramValue); } @Override public String getParameterized(String key, String paramName1, String paramValue1, String paramName2, String paramValue2) { return get(key, key).replace(paramName1, paramValue1).replace(paramName2, paramValue2); } @Override public String getRandomized(String key) { if (!randomized.containsKey(key)) return null; List<String> options = randomized.get(key); if (options.size() == 0) return ""; return options.get(random.nextInt(options.size())); } @Override public String escape(String source) { Matcher matcher = PARAMETER_PATTERN.matcher(source); String result = source; while (matcher.find()) { String key = matcher.group(1); if (key != null) { String randomized = getRandomized(key); if (randomized != null) { result = result.replace("$" + key, randomized); } } } return result; } @Override public String describeItem(ItemStack item) { String displayName = null; if (item.hasItemMeta()) { ItemMeta meta = item.getItemMeta(); displayName = meta.getDisplayName(); if ((displayName == null || displayName.isEmpty()) && meta instanceof BookMeta) { BookMeta book = (BookMeta)meta; displayName = book.getTitle(); } } if (displayName == null || displayName.isEmpty()) { MaterialAndData material = new MaterialAndData(item); displayName = material.getName(); } return displayName; } @Override public String describeCurrency(double amount) { VaultController vault = VaultController.getInstance(); String formatted = vault.format(amount); if (!VaultController.hasEconomy()) { formatted = get("costs.currency_amount").replace("$amount", formatted); } return formatted; } @Override public String getCurrency() { VaultController vault = VaultController.getInstance(); if (VaultController.hasEconomy()) { return vault.getCurrency(); } return get("costs.currency"); } @Override public String getCurrencyPlural() { VaultController vault = VaultController.getInstance(); if (VaultController.hasEconomy()) { return vault.getCurrencyPlural(); } return get("costs.currency_plural"); } @Override public String formatList(String basePath, Collection<String> nodes, String nameKey) { StringBuilder buffer = new StringBuilder(); for (String node : nodes) { if (buffer.length() != 0) { buffer.append(", "); } String path = node; if (basePath != null) { path = basePath + "." + path; } if (nameKey != null) { path = path + "." + nameKey; } node = get(path, node); buffer.append(node); } return buffer.toString(); } @Override public String getLevelString(String templateName, float amount) { return getLevelString(templateName, amount, 1); } @Override public String getLevelString(String templateName, float amount, float max) { String templateString = get(templateName, ""); if (templateString.contains("$roman")) { if (max != 1) { amount = amount / max; } templateString = templateString.replace("$roman", getRomanString(amount)); } return templateString.replace("$amount", Integer.toString((int) amount)); } @Override public String getPercentageString(String templateName, float amount) { String templateString = get(templateName, ""); return templateString.replace("$amount", Integer.toString((int)(amount * 100))); } private String getRomanString(float amount) { String roman = ""; if (amount > 1) { roman = get("wand.enchantment_level_max"); } else if (amount > 0.8) { roman = get("wand.enchantment_level_5"); } else if (amount > 0.6) { roman = get("wand.enchantment_level_4"); } else if (amount > 0.4) { roman = get("wand.enchantment_level_3"); } else if (amount > 0.2) { roman = get("wand.enchantment_level_2"); } else { roman = get("wand.enchantment_level_1"); } return roman; } }
package com.smartdevicelink.managers.screen; import com.smartdevicelink.AndroidTestCase2; import com.smartdevicelink.managers.CompletionListener; import com.smartdevicelink.managers.file.FileManager; import com.smartdevicelink.managers.file.MultipleFileCompletionListener; import com.smartdevicelink.managers.file.filetypes.SdlArtwork; import com.smartdevicelink.protocol.enums.FunctionID; import com.smartdevicelink.proxy.interfaces.ISdl; import com.smartdevicelink.proxy.rpc.Image; import com.smartdevicelink.proxy.rpc.OnHMIStatus; import com.smartdevicelink.proxy.rpc.Show; import com.smartdevicelink.proxy.rpc.SoftButton; import com.smartdevicelink.proxy.rpc.SoftButtonCapabilities; import com.smartdevicelink.proxy.rpc.WindowCapability; import com.smartdevicelink.proxy.rpc.enums.FileType; import com.smartdevicelink.proxy.rpc.enums.HMILevel; import com.smartdevicelink.proxy.rpc.enums.ImageType; import com.smartdevicelink.proxy.rpc.enums.SoftButtonType; import com.smartdevicelink.proxy.rpc.enums.StaticIconName; import com.smartdevicelink.proxy.rpc.listeners.OnRPCNotificationListener; import com.smartdevicelink.test.Validator; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import java.util.Arrays; import java.util.Collections; import java.util.List; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; /** * This is a unit test class for the SmartDeviceLink library manager class : * {@link SoftButtonManager} */ public class SoftButtonManagerTests extends AndroidTestCase2 { private SoftButtonManager softButtonManager; private boolean fileManagerUploadArtworksGotCalled; private boolean internalInterfaceSendRPCGotCalled; private boolean softButtonMangerUpdateCompleted; private int softButtonObject1Id = 1000, softButtonObject2Id = 2000; private SoftButtonObject softButtonObject1, softButtonObject2; private SoftButtonState softButtonState1, softButtonState2, softButtonState3, softButtonState4; @Override public void setUp() throws Exception { super.setUp(); // When internalInterface.addOnRPCNotificationListener(FunctionID.ON_HMI_STATUS, OnRPCNotificationListener) is called // inside SoftButtonManager, respond with a fake HMILevel.HMI_FULL response to let the SoftButtonManager continue working. ISdl internalInterface = mock(ISdl.class); Answer<Void> onHMIStatusAnswer = new Answer<Void>() { @Override public Void answer(InvocationOnMock invocation) { Object[] args = invocation.getArguments(); OnRPCNotificationListener onHMIStatusListener = (OnRPCNotificationListener) args[1]; OnHMIStatus onHMIStatusFakeNotification = new OnHMIStatus(); onHMIStatusFakeNotification.setHmiLevel(HMILevel.HMI_FULL); onHMIStatusListener.onNotified(onHMIStatusFakeNotification); return null; } }; doAnswer(onHMIStatusAnswer).when(internalInterface).addOnRPCNotificationListener(eq(FunctionID.ON_HMI_STATUS), any(OnRPCNotificationListener.class)); // When fileManager.uploadArtworks() is called inside the SoftButtonManager, respond with // a fake onComplete() callback to let the SoftButtonManager continue working. FileManager fileManager = mock(FileManager.class); Answer<Void> onFileManagerUploadAnswer = new Answer<Void>() { @Override public Void answer(InvocationOnMock invocation) { fileManagerUploadArtworksGotCalled = true; Object[] args = invocation.getArguments(); MultipleFileCompletionListener multipleFileCompletionListener = (MultipleFileCompletionListener) args[1]; multipleFileCompletionListener.onComplete(null); return null; } }; doAnswer(onFileManagerUploadAnswer).when(fileManager).uploadArtworks(any(List.class), any(MultipleFileCompletionListener.class)); // Create softButtonManager softButtonManager = new SoftButtonManager(internalInterface, fileManager); // When internalInterface.sendRPC() is called inside SoftButtonManager: // 1) respond with a fake onResponse() callback to let the SoftButtonManager continue working Answer<Void> onSendShowRPCAnswer = new Answer<Void>() { @Override public Void answer(InvocationOnMock invocation) { internalInterfaceSendRPCGotCalled = true; Object[] args = invocation.getArguments(); Show show = (Show) args[0]; show.getOnRPCResponseListener().onResponse(0, null); assertEquals(show.getMainField1(), softButtonManager.getCurrentMainField1()); assertEquals(show.getSoftButtons().size(), softButtonManager.createSoftButtonsForCurrentState().size()); return null; } }; doAnswer(onSendShowRPCAnswer).when(internalInterface).sendRPC(any(Show.class)); // Create soft button objects softButtonState1 = new SoftButtonState("object1-state1", "o1s1", new SdlArtwork("image1", FileType.GRAPHIC_PNG, 1, true)); softButtonState2 = new SoftButtonState("object1-state2", "o1s2", new SdlArtwork(StaticIconName.ALBUM)); softButtonObject1 = new SoftButtonObject("object1", Arrays.asList(softButtonState1, softButtonState2), softButtonState1.getName(), null); softButtonObject1.setButtonId(softButtonObject1Id); softButtonState3 = new SoftButtonState("object2-state1", "o2s1", null); softButtonState4 = new SoftButtonState("object2-state2", "o2s2", new SdlArtwork("image3", FileType.GRAPHIC_PNG, 3, true)); softButtonObject2 = new SoftButtonObject("object2", Arrays.asList(softButtonState3, softButtonState4), softButtonState3.getName(), null); softButtonObject2.setButtonId(softButtonObject2Id); } @Override public void tearDown() throws Exception { super.tearDown(); } public void testSoftButtonManagerUpdate() { // Reset the boolean variables fileManagerUploadArtworksGotCalled = false; internalInterfaceSendRPCGotCalled = false; softButtonMangerUpdateCompleted = false; SoftButtonCapabilities softCap = new SoftButtonCapabilities(); softCap.setImageSupported(true); WindowCapability defaultCap = new WindowCapability(); defaultCap.setSoftButtonCapabilities(Collections.singletonList(softCap)); softButtonManager.defaultMainWindowCapability = defaultCap; // Test batch update softButtonManager.setBatchUpdates(true); List<SoftButtonObject> softButtonObjects = Arrays.asList(softButtonObject1, softButtonObject2); softButtonManager.setSoftButtonObjects(Arrays.asList(softButtonObject1, softButtonObject2)); softButtonManager.setBatchUpdates(false); softButtonManager.update(new CompletionListener() { @Override public void onComplete(boolean success) { softButtonMangerUpdateCompleted = true; } }); // Test single update, setCurrentMainField1, and transitionToNextState softButtonManager.setCurrentMainField1("It is Wednesday my dudes!"); softButtonObject1.transitionToNextState(); // Check that everything got called as expected assertTrue("FileManager.uploadArtworks() did get called", fileManagerUploadArtworksGotCalled); assertTrue("InternalInterface.sendRPC() did not get called", internalInterfaceSendRPCGotCalled); assertTrue("SoftButtonManger update onComplete() did not get called", softButtonMangerUpdateCompleted); // Test getSoftButtonObjects assertEquals("Returned softButtonObjects value doesn't match the expected value", softButtonObjects, softButtonManager.getSoftButtonObjects()); } public void testSoftButtonManagerGetSoftButtonObject() { softButtonManager.setSoftButtonObjects(Arrays.asList(softButtonObject1, softButtonObject2)); // Test get by valid name assertEquals("Returned SoftButtonObject doesn't match the expected value", softButtonObject2, softButtonManager.getSoftButtonObjectByName("object2")); // Test get by invalid name assertNull("Returned SoftButtonObject doesn't match the expected value", softButtonManager.getSoftButtonObjectByName("object300")); // Test get by valid id assertEquals("Returned SoftButtonObject doesn't match the expected value", softButtonObject2, softButtonManager.getSoftButtonObjectById(softButtonObject2Id)); // Test get by invalid id assertNull("Returned SoftButtonObject doesn't match the expected value", softButtonManager.getSoftButtonObjectById(5555)); } public void testSoftButtonState(){ // Test SoftButtonState.getName() String nameExpectedValue = "object1-state1"; assertEquals("Returned state name doesn't match the expected value", nameExpectedValue, softButtonState1.getName()); // Test SoftButtonState.getArtwork() SdlArtwork artworkExpectedValue = new SdlArtwork("image1", FileType.GRAPHIC_PNG, 1, true); assertTrue("Returned SdlArtwork doesn't match the expected value", Validator.validateSdlFile(artworkExpectedValue, softButtonState1.getArtwork())); SdlArtwork artworkExpectedValue2 = new SdlArtwork(StaticIconName.ALBUM); assertTrue("Returned SdlArtwork doesn't match the expected value", Validator.validateSdlFile(artworkExpectedValue2, softButtonState2.getArtwork())); // Test SoftButtonState.getSoftButton() SoftButton softButtonExpectedValue = new SoftButton(SoftButtonType.SBT_BOTH, SoftButtonObject.SOFT_BUTTON_ID_NOT_SET_VALUE); softButtonExpectedValue.setText("o1s1"); softButtonExpectedValue.setImage(new Image(artworkExpectedValue.getName(), ImageType.DYNAMIC)); SoftButton actual = softButtonState1.getSoftButton(); assertTrue("Returned SoftButton doesn't match the expected value", Validator.validateSoftButton(softButtonExpectedValue, softButtonState1.getSoftButton())); } public void testSoftButtonObject(){ // Test SoftButtonObject.getName() assertEquals("Returned object name doesn't match the expected value", "object1", softButtonObject1.getName()); // Test SoftButtonObject.getCurrentState() assertEquals("Returned current state doesn't match the expected value", softButtonState1, softButtonObject1.getCurrentState()); // Test SoftButtonObject.getCurrentStateName() assertEquals("Returned current state name doesn't match the expected value", softButtonState1.getName(), softButtonObject1.getCurrentStateName()); // Test SoftButtonObject.getButtonId() assertEquals("Returned button Id doesn't match the expected value", softButtonObject1Id, softButtonObject1.getButtonId()); // Test SoftButtonObject.getCurrentStateSoftButton() SoftButton softButtonExpectedValue = new SoftButton(SoftButtonType.SBT_TEXT, softButtonObject2Id); softButtonExpectedValue.setText("o2s1"); assertTrue("Returned current state SoftButton doesn't match the expected value", Validator.validateSoftButton(softButtonExpectedValue, softButtonObject2.getCurrentStateSoftButton())); // Test SoftButtonObject.getStates() assertEquals("Returned object states doesn't match the expected value", Arrays.asList(softButtonState1, softButtonState2), softButtonObject1.getStates()); // Test SoftButtonObject.transitionToNextState() assertEquals(softButtonState1, softButtonObject1.getCurrentState()); softButtonObject1.transitionToNextState(); assertEquals(softButtonState2, softButtonObject1.getCurrentState()); // Test SoftButtonObject.transitionToStateByName() - transitioning to a none existing state boolean success = softButtonObject1.transitionToStateByName("none existing name"); assertFalse(success); // Test SoftButtonObject.transitionToStateByName() - transitioning to an existing state success = softButtonObject1.transitionToStateByName("object1-state1"); assertTrue(success); assertEquals(softButtonState1, softButtonObject1.getCurrentState()); } public void testAssigningIdsToSoftButtonObjects() { SoftButtonObject sbo1, sbo2, sbo3, sbo4, sbo5; // Case 1 - don't set id for any button (Manager should set ids automatically starting from 1 and up) sbo1 = new SoftButtonObject(null, Collections.EMPTY_LIST, null, null); sbo2 = new SoftButtonObject(null, Collections.EMPTY_LIST, null, null); sbo3 = new SoftButtonObject(null, Collections.EMPTY_LIST, null, null); sbo4 = new SoftButtonObject(null, Collections.EMPTY_LIST, null, null); sbo5 = new SoftButtonObject(null, Collections.EMPTY_LIST, null, null); softButtonManager.checkAndAssignButtonIds(Arrays.asList(sbo1, sbo2, sbo3, sbo4, sbo5)); assertEquals("SoftButtonObject id doesn't match the expected value", 1, sbo1.getButtonId()); assertEquals("SoftButtonObject id doesn't match the expected value", 2, sbo2.getButtonId()); assertEquals("SoftButtonObject id doesn't match the expected value", 3, sbo3.getButtonId()); assertEquals("SoftButtonObject id doesn't match the expected value", 4, sbo4.getButtonId()); assertEquals("SoftButtonObject id doesn't match the expected value", 5, sbo5.getButtonId()); // Case 2 - Set ids for all buttons (Manager shouldn't alter the ids set by developer) sbo1 = new SoftButtonObject(null, Collections.EMPTY_LIST, null, null); sbo1.setButtonId(100); sbo2 = new SoftButtonObject(null, Collections.EMPTY_LIST, null, null); sbo2.setButtonId(200); sbo3 = new SoftButtonObject(null, Collections.EMPTY_LIST, null, null); sbo3.setButtonId(300); sbo4 = new SoftButtonObject(null, Collections.EMPTY_LIST, null, null); sbo4.setButtonId(400); sbo5 = new SoftButtonObject(null, Collections.EMPTY_LIST, null, null); sbo5.setButtonId(500); softButtonManager.checkAndAssignButtonIds(Arrays.asList(sbo1, sbo2, sbo3, sbo4, sbo5)); assertEquals("SoftButtonObject id doesn't match the expected value", 100, sbo1.getButtonId()); assertEquals("SoftButtonObject id doesn't match the expected value", 200, sbo2.getButtonId()); assertEquals("SoftButtonObject id doesn't match the expected value", 300, sbo3.getButtonId()); assertEquals("SoftButtonObject id doesn't match the expected value", 400, sbo4.getButtonId()); assertEquals("SoftButtonObject id doesn't match the expected value", 500, sbo5.getButtonId()); // Case 3 - Set ids for some buttons (Manager shouldn't alter the ids set by developer. And it should assign ids for the ones that don't have id) sbo1 = new SoftButtonObject(null, Collections.EMPTY_LIST, null, null); sbo1.setButtonId(50); sbo2 = new SoftButtonObject(null, Collections.EMPTY_LIST, null, null); sbo3 = new SoftButtonObject(null, Collections.EMPTY_LIST, null, null); sbo4 = new SoftButtonObject(null, Collections.EMPTY_LIST, null, null); sbo4.setButtonId(100); sbo5 = new SoftButtonObject(null, Collections.EMPTY_LIST, null, null); softButtonManager.checkAndAssignButtonIds(Arrays.asList(sbo1, sbo2, sbo3, sbo4, sbo5)); assertEquals("SoftButtonObject id doesn't match the expected value", 50, sbo1.getButtonId()); assertEquals("SoftButtonObject id doesn't match the expected value", 101, sbo2.getButtonId()); assertEquals("SoftButtonObject id doesn't match the expected value", 102, sbo3.getButtonId()); assertEquals("SoftButtonObject id doesn't match the expected value", 100, sbo4.getButtonId()); assertEquals("SoftButtonObject id doesn't match the expected value", 103, sbo5.getButtonId()); } /** * Test custom overridden softButtonState equals method */ public void testSoftButtonStateEquals() { assertFalse(softButtonState1.equals(softButtonState2)); SdlArtwork artwork1 = new SdlArtwork("image1", FileType.GRAPHIC_PNG, 1, true); SdlArtwork artwork2 = new SdlArtwork("image2", FileType.GRAPHIC_PNG, 1, true); // Case 1: object is null, assertFalse softButtonState1 = new SoftButtonState("object1-state1", "o1s1", artwork1); softButtonState2 = null; assertFalse(softButtonState1.equals(softButtonState2)); // Case 2 SoftButtonObjects are the same, assertTrue assertTrue(softButtonState1.equals(softButtonState1)); // Case 3: object is not an instance of SoftButtonState, assertFalse assertFalse(softButtonState1.equals(artwork1)); // Case 4: different artwork, assertFalse softButtonState2 = new SoftButtonState("object1-state1", "o1s1", artwork2); assertFalse(softButtonState1.equals(softButtonState2)); // Case 5: different name, assertFalse softButtonState2 = new SoftButtonState("object1-state1 different name", "o1s1", artwork1); assertFalse(softButtonState1.equals(softButtonState2)); // Case 6 they are equal, assertTrue softButtonState2 = new SoftButtonState("object1-state1", "o1s1", artwork1); assertTrue(softButtonState1.equals(softButtonState2)); } }
package nodomain.freeyourgadget.gadgetbridge.service.devices.amazfitbip; import android.bluetooth.BluetoothGatt; import android.bluetooth.BluetoothGattCharacteristic; import android.content.Context; import android.net.Uri; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.Locale; import java.util.SimpleTimeZone; import java.util.UUID; import nodomain.freeyourgadget.gadgetbridge.GBApplication; import nodomain.freeyourgadget.gadgetbridge.devices.huami.HuamiFWHelper; import nodomain.freeyourgadget.gadgetbridge.devices.huami.HuamiWeatherConditions; import nodomain.freeyourgadget.gadgetbridge.devices.huami.amazfitbip.AmazfitBipFWHelper; import nodomain.freeyourgadget.gadgetbridge.devices.huami.amazfitbip.AmazfitBipService; import nodomain.freeyourgadget.gadgetbridge.devices.miband.MiBand2Service; import nodomain.freeyourgadget.gadgetbridge.impl.GBDevice; import nodomain.freeyourgadget.gadgetbridge.model.CallSpec; import nodomain.freeyourgadget.gadgetbridge.model.DeviceType; import nodomain.freeyourgadget.gadgetbridge.model.NotificationSpec; import nodomain.freeyourgadget.gadgetbridge.model.NotificationType; import nodomain.freeyourgadget.gadgetbridge.model.Weather; import nodomain.freeyourgadget.gadgetbridge.model.WeatherSpec; import nodomain.freeyourgadget.gadgetbridge.service.btle.TransactionBuilder; import nodomain.freeyourgadget.gadgetbridge.service.btle.actions.ConditionalWriteAction; import nodomain.freeyourgadget.gadgetbridge.service.btle.profiles.alertnotification.AlertCategory; import nodomain.freeyourgadget.gadgetbridge.service.btle.profiles.alertnotification.AlertNotificationProfile; import nodomain.freeyourgadget.gadgetbridge.service.btle.profiles.alertnotification.NewAlert; import nodomain.freeyourgadget.gadgetbridge.service.devices.amazfitbip.operations.AmazfitBipFetchLogsOperation; import nodomain.freeyourgadget.gadgetbridge.service.devices.huami.HuamiIcon; import nodomain.freeyourgadget.gadgetbridge.service.devices.miband.NotificationStrategy; import nodomain.freeyourgadget.gadgetbridge.service.devices.miband2.MiBand2Support; import nodomain.freeyourgadget.gadgetbridge.util.StringUtils; import nodomain.freeyourgadget.gadgetbridge.util.Version; public class AmazfitBipSupport extends MiBand2Support { private static final Logger LOG = LoggerFactory.getLogger(AmazfitBipSupport.class); public AmazfitBipSupport() { super(LOG); } @Override public NotificationStrategy getNotificationStrategy() { return new AmazfitBipTextNotificationStrategy(this); } @Override public void onNotification(NotificationSpec notificationSpec) { if (notificationSpec.type == NotificationType.GENERIC_ALARM_CLOCK) { onAlarmClock(notificationSpec); return; } String senderOrTiltle = StringUtils.getFirstOf(notificationSpec.sender, notificationSpec.title); String message = StringUtils.truncate(senderOrTiltle, 32) + "\0"; if (notificationSpec.subject != null) { message += StringUtils.truncate(notificationSpec.subject, 128) + "\n\n"; } if (notificationSpec.body != null) { message += StringUtils.truncate(notificationSpec.body, 128); } try { TransactionBuilder builder = performInitialized("new notification"); AlertNotificationProfile<?> profile = new AlertNotificationProfile(this); profile.setMaxLength(230); byte customIconId = HuamiIcon.mapToIconId(notificationSpec.type); AlertCategory alertCategory = AlertCategory.CustomHuami; // The SMS icon for AlertCategory.SMS is unique and not available as iconId if (notificationSpec.type == NotificationType.GENERIC_SMS) { alertCategory = AlertCategory.SMS; } // EMAIL icon does not work in FW 0.0.8.74, it did in 0.0.7.90 else if (customIconId == HuamiIcon.EMAIL) { alertCategory = AlertCategory.Email; } NewAlert alert = new NewAlert(alertCategory, 1, message, customIconId); profile.newAlert(builder, alert); builder.queue(getQueue()); } catch (IOException ex) { LOG.error("Unable to send notification to Amazfit Bip", ex); } } @Override public void onFindDevice(boolean start) { CallSpec callSpec = new CallSpec(); callSpec.command = start ? CallSpec.CALL_INCOMING : CallSpec.CALL_END; callSpec.name = "Gadgetbridge"; onSetCallState(callSpec); } @Override public void handleButtonEvent() { // ignore } @Override protected AmazfitBipSupport setDisplayItems(TransactionBuilder builder) { /* LOG.info("Enabling all display items"); // This will brick the watch, don't enable it! byte[] data = new byte[]{ENDPOINT_DISPLAY_ITEMS, (byte) 0xff, 0x01, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08}; builder.write(getCharacteristic(MiBand2Service.UUID_CHARACTERISTIC_3_CONFIGURATION), data); */ return this; } @Override public void onSendWeather(WeatherSpec weatherSpec) { if (gbDevice.getFirmwareVersion() == null) { LOG.warn("Device not initialized yet, so not sending weather info"); return; } boolean supportsConditionString = false; Version version = new Version(gbDevice.getFirmwareVersion()); if (version.compareTo(new Version("0.0.8.74")) >= 0) { supportsConditionString = true; } int tz_offset_hours = SimpleTimeZone.getDefault().getOffset(weatherSpec.timestamp * 1000L) / (1000 * 60 * 60); try { TransactionBuilder builder; builder = performInitialized("Sending current temp"); byte condition = HuamiWeatherConditions.mapToAmazfitBipWeatherCode(weatherSpec.currentConditionCode); int length = 8; if (supportsConditionString) { length += weatherSpec.currentCondition.getBytes().length + 1; } ByteBuffer buf = ByteBuffer.allocate(length); buf.order(ByteOrder.LITTLE_ENDIAN); buf.put((byte) 2); buf.putInt(weatherSpec.timestamp); buf.put((byte) (tz_offset_hours * 4)); buf.put(condition); buf.put((byte) (weatherSpec.currentTemp - 273)); if (supportsConditionString) { buf.put(weatherSpec.currentCondition.getBytes()); buf.put((byte) 0); } builder.write(getCharacteristic(AmazfitBipService.UUID_CHARACTERISTIC_WEATHER), buf.array()); builder.queue(getQueue()); } catch (Exception ex) { LOG.error("Error sending current weather", ex); } try { TransactionBuilder builder; builder = performInitialized("Sending air quality index"); int length = 8; String aqiString = "(n/a)"; if (supportsConditionString) { length += aqiString.getBytes().length + 1; } ByteBuffer buf = ByteBuffer.allocate(length); buf.order(ByteOrder.LITTLE_ENDIAN); buf.put((byte) 4); buf.putInt(weatherSpec.timestamp); buf.put((byte) (tz_offset_hours * 4)); buf.putShort((short) 0); if (supportsConditionString) { buf.put(aqiString.getBytes()); buf.put((byte) 0); } builder.write(getCharacteristic(AmazfitBipService.UUID_CHARACTERISTIC_WEATHER), buf.array()); builder.queue(getQueue()); } catch (IOException ex) { LOG.error("Error sending air quality"); } try { TransactionBuilder builder = performInitialized("Sending weather forecast"); final byte NR_DAYS = (byte) (1 + weatherSpec.forecasts.size()); int bytesPerDay = 4; int conditionsLength = 0; if (supportsConditionString) { bytesPerDay = 5; conditionsLength = weatherSpec.currentCondition.getBytes().length; for (WeatherSpec.Forecast forecast : weatherSpec.forecasts) { conditionsLength += Weather.getConditionString(forecast.conditionCode).getBytes().length; } } int length = 7 + bytesPerDay * NR_DAYS + conditionsLength; ByteBuffer buf = ByteBuffer.allocate(length); buf.order(ByteOrder.LITTLE_ENDIAN); buf.put((byte) 1); buf.putInt(weatherSpec.timestamp); buf.put((byte) (tz_offset_hours * 4)); buf.put(NR_DAYS); byte condition = HuamiWeatherConditions.mapToAmazfitBipWeatherCode(weatherSpec.currentConditionCode); buf.put(condition); buf.put(condition); buf.put((byte) (weatherSpec.todayMaxTemp - 273)); buf.put((byte) (weatherSpec.todayMinTemp - 273)); if (supportsConditionString) { buf.put(weatherSpec.currentCondition.getBytes()); buf.put((byte) 0); } for (WeatherSpec.Forecast forecast : weatherSpec.forecasts) { condition = HuamiWeatherConditions.mapToAmazfitBipWeatherCode(forecast.conditionCode); buf.put(condition); buf.put(condition); buf.put((byte) (forecast.maxTemp - 273)); buf.put((byte) (forecast.minTemp - 273)); if (supportsConditionString) { buf.put(Weather.getConditionString(forecast.conditionCode).getBytes()); buf.put((byte) 0); } } builder.write(getCharacteristic(AmazfitBipService.UUID_CHARACTERISTIC_WEATHER), buf.array()); builder.queue(getQueue()); } catch (Exception ex) { LOG.error("Error sending weather forecast", ex); } if (gbDevice.getType() == DeviceType.AMAZFITCOR) { try { TransactionBuilder builder; builder = performInitialized("Sending forecast location"); int length = 2 + weatherSpec.location.getBytes().length; ByteBuffer buf = ByteBuffer.allocate(length); buf.order(ByteOrder.LITTLE_ENDIAN); buf.put((byte) 8); buf.put(weatherSpec.location.getBytes()); buf.put((byte) 0); builder.write(getCharacteristic(AmazfitBipService.UUID_CHARACTERISTIC_WEATHER), buf.array()); builder.queue(getQueue()); } catch (Exception ex) { LOG.error("Error sending current forecast location", ex); } } } @Override public void onTestNewFunction() { try { new AmazfitBipFetchLogsOperation(this).perform(); } catch (IOException ex) { LOG.error("Unable to fetch logs", ex); } } @Override public boolean onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) { boolean handled = super.onCharacteristicChanged(gatt, characteristic); if (!handled) { UUID characteristicUUID = characteristic.getUuid(); if (MiBand2Service.UUID_CHARACTERISTIC_3_CONFIGURATION.equals(characteristicUUID)) { return handleConfigurationInfo(characteristic.getValue()); } } return false; } private boolean handleConfigurationInfo(byte[] value) { if (value == null || value.length < 4) { return false; } if (value[0] == 0x10 && value[1] == 0x0e && value[2] == 0x01) { String gpsVersion = new String(value, 3, value.length - 3); LOG.info("got gps version = " + gpsVersion); gbDevice.setFirmwareVersion2(gpsVersion); return true; } return false; } // this probably does more than only getting the GPS version... private AmazfitBipSupport requestGPSVersion(TransactionBuilder builder) { LOG.info("Requesting GPS version"); builder.write(getCharacteristic(MiBand2Service.UUID_CHARACTERISTIC_3_CONFIGURATION), AmazfitBipService.COMMAND_REQUEST_GPS_VERSION); return this; } private AmazfitBipSupport setLanguage(TransactionBuilder builder) { String language = Locale.getDefault().getLanguage(); String country = Locale.getDefault().getCountry(); LOG.info("Setting watch language, phone language = " + language + " country = " + country); final byte[] command_new; final byte[] command_old; String localeString; switch (GBApplication.getPrefs().getInt("amazfitbip_language", -1)) { case 0: command_old = AmazfitBipService.COMMAND_SET_LANGUAGE_SIMPLIFIED_CHINESE; localeString = "zh_CN"; break; case 1: command_old = AmazfitBipService.COMMAND_SET_LANGUAGE_TRADITIONAL_CHINESE; localeString = "zh_TW"; break; case 2: command_old = AmazfitBipService.COMMAND_SET_LANGUAGE_ENGLISH; localeString = "en_US"; break; case 3: command_old = AmazfitBipService.COMMAND_SET_LANGUAGE_SPANISH; localeString = "es_ES"; break; default: switch (language) { case "zh": if (country.equals("TW") || country.equals("HK") || country.equals("MO")) { // Taiwan, Hong Kong, Macao command_old = AmazfitBipService.COMMAND_SET_LANGUAGE_TRADITIONAL_CHINESE; localeString = "zh_TW"; } else { command_old = AmazfitBipService.COMMAND_SET_LANGUAGE_SIMPLIFIED_CHINESE; localeString = "zh_CN"; } break; case "es": command_old = AmazfitBipService.COMMAND_SET_LANGUAGE_SPANISH; localeString = "es_ES"; break; default: command_old = AmazfitBipService.COMMAND_SET_LANGUAGE_ENGLISH; localeString = "en_US"; break; } } command_new = AmazfitBipService.COMMAND_SET_LANGUAGE_NEW_TEMPLATE; System.arraycopy(localeString.getBytes(), 0, command_new, 3, localeString.getBytes().length); builder.add(new ConditionalWriteAction(getCharacteristic(MiBand2Service.UUID_CHARACTERISTIC_3_CONFIGURATION)) { @Override protected byte[] checkCondition() { if (gbDevice.getType() == DeviceType.AMAZFITBIP && new Version(gbDevice.getFirmwareVersion()).compareTo(new Version("0.1.0.77")) >= 0) { return command_new; } else { return command_old; } } }); return this; } @Override public void phase2Initialize(TransactionBuilder builder) { super.phase2Initialize(builder); LOG.info("phase2Initialize..."); setLanguage(builder); requestGPSVersion(builder); } @Override public HuamiFWHelper createFWHelper(Uri uri, Context context) throws IOException { return new AmazfitBipFWHelper(uri, context); } }
package gov.nih.nci.caadapter.hl7.transformation.data; import gov.nih.nci.caadapter.common.Message; import gov.nih.nci.caadapter.common.MessageResources; import gov.nih.nci.caadapter.common.validation.ValidatorResult; import gov.nih.nci.caadapter.common.validation.ValidatorResults; import gov.nih.nci.caadapter.hl7.datatype.Datatype; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.HashSet; import java.util.Hashtable; import java.util.List; import java.util.Vector; public class XMLElement implements Cloneable{ private String name; private ArrayList<Attribute> attributes = new ArrayList<Attribute>(); private Vector<XMLElement> children = new Vector<XMLElement>(); private ArrayList<String> segments = new ArrayList<String>(); private ValidatorResults validatorResults = null; private boolean hasUserMappedData = false; /** * @return the name */ public String getName() { return name; } /** * @param name the name to set */ public void setName(String name) { this.name = name; } /** * @param child the child XMLElement to be added */ public void addChild(XMLElement child) { children.add(child); } /** * @param children the children XMLElements to be added */ public void addChildren(List<XMLElement> children) { for(XMLElement child:children) this.children.add(child); } /** * @param name the name of the attribute * @param value the value of the attribute */ public void addAttribute(String name, String value, String datatype) { // System.out.println("name" + name + " type:"+datatype); Attribute attribute = new Attribute(); attribute.setName(name); attribute.setValue(value); attribute.setDatatype(datatype); attributes.add(attribute); } /** * @return the attributes */ public ArrayList<Attribute> getAttributes() { return attributes; } /** * @return the children */ public Vector<XMLElement> getChildren() { return children; } public XMLElement clone() { try { return (XMLElement)super.clone(); } catch (CloneNotSupportedException e) { return null; // never invoked } } public ArrayList<String> getSegments() { return segments; } public void addSegment(String segment) { segments.add(segment); } /** * @return the validatorResults */ public ValidatorResults getValidatorResults() { return validatorResults; } /** * @param validatorResults the validatorResults to set */ public void setValidatorResults(ValidatorResults validatorResults) { this.validatorResults = validatorResults; } /** * @param attributes the attributes to set */ public void setAttributes(ArrayList<Attribute> attributes) { this.attributes = attributes; } /** * @return the hasUserMappedData */ public boolean hasUserMappedData() { return hasUserMappedData; } /** * @param hasUserMappedData the hasUserMappedData to set */ public void setHasUserMappedData(boolean hasUserMappedData) { this.hasUserMappedData = hasUserMappedData; } public StringBuffer toXML() { StringBuffer output = new StringBuffer(); output.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"); output.append(toXMLBody(0)); return output; } public StringBuffer toXMLBody(int level) { boolean addBody = false; String bodyValue = ""; StringBuffer output = new StringBuffer(); for(int i = 0; i<level;i++) output.append(" "); output.append("<" + getName()); if (level == 0) { output.append(" xmlns=\"urn:hl7-org:v3\""); output.append(" xmlns:xsi=\"http: } for(Attribute attribute:attributes) { String key = attribute.getName(); String value = attribute.getValue(); if (key.equalsIgnoreCase("inlineText")) { addBody = true; bodyValue = value; } else { output.append(" "+key+"="+"\""+value+"\""); } } if (getChildren().size() == 0&&!addBody) { output.append("/>\n"); } else { if (!addBody) { output.append(">\n"); for(XMLElement xmlElement:getChildren()) { output.append(xmlElement.toXMLBody(level+1)); } for(int i = 0; i<level;i++) output.append(" "); output.append("</" + getName() + ">\n"); } else { output.append(">"); output.append(bodyValue); output.append("</" + getName() + ">\n"); } } return output; } public ValidatorResults validate() { try { Hashtable datatypes = new Hashtable(); InputStream is = this.getClass().getResourceAsStream("/datatypes"); ObjectInputStream ois = new ObjectInputStream(is); datatypes = (Hashtable)ois.readObject(); ois.close(); is.close(); ValidatorResults validatorResults_sub = validate(datatypes, name); if (validatorResults_sub == null) return validatorResults; if (validatorResults_sub.getAllMessages().size() == 0) return validatorResults; validatorResults.addValidatorResults(validatorResults_sub); }catch(Exception e) { e.printStackTrace(); } return validatorResults; } public ValidatorResults validate(Hashtable datatypes, String pXmlPath) { ValidatorResults validatorResults_temp = new ValidatorResults(); for(Attribute attribute: attributes) { if (attribute.getDatatype() != null) { if (!attribute.getDatatype().equals("")) { String dt = attribute.getDatatype(); if (dt.equals("cs")) continue; // System.out.println("Validating:"+pXmlPath + "." + attribute.getName()); Datatype datatype = (Datatype)datatypes.get(dt); if (datatype!= null) { HashSet predefinedValues = datatype.getPredefinedValues(); if (predefinedValues.size()>0) { if (!predefinedValues.contains(attribute.getValue())) { Message msg = MessageResources.getMessage("EMP_IN", new Object[]{"Attribute" + pXmlPath + "." + attribute.getName() + " does not contain valid value (" + attribute.getValue() + ")"}); validatorResults_temp.addValidatorResult(new ValidatorResult(ValidatorResult.Level.ERROR, msg)); } } if (datatype.getPatterns().size() > 0) { String vPattern = ""; boolean patternMatch = false; for (String pattern:datatype.getPatterns()) { vPattern = vPattern + " " + pattern; if (attribute.getValue().matches(pattern)) { patternMatch = true; break; } } if (!patternMatch) { Message msg = MessageResources.getMessage("EMP_IN", new Object[]{"Attribute" + pXmlPath + "." + attribute.getName() + " does not match attribute pattern " + vPattern + "(" + attribute.getValue() + ")"}); validatorResults_temp.addValidatorResult(new ValidatorResult(ValidatorResult.Level.ERROR, msg)); } } } } } } for (XMLElement xmlElement:children) { ValidatorResults validatorResults_sub = xmlElement.validate(datatypes, pXmlPath+"."+xmlElement.getName()); if (validatorResults_sub == null) continue; if (validatorResults_sub.getAllMessages().size() == 0) continue; validatorResults_temp.addValidatorResults(validatorResults_sub); } return validatorResults_temp; } }
package gov.nih.nci.caintegrator2.application.analysis.grid; import edu.columbia.geworkbench.cagrid.MageBioAssayGenerator; import gov.nih.nci.caintegrator2.application.analysis.ClassificationsToClsConverter; import gov.nih.nci.caintegrator2.application.analysis.GctDataset; import gov.nih.nci.caintegrator2.application.analysis.GctDatasetFileWriter; import gov.nih.nci.caintegrator2.application.analysis.GenePatternGridClientFactory; import gov.nih.nci.caintegrator2.application.analysis.StatusUpdateListener; import gov.nih.nci.caintegrator2.application.analysis.grid.comparativemarker.ComparativeMarkerSelectionGridRunner; import gov.nih.nci.caintegrator2.application.analysis.grid.comparativemarker.ComparativeMarkerSelectionParameters; import gov.nih.nci.caintegrator2.application.analysis.grid.gistic.GisticGridRunner; import gov.nih.nci.caintegrator2.application.analysis.grid.gistic.GisticParameters; import gov.nih.nci.caintegrator2.application.analysis.grid.gistic.GisticSamplesMarkers; import gov.nih.nci.caintegrator2.application.analysis.grid.pca.PCAGridRunner; import gov.nih.nci.caintegrator2.application.analysis.grid.pca.PCAParameters; import gov.nih.nci.caintegrator2.application.analysis.grid.preprocess.PreprocessDatasetGridRunner; import gov.nih.nci.caintegrator2.application.analysis.grid.preprocess.PreprocessDatasetParameters; import gov.nih.nci.caintegrator2.application.query.InvalidCriterionException; import gov.nih.nci.caintegrator2.application.query.QueryManagementService; import gov.nih.nci.caintegrator2.common.Cai2Util; import gov.nih.nci.caintegrator2.common.GenePatternUtil; import gov.nih.nci.caintegrator2.common.TimeLoggerHelper; import gov.nih.nci.caintegrator2.domain.analysis.MarkerResult; import gov.nih.nci.caintegrator2.domain.application.AbstractPersistedAnalysisJob; import gov.nih.nci.caintegrator2.domain.application.AnalysisJobStatusEnum; import gov.nih.nci.caintegrator2.domain.application.ComparativeMarkerSelectionAnalysisJob; import gov.nih.nci.caintegrator2.domain.application.GisticAnalysisJob; import gov.nih.nci.caintegrator2.domain.application.PrincipalComponentAnalysisJob; import gov.nih.nci.caintegrator2.domain.application.Query; import gov.nih.nci.caintegrator2.domain.application.StudySubscription; import gov.nih.nci.caintegrator2.external.ConnectionException; import gov.nih.nci.caintegrator2.external.ParameterException; import gov.nih.nci.caintegrator2.file.FileManager; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.genepattern.cagrid.service.compmarker.mage.common.ComparativeMarkerSelMAGESvcI; import org.genepattern.cagrid.service.preprocessdataset.mage.common.PreprocessDatasetMAGEServiceI; import org.genepattern.gistic.common.GisticI; import org.genepattern.pca.common.PCAI; /** * Entry point to run all GenePattern grid jobs. */ public class GenePatternGridRunnerImpl implements GenePatternGridRunner { private GenePatternGridClientFactory genePatternGridClientFactory; private QueryManagementService queryManagementService; private MageBioAssayGenerator mbaGenerator; private FileManager fileManager; private final Map<String, String> reporterGeneSymbols = new HashMap<String, String>(); private static final int DESCRIPTION_LENGTH = 200; /** * {@inheritDoc} */ public File runGistic(StatusUpdateListener updater, GisticAnalysisJob job) throws ConnectionException, InvalidCriterionException, ParameterException, IOException { GisticParameters parameters = job.getGisticAnalysisForm().getGisticParameters(); StudySubscription studySubscription = job.getSubscription(); GisticI gisticClient = genePatternGridClientFactory.createGisticClient(parameters.getServer()); GisticGridRunner runner = new GisticGridRunner(gisticClient, fileManager); try { GisticSamplesMarkers gisticSamplesMarkers = GenePatternUtil. createGisticSamplesMarkers(queryManagementService, parameters.getClinicalQuery(), studySubscription); updateStatus(updater, job, AnalysisJobStatusEnum.PROCESSING_REMOTELY); return runner.execute(studySubscription, parameters, gisticSamplesMarkers); } catch (InterruptedException e) { return null; } finally { updateStatus(updater, job, AnalysisJobStatusEnum.PROCESSING_LOCALLY); } } /** * {@inheritDoc} * @throws InvalidCriterionException */ public List<MarkerResult> runPreprocessComparativeMarkerSelection(StatusUpdateListener updater, ComparativeMarkerSelectionAnalysisJob job) throws ConnectionException, InvalidCriterionException { StudySubscription studySubscription = job.getSubscription(); PreprocessDatasetParameters preprocessParams = job.getForm().getPreprocessDatasetparameters(); ComparativeMarkerSelectionParameters comparativeMarkerParams = job.getForm().getComparativeMarkerSelectionParameters(); // Need to validate that the clinical queries in both params are the same. return executeComparativeMarkerSelection(studySubscription, preprocessParams, comparativeMarkerParams, updater, job); } private List <MarkerResult> executeComparativeMarkerSelection(StudySubscription studySubscription, PreprocessDatasetParameters preprocessParams, ComparativeMarkerSelectionParameters comparativeMarkerParams, StatusUpdateListener updater, ComparativeMarkerSelectionAnalysisJob job) throws ConnectionException, InvalidCriterionException { String jobInfoString = studySubscription.getUserWorkspace().getUsername() + "_" + preprocessParams.getProcessedGctFilename().replace(".gct", "") + " -- Full ComparativeMarkerSelection Job"; TimeLoggerHelper timeLogger = new TimeLoggerHelper(this.getClass()); timeLogger.startLog(jobInfoString); File gctFile = runPreprocessDataset(updater, job, job.getForm().getPreprocessDatasetparameters()); timeLogger.logInfo("Preprocessed Dataset Filename = " + gctFile.getAbsolutePath()); File clsFile = createClassificationFile(studySubscription, comparativeMarkerParams.getClinicalQueries(), comparativeMarkerParams.getClassificationFileName()); updateStatus(updater, job, AnalysisJobStatusEnum.PROCESSING_REMOTELY); List <MarkerResult> results = runComparativeMarkerSelection(comparativeMarkerParams, gctFile, clsFile); updateStatus(updater, job, AnalysisJobStatusEnum.PROCESSING_LOCALLY); timeLogger.stopLog(jobInfoString); return results; } /** * {@inheritDoc} */ public File runPreprocessDataset(StatusUpdateListener updater, AbstractPersistedAnalysisJob job, PreprocessDatasetParameters parameters) throws ConnectionException, InvalidCriterionException { StudySubscription studySubscription = job.getSubscription(); Set<Query> querySet = new HashSet<Query>(); querySet.addAll(parameters.getClinicalQueries()); GctDataset gctDataset = GenePatternUtil.createGctDataset(studySubscription, querySet, queryManagementService); populateReporterGeneSymbols(gctDataset); updateStatus(updater, job, AnalysisJobStatusEnum.PROCESSING_REMOTELY); PreprocessDatasetMAGEServiceI client = genePatternGridClientFactory.createPreprocessDatasetClient(parameters.getServer()); PreprocessDatasetGridRunner runner = new PreprocessDatasetGridRunner(client, fileManager); try { return runner.execute(studySubscription, parameters, gctDataset); } catch (InterruptedException e) { return null; } finally { updateStatus(updater, job, AnalysisJobStatusEnum.PROCESSING_LOCALLY); } } /** * {@inheritDoc} */ public File runPCA(StatusUpdateListener updater, PrincipalComponentAnalysisJob job, File preprocessedGctFile) throws ConnectionException, InvalidCriterionException { StudySubscription studySubscription = job.getSubscription(); PCAParameters parameters = job.getForm().getPcaParameters(); PCAI client = genePatternGridClientFactory.createPCAClient(parameters.getServer()); Set<Query> querySet = new HashSet<Query>(); querySet.addAll(parameters.getClinicalQueries()); File gctFile = preprocessedGctFile; if (gctFile == null) { gctFile = createGctFile(studySubscription, querySet, parameters.getGctFileName()); } File clsFile = createClassificationFile(studySubscription, parameters.getClinicalQueries(), parameters.getClassificationFileName()); return executePCA(updater, job, client, gctFile, clsFile); } private File executePCA(StatusUpdateListener updater, PrincipalComponentAnalysisJob job, PCAI client, File gctFile, File clsFile) throws ConnectionException { File zipFile = null; try { updateStatus(updater, job, AnalysisJobStatusEnum.PROCESSING_REMOTELY); PCAGridRunner runner = new PCAGridRunner(client, fileManager); zipFile = runner.execute(job.getSubscription(), job.getForm().getPcaParameters(), gctFile); updateStatus(updater, job, AnalysisJobStatusEnum.PROCESSING_LOCALLY); Cai2Util.addFilesToZipFile(zipFile, gctFile, clsFile); } catch (IOException e) { if (zipFile != null) { zipFile.delete(); } throw new IllegalStateException("Invalid Zip File retrieved from grid service: " + "Unable to add gct/cls files to the zip file.", e); } catch (InterruptedException e) { return null; } finally { gctFile.delete(); clsFile.delete(); } return zipFile; } private void populateReporterGeneSymbols(GctDataset gctDataset) { for (int i = 0; i < gctDataset.getRowReporterNames().size(); i++) { String geneSymbols = gctDataset.getRowDescription().get(i); if (geneSymbols.length() > DESCRIPTION_LENGTH) { geneSymbols = geneSymbols.substring(0, DESCRIPTION_LENGTH); } reporterGeneSymbols.put(gctDataset.getRowReporterNames().get(i), geneSymbols); } } private List<MarkerResult> runComparativeMarkerSelection(ComparativeMarkerSelectionParameters parameters, File gctFile, File clsFile) throws ConnectionException { ComparativeMarkerSelMAGESvcI client = genePatternGridClientFactory.createComparativeMarkerSelClient(parameters.getServer()); ComparativeMarkerSelectionGridRunner runner = new ComparativeMarkerSelectionGridRunner(client, mbaGenerator, reporterGeneSymbols); return runner.execute(parameters, gctFile, clsFile); } private File createClassificationFile(StudySubscription studySubscription, List<Query> clinicalQueries, String classificationFileName) throws InvalidCriterionException { return ClassificationsToClsConverter.writeAsCls( GenePatternUtil.createSampleClassification(queryManagementService, clinicalQueries), new File(fileManager.getUserDirectory(studySubscription) + File.separator + classificationFileName).getAbsolutePath()); } private File createGctFile(StudySubscription studySubscription, Set<Query> clinicalQueries, String fileName) throws InvalidCriterionException { return GctDatasetFileWriter.writeAsGct( GenePatternUtil.createGctDataset(studySubscription, clinicalQueries, queryManagementService), new File(fileManager.getUserDirectory(studySubscription) + File.separator + fileName).getAbsolutePath()); } /** * @param genePatternGridClientFactory the genePatternGridClientFactory to set */ public void setGenePatternGridClientFactory(GenePatternGridClientFactory genePatternGridClientFactory) { this.genePatternGridClientFactory = genePatternGridClientFactory; } /** * @param queryManagementService the queryManagementService to set */ public void setQueryManagementService(QueryManagementService queryManagementService) { this.queryManagementService = queryManagementService; } /** * @param mbaGenerator the mbaGenerator to set */ public void setMbaGenerator(MageBioAssayGenerator mbaGenerator) { this.mbaGenerator = mbaGenerator; } /** * @param fileManager the fileManager to set */ public void setFileManager(FileManager fileManager) { this.fileManager = fileManager; } private void updateStatus(StatusUpdateListener updater, AbstractPersistedAnalysisJob job, AnalysisJobStatusEnum status) { job.setStatus(status); updater.updateStatus(job); } }
import java.util.Arrays; import java.util.Collections; import java.util.List; import org.junit.Test; import org.junit.Ignore; import org.junit.Rule; import org.junit.rules.ExpectedException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; public class SeriesTest { @Rule public ExpectedException expectedException = ExpectedException.none(); @Test public void hasDigitsShort() { Series series = new Series("01234"); List<Integer> expected = Arrays.asList(0, 1, 2, 3, 4); List<Integer> actual = series.getDigits(); assertNotNull(actual); assertFalse(actual.isEmpty()); assertEquals(expected, actual); } @Ignore("Remove to run test") @Test public void hasDigitsLong() { Series series = new Series("0123456789"); List<Integer> expected = Arrays.asList(0, 1, 2, 3, 4, 5, 6, 7, 8, 9); List<Integer> actual = series.getDigits(); assertNotNull(actual); assertFalse(actual.isEmpty()); assertEquals(expected, actual); } @Ignore("Remove to run test") @Test public void keepsTheDigitOrderIfReversed() { Series series = new Series("9876543210"); List<Integer> expected = Arrays.asList(9, 8, 7, 6, 5, 4, 3, 2, 1, 0); List<Integer> actual = series.getDigits(); assertNotNull(actual); assertFalse(actual.isEmpty()); assertEquals(expected, actual); } @Ignore("Remove to run test") @Test public void keepsArbitraryDigitOrder() { Series series = new Series("936923468"); List<Integer> expected = Arrays.asList(9, 3, 6, 9, 2, 3, 4, 6, 8); List<Integer> actual = series.getDigits(); assertNotNull(actual); assertFalse(actual.isEmpty()); assertEquals(expected, actual); } @Ignore("Remove to run test") @Test public void canSliceByOne() { Series series = new Series("01234"); List<List<Integer>> expected = Arrays.asList( Collections.singletonList(0), Collections.singletonList(1), Collections.singletonList(2), Collections.singletonList(3), Collections.singletonList(4) ); List<List<Integer>> actual = series.slices(1); assertNotNull(actual); assertFalse(actual.isEmpty()); assertEquals(expected, actual); } @Ignore("Remove to run test") @Test public void canSliceByTwo() { Series series = new Series("98273463"); List<List<Integer>> expected = Arrays.asList( Arrays.asList(9, 8), Arrays.asList(8, 2), Arrays.asList(2, 7), Arrays.asList(7, 3), Arrays.asList(3, 4), Arrays.asList(4, 6), Arrays.asList(6, 3) ); List<List<Integer>> actual = series.slices(2); assertNotNull(actual); assertFalse(actual.isEmpty()); assertEquals(expected, actual); } @Ignore("Remove to run test") @Test public void canSliceByThree() { Series series = new Series("01234"); List<List<Integer>> expected = Arrays.asList( Arrays.asList(0, 1, 2), Arrays.asList(1, 2, 3), Arrays.asList(2, 3, 4) ); List<List<Integer>> actual = series.slices(3); assertNotNull(actual); assertFalse(actual.isEmpty()); assertEquals(expected, actual); } @Ignore("Remove to run test") @Test public void canSliceByThreeWithDuplicateDigits() { Series series = new Series("31001"); List<List<Integer>> expected = Arrays.asList( Arrays.asList(3, 1, 0), Arrays.asList(1, 0, 0), Arrays.asList(0, 0, 1) ); List<List<Integer>> actual = series.slices(3); assertNotNull(actual); assertFalse(actual.isEmpty()); assertEquals(expected, actual); } @Ignore("Remove to run test") @Test public void canSliceByFour() { Series series = new Series("91274"); List<List<Integer>> expected = Arrays.asList( Arrays.asList(9, 1, 2, 7), Arrays.asList(1, 2, 7, 4) ); List<List<Integer>> actual = series.slices(4); assertNotNull(actual); assertFalse(actual.isEmpty()); assertEquals(expected, actual); } @Ignore("Remove to run test") @Test public void canSliceByFive() { Series series = new Series("81228"); List<List<Integer>> expected = Arrays.asList( Arrays.asList(8, 1, 2, 2, 8) ); List<List<Integer>> actual = series.slices(5); assertNotNull(actual); assertFalse(actual.isEmpty()); assertEquals(expected, actual); } @Ignore("Remove to run test") @Test public void throwsAnErrorIfNotEnoughDigitsToSlice() { expectedException.expect(IllegalArgumentException.class); new Series("01032987583").slices(12); } }
package org.eclipse.kapua.app.console.module.api.client.ui.grid; import com.extjs.gxt.ui.client.Style.SelectionMode; import com.extjs.gxt.ui.client.data.BasePagingLoader; import com.extjs.gxt.ui.client.data.PagingLoadResult; import com.extjs.gxt.ui.client.data.RpcProxy; import com.extjs.gxt.ui.client.event.SelectionChangedEvent; import com.extjs.gxt.ui.client.event.SelectionChangedListener; import com.extjs.gxt.ui.client.store.ListStore; import com.extjs.gxt.ui.client.widget.grid.ColumnConfig; import com.extjs.gxt.ui.client.widget.grid.ColumnModel; import com.extjs.gxt.ui.client.widget.grid.GridSelectionModel; import com.extjs.gxt.ui.client.widget.grid.GridView; import com.extjs.gxt.ui.client.widget.layout.FitLayout; import com.extjs.gxt.ui.client.widget.toolbar.PagingToolBar; import com.google.gwt.core.client.GWT; import com.google.gwt.user.client.Element; import org.eclipse.kapua.app.console.module.api.client.messages.ConsoleMessages; import org.eclipse.kapua.app.console.module.api.client.ui.panel.ContentPanel; import org.eclipse.kapua.app.console.module.api.client.ui.panel.EntityFilterPanel; import org.eclipse.kapua.app.console.module.api.client.ui.view.AbstractEntityView; import org.eclipse.kapua.app.console.module.api.client.ui.widget.EntityCRUDToolbar; import org.eclipse.kapua.app.console.module.api.client.ui.widget.KapuaPagingToolBar; import org.eclipse.kapua.app.console.module.api.shared.model.GwtEntityModel; import org.eclipse.kapua.app.console.module.api.shared.model.query.GwtQuery; import org.eclipse.kapua.app.console.module.api.shared.model.session.GwtSession; import java.util.List; public abstract class EntityGrid<M extends GwtEntityModel> extends ContentPanel { private static final ConsoleMessages MSGS = GWT.create(ConsoleMessages.class); private static final int ENTITY_PAGE_SIZE = 100; protected GwtSession currentSession; private AbstractEntityView<M> parentEntityView; private EntityCRUDToolbar<M> entityCRUDToolbar; private boolean entityGridConfigured; private SelectionMode selectionMode = SelectionMode.SINGLE; protected KapuaGrid<M> entityGrid; protected BasePagingLoader<PagingLoadResult<M>> entityLoader; protected ListStore<M> entityStore; protected PagingToolBar entityPagingToolbar; protected EntityFilterPanel<M> filterPanel; /* Some grids (most notably "slave" grids, i.e. the ones that depends from the entity * * selected in another grid) should not be refreshed on render, otherwise they would be * * refreshed twice and the paging toolbar may be disabled because of this */ protected boolean refreshOnRender = true; protected EntityGrid(AbstractEntityView<M> entityView, GwtSession currentSession) { super(new FitLayout()); // Set other properties this.parentEntityView = entityView; this.currentSession = currentSession; // Container borders setBorders(false); setBodyBorder(true); setHeaderVisible(false); // CRUD toolbar entityCRUDToolbar = getToolbar(); if (entityCRUDToolbar != null) { setTopComponent(entityCRUDToolbar); } // Paging toolbar entityPagingToolbar = getPagingToolbar(); if (entityPagingToolbar != null) { setBottomComponent(entityPagingToolbar); } } @Override protected void onRender(Element target, int index) { super.onRender(target, index); // Configure Entity Grid if (!entityGridConfigured) { configureEntityGrid(SelectionMode.SINGLE); } // Force layout so the entityGrid gets rendered and its listeners initialized layout(); // Bind the grid to CRUD toolbar entityCRUDToolbar.setEntityGrid(this); // Grid selection mode GridSelectionModel<M> selectionModel = entityGrid.getSelectionModel(); selectionModel.setSelectionMode(selectionMode); selectionModel.addSelectionChangedListener(new SelectionChangedListener<M>() { @Override public void selectionChanged(SelectionChangedEvent<M> se) { selectionChangedEvent(se.getSelectedItem()); } }); // Grid view options GridView gridView = entityGrid.getView(); gridView.setEmptyText(MSGS.gridEmptyResult()); // Do first load if (refreshOnRender) { refresh(); } } protected EntityCRUDToolbar<M> getToolbar() { return new EntityCRUDToolbar<M>(currentSession); } protected abstract RpcProxy<PagingLoadResult<M>> getDataProxy(); protected PagingToolBar getPagingToolbar() { return new KapuaPagingToolBar(ENTITY_PAGE_SIZE); } /** * Configuring entity grid, because it needs to be configured before * onRender method is called. * * @param selectionMode selection mode on grid, default is SINGLE. */ protected void configureEntityGrid(SelectionMode selectionMode) { // Data Proxy RpcProxy<PagingLoadResult<M>> dataProxy = getDataProxy(); // Data Loader entityLoader = new BasePagingLoader<PagingLoadResult<M>>(dataProxy); // Data Store entityStore = new ListStore<M>(entityLoader); // Grid Data Load Listener entityLoader.addLoadListener(new EntityGridLoadListener<M>(this, entityStore)); // Bind Entity Paging Toolbar if (entityPagingToolbar != null) { entityPagingToolbar.bind(entityLoader); } // Configure columns ColumnModel columnModel = new ColumnModel(getColumns()); // Set grid entityGrid = new KapuaGrid<M>(entityStore, columnModel); add(entityGrid); entityGridConfigured = true; this.selectionMode = selectionMode; } protected abstract List<ColumnConfig> getColumns(); public void clearGridElement() { entityStore.removeAll(); } public void refresh() { entityCRUDToolbar.getRefreshEntityButton().setEnabled(false); entityLoader.load(0, entityLoader.getLimit()); } public void refresh(GwtQuery query) { setFilterQuery(query); entityLoader.load(0, entityLoader.getLimit()); } public void setFilterPanel(EntityFilterPanel<M> filterPanel) { this.filterPanel = filterPanel; entityCRUDToolbar.setFilterPanel(filterPanel); } protected void selectionChangedEvent(M selectedItem) { if (parentEntityView != null) { parentEntityView.setSelectedEntity(selectedItem); } if (entityCRUDToolbar != null) { entityCRUDToolbar.setSelectedEntity(selectedItem); } } public void setPagingToolbar(PagingToolBar entityPagingToolbar) { this.entityPagingToolbar = entityPagingToolbar; } public GridSelectionModel<M> getSelectionModel() { return entityGrid.getSelectionModel(); } public boolean isRefreshOnRender() { return refreshOnRender; } public void setRefreshOnRender(boolean refreshOnRender) { this.refreshOnRender = refreshOnRender; } public abstract GwtQuery getFilterQuery(); public abstract void setFilterQuery(GwtQuery filterQuery); /** * Method is called when grid is loaded. */ public void loaded() { entityCRUDToolbar.getRefreshEntityButton().setEnabled(true); } }
package org.csstudio.platform.libs.jms; import java.util.Enumeration; import java.util.Hashtable; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.logging.Level; import java.util.logging.Logger; import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.MessageConsumer; import javax.jms.Session; import javax.jms.Topic; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; /** * * The class <code>JmsRedundantReceiver</code> handles the redundant connections to JMS servers. It uses queues * to store messages if two or more servers holds messages for a consumer. They will be stored chronological. The * oldest message will be returned first to a client. * * @author Markus Moeller * @version 1.0 * */ public class JmsRedundantReceiver { /** Number of redundant connections */ private final int CONNECTION_COUNT = 2; /** Client id */ private String clientId = null; /** Property set for JNDI */ private Hashtable<String, String> properties = null; /** Array of contexts */ private Context[] context = null; /** Array of factories */ private ConnectionFactory[] factory = null; /** Array of JMS connections */ private Connection[] connection = null; /** Array of JMS sessions */ private Session[] session = null; /** Message consumers. Key -> name, Value -> Array of message consumers */ private Hashtable<String, MessageConsumer[]> subscriber = null; /** Queues for the messages */ private Hashtable<String, ConcurrentLinkedQueue<Message>> messages = null; /** Array of URL strings */ private String[] urls = null; /** Number of redundant connections */ private boolean connected = false; /** * * @param id - The client Id used by the connection object. * @param url1 - URL of the first JMS Server * @param url2 - URL of the second JMS Server */ public JmsRedundantReceiver(String id, String url1, String url2) { urls = new String[CONNECTION_COUNT]; urls[0] = url1; urls[1] = url2; clientId = id; context = new Context[CONNECTION_COUNT]; factory = new ConnectionFactory[CONNECTION_COUNT]; connection = new Connection[CONNECTION_COUNT]; session = new Session[CONNECTION_COUNT]; for(int i = 0;i < CONNECTION_COUNT;i++) { properties = new Hashtable<String, String>(); properties.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.activemq.jndi.ActiveMQInitialContextFactory"); properties.put(Context.PROVIDER_URL, urls[i]); try { context[i] = new InitialContext(properties); factory[i] = (ConnectionFactory)context[i].lookup("ConnectionFactory"); connection[i] = factory[i].createConnection(); connection[i].setClientID(clientId); session[i] = connection[i].createSession(false, Session.CLIENT_ACKNOWLEDGE); connection[i].start(); connected = true; } catch(NamingException ne) { connected = false; } catch(JMSException jmse) { connected = false; } } } /** * * @param name Name of the subscriber * @param destination Name of the topic * @return True - Subscriber have been created, false - Subscriber have not been created * */ public boolean createRedundantSubscriber(String name, String destination) { MessageConsumer[] sub = null; Topic topic = null; boolean result = false; if(subscriber == null) { subscriber = new Hashtable<String, MessageConsumer[]>(); } if(subscriber.containsKey(name)) { return false; } sub = new MessageConsumer[CONNECTION_COUNT]; try { for(int i = 0;i < CONNECTION_COUNT;i++) { topic = session[i].createTopic(destination); sub[i] = session[i].createConsumer(topic); Logger.getLogger(this.getClass().getName()).log(Level.INFO, name + " -> Topic: " + destination + " " + urls[i]); } subscriber.put(name, sub); if(messages == null) { messages = new Hashtable<String, ConcurrentLinkedQueue<Message>>(); } messages.put(name, new ConcurrentLinkedQueue<Message>()); result = true; } catch(JMSException jmse) { result = false; } catch(NullPointerException npe) { result = false; } return result; } /** * Returns the current message. The method does not wait and returns immediately if no message * have been received. * <p> * It takes the messages from the internal queue first. If the * queue does not contain a message, the method calls the receive() method of the MessageConsumer * object. * If more then one server hold a message, the messages will be stored in the internal queue. * * @param name The internal name of the message consumer * @return Current message from the JMS server */ public Message receive(String name) { return receive(name, 0); } /** * Returns the current message. The method waits <code>waitTime</code> miliseconds and returns if * no message have been received. * <p> * It takes the messages from the internal queue first. If the * queue does not contain a message, the method calls the receive() method of the MessageConsumer * object. * If more then one server hold a message, the messages will be stored in the internal queue. * * @param name The internal name of the message consumer * @param waitTime The time to wait(in ms) until the receive method returns * @return Current message from the JMS server */ public Message receive(String name, long waitTime) { ConcurrentLinkedQueue<Message> queue = null; MessageConsumer[] c = null; Message[] m = null; Message result = null; // First check the internal message queue if(messages.containsKey(name)) { queue = messages.get(name); if(!queue.isEmpty()) { result = queue.poll(); } } // Return when a message was found in the queue if(result != null) { return result; } // Do we have a subscriber with the given name? if(subscriber.containsKey(name)) { // Get the MessageConsumer objects for all hosts c = subscriber.get(name); // Create a new array of Message m = new Message[c.length]; // Receive the next message from all hosts for(int i = 0;i < c.length;i++) { try { if(waitTime > 0) { m[i] = c[i].receive(waitTime); } else { m[i] = c[i].receiveNoWait(); } } catch(JMSException jmse) { m[i] = null; } } // All servers sent a message if((m[0] != null) && (m[1] != null)) { try { // Check the time stamp if(m[0].getJMSTimestamp() <= m[1].getJMSTimestamp()) { // The oldest message first result = m[0]; // The newest message will be stored in the queue if(queue != null) { queue.add(m[1]); } } else // and vice versa... { result = m[1]; if(queue != null) { queue.add(m[0]); } } } catch(JMSException jmse) { result = m[0]; if(queue != null) { queue.add(m[1]); } } } else if(m[0] == null && m[1] != null) // Only one message { result = m[1]; } else if(m[0] != null && m[1] == null) // Only one message { result = m[0]; } } return result; } /** * * @return True, if the receiver is connected. False otherwise */ public boolean isConnected() { return connected; } public void closeAll() { MessageConsumer[] c = null; if(connection != null) { for(int i = 0;i < CONNECTION_COUNT;i++) { if(connection[i] != null) { try { connection[i].stop(); } catch(JMSException jmse) { } } } } if(subscriber != null) { Enumeration<MessageConsumer[]> list = subscriber.elements(); while(list.hasMoreElements()) { c = list.nextElement(); for(int i = 0;i < c.length;i++) { try { c[i].close(); } catch(JMSException jmse) { } } } subscriber.clear(); subscriber = null; } for(int i = 0;i < CONNECTION_COUNT;i++) { if(session != null) { if(session[i] != null) { try { session[i].close(); } catch(JMSException jmse) { } session[i] = null; } } if(connection != null) { if(connection[i] != null) { try { connection[i].close(); } catch(JMSException jmse) { } connection[i] = null; } } if(factory != null) { factory[i] = null; } if(context != null) { if(context[i] != null) { try { context[i].close(); } catch(NamingException ne) { } context[i] = null; } } } factory = null; connection = null; session = null; context = null; if (properties!=null) { properties.clear(); } properties = null; } }
package io.debezium.connector.cassandra; import java.time.Duration; import java.util.Arrays; import java.util.Map; import java.util.Optional; import java.util.Properties; import java.util.stream.Collectors; import org.apache.kafka.clients.producer.ProducerConfig; import com.datastax.driver.core.ConsistencyLevel; import io.confluent.kafka.serializers.KafkaAvroSerializer; import io.debezium.connector.cassandra.exceptions.CassandraConnectorConfigException; /** * All configs used by a Cassandra connector agent. */ public class CassandraConnectorConfig { /** * The set of predefined SnapshotMode options. */ public enum SnapshotMode { /** * Perform a snapshot whenever a new table with cdc enabled is detected. This is detected by periodically * scanning tables in Cassandra. */ ALWAYS, /** * Perform a snapshot for unsnapshotted tables upon initial startup of the cdc agent. */ INITIAL, /** * Never perform a snapshot, instead change events are only read from commit logs. */ NEVER; public static Optional<SnapshotMode> fromText(String text) { return Arrays.stream(values()) .filter(v -> text != null && v.name().toLowerCase().equals(text.toLowerCase())) .findFirst(); } } /** * Logical name for the Cassandra connector. This name should uniquely identify the connector from * those that reside in other Cassandra nodes. */ public static final String CONNECTOR_NAME = "connector.name"; /** * Logical name for the Cassandra cluster. This name should be identical across all Cassandra connectors * in a Cassandra cluster */ public static final String KAFKA_TOPIC_PREFIX ="kafka.topic.prefix"; /** * The prefix prepended to all Kafka producer configurations, including schema registry */ public static final String KAFKA_PRODUCER_CONFIG_PREFIX = "kafka.producer."; /** * Specifies the criteria for running a snapshot (eg. initial sync) upon startup of the cassandra connector agent. * Must be one of 'INITIAL', 'ALWAYS', or 'NEVER'. The default snapshot mode is 'INITIAL'. * See {@link SnapshotMode for details}. */ public static final String SNAPSHOT_MODE = "snapshot.mode"; public static final String DEFAULT_SNAPSHOT_MODE = "INITIAL"; /** * Specify the {@link ConsistencyLevel} used for the snapshot query. */ public static final String SNAPSHOT_CONSISTENCY = "snapshot.consistency"; public static final String DEFAULT_SNAPSHOT_CONSISTENCY = "QUORUM"; /** * The port used by the HTTP server for ping, health check, and build info */ public static final String HTTP_PORT = "http.port"; public static final int DEFAULT_HTTP_PORT = 8000; /** * The absolute path of the YAML config file used by a Cassandra node. */ public static final String CASSANDRA_CONFIG = "cassandra.config"; /** * One or more addresses of Cassandra nodes that driver uses to discover topology, separated by "," */ public static final String CASSANDRA_HOSTS = "cassandra.hosts"; public static final String DEFAULT_CASSANDRA_HOST = "localhost"; /** * The port used to connect to Cassandra host(s). */ public static final String CASSANDRA_PORT = "cassandra.port"; public static final int DEFAULT_CASSANDRA_PORT = 9042; /** * The username used when connecting to Cassandra hosts. */ public static final String CASSANDRA_USERNAME = "cassandra.username"; /** * The password used when connecting to Cassandra hosts. */ public static final String CASSANDRA_PASSWORD = "cassandra.password"; /** * If set to true, Cassandra connector agent will use SSL to connect to Cassandra node. */ public static final String CASSANDRA_SSL_ENABLED = "cassandra.ssl.enabled"; public static final boolean DEFAULT_CASSANDRA_SSL_ENABLED = false; /** * The SSL config file path required for storage node. */ public static final String CASSANDRA_SSL_CONFIG_PATH = "cassandra.ssl.config.path"; /** * The local directory which commit logs get relocated to once processed. */ public static final String COMMIT_LOG_RELOCATION_DIR = "commit.log.relocation.dir"; /** * Determines whether or not the CommitLogPostProcessor should run. * If disabled, commit logs would not be deleted post-process, and this could lead to disk storage */ public static final String COMMIT_LOG_POST_PROCESSING_ENABLED = "commit.log.post.processing.enabled"; public static final boolean DEFAULT_COMMIT_LOG_POST_PROCESSING_ENABLED = true; /** * The fully qualified {@link CommitLogTransfer} class used to transfer commit logs. * The default option will delete all commit log files after processing (successful or otherwise). * You can extend a custom implementation. */ public static final String COMMIT_LOG_TRANSFER_CLASS = "commit.log.transfer.class"; public static final String DEFAULT_COMMIT_LOG_TRANSFER_CLASS = "io.debezium.connector.cassandra.BlackHoleCommitLogTransfer"; /** * The prefix for all {@link CommitLogTransfer} configurations. */ public static final String COMMIT_LOG_TRANSFER_CONFIG_PREFIX = "commit.log.transfer."; /** * The directory to store offset tracking files. */ public static final String OFFSET_BACKING_STORE_DIR = "offset.backing.store.dir"; /** * The minimum amount of time to wait before committing the offset. The default value of 0 implies * the offset will be flushed every time. */ public static final String OFFSET_FLUSH_INTERVAL_MS = "offset.flush.interval.ms"; public static final int DEFAULT_OFFSET_FLUSH_INTERVAL_MS = 0; /** * The maximum records that are allowed to be processed until it is required to flush offset to disk. * This config is effective only if offset_flush_interval_ms != 0 */ public static final String MAX_OFFSET_FLUSH_SIZE = "max.offset.flush.size"; public static final int DEFAULT_MAX_OFFSET_FLUSH_SIZE = 100; /** * Positive integer value that specifies the maximum size of the blocking queue into which change events read from * the commit log are placed before they are written to Kafka. This queue can provide back pressure to the commit log * reader when, for example, writes to Kafka are slower or if Kafka is not available. Events that appear in the queue * are not included in the offsets periodically recorded by this connector. Defaults to 8192, and should always be * larger than the maximum batch size specified in the max.batch.size property. * The capacity of the queue to hold deserialized {@link Record} * before they are converted to Avro Records and emitted to Kafka. */ public static final String MAX_QUEUE_SIZE = "max.queue.size"; public static final int DEFAULT_MAX_QUEUE_SIZE = 8192; /** * The maximum number of change events to dequeue each time. */ public static final String MAX_BATCH_SIZE = "max.batch.size"; public static final int DEFAULT_MAX_BATCH_SIZE = 2048; /** * Positive integer value that specifies the number of milliseconds the commit log processor should wait during * each iteration for new change events to appear in the queue. Defaults to 1000 milliseconds, or 1 second. */ public static final String POLL_INTERVAL_MS = "poll.interval.ms"; public static final int DEFAULT_POLL_INTERVAL_MS = 1000; /** * Positive integer value that specifies the number of milliseconds the schema processor should wait before * refreshing the cached Cassandra table schemas. */ public static final String SCHEMA_POLL_INTERVAL_MS = "schema.refresh.interval.ms"; public static final int DEFAULT_SCHEMA_POLL_INTERVAL_MS = 10000; /** * The maximum amount of time to wait on each poll before reattempt. */ public static final String CDC_DIR_POLL_INTERVAL_MS = "cdc.dir.poll.interval.ms"; public static final int DEFAULT_CDC_DIR_POLL_INTERVAL_MS = 10000; /** * Positive integer value that specifies the number of milliseconds the snapshot processor should wait before * re-scanning tables to look for new cdc-enabled tables. Defaults to 10000 milliseconds, or 10 seconds. */ public static final String SNAPSHOT_POLL_INTERVAL_MS = "snapshot.scan.interval.ms"; public static final int DEFAULT_SNAPSHOT_POLL_INTERVAL_MS = 10000; /** * Whether deletion events should have a subsequent tombstone event (true) or not (false). * It's important to note that in Cassandra, two events with the same key may be updating * different columns of a given table. So this could potentially result in records being lost * during compaction if they haven't been consumed by the consumer yet. In other words, do NOT * set this to true if you have kafka compaction turned on. */ public static final String TOMBSTONES_ON_DELETE = "tombstones.on.delete"; public static final boolean DEFAULT_TOMBSTONES_ON_DELETE = false; /** * A comma-separated list of fully-qualified names of fields that should be excluded from change event message values. * Fully-qualified names for fields are in the form {@code <keyspace_name>.<field_name>.<nested_field_name>}. */ public static final String FIELD_BLACKLIST = "field.blacklist"; /** * Instead of parsing commit logs from CDC directory, this will look for the commit log with the * latest modified timestamp in the commit log directory and attempt to process this file only. * Only used for Testing! */ public static final String LATEST_COMMIT_LOG_ONLY = "latest.commit.log.only"; public static final boolean DEFAULT_LATEST_COMMIT_LOG_ONLY = false; private final Properties configs; public CassandraConnectorConfig(Properties configs) { this.configs = configs; } public String connectorName() { return (String) configs.get(CONNECTOR_NAME); } public String kafkaTopicPrefix() { return (String) configs.get(KAFKA_TOPIC_PREFIX); } public Properties getKafkaConfigs() { Properties props = new Properties(); // default configs props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, KafkaAvroSerializer.class); props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, KafkaAvroSerializer.class); configs.entrySet().stream() .filter(entry -> entry.getKey().toString().startsWith(KAFKA_PRODUCER_CONFIG_PREFIX)) .forEach(entry -> { String k = entry.getKey().toString().replace(KAFKA_PRODUCER_CONFIG_PREFIX, ""); Object v = entry.getValue(); props.put(k, v); }); return props; } public Properties commitLogTransferConfigs() { Properties props = new Properties(); configs.entrySet().stream() .filter(entry -> entry.getKey().toString().startsWith(COMMIT_LOG_TRANSFER_CONFIG_PREFIX)) .forEach(entry -> props.put(entry.getKey(), entry.getValue())); return props; } public boolean latestCommitLogOnly() { return configs.containsKey(LATEST_COMMIT_LOG_ONLY) ? Boolean.parseBoolean((String) configs.get(LATEST_COMMIT_LOG_ONLY)) : DEFAULT_LATEST_COMMIT_LOG_ONLY; } public SnapshotMode snapshotMode() { String mode = (String) configs.getOrDefault(SNAPSHOT_MODE, DEFAULT_SNAPSHOT_MODE); Optional<SnapshotMode> snapshotModeOpt = SnapshotMode.fromText(mode); return snapshotModeOpt.orElseThrow(() -> new CassandraConnectorConfigException(mode + " is not a valid SnapshotMode")); } public ConsistencyLevel snapshotConsistencyLevel() { String cl = (String) configs.getOrDefault(SNAPSHOT_CONSISTENCY, DEFAULT_SNAPSHOT_CONSISTENCY); return ConsistencyLevel.valueOf(cl); } public int httpPort() { return configs.containsKey(HTTP_PORT) ? Integer.parseInt((String) configs.get(HTTP_PORT)) : DEFAULT_HTTP_PORT; } public String cassandraConfig() { return (String) configs.get(CASSANDRA_CONFIG); } public String[] cassandraHosts() { String hosts = (String) configs.getOrDefault(CASSANDRA_HOSTS, DEFAULT_CASSANDRA_HOST); return hosts.split(","); } public int cassandraPort() { return configs.containsKey(CASSANDRA_PORT) ? Integer.parseInt((String) configs.get(CASSANDRA_PORT)) : DEFAULT_CASSANDRA_PORT; } public boolean cassandraSslEnabled() { return configs.containsKey(CASSANDRA_SSL_ENABLED) ? Boolean.parseBoolean((String) configs.get(CASSANDRA_SSL_ENABLED)) : DEFAULT_CASSANDRA_SSL_ENABLED; } public String cassandraSslConfigPath() { return (String) configs.get(CASSANDRA_SSL_CONFIG_PATH); } public String cassandraUsername() { return (String) configs.get(CASSANDRA_USERNAME); } public String cassandraPassword() { return (String) configs.get(CASSANDRA_PASSWORD); } public String commitLogRelocationDir() { return (String) configs.get(COMMIT_LOG_RELOCATION_DIR); } public boolean postProcessEnabled() { return configs.containsKey(COMMIT_LOG_POST_PROCESSING_ENABLED) ? Boolean.parseBoolean((String) configs.get(COMMIT_LOG_POST_PROCESSING_ENABLED)) : DEFAULT_COMMIT_LOG_POST_PROCESSING_ENABLED; } public CommitLogTransfer getCommitLogTransfer() { try { String clazz = (String) configs.getOrDefault(COMMIT_LOG_TRANSFER_CLASS, DEFAULT_COMMIT_LOG_TRANSFER_CLASS); CommitLogTransfer transfer = (CommitLogTransfer) Class.forName(clazz).newInstance(); transfer.init(commitLogTransferConfigs()); return transfer; } catch (Exception e) { throw new CassandraConnectorConfigException(e); } } public String offsetBackingStoreDir() { return (String) configs.get(OFFSET_BACKING_STORE_DIR); } public Duration offsetFlushIntervalMs() { int ms = configs.containsKey(OFFSET_FLUSH_INTERVAL_MS) ? Integer.parseInt((String) configs.get(OFFSET_FLUSH_INTERVAL_MS)) : DEFAULT_OFFSET_FLUSH_INTERVAL_MS; return Duration.ofMillis(ms); } public long maxOffsetFlushSize() { return configs.containsKey(MAX_OFFSET_FLUSH_SIZE) ? Long.parseLong((String) configs.get(MAX_OFFSET_FLUSH_SIZE)) : DEFAULT_MAX_OFFSET_FLUSH_SIZE; } public int maxQueueSize() { return configs.containsKey(MAX_QUEUE_SIZE) ? Integer.parseInt((String) configs.get(MAX_QUEUE_SIZE)) : DEFAULT_MAX_QUEUE_SIZE; } public int maxBatchSize() { return configs.containsKey(MAX_BATCH_SIZE) ? Integer.parseInt((String) configs.get(MAX_BATCH_SIZE)) : DEFAULT_MAX_BATCH_SIZE; } public Duration pollIntervalMs() { int ms = configs.containsKey(POLL_INTERVAL_MS) ? Integer.parseInt((String) configs.get(POLL_INTERVAL_MS)) : DEFAULT_POLL_INTERVAL_MS; return Duration.ofMillis(ms); } public Duration schemaPollIntervalMs() { int ms = configs.containsKey(SCHEMA_POLL_INTERVAL_MS) ? Integer.parseInt((String) configs.get(SCHEMA_POLL_INTERVAL_MS)) : DEFAULT_SCHEMA_POLL_INTERVAL_MS; return Duration.ofMillis(ms); } public Duration cdcDirPollIntervalMs() { int ms = configs.containsKey(CDC_DIR_POLL_INTERVAL_MS) ? Integer.parseInt((String) configs.get(CDC_DIR_POLL_INTERVAL_MS)) : DEFAULT_CDC_DIR_POLL_INTERVAL_MS; return Duration.ofMillis(ms); } public Duration snapshotPollIntervalMs() { int ms = configs.containsKey(SNAPSHOT_POLL_INTERVAL_MS) ? Integer.parseInt((String) configs.get(SNAPSHOT_POLL_INTERVAL_MS)) : DEFAULT_SNAPSHOT_POLL_INTERVAL_MS; return Duration.ofMillis(ms); } public String[] fieldBlacklist() { String hosts = (String) configs.get(FIELD_BLACKLIST); if (hosts == null) { return new String[0]; } return hosts.split(","); } public boolean tombstonesOnDelete() { return configs.containsKey(TOMBSTONES_ON_DELETE) ? Boolean.parseBoolean((String) configs.get(TOMBSTONES_ON_DELETE)) : DEFAULT_TOMBSTONES_ON_DELETE; } @Override public String toString() { return configs.entrySet().stream() .filter(e -> !e.getKey().toString().toLowerCase().contains("username") && !e.getKey().toString().toLowerCase().contains("password")) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)) .toString(); } }
//$HeadURL: svn+ssh://mschneider@svn.wald.intevation.org/deegree/base/trunk/resources/eclipse/files_template.xml $ package org.deegree.services.wfs; import static org.deegree.commons.xml.CommonNamespaces.GML3_2_NS; import static org.deegree.commons.xml.CommonNamespaces.GMLNS; import static org.deegree.services.i18n.Messages.get; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import javax.xml.namespace.QName; import org.deegree.commons.config.DeegreeWorkspace; import org.deegree.commons.config.ResourceInitException; import org.deegree.commons.config.ResourceState; import org.deegree.commons.utils.QNameUtils; import org.deegree.feature.persistence.FeatureStore; import org.deegree.feature.persistence.FeatureStoreException; import org.deegree.feature.persistence.FeatureStoreManager; import org.deegree.feature.types.AppSchema; import org.deegree.feature.types.FeatureType; import org.deegree.services.jaxb.wfs.DeegreeWFS; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class WFSFeatureStoreManager { private static final Logger LOG = LoggerFactory.getLogger( WFSFeatureStoreManager.class ); private final Map<QName, FeatureType> ftNameToFt = new HashMap<QName, FeatureType>(); private final Map<AppSchema, FeatureStore> schemaToStore = new HashMap<AppSchema, FeatureStore>(); private final Map<String, String> prefixToNs = new LinkedHashMap<String, String>(); private Map<String, String> targetNsToPrefix = new LinkedHashMap<String, String>(); private int indexPrefix = 0; /** * @param sc * @param baseURL * @throws FeatureStoreException */ public void init( DeegreeWFS sc, String baseURL, DeegreeWorkspace workspace ) throws ResourceInitException { FeatureStoreManager mgr = workspace.getSubsystemManager( FeatureStoreManager.class ); List<String> ids = sc.getFeatureStoreId(); if ( ids.isEmpty() ) { LOG.debug( "Feature store ids not configured. Adding all active feature stores." ); for ( ResourceState<FeatureStore> state : mgr.getStates() ) { if ( state.getResource() != null ) { addStore( state.getResource() ); addNotYetHintedNamespaces( state.getResource().getSchema().getNamespaceBindings().values() ); } } } else { LOG.debug( "Adding configured feature stores." ); for ( String id : ids ) { ResourceState<FeatureStore> state = mgr.getState( id ); if ( state == null ) { String msg = "Cannot add feature store '" + id + "': no such feature store has been configured."; throw new ResourceInitException( msg ); } if ( state.getResource() == null ) { String msg = "Cannot add feature store '" + id + "': no such feature store has been configured."; throw new ResourceInitException( msg ); } addStore( state.getResource() ); addNotYetHintedNamespaces( state.getResource().getSchema().getNamespaceBindings().values() ); } } LOG.debug( "The following prefix-to-namespace and namespace-to-prefix bindings are used for resolution..." ); for ( String prefix : prefixToNs.keySet() ) { LOG.debug( prefix + " --> " + prefixToNs.get( prefix ) ); } for ( String ns : targetNsToPrefix.keySet() ) { LOG.debug( ns + " <-- " + targetNsToPrefix.get( ns ) ); } } private void addNotYetHintedNamespaces( Collection<String> namespaces ) { for ( String ns : namespaces ) { if ( !targetNsToPrefix.containsKey( ns ) ) { String prefix = "app" + ( indexPrefix++ ); prefixToNs.put( prefix, ns ); targetNsToPrefix.put( ns, prefix ); } } } /** * Returns the qualified names of all served {@link FeatureType}s. * * @return the qualified names, never <code>null</code> */ public QName[] getFeatureTypeNames() { return ftNameToFt.keySet().toArray( new QName[ftNameToFt.size()] ); } /** * Returns all {@link FeatureType}s. * * @return served feature types, may be empty, but never <code>null</code> */ public Collection<FeatureType> getFeatureTypes() { return ftNameToFt.values(); } /** * Looks up the {@link FeatureType} with the given qualified name (in a namespace-tolerant manner). * <p> * This method is tolerant to improve interoperability with clients (especially WFS 1.0.0) that only provide the * local name or the prefixed name without a namespace binding. * </p> * * @param ftName * feature type to look up, must not be <code>null</code> * @return feature type with the given name, or <code>null</code> if no such feature type is served */ public FeatureType lookupFeatureType( QName ftName ) { FeatureType ft = ftNameToFt.get( ftName ); if ( ft == null ) { QName match = QNameUtils.findBestMatch( ftName, ftNameToFt.keySet() ); if ( match != null && ( !match.equals( ftName ) ) ) { LOG.debug( "Repairing unqualified FeatureType name: " + QNameUtils.toString( ftName ) + " -> " + QNameUtils.toString( match ) ); ft = ftNameToFt.get( match ); } } return ft; } /** * Returns the {@link FeatureStore} instance which is responsible for the specified feature type. * * @param ftName * name of the {@link FeatureType} * @return the responsible {@link FeatureStore} or <code>null</code> if no such store exists, i.e. the specified * feature type is not served */ public FeatureStore getStore( QName ftName ) { FeatureType ft = lookupFeatureType( ftName ); if ( ft == null ) { return null; } return schemaToStore.get( ft.getSchema() ); } /** * Get the prefix-to-namespace map that is constructed from the NamespaceHints in the configuration * * @return the prefix-to-namespace map */ public Map<String, String> getPrefixToNs() { return prefixToNs; } /** * Get the namespace-to-prefix bindings for the namespaces of the application schemas. * * @return the namespace-to-prefix map */ public Map<String, String> getTargetNsToPrefix() { return targetNsToPrefix; } /** * Returns all registered {@link FeatureStore} instances. * * @return all registered feature stores */ public FeatureStore[] getStores() { Set<FeatureStore> stores = new HashSet<FeatureStore>( schemaToStore.values() ); return stores.toArray( new FeatureStore[stores.size()] ); } /** * Registers a new {@link FeatureStore} to the WFS. * * @param fs * store to be registered */ public void addStore( FeatureStore fs ) { synchronized ( this ) { if ( schemaToStore.containsValue( fs ) ) { String msg = get( "WFS_FEATURESTORE_ALREADY_REGISTERED", fs ); LOG.error( msg ); throw new IllegalArgumentException( msg ); } for ( FeatureType ft : fs.getSchema().getFeatureTypes() ) { if ( ft.getName().getNamespaceURI().equals( GMLNS ) || ft.getName().getNamespaceURI().equals( GML3_2_NS ) ) { continue; } if ( ftNameToFt.containsKey( ft.getName() ) ) { String msg = get( "WFS_FEATURETYPE_ALREADY_SERVED", ft.getName() ); LOG.error( msg ); throw new IllegalArgumentException( msg ); } ftNameToFt.put( ft.getName(), ft ); } schemaToStore.put( fs.getSchema(), fs ); for ( Entry<String, String> e : fs.getSchema().getNamespaceBindings().entrySet() ) { prefixToNs.put( e.getKey(), e.getValue() ); targetNsToPrefix.put( e.getValue(), e.getKey() ); } } } /** * Deregisters the specified {@link FeatureStore} from the WFS. * * @param fs * store to be registered */ public void removeStore( FeatureStore fs ) { synchronized ( this ) { } } }
package dk.aau.sw402F15.TypeChecker; import dk.aau.sw402F15.Exception.TypeChecker.*; import dk.aau.sw402F15.Helper; import dk.aau.sw402F15.Symboltable.Scope; import dk.aau.sw402F15.Symboltable.Symbol; import dk.aau.sw402F15.Symboltable.SymbolArray; import dk.aau.sw402F15.Symboltable.SymbolFunction; import dk.aau.sw402F15.Symboltable.Type.SymbolType; import dk.aau.sw402F15.parser.analysis.DepthFirstAdapter; import dk.aau.sw402F15.parser.node.*; import sun.reflect.generics.reflectiveObjects.NotImplementedException; import java.util.ArrayList; import java.util.List; import java.util.Stack; public class ExpressionTypeEvaluator extends DepthFirstAdapter { private Stack<SymbolType> stack; private Scope scope; public ExpressionTypeEvaluator(Scope scope) { this.stack = new Stack<SymbolType>(); this.scope = scope; } public SymbolType getResult() { // Check if we only have 1 element on stack if (stack.size() != 1) { throw new NotImplementedException(); } return stack.pop(); } // Assignment @Override public void caseAAssignmentExpr(AAssignmentExpr node) { AssignmentTypeChecker assignmentChecker = new AssignmentTypeChecker(scope); node.apply(assignmentChecker); stack.push(assignmentChecker.getResult()); } // Member expression @Override public void caseAMemberExpr(AMemberExpr node) { MemberExpressionEvaluator memberExpressionEvaluator = new MemberExpressionEvaluator(scope); node.apply(memberExpressionEvaluator); stack.push(memberExpressionEvaluator.getSymbol()); } // Function call @Override public void caseAFunctionCallExpr(AFunctionCallExpr node) { Symbol symbol = scope.getSymbolOrThrow(node.getName().getText(), node); // Check if symbol is a function - if not throw a exception if (symbol.getClass() != SymbolFunction.class) { throw new RuntimeException(); } // Cast to symbolfunction SymbolFunction func = (SymbolFunction) symbol; // Check arguments { ExpressionTypeEvaluator expressionEvaluator = new ExpressionTypeEvaluator(scope); List<PExpr> copy = new ArrayList<PExpr>(node.getArgs()); // Check number of parameters if (copy.size() != func.getFormalParameters().size()) throw new WrongNumberOfParameters(node, func.getFormalParameters().size(), copy.size()); // Check each expression for (int i = 0; i < copy.size(); i++) { PExpr e = copy.get(i); // Get expression type e.apply(expressionEvaluator); SymbolType type = expressionEvaluator.getResult(); if (!type.equals(func.getFormalParameters().get(i))) throw new WrongParameterTypeException(node, func.getFormalParameters().get(i), type); } } // Push return type to stack stack.push(func.getReturnType()); } // Identifier (variables) @Override public void outAIdentifierExpr(AIdentifierExpr node) { super.outAIdentifierExpr(node); stack.push(scope.getSymbolOrThrow(node.getName().getText(), node).getType()); } // Constants @Override public void outAIntegerExpr(AIntegerExpr node) { super.outAIntegerExpr(node); stack.push(SymbolType.Int()); } @Override public void outADecimalExpr(ADecimalExpr node) { super.outADecimalExpr(node); stack.push(SymbolType.Decimal()); } @Override public void outATrueExpr(ATrueExpr node) { super.outATrueExpr(node); stack.push(SymbolType.Boolean()); } @Override public void outAFalseExpr(AFalseExpr node) { super.outAFalseExpr(node); stack.push(SymbolType.Boolean()); } // Casts @Override public void outATypeCastExpr(ATypeCastExpr node) { super.outATypeCastExpr(node); // Cast no typechecker test stack.pop(); stack.push(Helper.getSymbolTypeFromTypeSpecifier(node.getTargetType())); } // Increment and decrement @Override public void inAIncrementExpr(AIncrementExpr node) { super.inAIncrementExpr(node); // Push identifier on stack stack.push(scope.getSymbolOrThrow(node.getName().getText(), node).getType()); } @Override public void outAIncrementExpr(AIncrementExpr node) { super.outAIncrementExpr(node); checkUnary(node); } @Override public void inADecrementExpr(ADecrementExpr node) { super.inADecrementExpr(node); // Push identifier on stack stack.push(scope.getSymbolOrThrow(node.getName().getText(), node).getType()); } @Override public void outADecrementExpr(ADecrementExpr node) { super.outADecrementExpr(node); checkUnary(node); } // Unary plus and minus @Override public void outAUnaryPlusExpr(AUnaryPlusExpr node) { super.outAUnaryPlusExpr(node); checkUnary(node); } @Override public void outAUnaryMinusExpr(AUnaryMinusExpr node) { super.outAUnaryMinusExpr(node); checkUnary(node); } // Negation @Override public void outANegationExpr(ANegationExpr node) { super.outANegationExpr(node); checkUnaryBool(node); } // Logic comparison @Override public void outACompareAndExpr(ACompareAndExpr node) { super.outACompareAndExpr(node); checkLocicComparison(node); } @Override public void outACompareOrExpr(ACompareOrExpr node) { super.outACompareOrExpr(node); checkLocicComparison(node); } // Comparison @Override public void outACompareGreaterExpr(ACompareGreaterExpr node) { super.outACompareGreaterExpr(node); checkComparison(node, node.getLeft(), node.getRight()); } @Override public void outACompareLessExpr(ACompareLessExpr node) { super.outACompareLessExpr(node); checkComparison(node, node.getLeft(), node.getRight()); } @Override public void outACompareLessOrEqualExpr(ACompareLessOrEqualExpr node) { super.outACompareLessOrEqualExpr(node); checkComparison(node, node.getLeft(), node.getRight()); } @Override public void outACompareGreaterOrEqualExpr(ACompareGreaterOrEqualExpr node) { super.outACompareGreaterOrEqualExpr(node); checkComparison(node, node.getLeft(), node.getRight()); } @Override public void outACompareEqualExpr(ACompareEqualExpr node) { super.outACompareEqualExpr(node); checkComparisonEquality(node, node.getLeft(), node.getRight()); } @Override public void outACompareNotEqualExpr(ACompareNotEqualExpr node) { super.outACompareNotEqualExpr(node); checkComparisonEquality(node, node.getLeft(), node.getRight()); } // Math operations @Override public void outAAddExpr(AAddExpr node) { super.outAAddExpr(node); checkExpression(node, node.getLeft(), node.getRight()); } @Override public void outASubExpr(ASubExpr node) { super.outASubExpr(node); checkExpression(node, node.getLeft(), node.getRight()); } @Override public void outAMultiExpr(AMultiExpr node) { super.outAMultiExpr(node); checkExpression(node, node.getLeft(), node.getRight()); } @Override public void outADivExpr(ADivExpr node) { super.outADivExpr(node); checkExpression(node, node.getLeft(), node.getRight()); // Checking that we don't divide by zero if (node.getRight().getClass() == AIntegerExpr.class) { if (Integer.parseInt(((AIntegerExpr) node.getRight()).getIntegerLiteral().getText()) == 0) throw new DivisionByZeroException(node); } else if (node.getRight().getClass() == ADecimalExpr.class) { if (Float.parseFloat(((ADecimalExpr) node.getRight()).getDecimalLiteral().getText()) == 0.0) throw new DivisionByZeroException(node); } } @Override public void outAModExpr(AModExpr node) { super.outAModExpr(node); checkExpression(node, node.getLeft(), node.getRight()); } // Ternary expr @Override public void outATernaryExpr(ATernaryExpr node) { super.outATernaryExpr(node); // expr = expr ? expr // All 3 types needs to be equal SymbolType arg3 = stack.pop(), arg2 = stack.pop(), arg1 = stack.pop(); if (!arg1.equals(arg2) || !arg2.equals(arg3)) { throw new IncompaitbleTypesException(node, arg1, arg2, arg3); } } // Array expr @Override public void outAArrayExpr(AArrayExpr node) { super.outAArrayExpr(node); // Get type of index (needs to be an int, since index cannot be a floating point number) SymbolType arg1 = stack.pop(); if (!arg1.equals(SymbolType.Int())) { throw new ArrayIndexIsIntException(node); } // Check identifier it needs to be an array Symbol symbol = scope.getSymbolOrThrow(node.getName().getText(), node); if (!symbol.getType().equals(SymbolType.Array())) { throw new ArrayIndexOfNonArrayException(node); } // Push correct type to stack SymbolArray array = (SymbolArray) symbol; stack.push(array.getContainedType()); } // Helper methods for compare and math operations private void checkComparisonEquality(Node node, PExpr left, PExpr right) { SymbolType arg2 = stack.pop(), arg1 = stack.pop(); if (arg1.equals(arg2)) { stack.push(SymbolType.Boolean()); } else { throw new IncompaitbleTypesException(node, arg1, arg2); } } private void checkComparison(Node node, PExpr left, PExpr right) { SymbolType arg2 = stack.pop(), arg1 = stack.pop(); if ((arg1.equals(SymbolType.Type.Int) && arg2.equals(SymbolType.Type.Int)) || (arg1.equals(SymbolType.Type.Decimal) && arg2.equals(SymbolType.Type.Decimal))) { stack.push(SymbolType.Boolean()); } else if ((arg1.equals(SymbolType.Type.Decimal) && arg2.equals(SymbolType.Type.Int))) { // Promote right right.replaceBy(new ATypeCastExpr(new ADoubleTypeSpecifier(), (PExpr) right.clone())); stack.push(SymbolType.Boolean()); } else if ((arg1.equals(SymbolType.Type.Int) && arg2.equals(SymbolType.Type.Decimal))) { // Promote left left.replaceBy(new ATypeCastExpr(new ADoubleTypeSpecifier(), (PExpr) left.clone())); stack.push(SymbolType.Boolean()); } else { throw new IncompaitbleTypesException(node, arg1, arg2); } } private void checkLocicComparison(Node node) { SymbolType arg2 = stack.pop(), arg1 = stack.pop(); if ((arg1.equals(SymbolType.Type.Boolean) && arg2.equals(SymbolType.Type.Boolean))) { stack.push(SymbolType.Boolean()); } else { throw new IncompaitbleTypesException(node, arg1, arg2); } } private void checkExpression(Node node, PExpr left, PExpr right) { SymbolType arg2 = stack.pop(), arg1 = stack.pop(); if (arg1.equals(SymbolType.Type.Int) && arg2.equals(SymbolType.Type.Int)) { stack.push(SymbolType.Int()); } else if (arg1.equals(SymbolType.Type.Decimal) && arg2.equals(SymbolType.Type.Decimal)) { stack.push(SymbolType.Decimal()); } else if ((arg1.equals(SymbolType.Type.Decimal) && arg2.equals(SymbolType.Type.Int))) { // Promote right right.replaceBy(new ATypeCastExpr(new ADoubleTypeSpecifier(), (PExpr) right.clone())); stack.push(SymbolType.Decimal()); } else if ((arg1.equals(SymbolType.Type.Int) && arg2.equals(SymbolType.Type.Decimal))) { // Promote left left.replaceBy(new ATypeCastExpr(new ADoubleTypeSpecifier(), (PExpr) left.clone())); stack.push(SymbolType.Decimal()); } else { throw new IncompaitbleTypesException(node, arg1, arg2); } } private void checkUnary(Node node) { // Don't pop - we don't change type SymbolType type = stack.peek(); if (!type.equals(SymbolType.Type.Int) && !type.equals(SymbolType.Type.Decimal)) { throw new ExpectingIntOrDecimalException(node, type); } } private void checkUnaryBool(Node node) { // Don't pop - we don't change type SymbolType type = stack.peek(); if (!type.equals(SymbolType.Type.Boolean)) { throw new ExpectingBoolException(node, type); } } }
package org.hisp.dhis.system.deletion; import org.hisp.dhis.attribute.Attribute; import org.hisp.dhis.attribute.AttributeValue; import org.hisp.dhis.category.Category; import org.hisp.dhis.category.CategoryCombo; import org.hisp.dhis.category.CategoryOption; import org.hisp.dhis.category.CategoryOptionCombo; import org.hisp.dhis.category.CategoryOptionGroup; import org.hisp.dhis.category.CategoryOptionGroupSet; import org.hisp.dhis.chart.Chart; import org.hisp.dhis.color.Color; import org.hisp.dhis.color.ColorSet; import org.hisp.dhis.constant.Constant; import org.hisp.dhis.dashboard.Dashboard; import org.hisp.dhis.dashboard.DashboardItem; import org.hisp.dhis.dataapproval.DataApproval; import org.hisp.dhis.dataapproval.DataApprovalLevel; import org.hisp.dhis.dataapproval.DataApprovalWorkflow; import org.hisp.dhis.dataelement.DataElement; import org.hisp.dhis.dataelement.DataElementGroup; import org.hisp.dhis.dataelement.DataElementGroupSet; import org.hisp.dhis.dataentryform.DataEntryForm; import org.hisp.dhis.dataset.CompleteDataSetRegistration; import org.hisp.dhis.dataset.DataSet; import org.hisp.dhis.dataset.LockException; import org.hisp.dhis.dataset.Section; import org.hisp.dhis.dataset.notifications.DataSetNotificationTemplate; import org.hisp.dhis.datavalue.DataValue; import org.hisp.dhis.document.Document; import org.hisp.dhis.eventchart.EventChart; import org.hisp.dhis.eventdatavalue.EventDataValue; import org.hisp.dhis.eventreport.EventReport; import org.hisp.dhis.expression.Expression; import org.hisp.dhis.fileresource.FileResource; import org.hisp.dhis.i18n.locale.I18nLocale; import org.hisp.dhis.indicator.Indicator; import org.hisp.dhis.indicator.IndicatorGroup; import org.hisp.dhis.indicator.IndicatorGroupSet; import org.hisp.dhis.indicator.IndicatorType; import org.hisp.dhis.interpretation.Interpretation; import org.hisp.dhis.legend.Legend; import org.hisp.dhis.legend.LegendSet; import org.hisp.dhis.mapping.ExternalMapLayer; import org.hisp.dhis.mapping.Map; import org.hisp.dhis.mapping.MapView; import org.hisp.dhis.message.MessageConversation; import org.hisp.dhis.minmax.MinMaxDataElement; import org.hisp.dhis.option.Option; import org.hisp.dhis.option.OptionGroup; import org.hisp.dhis.option.OptionGroupSet; import org.hisp.dhis.option.OptionSet; import org.hisp.dhis.organisationunit.OrganisationUnit; import org.hisp.dhis.organisationunit.OrganisationUnitGroup; import org.hisp.dhis.organisationunit.OrganisationUnitGroupSet; import org.hisp.dhis.organisationunit.OrganisationUnitLevel; import org.hisp.dhis.period.Period; import org.hisp.dhis.period.RelativePeriods; import org.hisp.dhis.predictor.Predictor; import org.hisp.dhis.predictor.PredictorGroup; import org.hisp.dhis.program.Program; import org.hisp.dhis.program.ProgramExpression; import org.hisp.dhis.program.ProgramIndicator; import org.hisp.dhis.program.ProgramIndicatorGroup; import org.hisp.dhis.program.ProgramInstance; import org.hisp.dhis.program.ProgramStage; import org.hisp.dhis.program.ProgramStageDataElement; import org.hisp.dhis.program.ProgramStageInstance; import org.hisp.dhis.program.ProgramStageSection; import org.hisp.dhis.program.ProgramTrackedEntityAttribute; import org.hisp.dhis.program.ProgramTrackedEntityAttributeGroup; import org.hisp.dhis.program.message.ProgramMessage; import org.hisp.dhis.program.notification.ProgramNotificationTemplate; import org.hisp.dhis.programrule.ProgramRule; import org.hisp.dhis.programrule.ProgramRuleAction; import org.hisp.dhis.programrule.ProgramRuleVariable; import org.hisp.dhis.pushanalysis.PushAnalysis; import org.hisp.dhis.relationship.Relationship; import org.hisp.dhis.relationship.RelationshipType; import org.hisp.dhis.report.Report; import org.hisp.dhis.reporttable.ReportTable; import org.hisp.dhis.scheduling.JobConfiguration; import org.hisp.dhis.security.oauth2.OAuth2Client; import org.hisp.dhis.sms.command.SMSCommand; import org.hisp.dhis.sqlview.SqlView; import org.hisp.dhis.trackedentity.TrackedEntityAttribute; import org.hisp.dhis.trackedentity.TrackedEntityInstance; import org.hisp.dhis.trackedentity.TrackedEntityType; import org.hisp.dhis.trackedentityattributevalue.TrackedEntityAttributeValue; import org.hisp.dhis.trackedentitycomment.TrackedEntityComment; import org.hisp.dhis.user.User; import org.hisp.dhis.user.UserAuthorityGroup; import org.hisp.dhis.user.UserCredentials; import org.hisp.dhis.user.UserGroup; import org.hisp.dhis.user.UserSetting; import org.hisp.dhis.validation.ValidationResult; import org.hisp.dhis.validation.ValidationRule; import org.hisp.dhis.validation.ValidationRuleGroup; import org.hisp.dhis.validation.notification.ValidationNotificationTemplate; /** * A DeletionHandler should override methods for objects that, when deleted, * will affect the current object in any way. Eg. a DeletionHandler for * DataElementGroup should override the deleteDataElement(..) method which * should remove the DataElement from all DataElementGroups. Also, it should * override the allowDeleteDataElement() method and return a non-null String value * if there exists objects that are dependent on the DataElement and are * considered not be deleted. The return value could be a hint for which object * is denying the delete, like the name. * * @author Lars Helge Overland */ public abstract class DeletionHandler { protected static final String ERROR = ""; // Abstract methods protected abstract String getClassName(); // Public methods public void deleteAttribute( Attribute attribute ) { } public String allowDeleteAttribute( Attribute attribute ) { return null; } public void deleteAttributeValue( AttributeValue attributeValue ) { } public String allowDeleteAttributeValue( AttributeValue attributeValue ) { return null; } public void deleteChart( Chart chart ) { } public String allowDeleteChart( Chart chart ) { return null; } public void deleteDataApproval( DataApproval dataApproval ) { } public String allowDeleteDataApproval( DataApproval dataApproval ) { return null; } public void deleteDataApprovalLevel( DataApprovalLevel dataApprovalLevel ) { } public String allowDeleteDataApprovalLevel( DataApprovalLevel dataApprovalLevel ) { return null; } public void deleteDataApprovalWorkflow( DataApprovalWorkflow workflow ) { } public String allowDeleteDataApprovalWorkflow( DataApprovalWorkflow workflow ) { return null; } public void deleteDataElement( DataElement dataElement ) { } public String allowDeleteDataElement( DataElement dataElement ) { return null; } public void deleteDataElementGroup( DataElementGroup dataElementGroup ) { } public String allowDeleteDataElementGroup( DataElementGroup dataElementGroup ) { return null; } public void deleteDataElementGroupSet( DataElementGroupSet dataElementGroupSet ) { } public String allowDeleteDataElementGroupSet( DataElementGroupSet dataElementGroupSet ) { return null; } public void deleteCategory( Category category ) { } public String allowDeleteCategory( Category category ) { return null; } public void deleteCategoryOption( CategoryOption categoryOption ) { } public String allowDeleteCategoryOption( CategoryOption categoryOption ) { return null; } public void deleteCategoryCombo( CategoryCombo categoryCombo ) { } public String allowDeleteCategoryCombo( CategoryCombo categoryCombo ) { return null; } public void deleteCategoryOptionCombo( CategoryOptionCombo categoryOptionCombo ) { } public String allowDeleteCategoryOptionCombo( CategoryOptionCombo categoryOptionCombo ) { return null; } public void deleteProgramMessage( ProgramMessage programMessage ) { } public String allowDeleteProgramMessage( ProgramMessage programMessage ) { return null; } public void deleteDataSet( DataSet dataSet ) { } public String allowDeleteDataSet( DataSet dataSet ) { return null; } public void deleteSection( Section section ) { } public String allowDeleteSection( Section section ) { return null; } public void deleteCompleteDataSetRegistration( CompleteDataSetRegistration registration ) { } public String allowDeleteCompleteDataSetRegistration( CompleteDataSetRegistration registration ) { return null; } public void deleteDataValue( DataValue dataValue ) { } public String allowDeleteDataValue( DataValue dataValue ) { return null; } public void deleteExpression( Expression expression ) { } public String allowDeleteExpression( Expression expression ) { return null; } public void deleteMinMaxDataElement( MinMaxDataElement minMaxDataElement ) { } public String allowDeleteMinMaxDataElement( MinMaxDataElement minMaxDataElement ) { return null; } public void deleteIndicator( Indicator indicator ) { } public String allowDeleteIndicator( Indicator indicator ) { return null; } public void deleteIndicatorGroup( IndicatorGroup indicatorGroup ) { } public String allowDeleteIndicatorGroup( IndicatorGroup indicatorGroup ) { return null; } public void deleteIndicatorType( IndicatorType indicatorType ) { } public String allowDeleteIndicatorType( IndicatorType indicatorType ) { return null; } public void deleteIndicatorGroupSet( IndicatorGroupSet indicatorGroupSet ) { } public String allowDeleteIndicatorGroupSet( IndicatorGroupSet indicatorGroupSet ) { return null; } public void deletePeriod( Period period ) { } public String allowDeletePeriod( Period period ) { return null; } public void deleteRelativePeriods( RelativePeriods relativePeriods ) { } public String allowDeleteRelativePeriods( RelativePeriods relativePeriods ) { return null; } public void deletePredictor( Predictor predictor ) { } public String allowDeletePredictor( Predictor predictor ) { return null; } public void deletePredictorGroup( PredictorGroup predictorGroup ) { } public String allowDeletePredictorGroup( PredictorGroup predictorGroup ) { return null; } public void deleteValidationRule( ValidationRule validationRule ) { } public String allowDeleteValidationRule( ValidationRule validationRule ) { return null; } public String allowDeleteValidationResult( ValidationResult validationResult ) { return null; } public void deleteValidationRuleGroup( ValidationRuleGroup validationRuleGroup ) { } public String allowDeleteValidationRuleGroup( ValidationRuleGroup validationRuleGroup ) { return null; } public void deleteDataEntryForm( DataEntryForm form ) { } public String allowDeleteValidationNotificationTemplate( ValidationNotificationTemplate vrnt ) { return null; } public void deleteValidationNotificationTemplate( ValidationNotificationTemplate vrnt ) { } public String allowDeleteDataEntryForm( DataEntryForm form ) { return null; } public void deleteOrganisationUnit( OrganisationUnit unit ) { } public String allowDeleteOrganisationUnit( OrganisationUnit unit ) { return null; } public void deleteOrganisationUnitGroup( OrganisationUnitGroup group ) { } public String allowDeleteOrganisationUnitGroup( OrganisationUnitGroup group ) { return null; } public void deleteOrganisationUnitGroupSet( OrganisationUnitGroupSet groupSet ) { } public String allowDeleteOrganisationUnitGroupSet( OrganisationUnitGroupSet groupSet ) { return null; } public void deleteOrganisationUnitLevel( OrganisationUnitLevel level ) { } public String allowDeleteOrganisationUnitLevel( OrganisationUnitLevel level ) { return null; } public void deleteReport( Report report ) { } public String allowDeleteReport( Report report ) { return null; } public void deleteReportTable( ReportTable reportTable ) { } public String allowDeleteReportTable( ReportTable reportTable ) { return null; } public void deleteUser( User user ) { } public String allowDeleteUser( User user ) { return null; } public void deleteUserCredentials( UserCredentials credentials ) { } public String allowDeleteUserCredentials( UserCredentials credentials ) { return null; } public void deleteUserAuthorityGroup( UserAuthorityGroup authorityGroup ) { } public String allowDeleteUserAuthorityGroup( UserAuthorityGroup authorityGroup ) { return null; } public String allowDeleteUserGroup( UserGroup userGroup ) { return null; } public void deleteUserGroup( UserGroup userGroup ) { } public void deleteUserSetting( UserSetting userSetting ) { } public String allowDeleteUserSetting( UserSetting userSetting ) { return null; } public void deleteDocument( Document document ) { } public String allowDeleteDocument( Document document ) { return null; } public void deleteLegend( Legend mapLegend ) { } public String allowDeleteLegend( Legend mapLegend ) { return null; } public void deleteLegendSet( LegendSet legendSet ) { } public String allowDeleteLegendSet( LegendSet legendSet ) { return null; } public void deleteMap( Map map ) { } public String allowDeleteMap( Map map ) { return null; } public void deleteExternalMapLayer( ExternalMapLayer externalMapLayer ) { } public String allowDeleteExternalMapLayer( ExternalMapLayer externalMapLayer ) { return null; } public void deleteMapView( MapView mapView ) { } public String allowDeleteMapView( MapView mapView ) { return null; } public void deleteInterpretation( Interpretation interpretation ) { } public String allowDeleteIntepretation( Interpretation interpretation ) { return null; } public void deleteTrackedEntityInstance( TrackedEntityInstance entityInstance ) { } public String allowDeleteTrackedEntityInstance( TrackedEntityInstance entityInstance ) { return null; } public void deleteTrackedEntityComment( TrackedEntityComment entityComment ) { } public String allowDeleteTrackedEntityComment( TrackedEntityComment entityComment ) { return null; } public void deleteTrackedEntityAttribute( TrackedEntityAttribute attribute ) { } public String allowDeleteTrackedEntityAttribute( TrackedEntityAttribute attribute ) { return null; } public void deleteTrackedEntityAttributeValue( TrackedEntityAttributeValue attributeValue ) { } public String allowDeleteTrackedEntityAttributeValue( TrackedEntityAttributeValue attributeValue ) { return null; } public void deleteRelationship( Relationship relationship ) { } public String allowDeleteRelationship( Relationship relationship ) { return null; } public void deleteRelationshipType( RelationshipType relationshipType ) { } public String allowDeleteRelationshipType( RelationshipType relationshipType ) { return null; } public void deleteProgram( Program program ) { } public String allowDeleteProgram( Program program ) { return null; } public void deleteProgramInstance( ProgramInstance programInstance ) { } public String allowDeleteProgramInstance( ProgramInstance programInstance ) { return null; } public void deleteProgramStage( ProgramStage programStage ) { } public String allowDeleteProgramStage( ProgramStage programStage ) { return null; } public void deleteProgramStageSection( ProgramStageSection programStageSection ) { } public String allowDeleteProgramStageSection( ProgramStageSection programStageSection ) { return null; } public void deleteProgramStageInstance( ProgramStageInstance programStageInstance ) { } public String allowDeleteProgramStageInstance( ProgramStageInstance programStageInstance ) { return null; } public void deleteProgramNotificationTemplate( ProgramNotificationTemplate programNotificationTemplate ) { } public void allowDeleteProgramNotificationTemplate( ProgramNotificationTemplate programNotificationTemplate ) { } public void deleteProgramRule( ProgramRule programRule ) { } public String allowDeleteProgramRule( ProgramRule programRule ) { return null; } public void deleteProgramRuleVariable( ProgramRuleVariable programRuleVariable ) { } public String allowDeleteProgramRuleVariable( ProgramRuleVariable programRuleVariable ) { return null; } public void deleteProgramRuleAction( ProgramRuleAction programRuleAction ) { } public String allowDeleteProgramRuleAction( ProgramRuleAction programRuleAction ) { return null; } public void deleteProgramStageDataElement( ProgramStageDataElement programStageDataElement ) { } public String allowDeleteProgramStageDataElement( ProgramStageDataElement programStageDataElement ) { return null; } public void deleteEventDataValue( EventDataValue eventDataValue ) { } public String allowDeleteEventDataValue( EventDataValue eventDataValue ) { return null; } public void deleteProgramIndicator( ProgramIndicator programIndicator ) { } public String allowDeleteProgramIndicator( ProgramIndicator programIndicator ) { return null; } public void deleteProgramIndicatorGroup( ProgramIndicatorGroup programIndicatorGroup ) { } public String allowDeleteProgramIndicatorGroup( ProgramIndicatorGroup programIndicatorGroup ) { return null; } public void deleteProgramExpression( ProgramExpression programExpression ) { } public String allowDeleteProgramExpression( ProgramExpression programExpression ) { return null; } public void deleteConstant( Constant constant ) { } public String allowDeleteConstant( Constant constant ) { return null; } public void deleteOptionSet( OptionSet optionSet ) { } public String allowDeleteOptionSet( OptionSet optionSet ) { return null; } public void deleteOptionGroupSet( OptionGroupSet optionGroupSet ) { } public String allowDeleteOptionGroupSet( OptionGroupSet optionGroupSet ) { return null; } public void deleteOptionGroup( OptionGroup optionGroup ) { } public String allowDeleteOptionGroup( OptionGroup optionGroup ) { return null; } public void deleteOption( Option optionSet ) { } public String allowDeleteOption( Option option ) { return null; } public void deleteLockException( LockException lockException ) { } public String allowDeleteLockException( LockException lockException ) { return null; } public void deleteIntepretation( Interpretation interpretation ) { } public String allowDeleteInterpretation( Interpretation interpretation ) { return null; } public void deleteI18nLocale( I18nLocale i18nLocale ) { } public String allowDeleteI18nLocale( I18nLocale i18nLocale ) { return null; } public void deleteSqlView( SqlView sqlView ) { } public String allowDeleteSqlView( SqlView sqlView ) { return null; } public void deleteDashboard( Dashboard dashboard ) { } public String allowDeleteDashboard( Dashboard dashboard ) { return null; } public void deleteDashboardItem( DashboardItem dashboardItem ) { } public String allowDeleteDashboardItem( DashboardItem dashboardItem ) { return null; } public void deleteCategoryOptionGroup( CategoryOptionGroup categoryOptionGroup ) { } public String allowDeleteCategoryOptionGroup( CategoryOptionGroup categoryOptionGroup ) { return null; } public void deleteCategoryOptionGroupSet( CategoryOptionGroupSet categoryOptionGroupSet ) { } public String allowDeleteCategoryOptionGroupSet( CategoryOptionGroupSet categoryOptionGroupSet ) { return null; } public void deleteTrackedEntityType( TrackedEntityType trackedEntityType ) { } public String allowDeleteTrackedEntityType( TrackedEntityType trackedEntityType ) { return null; } public void deleteEventReport( EventReport eventReport ) { } public String allowDeleteEventReport( EventReport eventReport ) { return null; } public void deleteEventChart( EventChart eventChart ) { } public String allowDeleteEventChart( EventChart eventChart ) { return null; } public void deleteOAuth2Client( OAuth2Client oAuth2Client ) { } public String allowDeleteOAuth2Client( OAuth2Client oAuth2Client ) { return null; } public void deleteColorSet( ColorSet colorSet ) { } public String allowDeleteColorSet( ColorSet colorSet ) { return null; } public void deleteColor( Color color ) { } public String allowDeleteColor( Color color ) { return null; } public void deleteProgramTrackedEntityAttribute( ProgramTrackedEntityAttribute attribute ) { } public String allowDeleteProgramTrackedEntityAttribute( ProgramTrackedEntityAttribute attribute ) { return null; } public void deleteProgramTrackedEntityAttributeGroup( ProgramTrackedEntityAttributeGroup color ) { } public String allowDeleteProgramTrackedEntityAttributeGroup( ProgramTrackedEntityAttributeGroup group ) { return null; } public void deletePushAnalysis( PushAnalysis pushAnalysis ) { } public String allowDeletePushAnalysis( PushAnalysis pushAnalysis ) { return null; } public void deleteDataSetNotificationTemplate( DataSetNotificationTemplate dataSetNotificationTemplate ) { } public String allowDeleteDataSetNotificationTemplate( DataSetNotificationTemplate dataSetNotificationTemplate ) { return null; } public void deleteSMSCommand( SMSCommand smsCommand ) { } public String allowDeleteSMSCommand( SMSCommand smsCommand ) { return null; } public void deleteMessageConversation( MessageConversation messageConversation ) { } public String allowDeleteMessageConversation( MessageConversation messageConversation ) { return null; } public void deleteJobConfiguration( JobConfiguration jobConfiguration ) { } public String allowDeleteJobConfiguration(JobConfiguration jobConfiguration ) { return null; } public String allowDeleteFileResource( FileResource fileResource ) { return null; } public void deleteFileResource( FileResource fileResource ) { } }
package crazypants.enderio.base.item.darksteel.upgrade.elytra; import javax.annotation.Nonnull; import crazypants.enderio.api.upgrades.IRenderUpgrade; import crazypants.enderio.base.EnderIO; import net.minecraft.client.entity.AbstractClientPlayer; import net.minecraft.client.model.ModelElytra; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.renderer.entity.RenderPlayer; import net.minecraft.client.renderer.entity.layers.LayerArmorBase; import net.minecraft.entity.player.EnumPlayerModelParts; import net.minecraft.inventory.EntityEquipmentSlot; import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; public class ElytraUpgradeLayer implements IRenderUpgrade { private static final @Nonnull ResourceLocation TEXTURE_ELYTRA = new ResourceLocation(EnderIO.DOMAIN, "textures/models/armor/elytra.png"); private final @Nonnull ModelElytra modelElytra = new ModelElytra(); public static final @Nonnull ElytraUpgradeLayer instance = new ElytraUpgradeLayer(); private ElytraUpgradeLayer() { } @Override public void doRenderLayer(@Nonnull RenderPlayer renderPlayer, EntityEquipmentSlot equipmentSlot, @Nonnull ItemStack piece, @Nonnull AbstractClientPlayer entitylivingbaseIn, float limbSwing, float limbSwingAmount, float partialTicks, float ageInTicks, float netHeadYaw, float headPitch, float scale) { if (equipmentSlot != EntityEquipmentSlot.CHEST) { return; } GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); GlStateManager.enableBlend(); GlStateManager.blendFunc(GlStateManager.SourceFactor.ONE, GlStateManager.DestFactor.ZERO); final ResourceLocation locationElytra = entitylivingbaseIn.getLocationElytra(); if (entitylivingbaseIn.isPlayerInfoSet() && locationElytra != null) { renderPlayer.bindTexture(locationElytra); } else { final ResourceLocation locationCape = entitylivingbaseIn.getLocationCape(); if (entitylivingbaseIn.hasPlayerInfo() && locationCape != null && entitylivingbaseIn.isWearing(EnumPlayerModelParts.CAPE)) { renderPlayer.bindTexture(locationCape); } else { renderPlayer.bindTexture(TEXTURE_ELYTRA); } } GlStateManager.pushMatrix(); GlStateManager.translate(0.0F, 0.0F, 0.125F); modelElytra.setRotationAngles(limbSwing, limbSwingAmount, ageInTicks, netHeadYaw, headPitch, scale, entitylivingbaseIn); modelElytra.render(entitylivingbaseIn, limbSwing, limbSwingAmount, ageInTicks, netHeadYaw, headPitch, scale); if (piece.isItemEnchanted()) { LayerArmorBase.renderEnchantedGlint(renderPlayer, entitylivingbaseIn, modelElytra, limbSwing, limbSwingAmount, partialTicks, ageInTicks, netHeadYaw, headPitch, scale); } GlStateManager.disableBlend(); GlStateManager.popMatrix(); } }
package org.eclipse.birt.report.engine.emitter; import org.eclipse.birt.report.engine.content.IAutoTextContent; import org.eclipse.birt.report.engine.content.ICellContent; import org.eclipse.birt.report.engine.content.IContainerContent; import org.eclipse.birt.report.engine.content.IContent; import org.eclipse.birt.report.engine.content.IContentVisitor; import org.eclipse.birt.report.engine.content.IDataContent; import org.eclipse.birt.report.engine.content.IForeignContent; import org.eclipse.birt.report.engine.content.IGroupContent; import org.eclipse.birt.report.engine.content.IImageContent; import org.eclipse.birt.report.engine.content.ILabelContent; import org.eclipse.birt.report.engine.content.IListBandContent; import org.eclipse.birt.report.engine.content.IListContent; import org.eclipse.birt.report.engine.content.IListGroupContent; import org.eclipse.birt.report.engine.content.IPageContent; import org.eclipse.birt.report.engine.content.IRowContent; import org.eclipse.birt.report.engine.content.ITableBandContent; import org.eclipse.birt.report.engine.content.ITableContent; import org.eclipse.birt.report.engine.content.ITableGroupContent; import org.eclipse.birt.report.engine.content.ITextContent; public class ContentEmitterUtil { static IContentVisitor starter = new StartContentVisitor( ); static IContentVisitor ender = new EndContentVisitor( ); static public void startContent( IContent content, IContentEmitter emitter ) { String vformat = content.getStyle( ).getVisibleFormat( ); if ( vformat == null ) { starter.visit( content, emitter ); } else { if ( vformat.toLowerCase( ).indexOf( emitter.getOutputFormat( ).toLowerCase( ) ) > 0 || vformat.toLowerCase( ).indexOf( "all" ) > 0 ) { starter.visit( content, emitter ); } } } static public void endContent( IContent content, IContentEmitter emitter ) { String vformat = content.getStyle( ).getVisibleFormat( ); String format = emitter.getOutputFormat( ); if ( vformat == null ) { ender.visit( content, emitter ); } else { if ( vformat.toLowerCase( ).indexOf( emitter.getOutputFormat( ).toLowerCase( ) ) > 0 || vformat.toLowerCase( ).indexOf( "all" ) > 0 ) { ender.visit( content, emitter ); } } } private static class StartContentVisitor implements IContentVisitor { public Object visit( IContent content, Object value ) { return content.accept( this, value ); } public Object visitContent( IContent content, Object value ) { IContentEmitter emitter = (IContentEmitter) value; emitter.startContent( content ); return value; } public Object visitPage( IPageContent page, Object value ) { IContentEmitter emitter = (IContentEmitter) value; emitter.startPage( page ); return value; } public Object visitContainer( IContainerContent container, Object value ) { IContentEmitter emitter = (IContentEmitter) value; emitter.startContainer( container ); return value; } public Object visitTable( ITableContent table, Object value ) { IContentEmitter emitter = (IContentEmitter) value; emitter.startTable( table ); return value; } public Object visitTableBand( ITableBandContent tableBand, Object value ) { IContentEmitter emitter = (IContentEmitter) value; emitter.startTableBand( tableBand ); return value; } public Object visitRow( IRowContent row, Object value ) { IContentEmitter emitter = (IContentEmitter) value; emitter.startRow( row ); return value; } public Object visitCell( ICellContent cell, Object value ) { IContentEmitter emitter = (IContentEmitter) value; emitter.startCell( cell ); return value; } public Object visitText( ITextContent text, Object value ) { IContentEmitter emitter = (IContentEmitter) value; emitter.startText( text ); return value; } public Object visitLabel( ILabelContent label, Object value ) { IContentEmitter emitter = (IContentEmitter) value; emitter.startLabel( label ); return value; } public Object visitAutoText( IAutoTextContent autoText, Object value ) { IContentEmitter emitter = (IContentEmitter) value; emitter.startAutoText( autoText ); return value; } public Object visitData( IDataContent data, Object value ) { IContentEmitter emitter = (IContentEmitter) value; emitter.startData( data ); return value; } public Object visitImage( IImageContent image, Object value ) { IContentEmitter emitter = (IContentEmitter) value; emitter.startImage( image ); return value; } public Object visitForeign( IForeignContent content, Object value ) { IContentEmitter emitter = (IContentEmitter) value; emitter.startForeign( content ); return value; } public Object visitList( IListContent list, Object value ) { IContentEmitter emitter = (IContentEmitter) value; emitter.startList( list ); return value; } public Object visitListBand( IListBandContent listBand, Object value ) { IContentEmitter emitter = (IContentEmitter) value; emitter.startListBand( listBand ); return value; } public Object visitGroup( IGroupContent group, Object value ) { IContentEmitter emitter = (IContentEmitter) value; emitter.startGroup( group ); return value; } public Object visitListGroup( IListGroupContent group, Object value ) { IContentEmitter emitter = (IContentEmitter) value; emitter.startListGroup( group ); return value; } public Object visitTableGroup( ITableGroupContent group, Object value ) { IContentEmitter emitter = (IContentEmitter) value; emitter.startTableGroup( group ); return value; } } static private class EndContentVisitor implements IContentVisitor { public Object visit( IContent content, Object value ) { return content.accept( this, value ); } public Object visitContent( IContent content, Object value ) { IContentEmitter emitter = (IContentEmitter) value; emitter.endContent( content ); return value; } public Object visitPage( IPageContent page, Object value ) { IContentEmitter emitter = (IContentEmitter) value; emitter.endPage( page ); return value; } public Object visitContainer( IContainerContent container, Object value ) { IContentEmitter emitter = (IContentEmitter) value; emitter.endContainer( container ); return value; } public Object visitTable( ITableContent table, Object value ) { IContentEmitter emitter = (IContentEmitter) value; emitter.endTable( table ); return value; } public Object visitTableBand( ITableBandContent tableBand, Object value ) { IContentEmitter emitter = (IContentEmitter) value; emitter.endTableBand( tableBand ); return value; } public Object visitRow( IRowContent row, Object value ) { IContentEmitter emitter = (IContentEmitter) value; emitter.endRow( row ); return value; } public Object visitCell( ICellContent cell, Object value ) { IContentEmitter emitter = (IContentEmitter) value; emitter.endCell( cell ); return value; } public Object visitText( ITextContent text, Object value ) { return value; } public Object visitLabel( ILabelContent label, Object value ) { return value; } public Object visitAutoText( IAutoTextContent autoText, Object value ) { return value; } public Object visitData( IDataContent data, Object value ) { return value; } public Object visitImage( IImageContent image, Object value ) { return value; } public Object visitForeign( IForeignContent content, Object value ) { return value; } public Object visitList( IListContent list, Object value ) { IContentEmitter emitter = (IContentEmitter) value; emitter.endList( list ); return value; } public Object visitListBand( IListBandContent listBand, Object value ) { IContentEmitter emitter = (IContentEmitter) value; emitter.endListBand( listBand ); return value; } public Object visitGroup( IGroupContent group, Object value ) { IContentEmitter emitter = (IContentEmitter) value; emitter.endGroup( group ); return value; } public Object visitListGroup( IListGroupContent group, Object value ) { IContentEmitter emitter = (IContentEmitter) value; emitter.endListGroup( group ); return value; } public Object visitTableGroup( ITableGroupContent group, Object value ) { IContentEmitter emitter = (IContentEmitter) value; emitter.endTableGroup( group ); return value; } } }
package org.eclipse.birt.report.engine.nLayout.area.impl; import java.util.ArrayList; import java.util.Iterator; import org.eclipse.birt.core.exception.BirtException; import org.eclipse.birt.report.engine.content.IStyle; import org.eclipse.birt.report.engine.content.ITextContent; import org.eclipse.birt.report.engine.css.engine.StyleConstants; import org.eclipse.birt.report.engine.layout.pdf.util.PropertyUtil; import org.eclipse.birt.report.engine.nLayout.LayoutContext; import org.eclipse.birt.report.engine.nLayout.area.IArea; import org.eclipse.birt.report.engine.nLayout.area.style.BoxStyle; import org.eclipse.birt.report.engine.nLayout.area.style.TextStyle; import org.eclipse.birt.report.engine.util.BidiAlignmentResolver; import org.w3c.dom.css.CSSValue; import com.ibm.icu.text.Bidi; public class LineArea extends InlineStackingArea { protected byte baseLevel = Bidi.DIRECTION_LEFT_TO_RIGHT; protected boolean setIndent = false; public LineArea( ContainerArea parent, LayoutContext context ) { super( parent, context, null ); assert(parent!=null); isInInlineStacking = parent.isInInlineStacking; } public LineArea( LineArea area ) { super( area ); this.baseLevel = area.baseLevel; this.isInlineStacking = true; } public void setBaseLevel( byte baseLevel ) { this.baseLevel = baseLevel; } public void addChild( IArea area ) { // FIXME ? int childHorizontalSpan = area.getX( ) + area.getWidth( ); int childVerticalSpan = area.getY( ) + area.getHeight( ); if ( childHorizontalSpan > width ) { setWidth( childHorizontalSpan ); } if ( childVerticalSpan > height ) { setHeight( childVerticalSpan ); } children.add( area ); } public void setTextIndent( ITextContent content ) { if ( currentIP == 0 && !setIndent && content != null ) { IStyle contentStyle = content.getComputedStyle( ); currentIP = PropertyUtil.getDimensionValue( contentStyle .getProperty( StyleConstants.STYLE_TEXT_INDENT ), maxAvaWidth ) ; setIndent = true; } } public void align( boolean endParagraph, LayoutContext context ) { assert ( parent instanceof BlockContainerArea ); CSSValue align = ( (BlockContainerArea) parent ).getTextAlign( ); // bidi_hcg: handle empty and justify align in RTL direction as right // alignment boolean isRightAligned = BidiAlignmentResolver.isRightAligned( parent.content, align, endParagraph ); // single line if ( ( isRightAligned || IStyle.CENTER_VALUE.equals( align ) ) ) { int spacing = width - currentIP; Iterator iter = getChildren( ); while ( iter.hasNext( ) ) { AbstractArea area = (AbstractArea) iter.next( ); if ( isRightAligned ) { if ( parent.content.isDirectionRTL( ) ) { area.setPosition( spacing + area.getX( ), area.getY( ) ); } else { area.setPosition( spacing + area.getX( ) + ignoreRightMostWhiteSpace( ), area.getY( ) ); } } else if ( IStyle.CENTER_VALUE.equals( align ) ) { area.setPosition( spacing / 2 + area.getX( ), area.getY( ) ); } } } else if ( IStyle.JUSTIFY_VALUE.equals( align ) && !endParagraph ) { justify( ); } if ( context.getBidiProcessing( ) ) reorderVisually( this ); verticalAlign( ); } private int ignoreRightMostWhiteSpace( ) { AbstractArea area = this; while ( area instanceof ContainerArea ) { ArrayList children = ( (ContainerArea) area ).children; if ( children != null && children.size( ) > 0 ) { area = (AbstractArea) children.get( children.size( ) - 1 ); } else { return 0; } if ( area instanceof TextArea ) { String text = ( (TextArea) area ).getText( ); if ( null != text ) { char[] charArray = text.toCharArray( ); int len = charArray.length; while ( len > 0 && ( charArray[len - 1] <= ' ' ) ) { len } if ( len != charArray.length ) { return ( (TextArea) area ).getTextWidth( text .substring( len ) ); } } } } return 0; } private int adjustWordSpacing( int wordSpacing, ContainerArea area ) { if ( wordSpacing == 0 ) return 0; Iterator iter = area.getChildren( ); int delta = 0; while ( iter.hasNext( ) ) { AbstractArea child = (AbstractArea) iter.next( ); if ( child instanceof TextArea ) { TextArea textArea = (TextArea) child; int whiteSpaceNumber = textArea.getWhiteSpaceNumber( ); if ( whiteSpaceNumber > 0 ) { TextStyle style = new TextStyle( textArea.getStyle( ) ); int original = style.getWordSpacing( ); style.setWordSpacing( original + wordSpacing ); textArea.setStyle( style ); int spacing = wordSpacing * whiteSpaceNumber; child.setWidth( child.getWidth( ) + spacing ); child.setPosition( child.getX( ) + delta, child.getY( ) ); delta += spacing; } } else if ( child instanceof ContainerArea ) { child.setPosition( child.getX( ) + delta, child.getY( ) ); int spacing = adjustWordSpacing( wordSpacing, (ContainerArea) child ); child.setWidth( child.getWidth( ) + spacing ); delta += spacing; } else { child.setPosition( child.getX( ) + delta, child.getY( ) ); } } return delta; } private int adjustLetterSpacing( int letterSpacing, ContainerArea area ) { Iterator iter = area.getChildren( ); int delta = 0; while ( iter.hasNext( ) ) { AbstractArea child = (AbstractArea) iter.next( ); if ( child instanceof TextArea ) { TextArea textArea = (TextArea) child; String text = textArea.getText( ); int letterSpacingNumber = ( text.length( ) > 1 ? ( text.length( ) - 1 ) : 0 ); TextStyle style = new TextStyle( textArea.getStyle( ) ); int original = style.getLetterSpacing( ); style.setLetterSpacing( original + letterSpacing ); textArea.setStyle( style ); int spacing = letterSpacing * letterSpacingNumber; child.setWidth( child.getWidth( ) + spacing ); child.setPosition( child.getX( ) + delta, child.getY( ) ); delta += spacing; } else if ( child instanceof ContainerArea ) { child.setPosition( child.getX( ) + delta, child.getY( ) ); int spacing = adjustLetterSpacing( letterSpacing, (ContainerArea) child ); child.setWidth( child.getWidth( ) + spacing ); delta += spacing; } else { child.setPosition( child.getX( ) + delta, child.getY( ) ); } } return delta; } /** * The last text area in a line. This field is only used for text alignment "justify". */ private TextArea lastTextAreaForJustify = null; /** * Gets the white space number, and the right most white spaces are ignored. * @param line * @return */ private int getWhiteSpaceNumber( LineArea line ) { int count = getWhiteSpaceRawNumber( line ); if ( lastTextAreaForJustify != null ) { String text = lastTextAreaForJustify.getText( ); if ( null != text ) { char[] charArray = text.toCharArray( ); int len = charArray.length; while ( len > 0 && ( charArray[len - 1] <= ' ' ) ) { len } if ( len != charArray.length ) { count = count - ( charArray.length - len ); lastTextAreaForJustify .setWhiteSpaceNumber( lastTextAreaForJustify .getWhiteSpaceNumber( ) - ( charArray.length - len ) ); lastTextAreaForJustify.setText( text.substring( 0, len ) ); lastTextAreaForJustify = null; } } } return count; } /** * Gets the white space number. * @param area * @return */ private int getWhiteSpaceRawNumber( ContainerArea area ) { int count = 0; Iterator iter = area.getChildren( ); while ( iter.hasNext( ) ) { AbstractArea child = (AbstractArea) iter.next( ); if ( child instanceof TextArea ) { int innerCount = 0; String text = ( (TextArea) child ).getText( ); for ( int i = 0; i < text.length( ); i++ ) { if ( text.charAt( i ) <= ' ' ) { innerCount++; } } count += innerCount; ((TextArea) child).setWhiteSpaceNumber( innerCount ); lastTextAreaForJustify = (TextArea) child; } else if ( child instanceof ContainerArea ) { count += getWhiteSpaceRawNumber( (ContainerArea) child ); } } return count; } private int getLetterNumber( ContainerArea area ) { int count = 0; Iterator iter = area.getChildren( ); while ( iter.hasNext( ) ) { AbstractArea child = (AbstractArea) iter.next( ); if ( child instanceof TextArea ) { String text = ( (TextArea) child ).getText( ); count = text.length( ); } else if ( child instanceof ContainerArea ) { count += getLetterNumber( (ContainerArea) child ); } } return count; } protected void justify( ) { // 1. Gets the white space number. The last white space of a line should not be counted. // 2. adjust the position for every text area in the line and ignore the right most white space by modifying the text. int spacing = width - currentIP; int whiteSpaceNumber = getWhiteSpaceNumber( this ); if ( whiteSpaceNumber > 0 ) { int wordSpacing = spacing / whiteSpaceNumber; adjustWordSpacing( wordSpacing, this ); } else { int letterNumber = getLetterNumber( this ); if ( letterNumber > 1 ) { int letterSpacing = spacing / ( letterNumber - 1 ); adjustLetterSpacing( letterSpacing, this ); } } } /** * Puts container's child areas into the visual (display) order and * repositions them following that order horizontally. * * @author Lina Kemmel */ private void reorderVisually( ContainerArea parent ) { int n = parent.getChildrenCount( ); if ( n == 0 ) return; int i = 0; AbstractArea[] areas = new AbstractArea[n]; byte[] levels = new byte[n]; Iterator<?> iter = parent.getChildren( ); for ( ; i < n && iter.hasNext( ); i++ ) { AbstractArea area = (AbstractArea) iter.next( ); areas[i] = area; if ( area instanceof TextArea ) levels[i] = (byte) ( (TextArea) area ).getRunLevel( ); else { levels[i] = baseLevel; if ( area instanceof InlineStackingArea ) { // We assume that each inline container area should be // treated as an inline block-level element. reorderVisually( (ContainerArea) area ); } } } if ( n > 1 ) { int x = areas[0].getAllocatedX( ); Bidi.reorderVisually( levels, 0, areas, 0, n ); for ( i = 0; i < n - 1; i++ ) { if ( !areas[i].isIgnoreReordering( ) ) { areas[i] .setAllocatedPosition( x, areas[i].getAllocatedY( ) ); x += areas[i].getAllocatedWidth( ); } } if ( !areas[i].isIgnoreReordering( ) ) { areas[i].setAllocatedPosition( x, areas[i].getAllocatedY( ) ); } } } public void endLine( boolean endParagraph ) throws BirtException { close( false, endParagraph ); // initialize( ); currentIP = 0; if ( endParagraph ) { setIndent = false; } } public int getMaxLineWidth( ) { return maxAvaWidth; } public boolean isEmptyLine( ) { return getChildrenCount( ) == 0; } public void update( AbstractArea area ) throws BirtException { int aWidth = area.getAllocatedWidth( ); if(aWidth + currentIP > maxAvaWidth ) { removeChild( area ); endLine( false ); children.add( area ); } area.setAllocatedPosition( currentIP, currentBP ); currentIP += aWidth; int height = area.getAllocatedHeight( ); if ( height > getHeight( ) ) { this.height = height; } } protected void close( boolean isLastLine, boolean endParagraph) throws BirtException { if ( children.size( ) == 0 ) { return; } int lineHeight = ( (BlockContainerArea) parent ).getLineHeight( ); height = Math.max( height, lineHeight ); width = Math.max( currentIP, maxAvaWidth ); align( endParagraph, context ); checkDisplayNone( ); if ( isLastLine ) { parent.add( this ); checkPageBreak( ); parent.update( this ); this.finished = true; } else { LineArea area = cloneArea( ); area.children = children; area.context = context; area.setParent( parent ); Iterator iter = area.getChildren( ); while ( iter.hasNext( ) ) { AbstractArea child = (AbstractArea) iter.next( ); child.setParent( area ); } children = new ArrayList( ); parent.add( area ); area.checkPageBreak( ); parent.update( area ); area.finished = true; // setPosition(parent.currentIP + parent.getOffsetX( ), // parent.getOffsetY() + parent.currentBP); height = 0; this.baseLine = 0; } } public void close( ) throws BirtException { close( true, true ); finished = true; } public void initialize( ) throws BirtException { hasStyle = false; boxStyle = BoxStyle.DEFAULT; localProperties = LocalProperties.DEFAULT; maxAvaWidth = parent.getCurrentMaxContentWidth( ); width = maxAvaWidth; // Derive the baseLevel from the parent content direction. if ( parent.content != null ) { // IContent#isDirectionRTL already looks at computed style if ( parent.content.isDirectionRTL( ) ) baseLevel = Bidi.DIRECTION_RIGHT_TO_LEFT; } //parent.add( this ); } public SplitResult split( int height, boolean force ) throws BirtException { assert ( height < this.height ); LineArea result = null; Iterator iter = children.iterator( ); while ( iter.hasNext( ) ) { ContainerArea child = (ContainerArea) iter.next( ); if ( child.getMinYPosition( ) <= height ) { iter.remove( ); if ( result == null ) { result = cloneArea( ); } result.addChild( child ); child.setParent( result ); } else { SplitResult splitChild = child.split( height - child.getY( ), force ); ContainerArea splitChildArea = splitChild.getResult( ); if ( splitChildArea != null ) { if ( result == null ) { result = cloneArea( ); } result.addChild( splitChildArea ); splitChildArea.setParent( result ); } else { child.setY( Math.max( 0, child.getY( ) - height ) ); } } } if ( result != null ) { int h = 0; iter = result.getChildren( ); while ( iter.hasNext( ) ) { ContainerArea child = (ContainerArea) iter.next( ); h = Math.max( h, child.getAllocatedHeight( ) ); } result.setHeight( h ); } if ( children.size( ) > 0 ) { int h = 0; iter = getChildren( ); while ( iter.hasNext( ) ) { ContainerArea child = (ContainerArea) iter.next( ); h = Math.max( h, child.getAllocatedHeight( ) ); } setHeight( h ); } if ( result != null ) { return new SplitResult( result, SplitResult.SPLIT_SUCCEED_WITH_PART ); } else { return SplitResult.SUCCEED_WITH_NULL; } } public LineArea cloneArea( ) { return new LineArea( this ); } public SplitResult splitLines( int lineCount ) throws BirtException { return SplitResult.SUCCEED_WITH_NULL; } public boolean isPageBreakAfterAvoid( ) { return false; } public boolean isPageBreakBeforeAvoid( ) { return false; } public boolean isPageBreakInsideAvoid( ) { return false; } }
package org.reldb.dbrowser.ui.content.cmd; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.StyledText; import org.eclipse.swt.events.KeyAdapter; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Dialog; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; public class SpecialCharacters extends Dialog { private Shell shlSpecialCharacters; private StyledText inputText; private static class SpecialCharacter { char symbol; char altOf; String description; char actualKeypress; public SpecialCharacter(char symbol, char altOf, String description, char actualKeypress) { this.symbol = symbol; this.altOf = altOf; this.description = description; this.actualKeypress = actualKeypress; } public SpecialCharacter(char symbol, char altOf, String description) { this(symbol, altOf, description, (char)0); } // Not universal! Works for the characters below. public boolean matches(KeyEvent e) { if ((e.stateMask & SWT.CTRL) == 0) return false; if ((e.stateMask & SWT.SHIFT) != 0) return (Character.isUpperCase(altOf) && e.keyCode == Character.toLowerCase(altOf)) || e.keyCode == actualKeypress; return e.keyCode == altOf; } } private static SpecialCharacter[] specialCharacters = { new SpecialCharacter('\u00D7', 't', "Times"), new SpecialCharacter('\u00F7', 'd', "Divide"), new SpecialCharacter('\u203C', '!', "Image in", '1'), new SpecialCharacter('\u2260', '=', "Not equal"), new SpecialCharacter('\u2264', 'l', "Less than or equal to"), new SpecialCharacter('\u2265', 'g', "Greater than or equal to"), new SpecialCharacter('\u2282', 'u', "Proper subset"), new SpecialCharacter('\u2283', 'p', "Proper superset"), new SpecialCharacter('\u2286', 'U', "Subset or equal to", ','), new SpecialCharacter('\u2287', 'P', "Superset or equal to", '.') }; /** * Create the dialog. * @param parent * @param style */ public SpecialCharacters(Shell parent, StyledText inputText) { super(parent, SWT.NONE); this.inputText = inputText; inputText.addKeyListener(new KeyAdapter() { @Override public void keyReleased(KeyEvent e) { // System.out.println("character = '" + e.character + "' keycode = '" + (char)e.keyCode + "' " + (((e.stateMask & SWT.CTRL) != 0) ? "CTRL" : "") + " " + (((e.stateMask & SWT.SHIFT) != 0) ? "SHIFT" : "")); for (SpecialCharacter specialCharacter: specialCharacters) { if (specialCharacter.matches(e)) { emit(specialCharacter.symbol); break; } } } }); } protected void emit(char symbol) { inputText.insert(Character.toString(symbol)); inputText.setCaretOffset(inputText.getCaretOffset() + 1); } /** * Open the dialog. * @return the result */ public void open() { createContents(); shlSpecialCharacters.open(); shlSpecialCharacters.layout(); Display display = getParent().getDisplay(); while (!shlSpecialCharacters.isDisposed()) { if (!display.readAndDispatch()) { display.sleep(); } } } /** * Create contents of the dialog. */ private void createContents() { shlSpecialCharacters = new Shell(getParent(), SWT.DIALOG_TRIM); shlSpecialCharacters.setText("Special Characters"); GridLayout gridLayout = new GridLayout(3, false); gridLayout.verticalSpacing = 2; shlSpecialCharacters.setLayout(gridLayout); Label heading = new Label(shlSpecialCharacters, SWT.NONE); heading.setText("Symbol"); heading.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); heading = new Label(shlSpecialCharacters, SWT.NONE); heading.setText("Ctrl-<key> shortcut"); heading.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); heading = new Label(shlSpecialCharacters, SWT.NONE); heading.setText("Description"); heading.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); for (SpecialCharacter special: specialCharacters) { Button charButton = new Button(shlSpecialCharacters, SWT.PUSH); System.out.println("SpecialCharacters: button font = " + charButton.getFont().getFontData()[0]); charButton.setText(Character.toString(special.symbol)); charButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { emit(special.symbol); } }); charButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, true)); Label charLabel = new Label(shlSpecialCharacters, SWT.NONE); charLabel.setText(Character.toString(special.altOf)); charLabel.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, true)); Label charDescription = new Label(shlSpecialCharacters, SWT.NONE); charDescription.setText(special.description); charDescription.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, true)); } shlSpecialCharacters.pack(); } }
package uk.ac.ebi.spot.goci.curation.controller; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; 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.ResponseStatus; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import uk.ac.ebi.spot.goci.curation.exception.PubmedImportException; import uk.ac.ebi.spot.goci.curation.model.PubmedIdForImport; import uk.ac.ebi.spot.goci.curation.model.StudySearchFilter; import uk.ac.ebi.spot.goci.curation.service.MailService; import uk.ac.ebi.spot.goci.model.Association; import uk.ac.ebi.spot.goci.model.CurationStatus; import uk.ac.ebi.spot.goci.model.Curator; import uk.ac.ebi.spot.goci.model.DiseaseTrait; import uk.ac.ebi.spot.goci.model.EfoTrait; import uk.ac.ebi.spot.goci.model.Ethnicity; import uk.ac.ebi.spot.goci.model.Housekeeping; import uk.ac.ebi.spot.goci.model.Study; import uk.ac.ebi.spot.goci.repository.AssociationRepository; import uk.ac.ebi.spot.goci.repository.CurationStatusRepository; import uk.ac.ebi.spot.goci.repository.CuratorRepository; import uk.ac.ebi.spot.goci.repository.DiseaseTraitRepository; import uk.ac.ebi.spot.goci.repository.EfoTraitRepository; import uk.ac.ebi.spot.goci.repository.EthnicityRepository; import uk.ac.ebi.spot.goci.repository.HousekeepingRepository; import uk.ac.ebi.spot.goci.repository.StudyRepository; import uk.ac.ebi.spot.goci.service.DefaultPubMedSearchService; import uk.ac.ebi.spot.goci.service.exception.PubmedLookupException; import javax.validation.Valid; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; @Controller @RequestMapping("/studies") public class StudyController { // Repositories allowing access to database objects associated with a study private StudyRepository studyRepository; private HousekeepingRepository housekeepingRepository; private DiseaseTraitRepository diseaseTraitRepository; private EfoTraitRepository efoTraitRepository; private CuratorRepository curatorRepository; private CurationStatusRepository curationStatusRepository; private AssociationRepository associationRepository; private EthnicityRepository ethnicityRepository; // Pubmed ID lookup service private DefaultPubMedSearchService defaultPubMedSearchService; private MailService mailService; public static final int MAX_PAGE_ITEM_DISPLAY = 25; private Logger log = LoggerFactory.getLogger(getClass()); protected Logger getLog() { return log; } @Autowired public StudyController(StudyRepository studyRepository, HousekeepingRepository housekeepingRepository, DiseaseTraitRepository diseaseTraitRepository, EfoTraitRepository efoTraitRepository, CuratorRepository curatorRepository, CurationStatusRepository curationStatusRepository, AssociationRepository associationRepository, EthnicityRepository ethnicityRepository, DefaultPubMedSearchService defaultPubMedSearchService, MailService mailService) { this.studyRepository = studyRepository; this.housekeepingRepository = housekeepingRepository; this.diseaseTraitRepository = diseaseTraitRepository; this.efoTraitRepository = efoTraitRepository; this.curatorRepository = curatorRepository; this.curationStatusRepository = curationStatusRepository; this.associationRepository = associationRepository; this.ethnicityRepository = ethnicityRepository; this.defaultPubMedSearchService = defaultPubMedSearchService; this.mailService = mailService; } /* All studies and various filtered lists */ @RequestMapping(produces = MediaType.TEXT_HTML_VALUE, method = RequestMethod.GET) public String allStudiesPage(Model model, @RequestParam(required = false) Integer page, @RequestParam(required = false) String pubmed, @RequestParam(required = false) String author, @RequestParam(value = "studytype", required = false) String studyType, @RequestParam(value = "efotraitid", required = false) Long efoTraitId, @RequestParam(value = "notesquery", required = false) String notesQuery, @RequestParam(required = false) Long status, @RequestParam(required = false) Long curator, @RequestParam(value = "sorttype", required = false) String sortType, @RequestParam(value = "diseasetraitid", required = false) Long diseaseTraitId) { // Return all studies ordered by date if no page number given if (page == null) { // Find all studies ordered by study date and only display first page return "redirect:/studies?page=1"; } // This will be returned to view and store what curator has searched for StudySearchFilter studySearchFilter = new StudySearchFilter(); // Store filters which will be need for pagination bar and to build URI passed back to view String filters = ""; // Set sort object and sort string for URI Sort sort = findSort(sortType); String sortString = ""; if (sortType != null && !sortType.isEmpty()) { sortString = "&sorttype=" + sortType; } // This is the default study page will all studies Page<Study> studyPage = studyRepository.findAll(constructPageSpecification(page - 1, sort)); // Search by pubmed ID option available from landing page if (pubmed != null && !pubmed.isEmpty()) { studyPage = studyRepository.findByPubmedId(pubmed, constructPageSpecification(page - 1, sort)); filters = filters + "&pubmed=" + pubmed; studySearchFilter.setPubmedId(pubmed); } // Search by author option available from landing page if (author != null && !author.isEmpty()) { studyPage = studyRepository.findByAuthorContainingIgnoreCase(author, constructPageSpecification(page - 1, sort)); filters = filters + "&author=" + author; studySearchFilter.setAuthor(author); } // Search by study type if (studyType != null && !studyType.isEmpty()) { if (studyType.equals("GXE")) { studyPage = studyRepository.findByGxe(true, constructPageSpecification(page - 1, sort)); } if (studyType.equals("GXG")) { studyPage = studyRepository.findByGxg(true, constructPageSpecification(page - 1, sort)); } if (studyType.equals("CNV")) { studyPage = studyRepository.findByCnv(true, constructPageSpecification(page - 1, sort)); } // Include the studies with status "NCBI pipeline error" // plus the ones that have the box "checked NCBI error" ticked if (studyType.equals("Studies with errors")) { CurationStatus errorStatus = curationStatusRepository.findByStatus("NCBI pipeline error"); Long errorStatusId = errorStatus.getId(); studyPage = studyRepository.findByHousekeepingCheckedNCBIErrorOrHousekeepingCurationStatusId(true, errorStatusId, constructPageSpecification( page - 1, sort)); } if (studyType.equals("Studies in curation queue")) { CurationStatus errorStatus = curationStatusRepository.findByStatus("Publish study"); Long errorStatusId = errorStatus.getId(); studyPage = studyRepository.findByHousekeepingCurationStatusIdNot(errorStatusId, constructPageSpecification( page - 1, sort)); } studySearchFilter.setStudyType(studyType); filters = filters + "&studytype=" + studyType; } // Search by efo trait id if (efoTraitId != null) { studyPage = studyRepository.findByEfoTraitsId(efoTraitId, constructPageSpecification(page - 1, sort)); studySearchFilter.setEfoTraitSearchFilterId(efoTraitId); filters = filters + "&efotraitid=" + efoTraitId; } // Search by disease trait id if (diseaseTraitId != null) { studyPage = studyRepository.findByDiseaseTraitId(diseaseTraitId, constructPageSpecification(page - 1, sort)); studySearchFilter.setDiseaseTraitSearchFilterId(diseaseTraitId); filters = filters + "&diseasetraitid=" + diseaseTraitId; } // Search by notes for entered string if (notesQuery != null && !notesQuery.isEmpty()) { studyPage = studyRepository.findByHousekeepingNotesContainingIgnoreCase(notesQuery, constructPageSpecification(page - 1, sort)); studySearchFilter.setNotesQuery(notesQuery); filters = filters + "&notesquery=" + notesQuery; } // If user entered a status if (status != null) { // If we have curator and status find by both if (curator != null) { studyPage = studyRepository.findByHousekeepingCurationStatusIdAndHousekeepingCuratorId(status, curator, constructPageSpecification( page - 1, sort)); filters = filters + "&status=" + status + "&curator=" + curator; // Return these values so they appear in filter results studySearchFilter.setCuratorSearchFilterId(curator); studySearchFilter.setStatusSearchFilterId(status); } else { studyPage = studyRepository.findByHousekeepingCurationStatusId(status, constructPageSpecification( page - 1, sort)); filters = filters + "&status=" + status; // Return this value so it appears in filter result studySearchFilter.setStatusSearchFilterId(status); } } // If user entered curator else { if (curator != null) { studyPage = studyRepository.findByHousekeepingCuratorId(curator, constructPageSpecification( page - 1, sort)); filters = filters + "&curator=" + curator; // Return this value so it appears in filter result studySearchFilter.setCuratorSearchFilterId(curator); } } // Return URI, this will build thymeleaf links using by sort buttons. // At present, do not add the current sort to the URI, // just maintain any filter values (pubmed id, author etc) used by curator String uri = "/studies?page=1"; if (!filters.isEmpty()) { uri = uri + filters; } model.addAttribute("uri", uri); // Return study page and filters, // filters will be used by pagination bar if (!filters.isEmpty()) { if (!sortString.isEmpty()) { filters = filters + sortString; } } // If user has just sorted without any filter we need // to pass this back to pagination bar else { if (!sortString.isEmpty()) { filters = sortString; } } model.addAttribute("filters", filters); model.addAttribute("studies", studyPage); //Pagination variables long totalStudies = studyPage.getTotalElements(); int current = studyPage.getNumber() + 1; int begin = Math.max(1, current - 5); // Returns the greater of two values int end = Math.min(begin + 10, studyPage.getTotalPages()); // how many pages to display in the pagination bar model.addAttribute("beginIndex", begin); model.addAttribute("endIndex", end); model.addAttribute("currentIndex", current); model.addAttribute("totalStudies", totalStudies); // Add studySearchFilter to model so user can filter table model.addAttribute("studySearchFilter", studySearchFilter); return "studies"; } // Redirects from landing page and main page @RequestMapping(produces = MediaType.TEXT_HTML_VALUE, method = RequestMethod.POST) public String searchForStudyByFilter(@ModelAttribute StudySearchFilter studySearchFilter, Model model, @RequestParam(required = true) String filters) { // Get ids of objects searched for Long status = studySearchFilter.getStatusSearchFilterId(); Long curator = studySearchFilter.getCuratorSearchFilterId(); String pubmedId = studySearchFilter.getPubmedId(); String author = studySearchFilter.getAuthor(); String studyType = studySearchFilter.getStudyType(); Long efoTraitId = studySearchFilter.getEfoTraitSearchFilterId(); String notesQuery = studySearchFilter.getNotesQuery(); Long diseaseTraitId = studySearchFilter.getDiseaseTraitSearchFilterId(); // Search by pubmed ID option available from landing page if (pubmedId != null && !pubmedId.isEmpty()) { return "redirect:/studies?page=1&pubmed=" + pubmedId; } // Search by author option available from landing page else if (author != null && !author.isEmpty()) { return "redirect:/studies?page=1&author=" + author; } // Search by study type else if (studyType != null && !studyType.isEmpty()) { return "redirect:/studies?page=1&studytype=" + studyType; } // Search by efo trait else if (efoTraitId != null) { return "redirect:/studies?page=1&efotraitid=" + efoTraitId; } // Search by disease trait else if (diseaseTraitId != null) { return "redirect:/studies?page=1&diseasetraitid=" + diseaseTraitId; } // Search by string in notes else if (notesQuery != null && !notesQuery.isEmpty()) { return "redirect:/studies?page=1&notesquery=" + notesQuery; } // If user entered a status else if (status != null) { // If we have curator and status find by both if (curator != null) { return "redirect:/studies?page=1&status=" + status + "&curator=" + curator; } else { return "redirect:/studies?page=1&status=" + status; } } // If user entered curator else if (curator != null) { return "redirect:/studies?page=1&curator=" + curator; } // If all else fails return all studies else { // Find all studies ordered by study date and only display first page return "redirect:/studies?page=1"; } } /* New Study*/ // Add a new study // Directs user to an empty form to which they can create a new study @RequestMapping(value = "/new", produces = MediaType.TEXT_HTML_VALUE, method = RequestMethod.GET) public String newStudyForm(Model model) { model.addAttribute("study", new Study()); // Return an empty pubmedIdForImport object to store user entered pubmed id model.addAttribute("pubmedIdForImport", new PubmedIdForImport()); return "add_study"; } // Save study found by Pubmed Id // @ModelAttribute is a reference to the object holding the data entered in the form @RequestMapping(value = "/new/import", produces = MediaType.TEXT_HTML_VALUE, method = RequestMethod.POST) public String importStudy(@ModelAttribute PubmedIdForImport pubmedIdForImport) throws PubmedImportException { // Remove whitespace String pubmedId = pubmedIdForImport.getPubmedId().trim(); // Check if there is an existing study with the same pubmed id Collection<Study> existingStudies = studyRepository.findByPubmedId(pubmedId); if (existingStudies.size() > 0) { throw new PubmedImportException(); } // Pass to importer Study importedStudy = defaultPubMedSearchService.findPublicationSummary(pubmedId); // Create housekeeping object Housekeeping studyHousekeeping = createHousekeeping(); // Update and save study importedStudy.setHousekeeping(studyHousekeeping); // Save new study studyRepository.save(importedStudy); return "redirect:/studies/" + importedStudy.getId(); } // Save newly added study details // @ModelAttribute is a reference to the object holding the data entered in the form @RequestMapping(value = "/new", produces = MediaType.TEXT_HTML_VALUE, method = RequestMethod.POST) public String addStudy(@Valid @ModelAttribute Study study, BindingResult bindingResult, Model model) { // If we have errors in the fields entered, i.e they are blank, then return these to form so user can fix if (bindingResult.hasErrors()) { model.addAttribute("study", study); // Return an empty pubmedIdForImport object to store user entered pubmed id model.addAttribute("pubmedIdForImport", new PubmedIdForImport()); return "add_study"; } // Create housekeeping object Housekeeping studyHousekeeping = createHousekeeping(); // Update and save study study.setHousekeeping(studyHousekeeping); Study newStudy = studyRepository.save(study); return "redirect:/studies/" + newStudy.getId(); } /* Exitsing study*/ // View a study @RequestMapping(value = "/{studyId}", produces = MediaType.TEXT_HTML_VALUE, method = RequestMethod.GET) public String viewStudy(Model model, @PathVariable Long studyId) { Study studyToView = studyRepository.findOne(studyId); model.addAttribute("study", studyToView); return "study"; } // Edit an existing study // @ModelAttribute is a reference to the object holding the data entered in the form @RequestMapping(value = "/{studyId}", produces = MediaType.TEXT_HTML_VALUE, method = RequestMethod.POST) public String updateStudy(@ModelAttribute Study study, Model model, @PathVariable Long studyId, RedirectAttributes redirectAttributes) { // Use id in URL to get study and then its associated housekeeping Study existingStudy = studyRepository.findOne(studyId); Housekeeping existingHousekeeping = existingStudy.getHousekeeping(); // Set the housekeeping of the study returned to one already linked to it in database // Need to do this as we don't return housekeeping in form study.setHousekeeping(existingHousekeeping); // Saves the new information returned from form studyRepository.save(study); // Add save message String message = "Changes saved successfully"; redirectAttributes.addFlashAttribute("changesSaved", message); return "redirect:/studies/" + study.getId(); } // Delete an existing study @RequestMapping(value = "/{studyId}/delete", produces = MediaType.TEXT_HTML_VALUE, method = RequestMethod.GET) public String viewStudyToDelete(Model model, @PathVariable Long studyId) { Study studyToDelete = studyRepository.findOne(studyId); // Check if it has any associations Collection<Association> associations = associationRepository.findByStudyId(studyId); // If so warn the curator if (!associations.isEmpty()) { return "delete_study_with_associations_warning"; } else { model.addAttribute("studyToDelete", studyToDelete); return "delete_study"; } } @RequestMapping(value = "/{studyId}/delete", produces = MediaType.TEXT_HTML_VALUE, method = RequestMethod.POST) public String deleteStudy(@PathVariable Long studyId) { // Find our study based on the ID Study studyToDelete = studyRepository.findOne(studyId); // Before we delete the study get its associated housekeeping and ethnicity Long housekeepingId = studyToDelete.getHousekeeping().getId(); Housekeeping housekeepingAttachedToStudy = housekeepingRepository.findOne(housekeepingId); Collection<Ethnicity> ethnicitiesAttachedToStudy = ethnicityRepository.findByStudyId(studyId); // Delete ethnicity information linked to this study for (Ethnicity ethnicity : ethnicitiesAttachedToStudy) { ethnicityRepository.delete(ethnicity); } // Delete study studyRepository.delete(studyToDelete); // Delete housekeeping housekeepingRepository.delete(housekeepingAttachedToStudy); return "redirect:/studies"; } // Duplicate a study @RequestMapping(value = "/{studyId}/duplicate", produces = MediaType.TEXT_HTML_VALUE, method = RequestMethod.GET) public String duplicateStudy(@PathVariable Long studyId, RedirectAttributes redirectAttributes) { // Find study user wants to duplicate, based on the ID Study studyToDuplicate = studyRepository.findOne(studyId); Study duplicateStudy = copyStudy(studyToDuplicate); // Create housekeeping object and add duplicate message Housekeeping studyHousekeeping = createHousekeeping(); studyHousekeeping.setNotes( "Duplicate of study: " + studyToDuplicate.getAuthor() + ", PMID: " + studyToDuplicate.getPubmedId()); duplicateStudy.setHousekeeping(studyHousekeeping); // Save newly duplicated study studyRepository.save(duplicateStudy); // Copy existing ethnicity Collection<Ethnicity> studyToDuplicateEthnicities = ethnicityRepository.findByStudyId(studyId); for (Ethnicity studyToDuplicateEthnicity : studyToDuplicateEthnicities) { Ethnicity duplicateEthnicity = copyEthnicity(studyToDuplicateEthnicity); duplicateEthnicity.setStudy(duplicateStudy); ethnicityRepository.save(duplicateEthnicity); } // Add duplicate message String message = "Study is a duplicate of " + studyToDuplicate.getAuthor() + ", PMID: " + studyToDuplicate.getPubmedId(); redirectAttributes.addFlashAttribute("duplicateMessage", message); return "redirect:/studies/" + duplicateStudy.getId(); } /* Study housekeeping/curator information */ // Generate page with housekeeping/curator information linked to a study @RequestMapping(value = "/{studyId}/housekeeping", produces = MediaType.TEXT_HTML_VALUE, method = RequestMethod.GET) public String viewStudyHousekeeping(Model model, @PathVariable Long studyId) { // Find study Study study = studyRepository.findOne(studyId); // If we don't have a housekeeping object create one, this should not occur though as they are created when study is created if (study.getHousekeeping() == null) { model.addAttribute("studyHousekeeping", new Housekeeping()); } else { model.addAttribute("studyHousekeeping", study.getHousekeeping()); } // Return the housekeeping object attached to study and return the study model.addAttribute("study", study); return "study_housekeeping"; } // Update page with housekeeping/curator information linked to a study @RequestMapping(value = "/{studyId}/housekeeping", produces = MediaType.TEXT_HTML_VALUE, method = RequestMethod.POST) public String updateStudyHousekeeping(@ModelAttribute Housekeeping housekeeping, @PathVariable Long studyId, RedirectAttributes redirectAttributes) { // Establish linked study Study study = studyRepository.findOne(studyId); // Before we save housekeeping get the status in database so we can check for a change CurationStatus statusInDatabase = housekeepingRepository.findOne(housekeeping.getId()).getCurationStatus(); // Save housekeeping returned from form straight away to save any curator entered details like notes etc housekeepingRepository.save(housekeeping); // For the study check all SNPs have been checked Collection<Association> associations = associationRepository.findByStudyId(studyId); int snpsNotChecked = 0; for (Association association : associations) { // If we have one that is not checked set value if (association.getSnpChecked() == false) { snpsNotChecked = 1; } } // Establish whether user has set status to "Publish study" and "Send to NCBI" // as corresponding dates will be set in housekeeping table CurationStatus currentStatus = housekeeping.getCurationStatus(); // If the status has changed if (currentStatus != statusInDatabase) { if (currentStatus != null && currentStatus.getStatus().equals("Publish study")) { // If not checked redirect back to page and make no changes if (snpsNotChecked == 1) { // Restore old status housekeeping.setCurationStatus(statusInDatabase); // Save any changes made to housekeeping housekeepingRepository.save(housekeeping); String message = "Some SNP associations have not been checked, please review before publishing"; redirectAttributes.addFlashAttribute("snpsNotChecked", message); return "redirect:/studies/" + study.getId() + "/housekeeping"; } else { java.util.Date publishDate = new java.util.Date(); housekeeping.setPublishDate(publishDate); } } //Set date and send email notification if (currentStatus != null && currentStatus.getStatus().equals("Send to NCBI")) { // If not checked redirect back to page and make no changes if (snpsNotChecked == 1) { // Restore old status housekeeping.setCurationStatus(statusInDatabase); // Save any changes made to housekeeping housekeepingRepository.save(housekeeping); String message = "Some SNP associations have not been checked, please review before sending to NCBI"; redirectAttributes.addFlashAttribute("snpsNotChecked", message); return "redirect:/studies/" + study.getId() + "/housekeeping"; } else { java.util.Date sendToNCBIDate = new java.util.Date(); housekeeping.setSendToNCBIDate(sendToNCBIDate); mailService.sendEmailNotification(study, currentStatus.getStatus()); } } // Send notification email to curators if (currentStatus != null && currentStatus.getStatus().equals("Level 1 curation done")) { mailService.sendEmailNotification(study, currentStatus.getStatus()); } } // Save any changes made to housekeeping housekeepingRepository.save(housekeeping); // Set study housekeeping study.setHousekeeping(housekeeping); // Save our study studyRepository.save(study); // Add save message String message = "Changes saved successfully"; redirectAttributes.addFlashAttribute("changesSaved", message); return "redirect:/studies/" + study.getId() + "/housekeeping"; } /* General purpose methods */ private Housekeeping createHousekeeping() { // Create housekeeping object and create the study added date Housekeeping housekeeping = new Housekeeping(); java.util.Date studyAddedDate = new java.util.Date(); housekeeping.setStudyAddedDate(studyAddedDate); // Set status CurationStatus status = curationStatusRepository.findByStatus("Awaiting Curation"); housekeeping.setCurationStatus(status); // Set curator Curator curator = curatorRepository.findByLastName("Level 1 Curator"); housekeeping.setCurator(curator); // Save housekeeping housekeepingRepository.save(housekeeping); // Save housekeeping return housekeeping; } private Study copyStudy(Study studyToDuplicate) { Study duplicateStudy = new Study(); duplicateStudy.setAuthor(studyToDuplicate.getAuthor() + " DUP"); duplicateStudy.setStudyDate(studyToDuplicate.getStudyDate()); duplicateStudy.setPublication(studyToDuplicate.getPublication()); duplicateStudy.setTitle(studyToDuplicate.getTitle()); duplicateStudy.setInitialSampleSize(studyToDuplicate.getInitialSampleSize()); duplicateStudy.setReplicateSampleSize(studyToDuplicate.getReplicateSampleSize()); duplicateStudy.setPlatform(studyToDuplicate.getPlatform()); duplicateStudy.setPubmedId(studyToDuplicate.getPubmedId()); duplicateStudy.setCnv(studyToDuplicate.getCnv()); duplicateStudy.setGxe(studyToDuplicate.getGxe()); duplicateStudy.setGxg(studyToDuplicate.getGxg()); duplicateStudy.setDiseaseTrait(studyToDuplicate.getDiseaseTrait()); // Deal with EFO traits Collection<EfoTrait> efoTraits = studyToDuplicate.getEfoTraits(); Collection<EfoTrait> efoTraitsDuplicateStudy = new ArrayList<EfoTrait>(); if (efoTraits != null && !efoTraits.isEmpty()) { efoTraitsDuplicateStudy.addAll(efoTraits); duplicateStudy.setEfoTraits(efoTraitsDuplicateStudy); } return duplicateStudy; } private Ethnicity copyEthnicity(Ethnicity studyToDuplicateEthnicity) { Ethnicity duplicateEthnicity = new Ethnicity(); duplicateEthnicity.setType(studyToDuplicateEthnicity.getType()); duplicateEthnicity.setNumberOfIndividuals(studyToDuplicateEthnicity.getNumberOfIndividuals()); duplicateEthnicity.setEthnicGroup(studyToDuplicateEthnicity.getEthnicGroup()); duplicateEthnicity.setCountryOfOrigin(studyToDuplicateEthnicity.getCountryOfOrigin()); duplicateEthnicity.setCountryOfRecruitment(studyToDuplicateEthnicity.getCountryOfRecruitment()); duplicateEthnicity.setDescription(studyToDuplicateEthnicity.getDescription()); duplicateEthnicity.setPreviouslyReported(studyToDuplicateEthnicity.getPreviouslyReported()); duplicateEthnicity.setSampleSizesMatch(studyToDuplicateEthnicity.getSampleSizesMatch()); duplicateEthnicity.setNotes(studyToDuplicateEthnicity.getNotes()); return duplicateEthnicity; } // Find correct sorting type and direction private Sort findSort(String sortType) { // Default sort by date Sort sort = sortByStudyDateDesc(); Map<String, Sort> sortTypeMap = new HashMap<>(); sortTypeMap.put("authorsortasc", sortByAuthorAsc()); sortTypeMap.put("authorsortdesc", sortByAuthorDesc()); sortTypeMap.put("titlesortasc", sortByTitleAsc()); sortTypeMap.put("titlesortdesc", sortByTitleDesc()); sortTypeMap.put("studydatesortasc", sortByStudyDateAsc()); sortTypeMap.put("studydatesortdesc", sortByStudyDateDesc()); sortTypeMap.put("pubmedsortasc", sortByPubmedIdAsc()); sortTypeMap.put("pubmedsortdesc", sortByPubmedIdDesc()); sortTypeMap.put("publicationsortasc", sortByPublicationAsc()); sortTypeMap.put("publicationsortdesc", sortByPublicationDesc()); sortTypeMap.put("efotraitsortasc", sortByEfoTraitAsc()); sortTypeMap.put("efotraitsortdesc", sortByEfoTraitDesc()); sortTypeMap.put("diseasetraitsortasc", sortByDiseaseTraitAsc()); sortTypeMap.put("diseasetraitsortdesc", sortByDiseaseTraitDesc()); sortTypeMap.put("curatorsortasc", sortByCuratorAsc()); sortTypeMap.put("curatorsortdesc", sortByCuratorDesc()); sortTypeMap.put("curationstatussortasc", sortByCurationStatusAsc()); sortTypeMap.put("curationstatussortdesc", sortByCurationStatusDesc()); if (sortType != null && !sortType.isEmpty()) { sort = sortTypeMap.get(sortType); } return sort; } /* Exception handling */ @ResponseStatus(HttpStatus.BAD_REQUEST) @ExceptionHandler(PubmedLookupException.class) public String handlePubmedLookupException(PubmedLookupException pubmedLookupException) { getLog().error("pubmed lookup exception", pubmedLookupException); return "pubmed_lookup_warning"; } @ExceptionHandler(PubmedImportException.class) public String handlePubmedImportException(PubmedImportException pubmedImportException) { getLog().error("pubmed import exception", pubmedImportException); return "pubmed_import_warning"; } /* Model Attributes : * Used for dropdowns in HTML forms */ // Disease Traits @ModelAttribute("diseaseTraits") public List<DiseaseTrait> populateDiseaseTraits(Model model) { return diseaseTraitRepository.findAll(sortByTraitAsc()); } // EFO traits @ModelAttribute("efoTraits") public List<EfoTrait> populateEFOTraits(Model model) { return efoTraitRepository.findAll(sortByTraitAsc()); } // Curators @ModelAttribute("curators") public List<Curator> populateCurators(Model model) { return curatorRepository.findAll(); } // Curation statuses @ModelAttribute("curationstatuses") public List<CurationStatus> populateCurationStatuses(Model model) { return curationStatusRepository.findAll(); } // Study types @ModelAttribute("studyTypes") public List<String> populateStudyTypeOptions(Model model) { List<String> studyTypesOptions = new ArrayList<String>(); studyTypesOptions.add("GXE"); studyTypesOptions.add("GXG"); studyTypesOptions.add("CNV"); studyTypesOptions.add("Studies with errors"); studyTypesOptions.add("Studies in curation queue"); return studyTypesOptions; } // Authors @ModelAttribute("authors") public List<String> populateAuthors(Model model) { return studyRepository.findAllStudyAuthors(sortByAuthorAsc()); } /* Sorting options */ // Returns a Sort object which sorts disease traits in ascending order by trait, ignoring case private Sort sortByTraitAsc() { return new Sort(new Sort.Order(Sort.Direction.ASC, "trait").ignoreCase()); } private Sort sortByStudyDateAsc() {return new Sort(new Sort.Order(Sort.Direction.ASC, "studyDate"));} private Sort sortByStudyDateDesc() {return new Sort(new Sort.Order(Sort.Direction.DESC, "studyDate"));} private Sort sortByAuthorAsc() {return new Sort(new Sort.Order(Sort.Direction.ASC, "author").ignoreCase());} private Sort sortByAuthorDesc() {return new Sort(new Sort.Order(Sort.Direction.DESC, "author").ignoreCase());} private Sort sortByTitleAsc() {return new Sort(new Sort.Order(Sort.Direction.ASC, "title").ignoreCase());} private Sort sortByTitleDesc() {return new Sort(new Sort.Order(Sort.Direction.DESC, "title").ignoreCase());} private Sort sortByPublicationAsc() {return new Sort(new Sort.Order(Sort.Direction.ASC, "publication").ignoreCase());} private Sort sortByPublicationDesc() {return new Sort(new Sort.Order(Sort.Direction.DESC, "publication").ignoreCase());} private Sort sortByPubmedIdAsc() {return new Sort(new Sort.Order(Sort.Direction.ASC, "pubmedId"));} private Sort sortByPubmedIdDesc() {return new Sort(new Sort.Order(Sort.Direction.DESC, "pubmedId"));} private Sort sortByDiseaseTraitAsc() {return new Sort(new Sort.Order(Sort.Direction.ASC, "diseaseTrait.trait").ignoreCase());} private Sort sortByDiseaseTraitDesc() {return new Sort(new Sort.Order(Sort.Direction.DESC, "diseaseTrait.trait").ignoreCase());} private Sort sortByEfoTraitAsc() {return new Sort(new Sort.Order(Sort.Direction.ASC, "efoTraits.trait").ignoreCase());} private Sort sortByEfoTraitDesc() {return new Sort(new Sort.Order(Sort.Direction.DESC, "efoTraits.trait").ignoreCase());} private Sort sortByCuratorAsc() {return new Sort(new Sort.Order(Sort.Direction.ASC, "housekeeping.curator.lastName").ignoreCase());} private Sort sortByCuratorDesc() {return new Sort(new Sort.Order(Sort.Direction.DESC, "housekeeping.curator.lastName").ignoreCase());} private Sort sortByCurationStatusAsc() { return new Sort(new Sort.Order(Sort.Direction.ASC, "housekeeping.curationStatus.status")); } private Sort sortByCurationStatusDesc() { return new Sort(new Sort.Order(Sort.Direction.DESC, "housekeeping.curationStatus.status")); } /* Pagination */ // Pagination, method passed page index and inlcudes max number of studies, sorted by study date, to return private Pageable constructPageSpecification(int pageIndex, Sort sort) { return new PageRequest(pageIndex, MAX_PAGE_ITEM_DISPLAY, sort); } }
package uk.ac.ebi.spot.goci.curation.controller; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.FileSystemResource; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; 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.bind.annotation.ResponseStatus; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import uk.ac.ebi.spot.goci.curation.exception.FileUploadException; import uk.ac.ebi.spot.goci.curation.exception.NoStudyDirectoryException; import uk.ac.ebi.spot.goci.curation.exception.PubmedImportException; import uk.ac.ebi.spot.goci.curation.model.Assignee; import uk.ac.ebi.spot.goci.curation.model.PubmedIdForImport; import uk.ac.ebi.spot.goci.curation.model.StatusAssignment; import uk.ac.ebi.spot.goci.curation.model.StudySearchFilter; import uk.ac.ebi.spot.goci.curation.service.CurrentUserDetailsService; import uk.ac.ebi.spot.goci.curation.service.MappingDetailsService; import uk.ac.ebi.spot.goci.curation.service.StudyDeletionService; import uk.ac.ebi.spot.goci.curation.service.StudyDuplicationService; import uk.ac.ebi.spot.goci.curation.service.StudyFileService; import uk.ac.ebi.spot.goci.curation.service.StudyOperationsService; import uk.ac.ebi.spot.goci.model.Association; import uk.ac.ebi.spot.goci.model.CurationStatus; import uk.ac.ebi.spot.goci.model.Curator; import uk.ac.ebi.spot.goci.model.DiseaseTrait; import uk.ac.ebi.spot.goci.model.EfoTrait; import uk.ac.ebi.spot.goci.model.Ethnicity; import uk.ac.ebi.spot.goci.model.Housekeeping; import uk.ac.ebi.spot.goci.model.Platform; import uk.ac.ebi.spot.goci.model.Study; import uk.ac.ebi.spot.goci.model.UnpublishReason; import uk.ac.ebi.spot.goci.repository.AssociationRepository; import uk.ac.ebi.spot.goci.repository.CurationStatusRepository; import uk.ac.ebi.spot.goci.repository.CuratorRepository; import uk.ac.ebi.spot.goci.repository.DiseaseTraitRepository; import uk.ac.ebi.spot.goci.repository.EfoTraitRepository; import uk.ac.ebi.spot.goci.repository.EthnicityRepository; import uk.ac.ebi.spot.goci.repository.HousekeepingRepository; import uk.ac.ebi.spot.goci.repository.PlatformRepository; import uk.ac.ebi.spot.goci.repository.StudyRepository; import uk.ac.ebi.spot.goci.repository.UnpublishReasonRepository; import uk.ac.ebi.spot.goci.service.DefaultPubMedSearchService; import uk.ac.ebi.spot.goci.service.exception.PubmedLookupException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.validation.Valid; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.Callable; @Controller @RequestMapping("/studies") public class StudyController { // Repositories allowing access to database objects associated with a study private StudyRepository studyRepository; private HousekeepingRepository housekeepingRepository; private DiseaseTraitRepository diseaseTraitRepository; private EfoTraitRepository efoTraitRepository; private CuratorRepository curatorRepository; private CurationStatusRepository curationStatusRepository; private PlatformRepository platformRepository; private AssociationRepository associationRepository; private EthnicityRepository ethnicityRepository; private UnpublishReasonRepository unpublishReasonRepository; // Services private DefaultPubMedSearchService defaultPubMedSearchService; private StudyOperationsService studyOperationsService; private MappingDetailsService mappingDetailsService; private CurrentUserDetailsService currentUserDetailsService; private StudyFileService studyFileService; private StudyDuplicationService studyDuplicationService; private StudyDeletionService studyDeletionService; private static final int MAX_PAGE_ITEM_DISPLAY = 25; private Logger log = LoggerFactory.getLogger(getClass()); protected Logger getLog() { return log; } @Autowired public StudyController(StudyRepository studyRepository, HousekeepingRepository housekeepingRepository, DiseaseTraitRepository diseaseTraitRepository, EfoTraitRepository efoTraitRepository, CuratorRepository curatorRepository, CurationStatusRepository curationStatusRepository, PlatformRepository platformRepository, AssociationRepository associationRepository, EthnicityRepository ethnicityRepository, UnpublishReasonRepository unpublishReasonRepository, DefaultPubMedSearchService defaultPubMedSearchService, StudyOperationsService studyOperationsService, MappingDetailsService mappingDetailsService, CurrentUserDetailsService currentUserDetailsService, StudyFileService studyFileService, StudyDuplicationService studyDuplicationService, StudyDeletionService studyDeletionService) { this.studyRepository = studyRepository; this.housekeepingRepository = housekeepingRepository; this.diseaseTraitRepository = diseaseTraitRepository; this.efoTraitRepository = efoTraitRepository; this.curatorRepository = curatorRepository; this.curationStatusRepository = curationStatusRepository; this.platformRepository = platformRepository; this.associationRepository = associationRepository; this.ethnicityRepository = ethnicityRepository; this.unpublishReasonRepository = unpublishReasonRepository; this.defaultPubMedSearchService = defaultPubMedSearchService; this.studyOperationsService = studyOperationsService; this.mappingDetailsService = mappingDetailsService; this.currentUserDetailsService = currentUserDetailsService; this.studyFileService = studyFileService; this.studyDuplicationService = studyDuplicationService; this.studyDeletionService = studyDeletionService; } /* All studies and various filtered lists */ @RequestMapping(produces = MediaType.TEXT_HTML_VALUE, method = RequestMethod.GET) public String allStudiesPage(Model model, @RequestParam(required = false) Integer page, @RequestParam(required = false) String pubmed, @RequestParam(required = false) String author, @RequestParam(value = "studytype", required = false) String studyType, @RequestParam(value = "efotraitid", required = false) Long efoTraitId, @RequestParam(value = "notesquery", required = false) String notesQuery, @RequestParam(required = false) Long status, @RequestParam(required = false) Long curator, @RequestParam(value = "sorttype", required = false) String sortType, @RequestParam(value = "diseasetraitid", required = false) Long diseaseTraitId, @RequestParam(required = false) Integer year, @RequestParam(required = false) Integer month) { // This is passed back to model and determines if pagination is applied Boolean pagination = true; // Return all studies ordered by date if no page number given if (page == null) { // Find all studies ordered by study date and only display first page return "redirect:/studies?page=1"; } // This will be returned to view and store what curator has searched for StudySearchFilter studySearchFilter = new StudySearchFilter(); // Store filters which will be need for pagination bar and to build URI passed back to view String filters = ""; // Set sort object and sort string for URI Sort sort = findSort(sortType); String sortString = ""; if (sortType != null && !sortType.isEmpty()) { sortString = "&sorttype=" + sortType; } // This is the default study page will all studies Page<Study> studyPage = studyRepository.findAll(constructPageSpecification(page - 1, sort)); // For multi-snp and snp interaction studies pagination is not applied as the query leads to duplicates List<Study> studies = null; // Search by pubmed ID option available from landing page if (pubmed != null && !pubmed.isEmpty()) { studyPage = studyRepository.findByPubmedId(pubmed, constructPageSpecification(page - 1, sort)); filters = filters + "&pubmed=" + pubmed; studySearchFilter.setPubmedId(pubmed); } // Search by author option available from landing page if (author != null && !author.isEmpty()) { studyPage = studyRepository.findByAuthorContainingIgnoreCase(author, constructPageSpecification(page - 1, sort)); filters = filters + "&author=" + author; studySearchFilter.setAuthor(author); } // Search by study type if (studyType != null && !studyType.isEmpty()) { if (studyType.equals("GXE")) { studyPage = studyRepository.findByGxe(true, constructPageSpecification(page - 1, sort)); } if (studyType.equals("GXG")) { studyPage = studyRepository.findByGxg(true, constructPageSpecification(page - 1, sort)); } if (studyType.equals("CNV")) { studyPage = studyRepository.findByCnv(true, constructPageSpecification(page - 1, sort)); } if (studyType.equals("Genomewide array studies")) { studyPage = studyRepository.findByGenomewideArray(true, constructPageSpecification(page - 1, sort)); } if (studyType.equals("Targeted array studies")) { studyPage = studyRepository.findByTargetedArray(true, constructPageSpecification(page - 1, sort)); } if (studyType.equals("Studies in curation queue")) { CurationStatus errorStatus = curationStatusRepository.findByStatus("Publish study"); Long errorStatusId = errorStatus.getId(); studyPage = studyRepository.findByHousekeepingCurationStatusIdNot(errorStatusId, constructPageSpecification( page - 1, sort)); } if (studyType.equals("Multi-SNP haplotype studies")) { studies = studyRepository.findStudyDistinctByAssociationsMultiSnpHaplotypeTrue(sort); pagination = false; } if (studyType.equals("SNP Interaction studies")) { studies = studyRepository.findStudyDistinctByAssociationsSnpInteractionTrue(sort); pagination = false; } studySearchFilter.setStudyType(studyType); filters = filters + "&studytype=" + studyType; } // Search by efo trait id if (efoTraitId != null) { studyPage = studyRepository.findByEfoTraitsId(efoTraitId, constructPageSpecification(page - 1, sort)); studySearchFilter.setEfoTraitSearchFilterId(efoTraitId); filters = filters + "&efotraitid=" + efoTraitId; } // Search by disease trait id if (diseaseTraitId != null) { studyPage = studyRepository.findByDiseaseTraitId(diseaseTraitId, constructPageSpecification(page - 1, sort)); studySearchFilter.setDiseaseTraitSearchFilterId(diseaseTraitId); filters = filters + "&diseasetraitid=" + diseaseTraitId; } // Search by notes for entered string if (notesQuery != null && !notesQuery.isEmpty()) { studyPage = studyRepository.findByHousekeepingNotesContainingIgnoreCase(notesQuery, constructPageSpecification(page - 1, sort)); studySearchFilter.setNotesQuery(notesQuery); filters = filters + "&notesquery=" + notesQuery; } // If user entered a status if (status != null) { // If we have curator and status find by both if (curator != null) { // This is just used to link from reports tab if (year != null && month != null) { studyPage = studyRepository.findByPublicationDateAndCuratorAndStatus(curator, status, year, month, constructPageSpecification( page - 1, sort)); studySearchFilter.setMonthFilter(month); studySearchFilter.setYearFilter(year); filters = filters + "&status=" + status + "&curator=" + curator + "&year=" + year + "&month=" + month; } else { studyPage = studyRepository.findByHousekeepingCurationStatusIdAndHousekeepingCuratorId(status, curator, constructPageSpecification( page - 1, sort)); filters = filters + "&status=" + status + "&curator=" + curator; } // Return these values so they appear in filter results studySearchFilter.setCuratorSearchFilterId(curator); studySearchFilter.setStatusSearchFilterId(status); } else { studyPage = studyRepository.findByHousekeepingCurationStatusId(status, constructPageSpecification( page - 1, sort)); filters = filters + "&status=" + status; // Return this value so it appears in filter result studySearchFilter.setStatusSearchFilterId(status); } } // If user entered curator else { if (curator != null) { studyPage = studyRepository.findByHousekeepingCuratorId(curator, constructPageSpecification( page - 1, sort)); filters = filters + "&curator=" + curator; // Return this value so it appears in filter result studySearchFilter.setCuratorSearchFilterId(curator); } } // Return URI, this will build thymeleaf links using by sort buttons. // At present, do not add the current sort to the URI, // just maintain any filter values (pubmed id, author etc) used by curator String uri = "/studies?page=1"; if (!filters.isEmpty()) { uri = uri + filters; } model.addAttribute("uri", uri); // Return study page and filters, // filters will be used by pagination bar if (!filters.isEmpty()) { if (!sortString.isEmpty()) { filters = filters + sortString; } } // If user has just sorted without any filter we need // to pass this back to pagination bar else { if (!sortString.isEmpty()) { filters = sortString; } } model.addAttribute("filters", filters); long totalStudies; int current = 1; // Construct table using pagination if (studies == null) { model.addAttribute("studies", studyPage); //Pagination variables totalStudies = studyPage.getTotalElements(); current = studyPage.getNumber() + 1; int begin = Math.max(1, current - 5); // Returns the greater of two values int end = Math.min(begin + 10, studyPage.getTotalPages()); // how many pages to display in the pagination bar model.addAttribute("beginIndex", begin); model.addAttribute("endIndex", end); model.addAttribute("currentIndex", current); } else { model.addAttribute("studies", studies); totalStudies = studies.size(); } model.addAttribute("totalStudies", totalStudies); model.addAttribute("pagination", pagination); // Add studySearchFilter to model so user can filter table model.addAttribute("studySearchFilter", studySearchFilter); // Add assignee and status assignment so user can assign // study to curator or assign a status // Also set uri so we can redirect to page user was on Assignee assignee = new Assignee(); StatusAssignment statusAssignment = new StatusAssignment(); assignee.setUri("/studies?page=" + current + filters); statusAssignment.setUri("/studies?page=" + current + filters); model.addAttribute("assignee", assignee); model.addAttribute("statusAssignment", statusAssignment); return "studies"; } // Redirects from landing page and main page @RequestMapping(produces = MediaType.TEXT_HTML_VALUE, method = RequestMethod.POST) public String searchForStudyByFilter(@ModelAttribute StudySearchFilter studySearchFilter) { // Get ids of objects searched for Long status = studySearchFilter.getStatusSearchFilterId(); Long curator = studySearchFilter.getCuratorSearchFilterId(); String pubmedId = studySearchFilter.getPubmedId(); String author = studySearchFilter.getAuthor(); String studyType = studySearchFilter.getStudyType(); Long efoTraitId = studySearchFilter.getEfoTraitSearchFilterId(); String notesQuery = studySearchFilter.getNotesQuery(); Long diseaseTraitId = studySearchFilter.getDiseaseTraitSearchFilterId(); // Search by pubmed ID option available from landing page if (pubmedId != null && !pubmedId.isEmpty()) { return "redirect:/studies?page=1&pubmed=" + pubmedId; } // Search by author option available from landing page else if (author != null && !author.isEmpty()) { return "redirect:/studies?page=1&author=" + author; } // Search by study type else if (studyType != null && !studyType.isEmpty()) { return "redirect:/studies?page=1&studytype=" + studyType; } // Search by efo trait else if (efoTraitId != null) { return "redirect:/studies?page=1&efotraitid=" + efoTraitId; } // Search by disease trait else if (diseaseTraitId != null) { return "redirect:/studies?page=1&diseasetraitid=" + diseaseTraitId; } // Search by string in notes else if (notesQuery != null && !notesQuery.isEmpty()) { return "redirect:/studies?page=1&notesquery=" + notesQuery; } // If user entered a status else if (status != null) { // If we have curator and status find by both if (curator != null) { return "redirect:/studies?page=1&status=" + status + "&curator=" + curator; } else { return "redirect:/studies?page=1&status=" + status; } } // If user entered curator else if (curator != null) { return "redirect:/studies?page=1&curator=" + curator; } // If all else fails return all studies else { // Find all studies ordered by study date and only display first page return "redirect:/studies?page=1"; } } /* New Study: * * Adding a study is synchronised to ensure the method can only be accessed once. * * */ // Add a new study // Directs user to an empty form to which they can create a new study @RequestMapping(value = "/new", produces = MediaType.TEXT_HTML_VALUE, method = RequestMethod.GET) public String newStudyForm(Model model) { model.addAttribute("study", new Study()); // Return an empty pubmedIdForImport object to store user entered pubmed id model.addAttribute("pubmedIdForImport", new PubmedIdForImport()); return "add_study"; } // Save study found by Pubmed Id // @ModelAttribute is a reference to the object holding the data entered in the form @RequestMapping(value = "/new/import", produces = MediaType.TEXT_HTML_VALUE, method = RequestMethod.POST) public synchronized String importStudy(@ModelAttribute PubmedIdForImport pubmedIdForImport, HttpServletRequest request, Model model) throws PubmedImportException, NoStudyDirectoryException { // Remove whitespace String pubmedId = pubmedIdForImport.getPubmedId().trim(); // Check if there is an existing study with the same pubmed id Collection<Study> existingStudies = studyRepository.findByPubmedId(pubmedId); if (existingStudies.size() > 0) { throw new PubmedImportException(); } else { // Pass to importer Study importedStudy = defaultPubMedSearchService.findPublicationSummary(pubmedId); Study savedStudy = studyOperationsService.createStudy(importedStudy, currentUserDetailsService.getUserFromRequest(request)); // Create directory to store associated files try { studyFileService.createStudyDir(savedStudy.getId()); } catch (NoStudyDirectoryException e) { getLog().error("No study directory exception"); model.addAttribute("study", savedStudy); return "error_pages/study_dir_failure"; } return "redirect:/studies/" + savedStudy.getId(); } } // Save newly added study details // @ModelAttribute is a reference to the object holding the data entered in the form @RequestMapping(value = "/new", produces = MediaType.TEXT_HTML_VALUE, method = RequestMethod.POST) public synchronized String addStudy(@Valid @ModelAttribute Study study, BindingResult bindingResult, Model model, HttpServletRequest request) throws NoStudyDirectoryException { // If we have errors in the fields entered, i.e they are blank, then return these to form so user can fix if (bindingResult.hasErrors()) { model.addAttribute("study", study); // Return an empty pubmedIdForImport object to store user entered pubmed id model.addAttribute("pubmedIdForImport", new PubmedIdForImport()); return "add_study"; } Study savedStudy = studyOperationsService.createStudy(study, currentUserDetailsService.getUserFromRequest(request)); // Create directory to store associated files try { studyFileService.createStudyDir(savedStudy.getId()); } catch (NoStudyDirectoryException e) { getLog().error("No study directory exception"); model.addAttribute("study", savedStudy); return "error_pages/study_dir_failure"; } return "redirect:/studies/" + savedStudy.getId(); } /* Existing study*/ // View a study @RequestMapping(value = "/{studyId}", produces = MediaType.TEXT_HTML_VALUE, method = RequestMethod.GET) public String viewStudy(Model model, @PathVariable Long studyId) { Study studyToView = studyRepository.findOne(studyId); model.addAttribute("study", studyToView); return "study"; } // Edit an existing study // @ModelAttribute is a reference to the object holding the data entered in the form @RequestMapping(value = "/{studyId}", produces = MediaType.TEXT_HTML_VALUE, method = RequestMethod.POST) public String updateStudy(@ModelAttribute Study study, @PathVariable Long studyId, RedirectAttributes redirectAttributes, HttpServletRequest request) { studyOperationsService.updateStudy(studyId, study, currentUserDetailsService.getUserFromRequest(request)); // Add save message String message = "Changes saved successfully"; redirectAttributes.addFlashAttribute("changesSaved", message); return "redirect:/studies/" + study.getId(); } // Delete an existing study @RequestMapping(value = "/{studyId}/delete", produces = MediaType.TEXT_HTML_VALUE, method = RequestMethod.GET) public String viewStudyToDelete(Model model, @PathVariable Long studyId) { Study studyToDelete = studyRepository.findOne(studyId); // Check if it has any associations Collection<Association> associations = associationRepository.findByStudyId(studyId); Long housekeepingId = studyToDelete.getHousekeeping().getId(); Housekeeping housekeepingAttachedToStudy = housekeepingRepository.findOne(housekeepingId); // If so warn the curator if (!associations.isEmpty()) { return "delete_study_with_associations_warning"; } else if (housekeepingAttachedToStudy.getCatalogPublishDate() != null) { model.addAttribute("studyToDelete", studyToDelete); return "delete_published_study_warning"; } else { model.addAttribute("studyToDelete", studyToDelete); return "delete_study"; } } @RequestMapping(value = "/{studyId}/delete", produces = MediaType.TEXT_HTML_VALUE, method = RequestMethod.POST) public String deleteStudy(@PathVariable Long studyId, HttpServletRequest request) { // Find our study based on the ID Study studyToDelete = studyRepository.findOne(studyId); studyDeletionService.deleteStudy(studyToDelete, currentUserDetailsService.getUserFromRequest(request)); return "redirect:/studies"; } // Duplicate a study @RequestMapping(value = "/{studyId}/duplicate", produces = MediaType.TEXT_HTML_VALUE, method = RequestMethod.GET) public String duplicateStudy(@PathVariable Long studyId, RedirectAttributes redirectAttributes, HttpServletRequest request) { // Find study user wants to duplicate, based on the ID Study studyToDuplicate = studyRepository.findOne(studyId); Study duplicateStudy = studyDuplicationService.duplicateStudy(studyToDuplicate, currentUserDetailsService.getUserFromRequest( request)); // Add duplicate message String message = "Study is a duplicate of " + studyToDuplicate.getAuthor() + ", PMID: " + studyToDuplicate.getPubmedId(); redirectAttributes.addFlashAttribute("duplicateMessage", message); return "redirect:/studies/" + duplicateStudy.getId(); } // Assign a curator to a study @RequestMapping(value = "/{studyId}/assign", produces = MediaType.TEXT_HTML_VALUE, method = RequestMethod.POST) public String assignStudyCurator(@PathVariable Long studyId, @ModelAttribute Assignee assignee, RedirectAttributes redirectAttributes, HttpServletRequest request) { // Find the study and the curator user wishes to assign Study study = studyRepository.findOne(studyId); if (assignee.getCuratorId() == null) { String blankAssignee = "Cannot assign a blank value as a curator for study: " + study.getAuthor() + ", " + " pubmed = " + study.getPubmedId(); redirectAttributes.addFlashAttribute("blankAssignee", blankAssignee); } else { studyOperationsService.assignStudyCurator(study, assignee, currentUserDetailsService.getUserFromRequest(request)); } return "redirect:" + assignee.getUri(); } // Assign a status to a study @RequestMapping(value = "/{studyId}/status_update", produces = MediaType.TEXT_HTML_VALUE, method = RequestMethod.POST) public String assignStudyStatus(@PathVariable Long studyId, @ModelAttribute StatusAssignment statusAssignment, RedirectAttributes redirectAttributes, HttpServletRequest request) { // Find the study and the curator user wishes to assign Study study = studyRepository.findOne(studyId); if (statusAssignment.getStatusId() == null) { String blankStatus = "Cannot assign a blank value as a status for study: " + study.getAuthor() + ", " + " pubmed = " + study.getPubmedId(); redirectAttributes.addFlashAttribute("blankStatus", blankStatus); } else { String message = studyOperationsService.assignStudyStatus(study, statusAssignment, currentUserDetailsService.getUserFromRequest( request)); redirectAttributes.addFlashAttribute("studySnpsNotApproved", message); } return "redirect:" + statusAssignment.getUri(); } /* Study housekeeping/curator information */ // Generate page with housekeeping/curator information linked to a study @RequestMapping(value = "/{studyId}/housekeeping", produces = MediaType.TEXT_HTML_VALUE, method = RequestMethod.GET) public String viewStudyHousekeeping(Model model, @PathVariable Long studyId) { // Find study Study study = studyRepository.findOne(studyId); // If we don't have a housekeeping object create one, this should not occur though as they are created when study is created if (study.getHousekeeping() == null) { model.addAttribute("studyHousekeeping", new Housekeeping()); } else { model.addAttribute("studyHousekeeping", study.getHousekeeping()); } // Return the housekeeping object attached to study and return the study model.addAttribute("study", study); // Return a DTO that holds a summary of any automated mappings model.addAttribute("mappingDetails", mappingDetailsService.createMappingSummary(study)); return "study_housekeeping"; } // Update page with housekeeping/curator information linked to a study @RequestMapping(value = "/{studyId}/housekeeping", produces = MediaType.TEXT_HTML_VALUE, method = RequestMethod.POST) public String updateStudyHousekeeping(@ModelAttribute Housekeeping housekeeping, @PathVariable Long studyId, RedirectAttributes redirectAttributes, HttpServletRequest request) { // Establish linked study Study study = studyRepository.findOne(studyId); // Update housekeeping String message = studyOperationsService.updateHousekeeping(housekeeping, study, currentUserDetailsService.getUserFromRequest(request)); // Add save message if (message == null) { message = "Changes saved successfully"; } redirectAttributes.addFlashAttribute("changesSaved", message); return "redirect:/studies/" + study.getId() + "/housekeeping"; } @RequestMapping(value = "/{studyId}/unpublish", produces = MediaType.TEXT_HTML_VALUE, method = RequestMethod.GET) public String viewStudyToUnpublish(Model model, @PathVariable Long studyId) { Study studyToUnpublish = studyRepository.findOne(studyId); // Check if it has any associations or ethnicity information Collection<Association> associations = associationRepository.findByStudyId(studyId); Collection<Ethnicity> ancestryInfo = ethnicityRepository.findByStudyId(studyId); // If so warn the curator if (!associations.isEmpty() || !ancestryInfo.isEmpty()) { model.addAttribute("study", studyToUnpublish); return "unpublish_study_with_associations_warning"; } else { model.addAttribute("studyToUnpublish", studyToUnpublish); return "unpublish_study"; } } @RequestMapping(value = "/{studyId}/unpublish", produces = MediaType.TEXT_HTML_VALUE, method = RequestMethod.POST) public String unpublishStudy(@ModelAttribute Study studyToUnpublish, @PathVariable Long studyId, HttpServletRequest request) { // studyToUnpuplish attribute is used simply to retrieve unpublsih reason studyOperationsService.unpublishStudy(studyId, studyToUnpublish.getHousekeeping().getUnpublishReason(), currentUserDetailsService.getUserFromRequest(request)); return "redirect:/studies/" + studyToUnpublish.getId() + "/housekeeping"; } // Find correct sorting type and direction private Sort findSort(String sortType) { // Default sort by date Sort sort = sortByPublicationDateDesc(); Map<String, Sort> sortTypeMap = new HashMap<>(); sortTypeMap.put("authorsortasc", sortByAuthorAsc()); sortTypeMap.put("authorsortdesc", sortByAuthorDesc()); sortTypeMap.put("titlesortasc", sortByTitleAsc()); sortTypeMap.put("titlesortdesc", sortByTitleDesc()); sortTypeMap.put("publicationdatesortasc", sortByPublicationDateAsc()); sortTypeMap.put("publicationdatesortdesc", sortByPublicationDateDesc()); sortTypeMap.put("pubmedsortasc", sortByPubmedIdAsc()); sortTypeMap.put("pubmedsortdesc", sortByPubmedIdDesc()); sortTypeMap.put("publicationsortasc", sortByPublicationAsc()); sortTypeMap.put("publicationsortdesc", sortByPublicationDesc()); sortTypeMap.put("efotraitsortasc", sortByEfoTraitAsc()); sortTypeMap.put("efotraitsortdesc", sortByEfoTraitDesc()); sortTypeMap.put("diseasetraitsortasc", sortByDiseaseTraitAsc()); sortTypeMap.put("diseasetraitsortdesc", sortByDiseaseTraitDesc()); sortTypeMap.put("curatorsortasc", sortByCuratorAsc()); sortTypeMap.put("curatorsortdesc", sortByCuratorDesc()); sortTypeMap.put("curationstatussortasc", sortByCurationStatusAsc()); sortTypeMap.put("curationstatussortdesc", sortByCurationStatusDesc()); if (sortType != null && !sortType.isEmpty()) { sort = sortTypeMap.get(sortType); } return sort; } /* Functionality to view, upload and download a study file(s)*/ @RequestMapping(value = "/{studyId}/studyfiles", produces = MediaType.TEXT_HTML_VALUE, method = RequestMethod.GET) public String getStudyFiles(Model model, @PathVariable Long studyId) { model.addAttribute("files", studyFileService.getStudyFiles(studyId)); model.addAttribute("study", studyRepository.findOne(studyId)); return "study_files"; } @RequestMapping(value = "/{studyId}/studyfiles/{fileName}", method = RequestMethod.GET) @ResponseBody public FileSystemResource downloadStudyFile(@PathVariable Long studyId, HttpServletRequest request, HttpServletResponse response) throws FileNotFoundException { // Using this logic so can get full file name, if it was an @PathVariable everything after final '.' would be removed String path = request.getServletPath(); String fileName = path.substring(path.lastIndexOf('/') + 1); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); response.setHeader("Content-Disposition", "attachment; filename=" + fileName); return new FileSystemResource(studyFileService.getFileFromFileName(studyId, fileName)); } @RequestMapping(value = "/{studyId}/studyfiles", produces = MediaType.TEXT_HTML_VALUE, method = RequestMethod.POST) public Callable<String> uploadStudyFile(@RequestParam("file") MultipartFile file, @PathVariable Long studyId, Model model, HttpServletRequest request) throws FileUploadException, IOException { model.addAttribute("study", studyRepository.findOne(studyId)); // Return view return () -> { try { studyFileService.upload(file, studyId); studyFileService.createFileUploadEvent(studyId, currentUserDetailsService.getUserFromRequest(request)); return "redirect:/studies/" + studyId + "/studyfiles"; } catch (FileUploadException | IOException e) { getLog().error("File upload exception", e); return "error_pages/study_file_upload_failure"; } }; } @RequestMapping(value = "/{studyId}/tracking", produces = MediaType.TEXT_HTML_VALUE, method = RequestMethod.GET) public String getStudyEvents(Model model, @PathVariable Long studyId) { model.addAttribute("events", studyRepository.findOne(studyId).getEvents()); model.addAttribute("study", studyRepository.findOne(studyId)); return "study_events"; } /* Exception handling */ @ResponseStatus(HttpStatus.BAD_REQUEST) @ExceptionHandler(PubmedLookupException.class) public String handlePubmedLookupException(PubmedLookupException pubmedLookupException) { getLog().error("pubmed lookup exception", pubmedLookupException); return "pubmed_lookup_warning"; } @ExceptionHandler(PubmedImportException.class) public String handlePubmedImportException(PubmedImportException pubmedImportException) { getLog().error("pubmed import exception", pubmedImportException); return "pubmed_import_warning"; } @ExceptionHandler({FileNotFoundException.class}) public String handleInvalidFormatExceptionAndInvalidOperationException() { return "error_pages/wrong_file_format_warning"; } /* Model Attributes : * Used for dropdowns in HTML forms */ // Disease Traits @ModelAttribute("diseaseTraits") public List<DiseaseTrait> populateDiseaseTraits() { return diseaseTraitRepository.findAll(sortByTraitAsc()); } // EFO traits @ModelAttribute("efoTraits") public List<EfoTrait> populateEFOTraits() { return efoTraitRepository.findAll(sortByTraitAsc()); } // Curators @ModelAttribute("curators") public List<Curator> populateCurators() { return curatorRepository.findAll(sortByLastNameAsc()); } //Platforms @ModelAttribute("platforms") public List<Platform> populatePlatforms() {return platformRepository.findAll(); } // Curation statuses @ModelAttribute("curationstatuses") public List<CurationStatus> populateCurationStatuses() { return curationStatusRepository.findAll(sortByStatusAsc()); } // Unpublish reasons @ModelAttribute("unpublishreasons") public List<UnpublishReason> populateUnpublishReasons() { return unpublishReasonRepository.findAll(); } // Study types @ModelAttribute("studyTypes") public List<String> populateStudyTypeOptions() { List<String> studyTypesOptions = new ArrayList<String>(); studyTypesOptions.add("GXE"); studyTypesOptions.add("GXG"); studyTypesOptions.add("CNV"); studyTypesOptions.add("Genomewide array studies"); studyTypesOptions.add("Targeted array studies"); studyTypesOptions.add("Studies in curation queue"); studyTypesOptions.add("Multi-SNP haplotype studies"); studyTypesOptions.add("SNP Interaction studies"); return studyTypesOptions; } @ModelAttribute("qualifiers") public List<String> populateQualifierOptions() { List<String> qualifierOptions = new ArrayList<>(); qualifierOptions.add("up to"); qualifierOptions.add("at least"); qualifierOptions.add("~"); qualifierOptions.add(">"); return qualifierOptions; } // Authors @ModelAttribute("authors") public List<String> populateAuthors() { return studyRepository.findAllStudyAuthors(sortByAuthorAsc()); } /* Sorting options */ private Sort sortByLastNameAsc() { return new Sort(new Sort.Order(Sort.Direction.ASC, "lastName").ignoreCase()); } private Sort sortByStatusAsc() { return new Sort(new Sort.Order(Sort.Direction.ASC, "status").ignoreCase()); } // Returns a Sort object which sorts disease traits in ascending order by trait, ignoring case private Sort sortByTraitAsc() { return new Sort(new Sort.Order(Sort.Direction.ASC, "trait").ignoreCase()); } private Sort sortByPublicationDateAsc() { return new Sort(new Sort.Order(Sort.Direction.ASC, "publicationDate")); } private Sort sortByPublicationDateDesc() { return new Sort(new Sort.Order(Sort.Direction.DESC, "publicationDate")); } private Sort sortByAuthorAsc() { return new Sort(new Sort.Order(Sort.Direction.ASC, "author").ignoreCase()); } private Sort sortByAuthorDesc() { return new Sort(new Sort.Order(Sort.Direction.DESC, "author").ignoreCase()); } private Sort sortByTitleAsc() { return new Sort(new Sort.Order(Sort.Direction.ASC, "title").ignoreCase()); } private Sort sortByTitleDesc() { return new Sort(new Sort.Order(Sort.Direction.DESC, "title").ignoreCase()); } private Sort sortByPublicationAsc() { return new Sort(new Sort.Order(Sort.Direction.ASC, "publication").ignoreCase()); } private Sort sortByPublicationDesc() { return new Sort(new Sort.Order(Sort.Direction.DESC, "publication").ignoreCase()); } private Sort sortByPubmedIdAsc() { return new Sort(new Sort.Order(Sort.Direction.ASC, "pubmedId")); } private Sort sortByPubmedIdDesc() { return new Sort(new Sort.Order(Sort.Direction.DESC, "pubmedId")); } private Sort sortByDiseaseTraitAsc() { return new Sort(new Sort.Order(Sort.Direction.ASC, "diseaseTrait.trait").ignoreCase()); } private Sort sortByDiseaseTraitDesc() { return new Sort(new Sort.Order(Sort.Direction.DESC, "diseaseTrait.trait").ignoreCase()); } private Sort sortByEfoTraitAsc() { return new Sort(new Sort.Order(Sort.Direction.ASC, "efoTraits.trait").ignoreCase()); } private Sort sortByEfoTraitDesc() { return new Sort(new Sort.Order(Sort.Direction.DESC, "efoTraits.trait").ignoreCase()); } private Sort sortByCuratorAsc() { return new Sort(new Sort.Order(Sort.Direction.ASC, "housekeeping.curator.lastName").ignoreCase()); } private Sort sortByCuratorDesc() { return new Sort(new Sort.Order(Sort.Direction.DESC, "housekeeping.curator.lastName").ignoreCase()); } private Sort sortByCurationStatusAsc() { return new Sort(new Sort.Order(Sort.Direction.ASC, "housekeeping.curationStatus.status")); } private Sort sortByCurationStatusDesc() { return new Sort(new Sort.Order(Sort.Direction.DESC, "housekeeping.curationStatus.status")); } /* Pagination */ // Pagination, method passed page index and includes max number of studies, sorted by study date, to return private Pageable constructPageSpecification(int pageIndex, Sort sort) { return new PageRequest(pageIndex, MAX_PAGE_ITEM_DISPLAY, sort); } }
package org.eclipse.hawkbit.repository; import java.io.Serializable; @FunctionalInterface public interface Identifiable<T extends Serializable> { T getId(); }
package org.innovateuk.ifs.commons.error.exception; import java.util.List; /** * This exception is thrown when a user tries to upload a file when one has already been uploaded on same form input response. * User will be shown a validation error asking they remove existing file first before uploading a different one. */ public class FileAlreadyUploadedException extends IFSRuntimeException { public FileAlreadyUploadedException() { // no-arg constructor } public FileAlreadyUploadedException(List<Object> arguments) { super(arguments); } public FileAlreadyUploadedException(String message, List<Object> arguments) { super(message, arguments); } public FileAlreadyUploadedException(String message, Throwable cause, List<Object> arguments) { super(message, cause, arguments); } public FileAlreadyUploadedException(Throwable cause, List<Object> arguments) { super(cause, arguments); } public FileAlreadyUploadedException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace, List<Object> arguments) { super(message, cause, enableSuppression, writableStackTrace, arguments); } }
class Node { String getType() { return ""; } String foo(Node left, Node right) { String leftType = left.getType().substring(1); <selection> String rightType = right.getType().substring(1); //line comment </selection> String type = "A".substring(1); return leftType + rightType + type; } }
package org.languagetool.rules.en; import org.jetbrains.annotations.Nullable; import org.languagetool.*; import org.languagetool.language.English; import org.languagetool.languagemodel.LanguageModel; import org.languagetool.rules.Example; import org.languagetool.rules.RuleMatch; import org.languagetool.rules.SuggestedReplacement; import org.languagetool.rules.spelling.morfologik.MorfologikSpellerRule; import org.languagetool.synthesis.en.EnglishSynthesizer; import org.languagetool.tools.StringTools; import java.io.IOException; import java.util.*; public abstract class AbstractEnglishSpellerRule extends MorfologikSpellerRule { private static final EnglishSynthesizer synthesizer = new EnglishSynthesizer(new English()); public AbstractEnglishSpellerRule(ResourceBundle messages, Language language) throws IOException { this(messages, language, null, Collections.emptyList()); } /** * @since 4.4 */ public AbstractEnglishSpellerRule(ResourceBundle messages, Language language, UserConfig userConfig, List<Language> altLanguages) throws IOException { this(messages, language, userConfig, altLanguages, null); } protected static Map<String,String> loadWordlist(String path, int column) { if (column != 0 && column != 1) { throw new IllegalArgumentException("Only column 0 and 1 are supported: " + column); } Map<String,String> words = new HashMap<>(); List<String> lines = JLanguageTool.getDataBroker().getFromResourceDirAsLines(path); for (String line : lines) { line = line.trim(); if (line.isEmpty() || line.startsWith(" continue; } String[] parts = line.split(";"); if (parts.length != 2) { throw new RuntimeException("Unexpected format in " + path + ": " + line + " - expected two parts delimited by ';'"); } words.put(parts[column].toLowerCase(), parts[column == 1 ? 0 : 1]); } return words; } /** * @since 4.5 * optional: language model for better suggestions */ @Experimental public AbstractEnglishSpellerRule(ResourceBundle messages, Language language, UserConfig userConfig, List<Language> altLanguages, LanguageModel languageModel) throws IOException { super(messages, language, userConfig, altLanguages, languageModel); super.ignoreWordsWithLength = 1; setCheckCompound(true); addExamplePair(Example.wrong("This <marker>sentenc</marker> contains a spelling mistake."), Example.fixed("This <marker>sentence</marker> contains a spelling mistake.")); String languageSpecificIgnoreFile = getSpellingFileName().replace(".txt", "_"+language.getShortCodeWithCountryAndVariant()+".txt"); for (String ignoreWord : wordListLoader.loadWords(languageSpecificIgnoreFile)) { addIgnoreWords(ignoreWord); } } @Override protected List<String> filterSuggestions(List<String> suggestions, AnalyzedSentence sentence, int i) { List<String> result = super.filterSuggestions(suggestions, sentence, i); List<String> clean = new ArrayList<>(); for (String suggestion : result) { if (!suggestion.matches(".* (s|t|d|ll|ve)")) { // e.g. 'timezones' suggests 'timezone s' clean.add(suggestion); } } return clean; } @Override protected List<RuleMatch> getRuleMatches(String word, int startPos, AnalyzedSentence sentence, List<RuleMatch> ruleMatchesSoFar, int idx, AnalyzedTokenReadings[] tokens) throws IOException { List<RuleMatch> ruleMatches = super.getRuleMatches(word, startPos, sentence, ruleMatchesSoFar, idx, tokens); if (ruleMatches.size() > 0) { // so 'word' is misspelled: IrregularForms forms = getIrregularFormsOrNull(word); if (forms != null) { String message = "Possible spelling mistake. Did you mean <suggestion>" + forms.forms.get(0) + "</suggestion>, the " + forms.formName + " form of the " + forms.posName + " '" + forms.baseform + "'?"; addFormsToFirstMatch(message, sentence, ruleMatches, forms.forms); } else { VariantInfo variantInfo = isValidInOtherVariant(word); if (variantInfo != null) { String message = "Possible spelling mistake. '" + word + "' is " + variantInfo.getVariantName() + "."; String suggestion = StringTools.startsWithUppercase(word) ? StringTools.uppercaseFirstChar(variantInfo.otherVariant()) : variantInfo.otherVariant(); replaceFormsOfFirstMatch(message, sentence, ruleMatches, suggestion); } } } return ruleMatches; } /** * @since 4.5 */ @Nullable protected VariantInfo isValidInOtherVariant(String word) { return null; } private void addFormsToFirstMatch(String message, AnalyzedSentence sentence, List<RuleMatch> ruleMatches, List<String> forms) { // recreating match, might overwrite information by SuggestionsRanker; // this has precedence RuleMatch oldMatch = ruleMatches.get(0); RuleMatch newMatch = new RuleMatch(this, sentence, oldMatch.getFromPos(), oldMatch.getToPos(), message); List<String> allSuggestions = new ArrayList<>(forms); for (String repl : oldMatch.getSuggestedReplacements()) { if (!allSuggestions.contains(repl)) { allSuggestions.add(repl); } } newMatch.setSuggestedReplacements(allSuggestions); ruleMatches.set(0, newMatch); } private void replaceFormsOfFirstMatch(String message, AnalyzedSentence sentence, List<RuleMatch> ruleMatches, String suggestion) { // recreating match, might overwrite information by SuggestionsRanker; // this has precedence RuleMatch oldMatch = ruleMatches.get(0); RuleMatch newMatch = new RuleMatch(this, sentence, oldMatch.getFromPos(), oldMatch.getToPos(), message); SuggestedReplacement sugg = new SuggestedReplacement(suggestion); sugg.setShortDescription(language.getName()); newMatch.setSuggestedReplacementObjects(Collections.singletonList(sugg)); ruleMatches.set(0, newMatch); } @SuppressWarnings({"ReuseOfLocalVariable", "ControlFlowStatementWithoutBraces"}) @Nullable private IrregularForms getIrregularFormsOrNull(String word) { IrregularForms irregularFormsOrNull = getIrregularFormsOrNull(word, "ed", Arrays.asList("ed"), "VBD", "verb", "past tense"); if (irregularFormsOrNull != null) return irregularFormsOrNull; irregularFormsOrNull = getIrregularFormsOrNull(word, "ed", Arrays.asList("d" /* e.g. awaked */), "VBD", "verb", "past tense"); if (irregularFormsOrNull != null) return irregularFormsOrNull; irregularFormsOrNull = getIrregularFormsOrNull(word, "s", Arrays.asList("s"), "NNS", "noun", "plural"); if (irregularFormsOrNull != null) return irregularFormsOrNull; irregularFormsOrNull = getIrregularFormsOrNull(word, "es", Arrays.asList("es"/* e.g. 'analysises' */), "NNS", "noun", "plural"); if (irregularFormsOrNull != null) return irregularFormsOrNull; irregularFormsOrNull = getIrregularFormsOrNull(word, "er", Arrays.asList("er"/* e.g. 'farer' */), "JJR", "adjective", "comparative"); if (irregularFormsOrNull != null) return irregularFormsOrNull; irregularFormsOrNull = getIrregularFormsOrNull(word, "est", Arrays.asList("est"/* e.g. 'farest' */), "JJS", "adjective", "superlative"); return irregularFormsOrNull; } @Nullable private IrregularForms getIrregularFormsOrNull(String word, String wordSuffix, List<String> suffixes, String posTag, String posName, String formName) { try { for (String suffix : suffixes) { if (word.endsWith(wordSuffix)) { String baseForm = word.substring(0, word.length() - suffix.length()); String[] forms = synthesizer.synthesize(new AnalyzedToken(word, null, baseForm), posTag); List<String> result = new ArrayList<>(); for (String form : forms) { if (!speller1.isMisspelled(form)) { // only accept suggestions that the spellchecker will accept result.add(form); } } // the internal dict might contain forms that the spell checker doesn't accept (e.g. 'criterions'), // but we trust the spell checker in this case: result.remove(word); result.remove("badder"); // non-standard usage result.remove("baddest"); // non-standard usage result.remove("spake"); // can be removed after dict update if (result.size() > 0) { return new IrregularForms(baseForm, posName, formName, result); } } } return null; } catch (IOException e) { throw new RuntimeException(e); } } /** * @since 2.7 */ @Override protected List<String> getAdditionalTopSuggestions(List<String> suggestions, String word) throws IOException { if ("Alot".equals(word)) { return Arrays.asList("A lot"); } else if ("alot".equals(word)) { return Arrays.asList("a lot"); } else if ("ad-hoc".equals(word) || "adhoc".equals(word)) { return Arrays.asList("ad hoc"); } else if ("Ad-hoc".equals(word) || "Adhoc".equals(word)) { return Arrays.asList("Ad hoc"); } else if ("ad-on".equals(word)) { return Arrays.asList("add-on"); } else if ("acc".equals(word)) { return Arrays.asList("account", "accusative"); } else if ("Acc".equals(word)) { return Arrays.asList("Account", "Accusative"); } else if ("jus".equals(word)) { return Arrays.asList("just", "juice"); } else if ("Jus".equals(word)) { return Arrays.asList("Just", "Juice"); } else if ("sayed".equals(word)) { return Arrays.asList("said"); } else if ("sess".equals(word)) { return Arrays.asList("says", "session", "cess"); } else if ("Addon".equals(word)) { return Arrays.asList("Add-on"); } else if ("Addons".equals(word)) { return Arrays.asList("Add-ons"); } else if ("ios".equals(word)) { return Arrays.asList("iOS"); } else if ("yrs".equals(word)) { return Arrays.asList("years"); } else if ("standup".equals(word)) { return Arrays.asList("stand-up"); } else if ("standups".equals(word)) { return Arrays.asList("stand-ups"); } else if ("Standup".equals(word)) { return Arrays.asList("Stand-up"); } else if ("Standups".equals(word)) { return Arrays.asList("Stand-ups"); } else if ("Playdough".equals(word)) { return Arrays.asList("Play-Doh"); } else if ("playdough".equals(word)) { return Arrays.asList("Play-Doh"); } else if ("biggy".equals(word)) { return Arrays.asList("biggie"); } else if ("lieing".equals(word)) { return Arrays.asList("lying"); } else if ("preffered".equals(word)) { return Arrays.asList("preferred"); } else if ("preffering".equals(word)) { return Arrays.asList("preferring"); } else if ("reffered".equals(word)) { return Arrays.asList("referred"); } else if ("reffering".equals(word)) { return Arrays.asList("referring"); } else if ("passthrough".equals(word)) { return Arrays.asList("pass-through"); } else if ("&&".equals(word)) { return Arrays.asList("&"); } else if ("cmon".equals(word)) { return Arrays.asList("c'mon"); } else if ("Cmon".equals(word)) { return Arrays.asList("C'mon"); } else if ("da".equals(word)) { return Arrays.asList("the"); } else if ("Da".equals(word)) { return Arrays.asList("The"); } else if ("Vue".equals(word)) { return Arrays.asList("Vue.JS"); } else if ("errornous".equals(word)) { return Arrays.asList("erroneous"); } else if ("brang".equals(word) || "brung".equals(word)) { return Arrays.asList("brought"); } else if ("thru".equals(word)) { return Arrays.asList("through"); } else if ("pitty".equals(word)) { return Arrays.asList("pity"); } else if ("speach".equals(word)) { // the replacement pairs would prefer "speak" return Arrays.asList("speech"); } else if ("icecreem".equals(word)) { return Arrays.asList("ice cream"); } else if ("math".equals(word)) { // in en-gb it's 'maths' return Arrays.asList("maths"); } else if ("fora".equals(word)) { return Arrays.asList("for a"); } else if ("lotsa".equals(word)) { return Arrays.asList("lots of"); } else if ("tryna".equals(word)) { return Arrays.asList("trying to"); } else if ("coulda".equals(word)) { return Arrays.asList("could have"); } else if ("shoulda".equals(word)) { return Arrays.asList("should have"); } else if ("woulda".equals(word)) { return Arrays.asList("would have"); } else if ("tellem".equals(word)) { return Arrays.asList("tell them"); } else if ("Tellem".equals(word)) { return Arrays.asList("Tell them"); } else if ("afro-american".equalsIgnoreCase(word)) { return Arrays.asList("Afro-American"); } else if ("Webex".equals(word)) { return Arrays.asList("WebEx"); } else if ("didint".equals(word)) { return Arrays.asList("didn't"); } else if ("Didint".equals(word)) { return Arrays.asList("Didn't"); } else if ("wasint".equals(word)) { return Arrays.asList("wasn't"); } else if ("hasint".equals(word)) { return Arrays.asList("hasn't"); } else if ("doesint".equals(word)) { return Arrays.asList("doesn't"); } else if ("ist".equals(word)) { return Arrays.asList("is"); } else if ("Boing".equals(word)) { return Arrays.asList("Boeing"); } else if ("te".equals(word)) { return Arrays.asList("the"); } else if ("todays".equals(word)) { return Arrays.asList("today's"); } else if ("Todays".equals(word)) { return Arrays.asList("Today's"); } else if ("todo".equals(word)) { return Arrays.asList("to-do", "to do"); } else if ("todos".equals(word)) { return Arrays.asList("to-dos", "to do"); } else if ("Todo".equalsIgnoreCase(word)) { return Arrays.asList("To-do", "To do"); } else if ("Todos".equalsIgnoreCase(word)) { return Arrays.asList("To-dos"); } else if ("heres".equals(word)) { return Arrays.asList("here's"); } else if ("Heres".equals(word)) { return Arrays.asList("Here's"); } else if ("aways".equals(word)) { return Arrays.asList("always"); } else if ("McDonalds".equals(word)) { return Arrays.asList("McDonald's"); } else if ("ux".equals(word)) { return Arrays.asList("UX"); } else if ("ive".equals(word)) { return Arrays.asList("I've"); } else if ("infos".equals(word)) { return Arrays.asList("informations"); } else if ("Infos".equals(word)) { return Arrays.asList("Informations"); } else if ("prios".equals(word)) { return Arrays.asList("priorities"); } else if ("Prio".equals(word)) { return Arrays.asList("Priority"); } else if ("prio".equals(word)) { return Arrays.asList("Priority"); } else if ("esport".equals(word)) { return Arrays.asList("e-sport"); } else if ("Esport".equals(word)) { return Arrays.asList("E-Sport"); } else if ("eSport".equals(word)) { return Arrays.asList("e-sport"); } else if ("esports".equals(word)) { return Arrays.asList("e-sports"); } else if ("Esports".equals(word)) { return Arrays.asList("E-Sports"); } else if ("eSports".equals(word)) { return Arrays.asList("e-sports"); } else if ("ecommerce".equals(word)) { return Arrays.asList("e-commerce"); } else if ("Ecommerce".equals(word)) { return Arrays.asList("E-Commerce"); } else if ("eCommerce".equals(word)) { return Arrays.asList("e-commerce"); } else if ("elearning".equals(word)) { return Arrays.asList("e-learning"); } else if ("eLearning".equals(word)) { return Arrays.asList("e-learning"); } else if ("ebook".equals(word)) { return Arrays.asList("e-book"); } else if ("ebooks".equals(word)) { return Arrays.asList("e-books"); } else if ("eBook".equals(word)) { return Arrays.asList("e-book"); } else if ("eBooks".equals(word)) { return Arrays.asList("e-books"); } else if ("Ebook".equals(word)) { return Arrays.asList("E-Book"); } else if ("Ebooks".equals(word)) { return Arrays.asList("E-Books"); } else if ("sport".equals(word)) { return Arrays.asList("e-sport"); } else if ("esports".equals(word)) { return Arrays.asList("e-sports"); } else if ("eSport".equals(word)) { return Arrays.asList("e-sport"); } else if ("eSports".equals(word)) { return Arrays.asList("e-sport"); } else if ("Esport".equals(word)) { return Arrays.asList("E-Sport"); } else if ("Esports".equals(word)) { return Arrays.asList("E-Sport"); } else if ("R&B".equals(word)) { return Arrays.asList("R & B", "R 'n' B"); } else if ("ie".equals(word)) { return Arrays.asList("i.e."); } else if ("eg".equals(word)) { return Arrays.asList("e.g."); } else if ("Thx".equals(word)) { return Arrays.asList("Thanks"); } else if ("thx".equals(word)) { return Arrays.asList("thanks"); } else if ("ty".equals(word)) { return Arrays.asList("thank you", "thanks"); } else if ("Sry".equals(word)) { return Arrays.asList("Sorry"); } else if ("sry".equals(word)) { return Arrays.asList("sorry"); } else if ("im".equals(word)) { return Arrays.asList("I'm"); } else if ("spoilt".equals(word)) { return Arrays.asList("spoiled"); } else if ("Lil".equals(word)) { return Arrays.asList("Little"); } else if ("lil".equals(word)) { return Arrays.asList("little"); } else if ("Sucka".equals(word)) { return Arrays.asList("Sucker"); } else if ("sucka".equals(word)) { return Arrays.asList("sucker"); } else if ("whaddya".equals(word)) { return Arrays.asList("what are you", "what do you"); } else if ("Whaddya".equals(word)) { return Arrays.asList("What are you", "What do you"); } else if ("sinc".equals(word)) { return Arrays.asList("sync"); } else if ("Hongkong".equals(word)) { return Arrays.asList("Hong Kong"); } else if ("center".equals(word)) { // For non-US English return Arrays.asList("centre"); } else if ("ur".equals(word)) { return Arrays.asList("your", "you are"); } else if ("Ur".equals(word)) { return Arrays.asList("Your", "You are"); } else if ("ure".equals(word)) { return Arrays.asList("your", "you are"); } else if ("Ure".equals(word)) { return Arrays.asList("Your", "You are"); } else if ("mins".equals(word)) { return Arrays.asList("minutes", "min"); } else if ("addon".equals(word)) { return Arrays.asList("add-on"); } else if ("addons".equals(word)) { return Arrays.asList("add-ons"); } else if ("afterparty".equals(word)) { return Arrays.asList("after-party"); } else if ("Afterparty".equals(word)) { return Arrays.asList("After-party"); } else if ("wellbeing".equals(word)) { return Arrays.asList("well-being"); } else if ("cuz".equals(word) || "coz".equals(word)) { return Arrays.asList("because"); } else if ("pls".equals(word)) { return Arrays.asList("please"); } else if ("Pls".equals(word)) { return Arrays.asList("Please"); } else if ("plz".equals(word)) { return Arrays.asList("please"); } else if ("Plz".equals(word)) { return Arrays.asList("Please"); } else if ("gmail".equals(word)) { return Arrays.asList("Gmail"); // AtD irregular plurals - START } else if ("addendums".equals(word)) { return Arrays.asList("addenda"); } else if ("algas".equals(word)) { return Arrays.asList("algae"); } else if ("alumnas".equals(word)) { return Arrays.asList("alumnae"); } else if ("alumnuses".equals(word)) { return Arrays.asList("alumni"); } else if ("analysises".equals(word)) { return Arrays.asList("analyses"); } else if ("appendixs".equals(word)) { return Arrays.asList("appendices"); } else if ("axises".equals(word)) { return Arrays.asList("axes"); } else if ("bacilluses".equals(word)) { return Arrays.asList("bacilli"); } else if ("bacteriums".equals(word)) { return Arrays.asList("bacteria"); } else if ("basises".equals(word)) { return Arrays.asList("bases"); } else if ("beaus".equals(word)) { return Arrays.asList("beaux"); } else if ("bisons".equals(word)) { return Arrays.asList("bison"); } else if ("buffalos".equals(word)) { return Arrays.asList("buffaloes"); } else if ("calfs".equals(word)) { return Arrays.asList("calves"); } else if ("childs".equals(word)) { return Arrays.asList("children"); } else if ("crisises".equals(word)) { return Arrays.asList("crises"); } else if ("criterions".equals(word)) { return Arrays.asList("criteria"); } else if ("curriculums".equals(word)) { return Arrays.asList("curricula"); } else if ("datums".equals(word)) { return Arrays.asList("data"); } else if ("deers".equals(word)) { return Arrays.asList("deer"); } else if ("diagnosises".equals(word)) { return Arrays.asList("diagnoses"); } else if ("echos".equals(word)) { return Arrays.asList("echoes"); } else if ("elfs".equals(word)) { return Arrays.asList("elves"); } else if ("ellipsises".equals(word)) { return Arrays.asList("ellipses"); } else if ("embargos".equals(word)) { return Arrays.asList("embargoes"); } else if ("erratums".equals(word)) { return Arrays.asList("errata"); } else if ("firemans".equals(word)) { return Arrays.asList("firemen"); } else if ("fishs".equals(word)) { return Arrays.asList("fishes", "fish"); } else if ("genuses".equals(word)) { return Arrays.asList("genera"); } else if ("gooses".equals(word)) { return Arrays.asList("geese"); } else if ("halfs".equals(word)) { return Arrays.asList("halves"); } else if ("heros".equals(word)) { return Arrays.asList("heroes"); } else if ("indexs".equals(word)) { return Arrays.asList("indices", "indexes"); } else if ("lifes".equals(word)) { return Arrays.asList("lives"); } else if ("mans".equals(word)) { return Arrays.asList("men"); } else if ("matrixs".equals(word)) { return Arrays.asList("matrices"); } else if ("meanses".equals(word)) { return Arrays.asList("means"); } else if ("mediums".equals(word)) { return Arrays.asList("media"); } else if ("memorandums".equals(word)) { return Arrays.asList("memoranda"); } else if ("mooses".equals(word)) { return Arrays.asList("moose"); } else if ("mosquitos".equals(word)) { return Arrays.asList("mosquitoes"); } else if ("neurosises".equals(word)) { return Arrays.asList("neuroses"); } else if ("nucleuses".equals(word)) { return Arrays.asList("nuclei"); } else if ("oasises".equals(word)) { return Arrays.asList("oases"); } else if ("ovums".equals(word)) { return Arrays.asList("ova"); } else if ("oxs".equals(word)) { return Arrays.asList("oxen"); } else if ("oxes".equals(word)) { return Arrays.asList("oxen"); } else if ("paralysises".equals(word)) { return Arrays.asList("paralyses"); } else if ("potatos".equals(word)) { return Arrays.asList("potatoes"); } else if ("radiuses".equals(word)) { return Arrays.asList("radii"); } else if ("selfs".equals(word)) { return Arrays.asList("selves"); } else if ("serieses".equals(word)) { return Arrays.asList("series"); } else if ("sheeps".equals(word)) { return Arrays.asList("sheep"); } else if ("shelfs".equals(word)) { return Arrays.asList("shelves"); } else if ("scissorses".equals(word)) { return Arrays.asList("scissors"); } else if ("specieses".equals(word)) { return Arrays.asList("species"); } else if ("stimuluses".equals(word)) { return Arrays.asList("stimuli"); } else if ("stratums".equals(word)) { return Arrays.asList("strata"); } else if ("tableaus".equals(word)) { return Arrays.asList("tableaux"); } else if ("thats".equals(word)) { return Arrays.asList("those"); } else if ("thesises".equals(word)) { return Arrays.asList("theses"); } else if ("thiefs".equals(word)) { return Arrays.asList("thieves"); } else if ("thises".equals(word)) { return Arrays.asList("these"); } else if ("tomatos".equals(word)) { return Arrays.asList("tomatoes"); } else if ("tooths".equals(word)) { return Arrays.asList("teeth"); } else if ("torpedos".equals(word)) { return Arrays.asList("torpedoes"); } else if ("vertebras".equals(word)) { return Arrays.asList("vertebrae"); } else if ("vetos".equals(word)) { return Arrays.asList("vetoes"); } else if ("vitas".equals(word)) { return Arrays.asList("vitae"); } else if ("watchs".equals(word)) { return Arrays.asList("watches"); } else if ("wifes".equals(word)) { return Arrays.asList("wives"); } else if ("womans".equals(word)) { return Arrays.asList("women"); // AtD irregular plurals - END } else if ("tippy-top".equals(word) || "tippytop".equals(word)) { // "tippy-top" is an often used word by Donald Trump return Arrays.asList("tip-top", "top most"); } else if ("imma".equals(word)) { return Arrays.asList("I'm going to", "I'm a"); } else if ("Imma".equals(word)) { return Arrays.asList("I'm going to", "I'm a"); } else if ("dontcha".equals(word)) { return Arrays.asList("don't you"); } else if ("tobe".equals(word)) { return Arrays.asList("to be"); } else if ("Gi".equals(word) || "Ji".equals(word)) { return Arrays.asList("Hi"); } else if ("Dontcha".equals(word)) { return Arrays.asList("don't you"); } else if ("greatfruit".equals(word)) { return Arrays.asList("grapefruit", "great fruit"); } else if (word.endsWith("ys")) { String suggestion = word.replaceFirst("ys$", "ies"); if (!speller1.isMisspelled(suggestion)) { return Arrays.asList(suggestion); } } return super.getAdditionalTopSuggestions(suggestions, word); } private static class IrregularForms { final String baseform; final String posName; final String formName; final List<String> forms; private IrregularForms(String baseform, String posName, String formName, List<String> forms) { this.baseform = baseform; this.posName = posName; this.formName = formName; this.forms = forms; } } }
package org.geotools.referencing.factory.epsg; import java.sql.Connection; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import javax.sql.DataSource; import org.geotools.util.factory.Hints; /** * An EPSG factory for the database generated by SQL scripts rather than the MS-Access one. * * @since 2.1 * @version $Id$ * @author Rueben Schulz * @author Martin Desruisseaux * @author Didier Richard * @author John Grange * @deprecated Please use {@link AnsiDialectEpsgFactory}. */ public class FactoryUsingAnsiSQL extends FactoryUsingSQL { /** The default map using ANSI names. */ private static final String[] ANSI = { "[Alias]", "epsg_alias", "[Area]", "epsg_area", "[Coordinate Axis]", "epsg_coordinateaxis", "[Coordinate Axis Name]", "epsg_coordinateaxisname", "[Coordinate_Operation]", "epsg_coordoperation", "[Coordinate_Operation Method]", "epsg_coordoperationmethod", "[Coordinate_Operation Parameter]", "epsg_coordoperationparam", "[Coordinate_Operation Parameter Usage]", "epsg_coordoperationparamusage", "[Coordinate_Operation Parameter Value]", "epsg_coordoperationparamvalue", "[Coordinate_Operation Path]", "epsg_coordoperationpath", "[Coordinate Reference System]", "epsg_coordinatereferencesystem", "[Coordinate System]", "epsg_coordinatesystem", "[Datum]", "epsg_datum", "[Ellipsoid]", "epsg_ellipsoid", "[Naming System]", "epsg_namingsystem", "[Prime Meridian]", "epsg_primemeridian", "[Supersession]", "epsg_supersession", "[Unit of Measure]", "epsg_unitofmeasure", "[Version History]", "epsg_versionhistory", "[ORDER]", "coord_axis_order" // a field in epsg_coordinateaxis }; /** * Maps the MS-Access names to ANSI names. Keys are MS-Access names including bracket. Values * are ANSI names. Keys and values are case-sensitive. The default content of this map is: * * <pre><table> * <tr><th align="center">MS-Access name</th> <th align="center">ANSI name</th></tr> * <tr><td>[Alias]</td> <td>epsg_alias</td></tr> * <tr><td>[Area]</td> <td>epsg_area</td></tr> * <tr><td>[Coordinate Axis]</td> <td>epsg_coordinateaxis</td></tr> * <tr><td>[Coordinate Axis Name]</td> <td>epsg_coordinateaxisname</td></tr> * <tr><td>[Coordinate_Operation]</td> <td>epsg_coordoperation</td></tr> * <tr><td>[Coordinate_Operation Method]</td> <td>epsg_coordoperationmethod</td></tr> * <tr><td>[Coordinate_Operation Parameter]</td> <td>epsg_coordoperationparam</td></tr> * <tr><td>[Coordinate_Operation Parameter Usage]</td> <td>epsg_coordoperationparamusage</td></tr> * <tr><td>[Coordinate_Operation Parameter Value]</td> <td>epsg_coordoperationparamvalue</td></tr> * <tr><td>[Coordinate_Operation Path]</td> <td>epsg_coordoperationpath</td></tr> * <tr><td>[Coordinate Reference System]</td> <td>epsg_coordinatereferencesystem</td></tr> * <tr><td>[Coordinate System]</td> <td>epsg_coordinatesystem</td></tr> * <tr><td>[Datum]</td> <td>epsg_datum</td></tr> * <tr><td>[Naming System]</td> <td>epsg_namingsystem</td></tr> * <tr><td>[Ellipsoid]</td> <td>epsg_ellipsoid</td></tr> * <tr><td>[Prime Meridian]</td> <td>epsg_primemeridian</td></tr> * <tr><td>[Supersession]</td> <td>epsg_supersession</td></tr> * <tr><td>[Unit of Measure]</td> <td>epsg_unitofmeasure</td></tr> * <tr><td>[CA.ORDER]</td> <td>coord_axis_order</td></tr> * </table></pre> * * Subclasses can modify this map in their constructor in order to provide a different mapping. */ protected final Map map = new LinkedHashMap(); /** * The prefix before any table name. May be replaced by a schema if {@link #setSchema} is * invoked. */ private String prefix = "epsg_"; /** * Constructs an authority factory using the specified connection. * * @param userHints The underlying factories used for objects creation. * @param connection The connection to the underlying EPSG database. * @since 2.2 */ public FactoryUsingAnsiSQL(final Hints userHints, final Connection connection) { super(userHints, connection); for (int i = 0; i < ANSI.length; i++) { map.put(ANSI[i], ANSI[++i]); } } /** * Constructs an authority factory using the specified source. * * @param userHints The underlying factories used for objects creation. * @param dataSource The connection to the underlying EPSG database. * @since 2.5 */ public FactoryUsingAnsiSQL(final Hints userHints, final DataSource dataSource) { super(userHints, dataSource); for (int i = 0; i < ANSI.length; i++) { map.put(ANSI[i], ANSI[++i]); } } /** * Replaces the {@code "epsg_"} prefix by the specified schema name. If the removal of the * {@code "epsg_"} prefix is not wanted, append it to the schema name (e.g. {@code * "myschema.epsg_"}). This method should be invoked at construction time only. * * @param schema The database schema in which the epsg tables are stored. * @since 2.2 */ public void setSchema(String schema) { schema = schema.trim(); final int length = schema.length(); if (length == 0) { throw new IllegalArgumentException(schema); } final char separator = schema.charAt(length - 1); if (separator != '.' && separator != '_') { schema += '.'; } else if (length == 1) { throw new IllegalArgumentException(schema); } for (final Iterator it = map.entrySet().iterator(); it.hasNext(); ) { final Map.Entry entry = (Map.Entry) it.next(); final String tableName = (String) entry.getValue(); /** * Update the map, prepending the schema name to the table name so long as the value is * a table name and not a field. This algorithm assumes that all old table names start * with "epsg_". */ if (tableName.startsWith(prefix)) { entry.setValue(schema + tableName.substring(prefix.length())); } } prefix = schema; } /** * Modifies the given SQL string to be suitable for non MS-Access databases. This replaces table * and field names in the SQL with the new names in the SQL DDL scripts provided with EPSG * database. * * @param statement The statement in MS-Access syntax. * @return The SQL statement in ANSI syntax. */ @Override protected String adaptSQL(final String statement) { final StringBuilder modified = new StringBuilder(statement); for (final Iterator it = map.entrySet().iterator(); it.hasNext(); ) { final Map.Entry entry = (Map.Entry) it.next(); final String oldName = (String) entry.getKey(); final String newName = (String) entry.getValue(); /* * Replaces all occurences of 'oldName' by 'newName'. */ int start = 0; while ((start = modified.indexOf(oldName, start)) >= 0) { modified.replace(start, start + oldName.length(), newName); start += newName.length(); } } return modified.toString(); } }
package org.gbif.occurrence.search.heatmap.es; import org.apache.lucene.search.BooleanClause; import org.apache.solr.client.solrj.response.QueryResponse; import org.codehaus.jackson.JsonNode; import org.codehaus.jackson.node.ObjectNode; import org.codehaus.jackson.node.POJONode; import org.gbif.occurrence.search.es.EsQueryUtils; import org.gbif.occurrence.search.es.OccurrenceEsField; import org.gbif.occurrence.search.heatmap.OccurrenceHeatmapRequest; import org.junit.Assert; import org.junit.Test; import static org.gbif.occurrence.search.es.EsQueryUtils.*; import static org.gbif.occurrence.search.heatmap.es.EsHeatmapRequestBuilder.BOX_AGGS; import static org.gbif.occurrence.search.heatmap.es.EsHeatmapRequestBuilder.CELL_AGGS; import static org.gbif.occurrence.search.heatmap.es.EsHeatmapRequestBuilder.HEATMAP_AGGS; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public class EsHeatmapRequestBuilderTest { // TODO: adapt tests!! @Test public void heatmapRequestTest() { OccurrenceHeatmapRequest request = new OccurrenceHeatmapRequest(); request.setGeometry("-44, 30, -32, 54"); request.setZoom(1); ObjectNode json = EsHeatmapRequestBuilder.buildQuery(request); System.out.println(json.toString()); assertEquals(0, json.get(SIZE).asInt()); // aggs assertTrue(json.path(AGGS).path(BOX_AGGS).path(FILTER).has(GEO_BOUNDING_BOX)); // assert bbox JsonNode bbox = json.path(AGGS) .path(BOX_AGGS) .path(FILTER) .path(GEO_BOUNDING_BOX) .path(OccurrenceEsField.COORDINATE_POINT.getFieldName()); assertEquals("[-44.0, 54.0]", ((POJONode) bbox.path("top_left")).asText()); assertEquals("[-32.0, 30.0]", ((POJONode) bbox.path("bottom_right")).asText()); // geohash_grid assertTrue(json.path(AGGS).path(BOX_AGGS).path(AGGS).path(HEATMAP_AGGS).has(GEOHASH_GRID)); JsonNode jsonGeohashGrid = json.path(AGGS).path(BOX_AGGS).path(AGGS).path(HEATMAP_AGGS).path(GEOHASH_GRID); assertEquals( OccurrenceEsField.COORDINATE_POINT.getFieldName(), jsonGeohashGrid.get(FIELD).asText()); assertEquals(1, jsonGeohashGrid.get(PRECISION).asInt()); // geo_bounds assertTrue( json.path(AGGS) .path(BOX_AGGS) .path(AGGS) .path(HEATMAP_AGGS) .path(AGGS) .path(CELL_AGGS) .has(GEO_BOUNDS)); JsonNode jsonGeobounds = json.path(AGGS) .path(BOX_AGGS) .path(AGGS) .path(HEATMAP_AGGS) .path(AGGS) .path(CELL_AGGS) .path(GEO_BOUNDS); assertEquals( OccurrenceEsField.COORDINATE_POINT.getFieldName(), jsonGeobounds.get(FIELD).asText()); } @Test public void heatmapRequestFilteredTest() { OccurrenceHeatmapRequest request = new OccurrenceHeatmapRequest(); request.addTaxonKeyFilter(4); request.setGeometry("-44, 30, -32, 54"); request.setZoom(1); ObjectNode json = EsHeatmapRequestBuilder.buildQuery(request); assertEquals(0, json.get(SIZE).asInt()); assertTrue(json.path(QUERY).path(BOOL).path(FILTER).isArray()); assertTrue(json.path(QUERY).path(BOOL).path(FILTER).get(0).has(TERM)); // taxon key assertEquals( 4, json.path(QUERY) .path(BOOL) .path(FILTER) .get(0) .path(TERM) .get(OccurrenceEsField.TAXA_KEY.getFieldName()) .asInt()); // aggs assertTrue(json.path(AGGS).path(BOX_AGGS).path(FILTER).has(GEO_BOUNDING_BOX)); // geohash_grid assertTrue(json.path(AGGS).path(BOX_AGGS).path(AGGS).path(HEATMAP_AGGS).has(GEOHASH_GRID)); // geo_bounds assertTrue( json.path(AGGS) .path(BOX_AGGS) .path(AGGS) .path(HEATMAP_AGGS) .path(AGGS) .path(CELL_AGGS) .has(GEO_BOUNDS)); } }
package org.eclipse.wst.html.webresources.core.utils; import java.io.IOException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; /** * URI Helper. * */ public class URIHelper { private static final String DATA_URI_SCHEME = "data:"; private static final String HTTP = "http"; private static final String DOUBLE_SLASH = " /** * Returns true if the given uri is a data URI scheme and false otherwise. * * @param uri * @return true if the given uri is a data URI scheme and false otherwise. */ public static boolean isDataURIScheme(String uri) { return uri != null && uri.startsWith(DATA_URI_SCHEME); } /** * Returns true if the given uri starts with http or with // * * @param url * @return true if the given uri starts with http or with // */ public static boolean isExternalURL(String url) { return url != null && (url.startsWith(HTTP) || url.startsWith(DOUBLE_SLASH)); } /** * Returns true of the given url can be connected an dfalse otherwise. * * @param url * @return true of the given url can be connected an dfalse otherwise. */ public static boolean validateExternalURL(String url) { try { if (url.startsWith(DOUBLE_SLASH)) { url = HTTP + ":" + url; } URLConnection conn = new URL(url).openConnection(); conn.connect(); if (conn instanceof HttpURLConnection) { int code = ((HttpURLConnection) conn).getResponseCode(); return code != HttpURLConnection.HTTP_NOT_FOUND; } } catch (MalformedURLException e) { // the URL is not in a valid form return false; } catch (IOException e) { // the connection couldn't be established return false; } return true; } }
package org.springsource.ide.eclipse.commons.core; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.zip.ZipEntry; import java.util.zip.ZipException; import java.util.zip.ZipInputStream; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.NullProgressMonitor; import org.springsource.ide.eclipse.commons.core.process.StandardProcessRunner; import org.springsource.ide.eclipse.commons.core.util.OsUtils; /** * @author Steffen Pingel * @author Leo Dos Santos * @author Christian Dupuis * @author Kris De Volder * @since 2.0 */ public class ZipFileUtil { public static abstract class PermissionSetter { /** * Called after a file was succesfully extracted from the zip archive. * @throws IOException */ public abstract void fileUnzipped(ZipEntry entry, File entryFile) throws IOException; public static final PermissionSetter NULL = new PermissionSetter() { @Override public void fileUnzipped(ZipEntry entry, File entryFile) { // Do nothing } }; public static PermissionSetter executableExtensions(final String... exts) { if (OsUtils.isWindows()) { // It may be ok to do nothing for windows? (note: not tested!) return NULL; } else { // Assume we are unix if not Windows (Mac OS X is ok) return new PermissionSetter() { @Override public void fileUnzipped(ZipEntry entry, File entryFile) throws IOException { for (String ext : exts) { if (entryFile.getName().endsWith(ext)) { // This only works with Java 6: // entryFile.setExecutable(true); // This only works on Unix: StandardProcessRunner runner = new StandardProcessRunner(); try { runner.run(new File("."), "chmod", "a+x", entryFile.toString()); } catch (InterruptedException e) { // Restore the interrupted status (see Thread.currentThread().interrupt(); } return; // No sense making a file executable // more than once. } } } }; } } } private static final int BUFFER_SIZE = 512 * 1024; public static void unzip(URL source, File targetFile, IProgressMonitor monitor) throws IOException { unzip(source, targetFile, null, monitor); } public static void unzip(URL source, File targetFile, String prefix, IProgressMonitor monitor) throws IOException { unzip(source, targetFile, prefix, PermissionSetter.NULL, monitor); } public static void unzip(URL source, File targetFile, String prefix, PermissionSetter permsetter, IProgressMonitor monitor) throws IOException { if (monitor == null) { monitor = new NullProgressMonitor(); } try { monitor.beginTask("Extracting " + source.getFile(), IProgressMonitor.UNKNOWN); byte[] buffer = new byte[BUFFER_SIZE]; ZipInputStream zipIn = new ZipInputStream(source.openStream()); try { ZipEntry entry; while ((entry = zipIn.getNextEntry()) != null) { String name = entry.getName(); if (prefix != null && name.startsWith(prefix)) { name = name.substring(prefix.length()); if (name.length() > 1) { // cut off separator name = name.substring(1); } } Policy.checkCancelled(monitor); monitor.subTask(name); File entryFile = new File(targetFile, name); if (name.contains("..") && !entryFile.getCanonicalPath().startsWith(targetFile.getCanonicalPath())) { throw new ZipException("The file " + name + " is trying to leave the target output directory of " + targetFile); } if (entry.isDirectory()) { entryFile.mkdirs(); } else { entryFile.getParentFile().mkdirs(); FileOutputStream out = new FileOutputStream(entryFile); try { int len; while ((len = zipIn.read(buffer)) >= 0) { Policy.checkCancelled(monitor); out.write(buffer, 0, len); } } finally { out.close(); } long modTime = entry.getTime(); if (modTime > 0) { entryFile.setLastModified(modTime); } permsetter.fileUnzipped(entry, entryFile); } } } finally { zipIn.close(); } } finally { monitor.done(); } } public static void unzip(File zipFile, File unzipDir, IProgressMonitor monitor) throws MalformedURLException, IOException { unzip(zipFile.toURI().toURL(), unzipDir, monitor); } }
package org.geomajas.layer.hibernate; import java.io.Serializable; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.annotation.PostConstruct; import org.apache.commons.beanutils.ConvertUtils; import org.geomajas.configuration.AssociationAttributeInfo; import org.geomajas.configuration.AssociationType; import org.geomajas.configuration.AttributeInfo; import org.geomajas.configuration.SortType; import org.geomajas.configuration.VectorLayerInfo; import org.geomajas.global.Api; import org.geomajas.global.ExceptionCode; import org.geomajas.global.GeomajasException; import org.geomajas.layer.LayerException; import org.geomajas.layer.VectorLayer; import org.geomajas.layer.VectorLayerAssociationSupport; import org.geomajas.layer.feature.Attribute; import org.geomajas.layer.feature.FeatureModel; import org.geomajas.service.DtoConverterService; import org.geomajas.service.FilterService; import org.geomajas.service.GeoService; import org.hibernate.Criteria; import org.hibernate.EntityMode; import org.hibernate.HibernateException; import org.hibernate.ScrollableResults; import org.hibernate.Session; import org.hibernate.criterion.Criterion; import org.hibernate.criterion.Order; import org.hibernate.metadata.ClassMetadata; import org.hibernate.type.CollectionType; import org.hibernate.type.Type; import org.opengis.filter.Filter; import org.opengis.referencing.crs.CoordinateReferenceSystem; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; import com.vividsolutions.jts.geom.Envelope; import com.vividsolutions.jts.geom.Geometry; /** * Hibernate layer model. * * @author Pieter De Graef * @author Jan De Moerloose * @author Kristof Heirwegh * @since 1.7.1 */ @Api @Transactional(rollbackFor = { Exception.class }) public class HibernateLayer extends HibernateLayerUtil implements VectorLayer, VectorLayerAssociationSupport { private final Logger log = LoggerFactory.getLogger(HibernateLayer.class); private FeatureModel featureModel; /** * <p> * Should the result be retrieved as a scrollable resultset? Your * database(driver) needs to support this. * </p> * * @since 1.8.0 */ private boolean scrollableResultSet; /** * When parsing dates from filters, this model must know how to parse these * strings into Date objects before transforming them into Hibernate * criteria. */ private DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy"); @Autowired private FilterService filterCreator; @Autowired private FilterService filterService; @Autowired private DtoConverterService converterService; @Autowired private GeoService geoService; private CoordinateReferenceSystem crs; private int srid; private String id; public String getId() { return id; } public void setId(String id) { this.id = id; } public CoordinateReferenceSystem getCrs() { return crs; } public FeatureModel getFeatureModel() { return this.featureModel; } /** * Set the layer configuration. * * @param layerInfo * layer information * @throws LayerException * oops * @since 1.7.1 */ @Api @Override public void setLayerInfo(VectorLayerInfo layerInfo) throws LayerException { super.setLayerInfo(layerInfo); if (null != featureModel) { featureModel.setLayerInfo(getLayerInfo()); } } @PostConstruct private void postConstruct() throws GeomajasException { crs = geoService.getCrs(getLayerInfo().getCrs()); srid = geoService.getSridFromCrs(crs); } public VectorLayerInfo getLayerInfo() { return super.getLayerInfo(); } public boolean isCreateCapable() { return true; } public boolean isUpdateCapable() { return true; } public boolean isDeleteCapable() { return true; } public void setFeatureModel(FeatureModel featureModel) throws LayerException { this.featureModel = featureModel; if (null != getLayerInfo()) { featureModel.setLayerInfo(getLayerInfo()); } filterService.registerFeatureModel(featureModel); } /** * This implementation does not support the 'offset' parameter. The * maxResultSize parameter is not used (limiting the result needs to be done * after security * {@link org.geomajas.internal.layer.vector.GetFeaturesEachStep * GetFeaturesEachStep}). If you expect large results to be returned enable * scrollableResultSet to retrieve only as many records as needed. */ public Iterator<?> getElements(Filter filter, int offset, int maxResultSize) throws LayerException { try { Session session = getSessionFactory().getCurrentSession(); Criteria criteria = session.createCriteria(getFeatureInfo().getDataSourceName()); if (filter != null) { if (filter != Filter.INCLUDE) { CriteriaVisitor visitor = new CriteriaVisitor((HibernateFeatureModel) getFeatureModel(), dateFormat); Criterion c = (Criterion) filter.accept(visitor, criteria); if (c != null) { criteria.add(c); } } } // Sorting of elements. if (getFeatureInfo().getSortAttributeName() != null) { if (SortType.ASC.equals(getFeatureInfo().getSortType())) { criteria.addOrder(Order.asc(getFeatureInfo().getSortAttributeName())); } else { criteria.addOrder(Order.desc(getFeatureInfo().getSortAttributeName())); } } criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); if (isScrollableResultSet()) { return (Iterator<?>) new ScrollIterator(criteria.scroll()); } else { List<?> list = criteria.list(); return list.iterator(); } } catch (HibernateException he) { throw new HibernateLayerException(he, ExceptionCode.HIBERNATE_LOAD_FILTER_FAIL, getFeatureInfo() .getDataSourceName(), filter.toString()); } } public Object create(Object feature) throws LayerException { // force the srid value enforceSrid(feature); // Replace associations with persistent versions: // Map<String, Object> attributes = featureModel.getAttributes(feature); setPersistentAssociations(feature); Session session = getSessionFactory().getCurrentSession(); session.save(feature); // do not replace feature by managed object ! // Set the original detached associations back where they belong: // @TODO THIS SHOULD ONLY RESTORE ASSOCIATIONS NOT ALL ATTRIBUTES (fails // for complex attributes (ddd/ddd) // featureModel.setAttributes(feature, attributes); return feature; } public Object saveOrUpdate(Object feature) throws LayerException { // force the srid value enforceSrid(feature); String id = getFeatureModel().getId(feature); if (getFeature(id) != null) { update(feature); } else { feature = create(feature); } return feature; } public void delete(String featureId) throws LayerException { Session session = getSessionFactory().getCurrentSession(); session.delete(getFeature(featureId)); session.flush(); } public Object read(String featureId) throws LayerException { Object object = getFeature(featureId); if (object == null) { throw new LayerException(ExceptionCode.LAYER_MODEL_FEATURE_NOT_FOUND, featureId); } return object; } public void update(Object feature) throws LayerException { Object persistent = read(getFeatureModel().getId(feature)); Map<String, Attribute> attributes = featureModel.getAttributes(feature); // replace all modified attributes by their new values featureModel.setAttributes(persistent, attributes); featureModel.setGeometry(feature, featureModel.getGeometry(feature)); } public Envelope getBounds() throws LayerException { return getBounds(filterCreator.createTrueFilter()); } /** * Retrieve the bounds of the specified features. * * @param filter * filter which needs to be applied * @return the bounds of the specified features */ public Envelope getBounds(Filter filter) throws LayerException { // Envelope bounds = getBoundsDb(filter); // if (bounds == null) // bounds = getBoundsLocal(filter); // return bounds; // @TODO getBoundsDb cannot handle hibernate Formula fields return getBoundsLocal(filter); } public List<Attribute<?>> getAttributes(String attributeName, Filter filter) throws LayerException { log.debug("creating iterator for attribute {} and filter: {}", attributeName, filter); AttributeInfo attributeInfo = null; for (AttributeInfo info : getFeatureInfo().getAttributes()) { if (info.getName().equals(attributeName)) { attributeInfo = info; break; } } String objectName = getObjectName(attributeName); if (objectName == null) { throw new HibernateLayerException(ExceptionCode.HIBERNATE_ATTRIBUTE_TYPE_PROBLEM, attributeName); } Session session = getSessionFactory().getCurrentSession(); Criteria criteria = session.createCriteria(objectName); CriteriaVisitor visitor = new CriteriaVisitor((HibernateFeatureModel) getFeatureModel(), dateFormat); Criterion c = (Criterion) filter.accept(visitor, null); if (c != null) { criteria.add(c); } List<Attribute<?>> attributes = new ArrayList<Attribute<?>>(); for (Object object : criteria.list()) { try { attributes.add(converterService.toDto(object, attributeInfo)); } catch (GeomajasException e) { throw new HibernateLayerException(ExceptionCode.HIBERNATE_ATTRIBUTE_TYPE_PROBLEM, attributeName); } } return attributes; } // Extra getters and setters: public DateFormat getDateFormat() { return dateFormat; } public void setDateFormat(DateFormat dateFormat) { this.dateFormat = dateFormat; } public boolean isScrollableResultSet() { return scrollableResultSet; } public void setScrollableResultSet(boolean scrollableResultSet) { this.scrollableResultSet = scrollableResultSet; } // Private functions: /** * A wrapper around a Hibernate {@link ScrollableResults} * * ScrollableResults are annoying they run 1 step behind an iterator... */ @SuppressWarnings("unchecked") private class ScrollIterator implements Iterator { private final ScrollableResults sr; private boolean hasnext; public ScrollIterator(ScrollableResults sr) { this.sr = sr; hasnext = sr.first(); } public boolean hasNext() { return hasnext; } public Object next() { Object o = sr.get(0); hasnext = sr.next(); return o; } public void remove() { // TODO the alternative (default) version with list allows remove(), // but this will // only remove it from the list, not from db, so maybe we should // just ignore instead of throwing an exception throw new HibernateException("Unsupported operation: You cannot remove records this way."); } } /** * Enforces the correct srid on incoming features. */ private void enforceSrid(Object feature) throws LayerException { Geometry geom = getFeatureModel().getGeometry(feature); if (null != geom) { geom.setSRID(srid); getFeatureModel().setGeometry(feature, geom); } } /** * Bounds are calculated locally, can use any filter, but slower than * native. * * @param filter * filter which needs to be applied * @return the bounds of the specified features * @throws LayerException * oops */ private Envelope getBoundsLocal(Filter filter) throws LayerException { try { Session session = getSessionFactory().getCurrentSession(); Criteria criteria = session.createCriteria(getFeatureInfo().getDataSourceName()); CriteriaVisitor visitor = new CriteriaVisitor((HibernateFeatureModel) getFeatureModel(), dateFormat); Criterion c = (Criterion) filter.accept(visitor, criteria); if (c != null) { criteria.add(c); } criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); List<?> features = criteria.list(); Envelope bounds = new Envelope(); for (Object f : features) { Envelope geomBounds = getFeatureModel().getGeometry(f).getEnvelopeInternal(); if (!geomBounds.isNull()) { bounds.expandToInclude(geomBounds); } } return bounds; } catch (HibernateException he) { throw new HibernateLayerException(he, ExceptionCode.HIBERNATE_LOAD_FILTER_FAIL, getFeatureInfo() .getDataSourceName(), filter.toString()); } } private String getObjectName(String attributeName) { for (AttributeInfo attribute : getFeatureInfo().getAttributes()) { if (attribute.getName().equals(attributeName)) { if (attribute instanceof AssociationAttributeInfo) { AssociationAttributeInfo association = (AssociationAttributeInfo) attribute; return association.getName(); } else { return null; } } } return null; } /** * The idea here is to replace association objects with their persistent * counterparts. This has to happen just before the saving to database. We * have to keep the persistent objects inside the HibernateLayer package. * Never let them out, because that way we'll invite exceptions. @TODO This * method is not recursive! * * @param feature * feature to persist * @throws LayerException * oops */ @SuppressWarnings("unchecked") private void setPersistentAssociations(Object feature) throws LayerException { try { Map<String, Attribute> attributes = featureModel.getAttributes(feature); for (AttributeInfo attribute : getFeatureInfo().getAttributes()) { // We're looping over all associations: if (attribute instanceof AssociationAttributeInfo) { String name = ((AssociationAttributeInfo) attribute).getFeature().getDataSourceName(); Object value = attributes.get(name); if (value != null) { // Find the association's meta-data: Session session = getSessionFactory().getCurrentSession(); AssociationAttributeInfo aso = (AssociationAttributeInfo) attribute; ClassMetadata meta = getSessionFactory().getClassMetadata(aso.getName()); AssociationType asoType = aso.getType(); if (asoType == AssociationType.MANY_TO_ONE) { // Many-to-one: Serializable id = meta.getIdentifier(value, EntityMode.POJO); if (id != null) { // We can only replace it, if it // has an ID: value = session.load(aso.getName(), id); getEntityMetadata().setPropertyValue(feature, name, value, EntityMode.POJO); } } else if (asoType == AssociationType.ONE_TO_MANY) { // One-to-many - value is a collection: // Get the reflection property name: String refPropName = null; Type[] types = meta.getPropertyTypes(); for (int i = 0; i < types.length; i++) { String name1 = types[i].getName(); String name2 = feature.getClass().getCanonicalName(); if (name1.equals(name2)) { // Only for circular references? refPropName = meta.getPropertyNames()[i]; } } // Instantiate a new collection: Object[] array = (Object[]) value; Type type = getEntityMetadata().getPropertyType(name); CollectionType colType = (CollectionType) type; Collection<Object> col = (Collection<Object>) colType.instantiate(0); // Loop over all detached values: for (int i = 0; i < array.length; i++) { Serializable id = meta.getIdentifier(array[i], EntityMode.POJO); if (id != null) { // Existing values: need replacing! Object persistent = session.load(aso.getName(), id); String[] props = meta.getPropertyNames(); for (String prop : props) { if (!(prop.equals(refPropName))) { Object propVal = meta.getPropertyValue(array[i], prop, EntityMode.POJO); meta.setPropertyValue(persistent, prop, propVal, EntityMode.POJO); } } array[i] = persistent; } else if (refPropName != null) { // Circular reference to the feature itself: meta.setPropertyValue(array[i], refPropName, feature, EntityMode.POJO); } else { // New values: // do nothing...it can stay a detached // value. Better hope for cascading. } col.add(array[i]); } getEntityMetadata().setPropertyValue(feature, name, col, EntityMode.POJO); } } } } } catch (Exception e) { throw new HibernateLayerException(e, ExceptionCode.HIBERNATE_ATTRIBUTE_SET_FAILED, getFeatureInfo() .getDataSourceName()); } } private Object getFeature(String featureId) throws HibernateLayerException { Session session = getSessionFactory().getCurrentSession(); return session.get(getFeatureInfo().getDataSourceName(), (Serializable) ConvertUtils.convert(featureId, getEntityMetadata().getIdentifierType().getReturnedClass())); } }
package com.redhat.ceylon.eclipse.imp.parser; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.antlr.runtime.ANTLRInputStream; import org.antlr.runtime.CommonToken; import org.antlr.runtime.CommonTokenStream; import org.antlr.runtime.RecognitionException; import org.antlr.runtime.Token; import org.eclipse.core.resources.IMarker; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.IJobManager; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.imp.editor.ParserScheduler; import org.eclipse.imp.editor.quickfix.IAnnotation; import org.eclipse.imp.model.ISourceProject; import org.eclipse.imp.parser.IMessageHandler; import org.eclipse.imp.parser.ParseControllerBase; import org.eclipse.imp.parser.SimpleAnnotationTypeInfo; import org.eclipse.imp.services.IAnnotationTypeInfo; import org.eclipse.imp.services.ILanguageSyntaxProperties; import org.eclipse.jdt.core.IJavaModelMarker; import org.eclipse.jface.text.IRegion; 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; import com.redhat.ceylon.compiler.typechecker.model.Module; import com.redhat.ceylon.compiler.typechecker.model.Modules; import com.redhat.ceylon.compiler.typechecker.model.Package; import com.redhat.ceylon.compiler.typechecker.parser.CeylonLexer; import com.redhat.ceylon.compiler.typechecker.parser.CeylonParser; import com.redhat.ceylon.compiler.typechecker.parser.LexError; import com.redhat.ceylon.compiler.typechecker.parser.ParseError; import com.redhat.ceylon.compiler.typechecker.tree.Message; import com.redhat.ceylon.compiler.typechecker.tree.Tree; import com.redhat.ceylon.eclipse.imp.builder.CeylonBuilder; import com.redhat.ceylon.eclipse.imp.parser.AnnotationVisitor.Span; import com.redhat.ceylon.eclipse.ui.CeylonPlugin; import com.redhat.ceylon.eclipse.util.ErrorVisitor; import com.redhat.ceylon.eclipse.vfs.IFolderVirtualFile; import com.redhat.ceylon.eclipse.vfs.SourceCodeVirtualFile; import com.redhat.ceylon.eclipse.vfs.TemporaryFile; public class CeylonParseController extends ParseControllerBase { public CeylonParseController() { super(CeylonPlugin.LANGUAGE_ID); } private final SimpleAnnotationTypeInfo simpleAnnotationTypeInfo = new SimpleAnnotationTypeInfo(); private CeylonSourcePositionLocator sourcePositionLocator; private List<CommonToken> tokens; private List<Span> annotationSpans; private TypeChecker typeChecker; /** * @param filePath Project-relative path of file * @param project Project that contains the file * @param handler A message handler to receive error messages (or any others) * from the parser */ public void initialize(IPath filePath, ISourceProject project, IMessageHandler handler) { super.initialize(filePath, project, handler); simpleAnnotationTypeInfo.addProblemMarkerType(CeylonBuilder.PROBLEM_MARKER_ID); } public CeylonSourcePositionLocator getSourcePositionLocator() { if (sourcePositionLocator == null) { sourcePositionLocator= new CeylonSourcePositionLocator(this); } return sourcePositionLocator; } public ILanguageSyntaxProperties getSyntaxProperties() { return CeylonLanguageSyntaxProperties.INSTANCE; } public IAnnotationTypeInfo getAnnotationTypeInfo() { return simpleAnnotationTypeInfo; } private Job retryJob = null; private synchronized void rescheduleJobIfNecessary() { final Job parsingJob = Job.getJobManager().currentJob(); if (parsingJob != null && parsingJob instanceof ParserScheduler) { // System.out.println("Start Rescheduling Parsing for " + getPath()); if (retryJob == null) { retryJob = new Job("Retry Parsing for " + getPath()) { @Override protected IStatus run(IProgressMonitor monitor) { if (CeylonBuilder.getProjectTypeChecker(getProject().getRawProject()) != null) { // System.out.println("parsingJob.schedule() for " + getPath()); parsingJob.schedule(); } else { // System.out.println("retryJob.schedule(1000) for " + getPath()); retryJob.schedule(1000); } return Status.OK_STATUS; } }; retryJob.setRule(null); } // System.out.println("retryJob.schedule(1000) for " + getPath()); retryJob.schedule(1000); } } public Object parse(String contents, IProgressMonitor monitor) { IPath path = getPath(); ISourceProject sourceProject = getProject(); IPath resolvedPath = path; VirtualFile file; if (path!=null) { if (sourceProject!=null) { resolvedPath = sourceProject.resolvePath(path); } file = new SourceCodeVirtualFile(contents, path); } else { file = new SourceCodeVirtualFile(contents); } if (! file.getName().endsWith(".ceylon")) { return fCurrentAst; } VirtualFile srcDir = null; if (sourceProject!=null) { srcDir = getSourceFolder(sourceProject, resolvedPath); IProject project = sourceProject.getRawProject(); typeChecker = CeylonBuilder.getProjectTypeChecker(project); if (typeChecker == null) { if (project != null) { try { IMarker[] projectMarkers = project.findMarkers(IJavaModelMarker.BUILDPATH_PROBLEM_MARKER, true, IResource.DEPTH_ZERO); if (projectMarkers.length ==0) { rescheduleJobIfNecessary(); return fCurrentAst; } } catch (CoreException e) { } } } } //System.out.println("Compiling " + file.getPath()); ANTLRInputStream input; try { input = new ANTLRInputStream(file.getInputStream()); } catch (IOException e) { throw new RuntimeException(e); } CeylonLexer lexer = new CeylonLexer(input); CommonTokenStream tokenStream = new CommonTokenStream(lexer); if (monitor.isCanceled()) return fCurrentAst; CeylonParser parser = new CeylonParser(tokenStream); Tree.CompilationUnit cu; try { cu = parser.compilationUnit(); } catch (RecognitionException e) { throw new RuntimeException(e); } tokens = new ArrayList<CommonToken>(tokenStream.getTokens().size()); tokens.addAll(tokenStream.getTokens()); List<LexError> lexerErrors = lexer.getErrors(); for (LexError le : lexerErrors) { //System.out.println("Lexer error in " + file.getName() + ": " + le.getMessage()); cu.addLexError(le); } lexerErrors.clear(); List<ParseError> parserErrors = parser.getErrors(); for (ParseError pe : parserErrors) { //System.out.println("Parser error in " + file.getName() + ": " + pe.getMessage()); cu.addParseError(pe); } parserErrors.clear(); List<Span> spans = new ArrayList<Span>(); cu.visit(new AnnotationVisitor(spans)); annotationSpans = spans; fCurrentAst = cu; if (monitor.isCanceled()) return fCurrentAst; // currentAst might (probably will) be inconsistent with the lex stream now if (srcDir==null || typeChecker == null) { TypeCheckerBuilder tcb = new TypeCheckerBuilder() .verbose(false); IProject project = null; if (sourceProject != null) { project = sourceProject.getRawProject(); } else { for (IProject p : ResourcesPlugin.getWorkspace().getRoot().getProjects()) { if (p.getLocation().isPrefixOf(path)) { project = p; break; } } } try { for (String repo : CeylonBuilder.getRepositories(project)) { tcb.addRepository(new File(repo)); } } catch (CoreException e) { throw new RuntimeException(e); } TypeChecker tc = tcb.getTypeChecker(); tc.process(); typeChecker = tc; } if (monitor.isCanceled()) return fCurrentAst; PhasedUnit builtPhasedUnit = typeChecker.getPhasedUnit(file); Package pkg = null; if (builtPhasedUnit!=null) { // Editing an already built file Package sourcePackage = builtPhasedUnit.getPackage(); pkg = new Package(); pkg.setName(sourcePackage.getName()); pkg.setModule(sourcePackage.getModule()); pkg.getUnits().addAll(sourcePackage.getUnits()); } else { // Editing a new file Modules modules = typeChecker.getContext().getModules(); if (srcDir==null) { srcDir = new TemporaryFile(); } else { // Retrieve the target package from the file src-relative path //TODO: this is very fragile! String packageName = constructPackageName(file, srcDir); for (Module module: modules.getListOfModules()) { for (Package p: module.getPackages()) { if (p.getQualifiedNameString().equals(packageName)) { pkg = p; break; } if (pkg != null) { break; } } } } if (pkg == null) { // Add the default package pkg = modules.getDefaultModule().getPackages().get(0); // TODO : iterate through parents to get the sub-package // in which the package has been created, until we find the module // Then the package can be created. // However this should preferably be done on notification of the // resource creation // A more global/systematic integration between the model element // (modules, packages, Units) and the IResourceModel should // maybe be considered. But for now it is not required. } } PhasedUnit phasedUnit; if (isExternalPath(path)) { // reuse the existing AST cu = builtPhasedUnit.getCompilationUnit(); fCurrentAst = cu; phasedUnit = builtPhasedUnit; // the type checker doesn't run all phases // on external modules, so we need to run // type analysis here the first time we // use it if (!phasedUnit.isFullyTyped()) { phasedUnit.validateRefinement(); phasedUnit.analyseTypes(); } } else { phasedUnit = new PhasedUnit(file, srcDir, cu, pkg, typeChecker.getPhasedUnits().getModuleManager(), typeChecker.getContext(), tokens); phasedUnit.validateTree(); phasedUnit.visitSrcModulePhase(); phasedUnit.visitRemainingModulePhase(); phasedUnit.scanDeclarations(); phasedUnit.scanTypeDeclarations(); phasedUnit.validateRefinement(); phasedUnit.analyseTypes(); phasedUnit.analyseFlow(); } //phasedUnit.display(); //fCurrentAst = cu; if (monitor.isCanceled()) return fCurrentAst; // currentAst might (probably will) be inconsistent with the lex stream now final IMessageHandler handler = getHandler(); if (handler!=null) { cu.visit(new ErrorVisitor(handler) { @Override public int getSeverity(Message error) { return IAnnotation.ERROR; } }); } //System.out.println("Finished compiling " + file.getPath()); return fCurrentAst; } public boolean isExternalPath(IPath path) { IWorkspaceRoot wsRoot= ResourcesPlugin.getWorkspace().getRoot(); // If the path is outside the workspace, or pointing inside the workspace, // but is still file-system-absolute. return path!=null && path.isAbsolute() && (wsRoot.getLocation().isPrefixOf(path) || !wsRoot.exists(path)); } private String constructPackageName(VirtualFile file, VirtualFile srcDir) { return file.getPath().replaceFirst(srcDir.getPath() + "/", "") .replace("/" + file.getName(), "").replace('/', '.'); } private VirtualFile getSourceFolder(ISourceProject project, IPath resolvedPath) { for (IPath folderPath: CeylonBuilder.getSourceFolders(project)) { if (folderPath.isPrefixOf(resolvedPath)) { return new IFolderVirtualFile(project.getRawProject(), folderPath.makeRelativeTo(project.getRawProject().getFullPath())); } } return null; } public Iterator<CommonToken> getTokenIterator(IRegion region) { return CeylonSourcePositionLocator.getTokenIterator(getTokens(), region); } public List<CommonToken> getTokens() { return tokens; } public TypeChecker getTypeChecker() { return typeChecker; } public boolean inAnnotationSpan(Token token) { if (annotationSpans==null) { return false; } CommonToken ct = (CommonToken) token; for (Span span: annotationSpans) { if (ct.getStartIndex()>=span.start && ct.getStopIndex()<=span.end) { return true; } if (ct.getStopIndex()<span.start) return false; } return false; } public Tree.CompilationUnit getRootNode() { return (Tree.CompilationUnit) getCurrentAst(); } }
package com.intellij.lang.properties.psi.impl; import com.intellij.extapi.psi.PsiFileBase; import com.intellij.lang.ASTFactory; import com.intellij.lang.ASTNode; import com.intellij.lang.injection.InjectedLanguageManager; import com.intellij.lang.properties.*; import com.intellij.lang.properties.parsing.PropertiesElementTypes; import com.intellij.lang.properties.parsing.PropertiesTokenTypes; import com.intellij.lang.properties.psi.*; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.project.DumbService; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.ProjectFileIndex; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.FileViewProvider; import com.intellij.psi.PsiElement; import com.intellij.psi.TokenType; import com.intellij.psi.impl.source.tree.ChangeUtil; import com.intellij.psi.impl.source.tree.TreeElement; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.stubs.StubElement; import com.intellij.psi.tree.TokenSet; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.ArrayUtil; import com.intellij.util.IncorrectOperationException; import com.intellij.util.containers.ContainerUtil; import gnu.trove.THashMap; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Collections; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream; public class PropertiesFileImpl extends PsiFileBase implements PropertiesFile { private static final Logger LOG = Logger.getInstance(PropertiesFileImpl.class); private static final TokenSet PROPERTIES_LIST_SET = TokenSet.create(PropertiesElementTypes.PROPERTIES_LIST); public PropertiesFileImpl(FileViewProvider viewProvider) { super(viewProvider, PropertiesLanguage.INSTANCE); } @Override @NotNull public FileType getFileType() { return PropertiesFileType.INSTANCE; } @Override @NonNls public String toString() { return "Properties file:" + getName(); } @Override @NotNull public List<IProperty> getProperties() { PropertiesList propertiesList; final StubElement<?> stub = getGreenStub(); if (stub != null) { PropertiesListStub propertiesListStub = stub.findChildStubByType(PropertiesElementTypes.PROPERTIES_LIST); propertiesList = propertiesListStub == null ? null : propertiesListStub.getPsi(); } else { propertiesList = PsiTreeUtil.findChildOfType(this, PropertiesList.class); } return Collections.unmodifiableList(PsiTreeUtil.getStubChildrenOfTypeAsList(propertiesList, Property.class)); } private ASTNode getPropertiesList() { return ArrayUtil.getFirstElement(getNode().getChildren(PROPERTIES_LIST_SET)); } @Nullable @Override public IProperty findPropertyByKey(@NotNull String key) { return propertiesByKey(key).findFirst().orElse(null); } @Override @NotNull public List<IProperty> findPropertiesByKey(@NotNull String key) { return propertiesByKey(key).collect(Collectors.toList()); } @Override @NotNull public ResourceBundle getResourceBundle() { return PropertiesImplUtil.getResourceBundle(this); } @Override @NotNull public Locale getLocale() { return PropertiesUtil.getLocale(this); } @Override public PsiElement add(@NotNull PsiElement element) throws IncorrectOperationException { if (element instanceof Property) { throw new IncorrectOperationException("Use addProperty() instead"); } return super.add(element); } @Override @NotNull public PsiElement addProperty(@NotNull IProperty property) throws IncorrectOperationException { final IProperty position = findInsertionPosition(property); return addPropertyAfter(property, position); } @Override @NotNull public PsiElement addPropertyAfter(@NotNull final IProperty property, @Nullable final IProperty anchor) throws IncorrectOperationException { final TreeElement copy = ChangeUtil.copyToElement(property.getPsiElement()); List<IProperty> properties = getProperties(); ASTNode anchorBefore = anchor == null ? properties.isEmpty() ? null : properties.get(0).getPsiElement().getNode() : anchor.getPsiElement().getNode().getTreeNext(); if (anchorBefore != null) { if (anchorBefore.getElementType() == TokenType.WHITE_SPACE) { anchorBefore = anchorBefore.getTreeNext(); } } if (anchorBefore == null && haveToAddNewLine()) { insertLineBreakBefore(null); } getPropertiesList().addChild(copy, anchorBefore); if (anchorBefore != null) { insertLineBreakBefore(anchorBefore); } return copy.getPsi(); } @NotNull @Override public IProperty addProperty(String key, String value) { return (IProperty)addProperty(PropertiesElementFactory.createProperty(getProject(), key, value, null)); } @NotNull @Override public IProperty addPropertyAfter(String key, String value, @Nullable IProperty anchor) { return (IProperty)addPropertyAfter(PropertiesElementFactory.createProperty(getProject(), key, value, null), anchor); } private void insertLineBreakBefore(final ASTNode anchorBefore) { ASTNode propertiesList = getPropertiesList(); if (anchorBefore == null && propertiesList.getFirstChildNode() == null) { getNode().addChild(ASTFactory.whitespace("\n"), propertiesList); } else { propertiesList.addChild(ASTFactory.whitespace("\n"), anchorBefore); } } private boolean haveToAddNewLine() { ASTNode propertiesList = getPropertiesList(); ASTNode lastChild = propertiesList.getLastChildNode(); if (lastChild != null) { return !lastChild.getText().endsWith("\n"); } ASTNode prev = propertiesList.getTreePrev(); return prev == null || !PropertiesTokenTypes.WHITESPACES.contains(prev.getElementType()); } @Override @NotNull public Map<String, String> getNamesMap() { Map<String, String> result = new THashMap<>(); for (IProperty property : getProperties()) { result.put(property.getUnescapedKey(), property.getValue()); } return result; } @Override public boolean isAlphaSorted() { return PropertiesImplUtil.isAlphaSorted(getProperties()); } private IProperty findInsertionPosition(@NotNull IProperty property) { List<IProperty> properties = getProperties(); if (properties.isEmpty()) return null; if (PropertiesImplUtil.isAlphaSorted(properties)) { final int insertIndex = Collections.binarySearch(getProperties(), property, (p1, p2) -> { final String k1 = p1.getKey(); final String k2 = p2.getKey(); LOG.assertTrue(k1 != null && k2 != null); return String.CASE_INSENSITIVE_ORDER.compare(k1, k2); }); return insertIndex == -1 ? null : getProperties().get(insertIndex < 0 ? -insertIndex - 2 : insertIndex); } return ContainerUtil.getLastItem(properties); } private Stream<? extends IProperty> propertiesByKey(@NotNull String key) { if (shouldReadIndex()) { return PropertyKeyIndex.getInstance().get(key, getProject(), GlobalSearchScope.fileScope(this)).stream(); } else { // see PropertiesElementFactory.createPropertiesFile(Project, Properties, String) return getProperties().stream().filter(p -> key.equals(p.getUnescapedKey())); } } private boolean shouldReadIndex() { Project project = getProject(); if (DumbService.isDumb(project)) return false; VirtualFile file = getVirtualFile(); return file != null && ProjectFileIndex.getInstance(project).isInContent(file) && !InjectedLanguageManager.getInstance(project).isInjectedFragment(getContainingFile()); } }
package org.xcolab.portlets.proposals.wrappers; import java.util.Date; import org.apache.commons.lang3.StringUtils; import com.ext.portlet.NoSuchContestPhaseException; import com.ext.portlet.contests.ContestStatus; import com.ext.portlet.model.ContestPhase; import com.ext.portlet.service.ContestPhaseLocalServiceUtil; import com.ext.portlet.service.ContestPhaseTypeLocalServiceUtil; import com.liferay.portal.kernel.exception.PortalException; import com.liferay.portal.kernel.exception.SystemException; public class ContestPhaseWrapper { private ContestPhase contestPhase; private ContestStatus status; public ContestPhaseWrapper(ContestPhase contestPhase) { this.contestPhase = contestPhase; } public long getContestPhasePK() { return contestPhase.getContestPhasePK(); } public void setContestPhasePK(long ContestPhasePK) { contestPhase.setContestPhasePK(ContestPhasePK); } public long getContestPK() { return contestPhase.getContestPK(); } public void setContestPK(long ContestPK) { contestPhase.setContestPK(ContestPK); } public long getContestPhaseType() { return contestPhase.getContestPhaseType(); } public void setContestPhaseType(long ContestPhaseType) { contestPhase.setContestPhaseType(ContestPhaseType); } public String getContestPhaseAutopromote() { return contestPhase.getContestPhaseAutopromote(); } public void setContestPhaseAutopromote(String contestPhaseAutopromote) { contestPhase.setContestPhaseAutopromote(contestPhaseAutopromote); } public String getContestPhaseDescriptionOverride() { return contestPhase.getContestPhaseDescriptionOverride(); } public void setContestPhaseDescriptionOverride(String ContestPhaseDescriptionOverride) { contestPhase.setContestPhaseDescriptionOverride(ContestPhaseDescriptionOverride); } public Date getPhaseStartDate() { return contestPhase.getPhaseStartDate(); } public Date getPhaseEndDate() { return contestPhase.getPhaseEndDate(); } public Date getCreated() { return contestPhase.getCreated(); } public void setCreated(Date created) { contestPhase.setCreated(created); } public long getAuthorId() { return contestPhase.getAuthorId(); } public void setAuthorId(long authorId) { contestPhase.setAuthorId(authorId); } public ContestStatus getStatus() throws PortalException, SystemException { if (status == null) { String statusStr = ContestPhaseLocalServiceUtil.getContestStatusStr(contestPhase); if (statusStr != null) { status = ContestStatus.valueOf(statusStr); } } return status; } public boolean getCanVote() throws PortalException, SystemException { if(getStatus() == null) return false; return getStatus().isCanVote(); } public boolean getCanEdit() throws PortalException, SystemException { if(getStatus() == null) return false; return getStatus().isCanEdit(); } public boolean isActive() { return ContestPhaseLocalServiceUtil.getPhaseActive(contestPhase); } public long getMilisecondsTillEnd() { return contestPhase.getPhaseEndDate() != null ? contestPhase.getPhaseEndDate().getTime() - System.currentTimeMillis() : -1; } public String getName() throws PortalException, SystemException { return ContestPhaseLocalServiceUtil.getName(contestPhase); } public boolean isEnded() { Date now = new Date(); if (contestPhase.getPhaseEndDate() != null) return contestPhase.getPhaseEndDate().before(now); return false; } public boolean isAlreadyStarted() { Date now = new Date(); return contestPhase.getPhaseStartDate().before(now); } public String getPhaseStatusDescription() throws PortalException, SystemException { String descriptionOverride = contestPhase.getContestPhaseDescriptionOverride(); if (StringUtils.isBlank(descriptionOverride)) { try { return ContestPhaseTypeLocalServiceUtil.getContestPhaseType(contestPhase.getContestPhaseType()).getDescription(); } catch (NoSuchContestPhaseException e) { // ignore } return null; } return descriptionOverride; } }
package cn.momia.service.product.facade.impl; import cn.momia.common.api.exception.MomiaFailedException; import cn.momia.common.service.DbAccessService; import cn.momia.common.util.TimeUtil; import cn.momia.service.product.facade.Product; import cn.momia.service.product.facade.ProductImage; import cn.momia.service.product.facade.ProductServiceFacade; import cn.momia.service.product.base.BaseProduct; import cn.momia.service.product.base.BaseProductService; import cn.momia.service.product.base.ProductSort; import cn.momia.service.product.place.Place; import cn.momia.service.product.place.PlaceService; import cn.momia.service.product.sku.Sku; import cn.momia.service.product.sku.SkuService; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.jdbc.core.RowCallbackHandler; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; public class ProductServiceFacadeImpl extends DbAccessService implements ProductServiceFacade { private static final Logger LOGGER = LoggerFactory.getLogger(ProductServiceFacadeImpl.class); private BaseProductService baseProductService; private PlaceService placeService; private SkuService skuService; public void setBaseProductService(BaseProductService baseProductService) { this.baseProductService = baseProductService; } public void setPlaceService(PlaceService placeService) { this.placeService = placeService; } public void setSkuService(SkuService skuService) { this.skuService = skuService; } @Override public Product get(long productId) { return get(productId, false); } @Override public Product get(long productId, boolean mini) { if (productId <= 0) return Product.NOT_EXIST_PRODUCT; BaseProduct baseProduct = baseProductService.get(productId); if (!baseProduct.exists()) return Product.NOT_EXIST_PRODUCT; Product product = new Product(); product.setBaseProduct(baseProduct); if (!mini) { product.setImgs(getProductImgs(baseProduct.getId())); List<Place> places = placeService.get(baseProduct.getPlaces()); if (places.isEmpty()) return Product.NOT_EXIST_PRODUCT; product.setPlaces(places); product.setSkus(buildFullSkus(skuService.queryByProduct(baseProduct.getId()))); } return product; } private List<Sku> buildFullSkus(List<Sku> skus) { List<Integer> placeIds = new ArrayList<Integer>(); for (Sku sku : skus) placeIds.add(sku.getPlaceId()); List<Place> places = placeService.get(placeIds); Map<Integer, Place> placesMap = new HashMap<Integer, Place>(); for (Place place : places) placesMap.put(place.getId(), place); for (Sku sku : skus) sku.setPlace(placesMap.get(sku.getPlaceId())); return skus; } private List<ProductImage> getProductImgs(long productId) { final List<ProductImage> imgs = new ArrayList<ProductImage>(); String sql = "SELECT url, width, height FROM t_product_img WHERE productId=? AND status=1"; jdbcTemplate.query(sql, new Object[] { productId }, new RowCallbackHandler() { @Override public void processRow(ResultSet rs) throws SQLException { imgs.add(buildImage(rs)); } }); return imgs; } private ProductImage buildImage(ResultSet rs) throws SQLException { ProductImage img = new ProductImage(); img.setUrl(rs.getString("url")); img.setWidth(rs.getInt("width")); img.setHeight(rs.getInt("height")); return img; } @Override public List<Product> list(Collection<Long> productIds) { if (productIds == null || productIds.isEmpty()) return new ArrayList<Product>(); List<BaseProduct> baseProducts = baseProductService.get(productIds); return buildProducts(baseProducts); } private List<Product> buildProducts(List<BaseProduct> baseProducts) { List<Product> products = new ArrayList<Product>(); if (baseProducts.isEmpty()) return products; List<Long> productIds = new ArrayList<Long>(); List<Integer> placeIds = new ArrayList<Integer>(); for (BaseProduct baseProduct : baseProducts) { if (!baseProduct.exists()) continue; productIds.add(baseProduct.getId()); placeIds.addAll(baseProduct.getPlaces()); } Map<Long, List<ProductImage>> imgsOfProducts = getProductsImgs(productIds); Map<Integer, Place> placesOfProducts = new HashMap<Integer, Place>(); for (Place place : placeService.get(placeIds)) placesOfProducts.put(place.getId(), place); List<Sku> skus = buildFullSkus(skuService.queryByProducts(productIds)); Map<Long, List<Sku>> skusOfProducts = new HashMap<Long, List<Sku>>(); for (Sku sku : skus) { List<Sku> skusOfProduct = skusOfProducts.get(sku.getProductId()); if (skusOfProduct == null) { skusOfProduct = new ArrayList<Sku>(); skusOfProducts.put(sku.getProductId(), skusOfProduct); } skusOfProduct.add(sku); } for (BaseProduct baseProduct : baseProducts) { if (!baseProduct.exists()) continue; Product product = new Product(); product.setBaseProduct(baseProduct); product.setImgs(imgsOfProducts.get(baseProduct.getId())); List<Place> places = new ArrayList<Place>(); for (int placeId : baseProduct.getPlaces()) { Place place = placesOfProducts.get(placeId); if (place != null) places.add(place); } product.setPlaces(places); product.setSkus(skusOfProducts.get(baseProduct.getId())); if (!product.isInvalid()) products.add(product); } return products; } private Map<Long, List<ProductImage>> getProductsImgs(List<Long> productIds) { final Map<Long, List<ProductImage>> imgsOfProducts = new HashMap<Long, List<ProductImage>>(); if (productIds.isEmpty()) return imgsOfProducts; try { String sql = "SELECT productId, url, width, height FROM t_product_img WHERE productId IN (" + StringUtils.join(productIds, ",") + ") AND status=1"; jdbcTemplate.query(sql, new RowCallbackHandler() { @Override public void processRow(ResultSet rs) throws SQLException { long productId = rs.getLong("productId"); ProductImage img = buildImage(rs); List<ProductImage> imgs = imgsOfProducts.get(productId); if (imgs == null) { imgs = new ArrayList<ProductImage>(); imgsOfProducts.put(productId, imgs); } imgs.add(img); } }); } catch (Exception e) { LOGGER.error("fail to get imgs of products: {}", productIds, e); } return imgsOfProducts; } @Override public Map<Long, List<Product>> listGrouped(Map<Long, List<Long>> groupedProductIds) { Set<Long> productIds = new HashSet<Long>(); for (List<Long> ids : groupedProductIds.values()) productIds.addAll(ids); List<Product> products = list(productIds); Map<Long, Product> productsMap = new HashMap<Long, Product>(); for (Product product : products) productsMap.put(product.getId(), product); Map<Long, List<Product>> groupedProducts = new HashMap<Long, List<Product>>(); for (Map.Entry<Long, List<Long>> entry : groupedProductIds.entrySet()) { long groupId = entry.getKey(); List<Product> productsOfGroup = groupedProducts.get(groupId); if (productsOfGroup == null) { productsOfGroup = new ArrayList<Product>(); groupedProducts.put(groupId, productsOfGroup); } for (long productId : entry.getValue()) { Product product = productsMap.get(productId); if (product != null) productsOfGroup.add(product); } } return groupedProducts; } @Override public String getDetail(long productId) { if (productId <= 0) return ""; return baseProductService.getDetail(productId); } @Override public long queryCount(int cityId) { if (cityId < 0) return 0; return baseProductService.queryCount(cityId); } @Override public List<Product> query(int cityId, int start, int count, ProductSort productSort) { return buildProducts(baseProductService.query(cityId, start, count, productSort)); } @Override public long queryCountByWeekend(int cityId) { if (cityId < 0) return 0; return baseProductService.queryCountByWeekend(cityId); } @Override public List<Product> queryByWeekend(int cityId, int start, int count) { return buildProducts(baseProductService.queryByWeekend(cityId, start, count)); } @Override public List<Product> queryByMonth(int cityId, int month) { if (cityId < 0 || month <= 0 || month > 12) return new ArrayList<Product>(); return buildProducts(baseProductService.queryByMonth(cityId, TimeUtil.formatYearMonth(month), TimeUtil.formatNextYearMonth(month))); } @Override public long queryCountNeedLeader(int cityId) { if (cityId < 0) return 0; return baseProductService.queryCountNeedLeader(cityId); } @Override public List<Product> queryNeedLeader(int cityId, int start, int count) { return buildProducts(baseProductService.queryNeedLeader(cityId, start, count)); } @Override public boolean sold(long productId, int count) { if (productId <= 0 || count <= 0) return true; return baseProductService.sold(productId, count); } @Override public List<Sku> listSkus(long productId) { if (productId <= 0) return new ArrayList<Sku>(); return buildFullSkus(skuService.queryByProduct(productId)); } @Override public Sku getSku(long skuId) { if (skuId <= 0) return Sku.NOT_EXIST_SKU; return buildFullSku(skuService.get(skuId)); } private Sku buildFullSku(Sku sku) { int placeId = sku.getPlaceId(); if (placeId > 0) { Place place = placeService.get(placeId); if (place.exists()) sku.setPlace(place); } return sku; } @Override public boolean lockStock(long productId, long skuId, int count, int joined) { if (productId <= 0 || skuId <= 0 || count <= 0) return false; boolean successful = skuService.lock(skuId, count); try { if (successful) { if (isSoldOut(productId)) baseProductService.soldOut(productId); baseProductService.join(productId, joined); } } catch (Exception e) { LOGGER.error("fail to update sold out/joined status of product: {}", productId, e); } return successful; } private boolean isSoldOut(long id) { if (id <= 0) return true; int unlockedStock = 0; List<Sku> skus = Sku.filterClosed(listSkus(id)); for (Sku sku : skus) { if (sku.getType() == Sku.Type.NO_CEILING) return false; unlockedStock += sku.getUnlockedStock(); } return unlockedStock <= 0; } @Override public boolean unlockStock(long productId, long skuId, int count, int joined) { if (productId <= 0 || skuId <= 0 || count <= 0) return true; try { baseProductService.unSoldOut(productId); } catch (Exception e) { LOGGER.error("fail to set sold out status of product: {}", productId, e); } boolean successful = skuService.unlock(skuId, count); if (successful) { try { baseProductService.decreaseJoined(productId, joined); } catch (Exception e) { LOGGER.error("fail to decrease joined of product: {}", productId, e); } } return successful; } @Override public boolean addSkuLeader(long userId, long productId, long skuId) { if (userId <= 0 || productId <= 0 || skuId <= 0) return false; Sku sku = skuService.get(skuId); if (!sku.exists() || sku.isClosed(new Date()) || !sku.isNeedLeader()) throw new MomiaFailedException(""); return skuService.addLeader(userId, productId, skuId); } @Override public long queryCountOfLedSkus(long userId) { if (userId <= 0) return 0; return skuService.queryCountOfLedSkus(userId); } @Override public List<Sku> queryLedSkus(long userId, int start, int count) { if (userId <= 0 || start < 0 || count <= 0) return new ArrayList<Sku>(); return buildFullSkus(skuService.queryLedSkus(userId, start, count)); } }
package com.opengamma.financial.convention; import java.util.Map; import org.joda.beans.Bean; import org.joda.beans.BeanBuilder; import org.joda.beans.BeanDefinition; import org.joda.beans.JodaBeanUtils; import org.joda.beans.MetaProperty; import org.joda.beans.Property; import org.joda.beans.PropertyDefinition; import org.joda.beans.impl.direct.DirectBeanBuilder; import org.joda.beans.impl.direct.DirectMetaProperty; import org.joda.beans.impl.direct.DirectMetaPropertyMap; import org.threeten.bp.Period; import com.opengamma.analytics.financial.credit.isdastandardmodel.StubType; import com.opengamma.core.convention.ConventionType; import com.opengamma.financial.convention.businessday.BusinessDayConvention; import com.opengamma.financial.convention.calendar.Calendar; import com.opengamma.financial.convention.daycount.DayCount; import com.opengamma.master.convention.ManageableConvention; /** * Fields defined here apply to CDSs created via the {@link com.opengamma.analytics.financial.credit.isdastandardmodel.CDSAnalyticFactory}. These apply to CDSs * created for curve calibration. * * For a more detailed explanation of each of the fields listed here, see {@link com.opengamma.analytics.financial.credit.isdastandardmodel.CDSAnalyticFactory}. */ @BeanDefinition public class IsdaCreditCurveConvention extends ManageableConvention { private static final long serialVersionUID = 1L; /** * The convention type. */ public static final ConventionType TYPE = ConventionType.of("ISDACreditCurve"); /** * The step-in date, relative to T. */ @PropertyDefinition private int _stepIn; /** * Cash settle date for which PV is calculated. */ @PropertyDefinition private int _cashSettle; /** * Whether accrued premium is paid on default. */ @PropertyDefinition(validate = "notNull") private boolean _payAccOnDefault; /** * The coupon interval. */ @PropertyDefinition(validate = "notNull") private Period _couponInterval; /** * The stub type. See {@link StubType} for available values. */ @PropertyDefinition(validate = "notNull") private StubType _stubType; /** * Protection starts at beginning of day if true, otherwise at the end. */ @PropertyDefinition private boolean _protectFromStartOfDay; /** * Business day convention used for date rolling. */ @PropertyDefinition(validate = "notNull") private BusinessDayConvention _businessDayConvention; /** * The calendar to use. */ @PropertyDefinition(validate = "notNull") private Calendar _regionCalendar; /** * Day count for accrual calculations. */ @PropertyDefinition(validate = "notNull") private DayCount _accrualDayCount; /** * Day count used for curve. (Note, values other than ACT/365 are not recommended. This is used by ISDA). */ @PropertyDefinition(validate = "notNull") private DayCount _curveDayCount; @Override public ConventionType getConventionType() { return TYPE; } ///CLOVER:OFF /** * The meta-bean for {@code IsdaCreditCurveConvention}. * @return the meta-bean, not null */ public static IsdaCreditCurveConvention.Meta meta() { return IsdaCreditCurveConvention.Meta.INSTANCE; } static { JodaBeanUtils.registerMetaBean(IsdaCreditCurveConvention.Meta.INSTANCE); } @Override public IsdaCreditCurveConvention.Meta metaBean() { return IsdaCreditCurveConvention.Meta.INSTANCE; } /** * Gets the step-in date, relative to T. * @return the value of the property */ public int getStepIn() { return _stepIn; } /** * Sets the step-in date, relative to T. * @param stepIn the new value of the property */ public void setStepIn(int stepIn) { this._stepIn = stepIn; } /** * Gets the the {@code stepIn} property. * @return the property, not null */ public final Property<Integer> stepIn() { return metaBean().stepIn().createProperty(this); } /** * Gets cash settle date for which PV is calculated. * @return the value of the property */ public int getCashSettle() { return _cashSettle; } /** * Sets cash settle date for which PV is calculated. * @param cashSettle the new value of the property */ public void setCashSettle(int cashSettle) { this._cashSettle = cashSettle; } /** * Gets the the {@code cashSettle} property. * @return the property, not null */ public final Property<Integer> cashSettle() { return metaBean().cashSettle().createProperty(this); } /** * Gets whether accrued premium is paid on default. * @return the value of the property, not null */ public boolean isPayAccOnDefault() { return _payAccOnDefault; } /** * Sets whether accrued premium is paid on default. * @param payAccOnDefault the new value of the property, not null */ public void setPayAccOnDefault(boolean payAccOnDefault) { JodaBeanUtils.notNull(payAccOnDefault, "payAccOnDefault"); this._payAccOnDefault = payAccOnDefault; } /** * Gets the the {@code payAccOnDefault} property. * @return the property, not null */ public final Property<Boolean> payAccOnDefault() { return metaBean().payAccOnDefault().createProperty(this); } /** * Gets the coupon interval. * @return the value of the property, not null */ public Period getCouponInterval() { return _couponInterval; } /** * Sets the coupon interval. * @param couponInterval the new value of the property, not null */ public void setCouponInterval(Period couponInterval) { JodaBeanUtils.notNull(couponInterval, "couponInterval"); this._couponInterval = couponInterval; } /** * Gets the the {@code couponInterval} property. * @return the property, not null */ public final Property<Period> couponInterval() { return metaBean().couponInterval().createProperty(this); } /** * Gets the stub type. See {@link StubType} for available values. * @return the value of the property, not null */ public StubType getStubType() { return _stubType; } /** * Sets the stub type. See {@link StubType} for available values. * @param stubType the new value of the property, not null */ public void setStubType(StubType stubType) { JodaBeanUtils.notNull(stubType, "stubType"); this._stubType = stubType; } /** * Gets the the {@code stubType} property. * @return the property, not null */ public final Property<StubType> stubType() { return metaBean().stubType().createProperty(this); } /** * Gets protection starts at beginning of day if true, otherwise at the end. * @return the value of the property */ public boolean isProtectFromStartOfDay() { return _protectFromStartOfDay; } /** * Sets protection starts at beginning of day if true, otherwise at the end. * @param protectFromStartOfDay the new value of the property */ public void setProtectFromStartOfDay(boolean protectFromStartOfDay) { this._protectFromStartOfDay = protectFromStartOfDay; } /** * Gets the the {@code protectFromStartOfDay} property. * @return the property, not null */ public final Property<Boolean> protectFromStartOfDay() { return metaBean().protectFromStartOfDay().createProperty(this); } /** * Gets business day convention used for date rolling. * @return the value of the property, not null */ public BusinessDayConvention getBusinessDayConvention() { return _businessDayConvention; } /** * Sets business day convention used for date rolling. * @param businessDayConvention the new value of the property, not null */ public void setBusinessDayConvention(BusinessDayConvention businessDayConvention) { JodaBeanUtils.notNull(businessDayConvention, "businessDayConvention"); this._businessDayConvention = businessDayConvention; } /** * Gets the the {@code businessDayConvention} property. * @return the property, not null */ public final Property<BusinessDayConvention> businessDayConvention() { return metaBean().businessDayConvention().createProperty(this); } /** * Gets the calendar to use. * @return the value of the property, not null */ public Calendar getRegionCalendar() { return _regionCalendar; } /** * Sets the calendar to use. * @param regionCalendar the new value of the property, not null */ public void setRegionCalendar(Calendar regionCalendar) { JodaBeanUtils.notNull(regionCalendar, "regionCalendar"); this._regionCalendar = regionCalendar; } /** * Gets the the {@code regionCalendar} property. * @return the property, not null */ public final Property<Calendar> regionCalendar() { return metaBean().regionCalendar().createProperty(this); } /** * Gets day count for accrual calculations. * @return the value of the property, not null */ public DayCount getAccrualDayCount() { return _accrualDayCount; } /** * Sets day count for accrual calculations. * @param accrualDayCount the new value of the property, not null */ public void setAccrualDayCount(DayCount accrualDayCount) { JodaBeanUtils.notNull(accrualDayCount, "accrualDayCount"); this._accrualDayCount = accrualDayCount; } /** * Gets the the {@code accrualDayCount} property. * @return the property, not null */ public final Property<DayCount> accrualDayCount() { return metaBean().accrualDayCount().createProperty(this); } /** * Gets day count used for curve. (Note, values other than ACT/365 are not recommended. This is used by ISDA). * @return the value of the property, not null */ public DayCount getCurveDayCount() { return _curveDayCount; } /** * Sets day count used for curve. (Note, values other than ACT/365 are not recommended. This is used by ISDA). * @param curveDayCount the new value of the property, not null */ public void setCurveDayCount(DayCount curveDayCount) { JodaBeanUtils.notNull(curveDayCount, "curveDayCount"); this._curveDayCount = curveDayCount; } /** * Gets the the {@code curveDayCount} property. * @return the property, not null */ public final Property<DayCount> curveDayCount() { return metaBean().curveDayCount().createProperty(this); } @Override public IsdaCreditCurveConvention clone() { return JodaBeanUtils.cloneAlways(this); } @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (obj != null && obj.getClass() == this.getClass()) { IsdaCreditCurveConvention other = (IsdaCreditCurveConvention) obj; return (getStepIn() == other.getStepIn()) && (getCashSettle() == other.getCashSettle()) && (isPayAccOnDefault() == other.isPayAccOnDefault()) && JodaBeanUtils.equal(getCouponInterval(), other.getCouponInterval()) && JodaBeanUtils.equal(getStubType(), other.getStubType()) && (isProtectFromStartOfDay() == other.isProtectFromStartOfDay()) && JodaBeanUtils.equal(getBusinessDayConvention(), other.getBusinessDayConvention()) && JodaBeanUtils.equal(getRegionCalendar(), other.getRegionCalendar()) && JodaBeanUtils.equal(getAccrualDayCount(), other.getAccrualDayCount()) && JodaBeanUtils.equal(getCurveDayCount(), other.getCurveDayCount()) && super.equals(obj); } return false; } @Override public int hashCode() { int hash = 7; hash = hash * 31 + JodaBeanUtils.hashCode(getStepIn()); hash = hash * 31 + JodaBeanUtils.hashCode(getCashSettle()); hash = hash * 31 + JodaBeanUtils.hashCode(isPayAccOnDefault()); hash = hash * 31 + JodaBeanUtils.hashCode(getCouponInterval()); hash = hash * 31 + JodaBeanUtils.hashCode(getStubType()); hash = hash * 31 + JodaBeanUtils.hashCode(isProtectFromStartOfDay()); hash = hash * 31 + JodaBeanUtils.hashCode(getBusinessDayConvention()); hash = hash * 31 + JodaBeanUtils.hashCode(getRegionCalendar()); hash = hash * 31 + JodaBeanUtils.hashCode(getAccrualDayCount()); hash = hash * 31 + JodaBeanUtils.hashCode(getCurveDayCount()); return hash ^ super.hashCode(); } @Override public String toString() { StringBuilder buf = new StringBuilder(352); buf.append("IsdaCreditCurveConvention{"); int len = buf.length(); toString(buf); if (buf.length() > len) { buf.setLength(buf.length() - 2); } buf.append('}'); return buf.toString(); } @Override protected void toString(StringBuilder buf) { super.toString(buf); buf.append("stepIn").append('=').append(JodaBeanUtils.toString(getStepIn())).append(',').append(' '); buf.append("cashSettle").append('=').append(JodaBeanUtils.toString(getCashSettle())).append(',').append(' '); buf.append("payAccOnDefault").append('=').append(JodaBeanUtils.toString(isPayAccOnDefault())).append(',').append(' '); buf.append("couponInterval").append('=').append(JodaBeanUtils.toString(getCouponInterval())).append(',').append(' '); buf.append("stubType").append('=').append(JodaBeanUtils.toString(getStubType())).append(',').append(' '); buf.append("protectFromStartOfDay").append('=').append(JodaBeanUtils.toString(isProtectFromStartOfDay())).append(',').append(' '); buf.append("businessDayConvention").append('=').append(JodaBeanUtils.toString(getBusinessDayConvention())).append(',').append(' '); buf.append("regionCalendar").append('=').append(JodaBeanUtils.toString(getRegionCalendar())).append(',').append(' '); buf.append("accrualDayCount").append('=').append(JodaBeanUtils.toString(getAccrualDayCount())).append(',').append(' '); buf.append("curveDayCount").append('=').append(JodaBeanUtils.toString(getCurveDayCount())).append(',').append(' '); } /** * The meta-bean for {@code IsdaCreditCurveConvention}. */ public static class Meta extends ManageableConvention.Meta { /** * The singleton instance of the meta-bean. */ static final Meta INSTANCE = new Meta(); /** * The meta-property for the {@code stepIn} property. */ private final MetaProperty<Integer> _stepIn = DirectMetaProperty.ofReadWrite( this, "stepIn", IsdaCreditCurveConvention.class, Integer.TYPE); /** * The meta-property for the {@code cashSettle} property. */ private final MetaProperty<Integer> _cashSettle = DirectMetaProperty.ofReadWrite( this, "cashSettle", IsdaCreditCurveConvention.class, Integer.TYPE); /** * The meta-property for the {@code payAccOnDefault} property. */ private final MetaProperty<Boolean> _payAccOnDefault = DirectMetaProperty.ofReadWrite( this, "payAccOnDefault", IsdaCreditCurveConvention.class, Boolean.TYPE); /** * The meta-property for the {@code couponInterval} property. */ private final MetaProperty<Period> _couponInterval = DirectMetaProperty.ofReadWrite( this, "couponInterval", IsdaCreditCurveConvention.class, Period.class); /** * The meta-property for the {@code stubType} property. */ private final MetaProperty<StubType> _stubType = DirectMetaProperty.ofReadWrite( this, "stubType", IsdaCreditCurveConvention.class, StubType.class); /** * The meta-property for the {@code protectFromStartOfDay} property. */ private final MetaProperty<Boolean> _protectFromStartOfDay = DirectMetaProperty.ofReadWrite( this, "protectFromStartOfDay", IsdaCreditCurveConvention.class, Boolean.TYPE); /** * The meta-property for the {@code businessDayConvention} property. */ private final MetaProperty<BusinessDayConvention> _businessDayConvention = DirectMetaProperty.ofReadWrite( this, "businessDayConvention", IsdaCreditCurveConvention.class, BusinessDayConvention.class); /** * The meta-property for the {@code regionCalendar} property. */ private final MetaProperty<Calendar> _regionCalendar = DirectMetaProperty.ofReadWrite( this, "regionCalendar", IsdaCreditCurveConvention.class, Calendar.class); /** * The meta-property for the {@code accrualDayCount} property. */ private final MetaProperty<DayCount> _accrualDayCount = DirectMetaProperty.ofReadWrite( this, "accrualDayCount", IsdaCreditCurveConvention.class, DayCount.class); /** * The meta-property for the {@code curveDayCount} property. */ private final MetaProperty<DayCount> _curveDayCount = DirectMetaProperty.ofReadWrite( this, "curveDayCount", IsdaCreditCurveConvention.class, DayCount.class); /** * The meta-properties. */ private final Map<String, MetaProperty<?>> _metaPropertyMap$ = new DirectMetaPropertyMap( this, (DirectMetaPropertyMap) super.metaPropertyMap(), "stepIn", "cashSettle", "payAccOnDefault", "couponInterval", "stubType", "protectFromStartOfDay", "businessDayConvention", "regionCalendar", "accrualDayCount", "curveDayCount"); /** * Restricted constructor. */ protected Meta() { } @Override protected MetaProperty<?> metaPropertyGet(String propertyName) { switch (propertyName.hashCode()) { case -892367599: // stepIn return _stepIn; case 1634469470: // cashSettle return _cashSettle; case -988493655: // payAccOnDefault return _payAccOnDefault; case 854432523: // couponInterval return _couponInterval; case 1873675528: // stubType return _stubType; case 2052802300: // protectFromStartOfDay return _protectFromStartOfDay; case -1002835891: // businessDayConvention return _businessDayConvention; case 1932874322: // regionCalendar return _regionCalendar; case -1387075166: // accrualDayCount return _accrualDayCount; case -1661418270: // curveDayCount return _curveDayCount; } return super.metaPropertyGet(propertyName); } @Override public BeanBuilder<? extends IsdaCreditCurveConvention> builder() { return new DirectBeanBuilder<IsdaCreditCurveConvention>(new IsdaCreditCurveConvention()); } @Override public Class<? extends IsdaCreditCurveConvention> beanType() { return IsdaCreditCurveConvention.class; } @Override public Map<String, MetaProperty<?>> metaPropertyMap() { return _metaPropertyMap$; } /** * The meta-property for the {@code stepIn} property. * @return the meta-property, not null */ public final MetaProperty<Integer> stepIn() { return _stepIn; } /** * The meta-property for the {@code cashSettle} property. * @return the meta-property, not null */ public final MetaProperty<Integer> cashSettle() { return _cashSettle; } /** * The meta-property for the {@code payAccOnDefault} property. * @return the meta-property, not null */ public final MetaProperty<Boolean> payAccOnDefault() { return _payAccOnDefault; } /** * The meta-property for the {@code couponInterval} property. * @return the meta-property, not null */ public final MetaProperty<Period> couponInterval() { return _couponInterval; } /** * The meta-property for the {@code stubType} property. * @return the meta-property, not null */ public final MetaProperty<StubType> stubType() { return _stubType; } /** * The meta-property for the {@code protectFromStartOfDay} property. * @return the meta-property, not null */ public final MetaProperty<Boolean> protectFromStartOfDay() { return _protectFromStartOfDay; } /** * The meta-property for the {@code businessDayConvention} property. * @return the meta-property, not null */ public final MetaProperty<BusinessDayConvention> businessDayConvention() { return _businessDayConvention; } /** * The meta-property for the {@code regionCalendar} property. * @return the meta-property, not null */ public final MetaProperty<Calendar> regionCalendar() { return _regionCalendar; } /** * The meta-property for the {@code accrualDayCount} property. * @return the meta-property, not null */ public final MetaProperty<DayCount> accrualDayCount() { return _accrualDayCount; } /** * The meta-property for the {@code curveDayCount} property. * @return the meta-property, not null */ public final MetaProperty<DayCount> curveDayCount() { return _curveDayCount; } @Override protected Object propertyGet(Bean bean, String propertyName, boolean quiet) { switch (propertyName.hashCode()) { case -892367599: // stepIn return ((IsdaCreditCurveConvention) bean).getStepIn(); case 1634469470: // cashSettle return ((IsdaCreditCurveConvention) bean).getCashSettle(); case -988493655: // payAccOnDefault return ((IsdaCreditCurveConvention) bean).isPayAccOnDefault(); case 854432523: // couponInterval return ((IsdaCreditCurveConvention) bean).getCouponInterval(); case 1873675528: // stubType return ((IsdaCreditCurveConvention) bean).getStubType(); case 2052802300: // protectFromStartOfDay return ((IsdaCreditCurveConvention) bean).isProtectFromStartOfDay(); case -1002835891: // businessDayConvention return ((IsdaCreditCurveConvention) bean).getBusinessDayConvention(); case 1932874322: // regionCalendar return ((IsdaCreditCurveConvention) bean).getRegionCalendar(); case -1387075166: // accrualDayCount return ((IsdaCreditCurveConvention) bean).getAccrualDayCount(); case -1661418270: // curveDayCount return ((IsdaCreditCurveConvention) bean).getCurveDayCount(); } return super.propertyGet(bean, propertyName, quiet); } @Override protected void propertySet(Bean bean, String propertyName, Object newValue, boolean quiet) { switch (propertyName.hashCode()) { case -892367599: // stepIn ((IsdaCreditCurveConvention) bean).setStepIn((Integer) newValue); return; case 1634469470: // cashSettle ((IsdaCreditCurveConvention) bean).setCashSettle((Integer) newValue); return; case -988493655: // payAccOnDefault ((IsdaCreditCurveConvention) bean).setPayAccOnDefault((Boolean) newValue); return; case 854432523: // couponInterval ((IsdaCreditCurveConvention) bean).setCouponInterval((Period) newValue); return; case 1873675528: // stubType ((IsdaCreditCurveConvention) bean).setStubType((StubType) newValue); return; case 2052802300: // protectFromStartOfDay ((IsdaCreditCurveConvention) bean).setProtectFromStartOfDay((Boolean) newValue); return; case -1002835891: // businessDayConvention ((IsdaCreditCurveConvention) bean).setBusinessDayConvention((BusinessDayConvention) newValue); return; case 1932874322: // regionCalendar ((IsdaCreditCurveConvention) bean).setRegionCalendar((Calendar) newValue); return; case -1387075166: // accrualDayCount ((IsdaCreditCurveConvention) bean).setAccrualDayCount((DayCount) newValue); return; case -1661418270: // curveDayCount ((IsdaCreditCurveConvention) bean).setCurveDayCount((DayCount) newValue); return; } super.propertySet(bean, propertyName, newValue, quiet); } @Override protected void validate(Bean bean) { JodaBeanUtils.notNull(((IsdaCreditCurveConvention) bean)._payAccOnDefault, "payAccOnDefault"); JodaBeanUtils.notNull(((IsdaCreditCurveConvention) bean)._couponInterval, "couponInterval"); JodaBeanUtils.notNull(((IsdaCreditCurveConvention) bean)._stubType, "stubType"); JodaBeanUtils.notNull(((IsdaCreditCurveConvention) bean)._businessDayConvention, "businessDayConvention"); JodaBeanUtils.notNull(((IsdaCreditCurveConvention) bean)._regionCalendar, "regionCalendar"); JodaBeanUtils.notNull(((IsdaCreditCurveConvention) bean)._accrualDayCount, "accrualDayCount"); JodaBeanUtils.notNull(((IsdaCreditCurveConvention) bean)._curveDayCount, "curveDayCount"); super.validate(bean); } } ///CLOVER:ON }
package szoftlab4; import java.awt.*; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.geom.Rectangle2D; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.imageio.ImageIO; import javax.swing.BorderFactory; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; @SuppressWarnings("serial") public class View { JPanel panel; JPanel mapPanel; JPanel mainPanel; JPanel menuPanel; JPanel magicPanel; List<Drawable> drawables; public View(Game game, Map map){ Controller c = new Controller(game); JButton buildTower = new JButton(); JButton buildObstacle = new JButton(); GemButton redGem = new GemButton(TowerGem.red); GemButton greenGem = new GemButton(TowerGem.green); GemButton blueGem = new GemButton(TowerGem.blue); GemButton yellowGem = new GemButton(ObstacleGem.yellow); GemButton orangeGem = new GemButton(ObstacleGem.orange); JLabel magic = new JLabel("Magic: "); drawables = new ArrayList<Drawable>(); drawables.add(new GraphicMap(map)); menuPanel = new JPanel(); mainPanel = new JPanel(); magicPanel = new JPanel(); /* wow such anonymous class */ mapPanel = new JPanel(){ List<Drawable> d; public JPanel init(List<Drawable> dr){ d = dr; return this; } public void paintComponent(Graphics g) { /* very thread-safe */ synchronized(d){ for (Drawable dr : d) dr.draw(g); } } }.init(drawables); mapPanel.setPreferredSize(new Dimension(800, 600)); panel = new JPanel(); panel.setLayout(new BorderLayout()); panel.add(mainPanel, BorderLayout.PAGE_START); panel.add(mapPanel, BorderLayout.CENTER); mainPanel.setLayout(new BorderLayout()); mainPanel.add(menuPanel); mainPanel.add(magicPanel, BorderLayout.EAST); menuPanel.setLayout(new FlowLayout(FlowLayout.LEFT)); menuPanel.setPreferredSize(new Dimension(0, 55)); menuPanel.add(buildTower); menuPanel.add(redGem); menuPanel.add(greenGem); menuPanel.add(blueGem); menuPanel.add(buildObstacle); menuPanel.add(yellowGem); menuPanel.add(orangeGem); magicPanel.setLayout(new FlowLayout(FlowLayout.RIGHT)); Font magicFont = new Font("Serif",Font.ITALIC,26); magic.setFont(magicFont); magic.setForeground(Color.BLUE); magicPanel.add(magic); redGem.setToolTipText("<html><center>Piros varázskő<br/>\nTöbbet sebez<br/>\n" + TowerGem.red.getCost() + " VE</center></html>"); greenGem.setToolTipText("<html><center>Zöld varázskő<br/>\n&lt; a varázskő hatása &gt;<br/>\n" + TowerGem.green.getCost() + " VE</center></html>"); blueGem.setToolTipText("<html><center>Kék varázskő<br/>\n&lt; a varázskő hatása &gt;<br/>\n" + TowerGem.blue.getCost() + " VE</center></html>"); yellowGem.setToolTipText("<html><center>Sárga varázskő<br/>\n&lt; a varázskő hatása &gt;<br/>\n" + ObstacleGem.yellow.getCost() + " VE</center></html>"); orangeGem.setToolTipText("<html><center>Narancssárga varázskő<br/>\n&lt; a varázskő hatása &gt;<br/>\n" + ObstacleGem.orange.getCost() + " VE</center></html>"); buildTower.setToolTipText("<html><center>Torony építése<br/>\n" + Tower.cost + " VE</center></html>"); buildObstacle.setToolTipText("<html><center>Akadály építése<br/>\n" + Obstacle.cost + " VE</center></html>"); buildTower.addMouseListener(c.new BuildTowerMouseEvent()); redGem.addMouseListener(c.new EnchantMouseEvent()); greenGem.addMouseListener(c.new EnchantMouseEvent()); blueGem.addMouseListener(c.new EnchantMouseEvent()); buildObstacle.addMouseListener(c.new BuildObstacleMouseEvent()); yellowGem.addMouseListener(c.new EnchantMouseEvent()); orangeGem.addMouseListener(c.new EnchantMouseEvent()); mapPanel.addMouseListener(c.new MapMouseEvent()); buildTower.setBackground(menuPanel.getBackground()); setButtonLook(buildTower, new ImageIcon("icons/tower.png")); buildObstacle.setBackground(menuPanel.getBackground()); setButtonLook(buildObstacle, new ImageIcon("icons/obstacle.png")); redGem.setBackground(menuPanel.getBackground()); setButtonLook(redGem, new ImageIcon("icons/red_gem.png")); greenGem.setBackground(menuPanel.getBackground()); setButtonLook(greenGem, new ImageIcon("icons/green_gem.png")); blueGem.setBackground(menuPanel.getBackground()); setButtonLook(blueGem, new ImageIcon("icons/blue_gem.png")); yellowGem.setBackground(menuPanel.getBackground()); setButtonLook(yellowGem, new ImageIcon("icons/yellow_gem.png")); orangeGem.setBackground(menuPanel.getBackground()); setButtonLook(orangeGem, new ImageIcon("icons/orange_gem.png")); } private void setButtonLook(JButton b, ImageIcon img){ b.setFocusPainted(false); b.setMargin(new Insets(1,1,1,1)); b.setContentAreaFilled(false); b.setIcon(img); b.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2)); } public void addDrawable(Drawable d){ synchronized(drawables){ drawables.add(d); } } public JPanel getPanel(){ return panel; } public void enemyAdded(Enemy en) { synchronized(drawables){ drawables.add(new GraphicEnemy(en)); Collections.sort(drawables, Collections.reverseOrder()); } } public void projectileExploded(Projectile p) { synchronized(drawables){ drawables.remove(new GraphicProjectile(p)); } } public void projectileAdded(Projectile p) { synchronized(drawables){ drawables.add(new GraphicProjectile(p)); Collections.sort(drawables, Collections.reverseOrder()); } } public void enemyDied(Enemy en) { synchronized(drawables){ drawables.remove(new GraphicEnemy(en)); } } public void towerAdded(Tower t) { synchronized(drawables){ drawables.add(new GraphicTower(t)); Collections.sort(drawables, Collections.reverseOrder()); } } public void obstacleAdded(Obstacle o) { synchronized(drawables){ drawables.add(new GraphicObstacle(o)); Collections.sort(drawables, Collections.reverseOrder()); } } public void towerEnchanted(Tower t){ synchronized(drawables){ GraphicTower gt = (GraphicTower)drawables.get(drawables.indexOf(new GraphicTower(t))); gt.setGem(); } } public void obstacleEnchanted(Obstacle o){ synchronized(drawables){ GraphicObstacle go = (GraphicObstacle)drawables.get(drawables.indexOf(new GraphicObstacle(o))); go.setGem(); } } public void drawAll() { mapPanel.repaint(); } public void magicChange(int magic){ JLabel magicLabel = (JLabel)magicPanel.getComponent(0); magicLabel.setText("Magic: " + magic); } private void winLoseScreen(String message, Image img) { Object lock = new Object(); synchronized(drawables){ drawables.add(new Drawable(){ String msg; public Drawable init(String st, Image i){ msg = st; img = i; z_index = 10; return this; } public void draw(Graphics g) { Graphics2D g2 = (Graphics2D)g; g2.setColor(Color.white); g2.setFont(new Font("Consolas", Font.BOLD, 36)); g2.setRenderingHint( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); FontMetrics fm = g2.getFontMetrics(); Rectangle2D r = fm.getStringBounds(msg, g2); int x = (800 - (int) r.getWidth()) / 2; int y = ((600 - (int) r.getHeight()) / 3 + fm.getAscent()); g2.drawString(msg, x, y); if (img != null) g2.drawImage(img, 800/2, 600/2, null); g2.setRenderingHint( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF); } }.init(message, img)); } drawAll(); mapPanel.addMouseListener(new MouseAdapter(){ Object lock; public MouseListener init(Object o){ lock = o; return this; } public void mousePressed(MouseEvent e){ synchronized(lock){ lock.notify(); } } }.init(lock)); synchronized(lock){ try { lock.wait(); } catch (InterruptedException e1) { e1.printStackTrace(); } } } public void gameLost() { winLoseScreen("Sajnálom kollega, vesztett", null); } public void gameWon() { try { winLoseScreen("Kíváló munka, kollega!", ImageIO.read(new File("icons/LZF.png"))); } catch (IOException e) { e.printStackTrace(); } } }
package net.grandcentrix.thirtyinch.sample.fragmentlifecycle; import net.grandcentrix.thirtyinch.sample.R; import android.os.Bundle; import android.provider.Settings; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.SwitchCompat; import android.util.Log; import android.view.View; import android.widget.TextView; import static android.provider.Settings.Global.ALWAYS_FINISH_ACTIVITIES; import static net.grandcentrix.thirtyinch.sample.fragmentlifecycle.TestFragment.testFragmentInstanceCount; public class FragmentLifecycleActivity extends AppCompatActivity { static int fragmentLifecycleActivityInstanceCount = -1; private final String TAG = this.getClass().getSimpleName() + "@" + Integer.toHexString(this.hashCode()); private SwitchCompat mSwitchAddToBackStack; private SwitchCompat mSwitchRetainFragmentInstance; public void addFragmentA(View view) { final TestFragmentA fragment = new TestFragmentA(); Log.v(TAG, "adding FragmentA"); addFragment(fragment); } public void addFragmentB(View view) { final TestFragmentB fragment = new TestFragmentB(); Log.v(TAG, "adding FragmentB"); addFragment(fragment); } @Override public void finish() { super.finish(); Log.v(TAG, "// When the Activity finishes"); } public void finishActivity(View view) { finish(); } @Override public void onBackPressed() { Log.v(TAG, "// When the back button gets pressed"); Log.v(TAG, "// When the top most fragment gets popped"); final FragmentManager fragmentManager = getSupportFragmentManager(); if (fragmentManager.getBackStackEntryCount() > 0) { fragmentManager.popBackStack(); } else { super.onBackPressed(); } } public void recreateActivity(View view) { Log.v(TAG, "// And when the Activity is changing its configurations."); recreate(); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); fragmentLifecycleActivityInstanceCount++; setContentView(R.layout.activity_fragment_lifecycle); mSwitchAddToBackStack = (SwitchCompat) findViewById(R.id.switch_add_back_stack); mSwitchRetainFragmentInstance = (SwitchCompat) findViewById( R.id.switch_retain_fragment_instance); final TextView textDontKeepActivities = (TextView) findViewById( R.id.text_dont_keep_activities); textDontKeepActivities.setText( isDontKeepActivities() ? R.string.dont_keep_activities_enabled : R.string.dont_keep_activities_disabled); Log.v(TAG, " Log.v(TAG, "final HostingActivity hostingActivity" + fragmentLifecycleActivityInstanceCount + " = new HostingActivity();"); } @Override protected void onDestroy() { super.onDestroy(); Log.v(TAG, "hostingActivity" + fragmentLifecycleActivityInstanceCount + ".setChangingConfiguration(" + isChangingConfigurations() + ");"); Log.v(TAG, "hostingActivity" + fragmentLifecycleActivityInstanceCount + ".setFinishing(" + isFinishing() + ");"); Log.v(TAG, "// hostingActivity" + fragmentLifecycleActivityInstanceCount + " got destroyed."); } @Override protected void onSaveInstanceState(final Bundle outState) { super.onSaveInstanceState(outState); Log.d(TAG, "onSaveInstanceState(Bundle)"); Log.v(TAG, "hostingActivity" + fragmentLifecycleActivityInstanceCount + "" + ".setChangingConfiguration(" + isChangingConfigurations() + ");"); Log.v(TAG, "hostingActivity" + fragmentLifecycleActivityInstanceCount + "" + ".setFinishing(" + isFinishing() + ");"); } @Override protected void onPause() { super.onPause(); Log.d(TAG, "onPause()"); Log.v(TAG, "hostingActivity" + fragmentLifecycleActivityInstanceCount + "" + ".setChangingConfiguration(" + isChangingConfigurations() + ");"); Log.v(TAG, "hostingActivity" + fragmentLifecycleActivityInstanceCount + "" + ".setFinishing(" + isFinishing() + ");"); } private void addFragment(final Fragment fragment) { final FragmentManager fragmentManager = getSupportFragmentManager(); final FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); if (isRetainFragmentInstance()) { Log.v(TAG, "retaining fragment instance"); fragment.setRetainInstance(true); } fragmentTransaction.replace(R.id.fragment_placeholder, fragment); if (isAddToBackStack()) { Log.v(TAG, "adding transaction to the back stack"); fragmentTransaction.addToBackStack(null); } final int backStackId = fragmentTransaction.commit(); Log.v(TAG, "\n// Given a Presenter ..."); // (testFragmentInstanceCount + 1) because it will be created after executing this code Log.v(TAG, "final TestPresenter presenter" + (testFragmentInstanceCount + 1) + " =" + " new TestPresenter(new TiConfiguration.Builder()\n" + " .setUseStaticSaviorToRetain(/*TODO set*/)\n" + " .setRetainPresenterEnabled(" + isRetainFragmentInstance() + ")\n" + " .build());"); Log.v(TAG, "\n// And given a Fragment."); Log.v(TAG, "final TiFragmentDelegate<TiPresenter<TiView>, TiView> " + "delegate" + (testFragmentInstanceCount + 1) + "\n" + " = new TiFragmentDelegateBuilder()\n" + " .setDontKeepActivitiesEnabled(" + isDontKeepActivities() + ")\n" + " .setHostingActivity(hostingActivity)\n" + " .setSavior(mSavior)\n" + " .setPresenter(presenter" + (testFragmentInstanceCount + 1) + ")\n" + " .build();"); if (backStackId >= 0) { Log.v(TAG, "Back stack ID: " + String.valueOf(backStackId)); } } private boolean isAddToBackStack() { return mSwitchAddToBackStack.isChecked(); } private boolean isDontKeepActivities() { // default behaviour int dontKeepActivities = 0; try { dontKeepActivities = Settings.Global .getInt(getContentResolver(), ALWAYS_FINISH_ACTIVITIES); } catch (Settings.SettingNotFoundException e) { e.printStackTrace(); } return dontKeepActivities != 0; } private boolean isRetainFragmentInstance() { return mSwitchRetainFragmentInstance.isChecked(); } }
package com.github.mjdbc.test; import com.github.mjdbc.DbImpl; import com.github.mjdbc.test.asset.EmptyQuerySql; import com.github.mjdbc.test.asset.EmptySql; import com.github.mjdbc.test.asset.MissedParameterSql; import com.github.mjdbc.test.asset.ReaderSql; import com.github.mjdbc.test.asset.UserSql; import com.github.mjdbc.test.asset.model.User; import com.github.mjdbc.test.asset.model.UserId; import com.github.mjdbc.test.util.DbUtils; import com.github.mjdbc.util.JavaType; import com.zaxxer.hikari.HikariDataSource; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import java.io.Reader; import java.io.StringReader; import java.sql.PreparedStatement; import java.util.ArrayList; import java.util.List; /** * Db interface tests */ public class DbTest extends Assert { /** * Low level connection pool. */ private HikariDataSource ds; /** * Database instance. */ private DbImpl db; @Before public void setUp() { ds = DbUtils.prepareDataSource("sample"); db = new DbImpl(ds); db.registerMapper(UserId.class, UserId.MAPPER); db.registerMapper(User.class, User.MAPPER); } @After public void tearDown() { ds.close(); } /** * Check new mapper registration */ @Test public void checkMapperOverride() { UserSql q = db.attachSql(UserSql.class); assertEquals(2, q.countUsers()); db.registerMapper(Integer.class, r -> -r.getInt(1)); assertEquals(-2, q.countUsers()); } /** * Check that collection mappers override are not supported. */ @Test(expected = IllegalArgumentException.class) public void checkCollectionMapperOverrideIsNotAllowed() { db.registerMapper(List.class, r -> new ArrayList()); fail(); } /** * Check that registration of null mapper triggers null pointer exception. */ @Test(expected = NullPointerException.class) public void checkNullMapperThrowsNullPointerException() { //noinspection ConstantConditions db.registerMapper(String.class, null); } /** * Check that registration of mapped class = null triggers null pointer exception. */ @Test(expected = NullPointerException.class) public void checkNullMappedClassThrowsNullPointerException() { //noinspection ConstantConditions db.registerMapper(null, JavaType.String.mapper); } /** * Check that new binder class can be registered and used. */ @Test public void checkBinderRegistration() { db.registerBinder(Reader.class, PreparedStatement::setCharacterStream); ReaderSql q1 = db.attachSql(ReaderSql.class); q1.updateFirstNameWithReader("u1", new StringReader("x")); UserSql q2 = db.attachSql(UserSql.class); User u = q2.getUserByLogin("u1"); assertNotNull(u); assertEquals("x", u.firstName); } @Test(expected = NullPointerException.class) public void checkNullBinderTriggersNullPointerException() { //noinspection ConstantConditions db.registerBinder((Class<Reader>) null, PreparedStatement::setCharacterStream); } @Test(expected = NullPointerException.class) public void checkNullBinderFunctionTriggersNullPointerException() { //noinspection ConstantConditions db.registerBinder(Reader.class, null); } /** * Check that empty Sql interface is OK. */ @Test public void checkAttachEmptySql() { EmptySql sql = db.attachSql(EmptySql.class); assertNotNull(sql); } @Test(expected = IllegalArgumentException.class) public void checkAttachClassThrowsIllegalArgumentException() { db.attachSql(String.class); } @Test(expected = IllegalArgumentException.class) public void checkEmptySqlQueryThrowsIllegalArgumentException() { db.attachSql(EmptyQuerySql.class); } @Test(expected = IllegalArgumentException.class) public void checkMissedParameterSqlThrowsIllegalArgumentException() { db.attachSql(MissedParameterSql.class); } @Test(expected = IllegalArgumentException.class) public void checkMissedBeanParameterSqlThrowsIllegalArgumentException() { db.attachSql(MissedParameterSql.class); } }
package de.naoth.rc; import de.naoth.rc.core.dialog.Dialog; import bibliothek.gui.DockUI; import bibliothek.gui.dock.util.laf.Nimbus6u10; import de.naoth.rc.components.preferences.PreferencesDialog; import de.naoth.rc.server.ConnectionManager; import de.naoth.rc.server.ConnectionStatusEvent; import de.naoth.rc.server.ConnectionStatusListener; import de.naoth.rc.server.MessageServer; import de.naoth.rc.statusbar.StatusbarPluginImpl; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ComponentAdapter; import java.awt.event.ComponentEvent; import java.awt.event.InputEvent; import java.awt.event.KeyEvent; import java.io.*; import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; import java.lang.invoke.MethodHandles.Lookup; import java.lang.reflect.Field; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Arrays; import java.util.Properties; import java.util.logging.Level; import java.util.logging.LogManager; import java.util.logging.Logger; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.KeyStroke; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; import net.xeoh.plugins.base.PluginManager; import net.xeoh.plugins.base.annotations.PluginImplementation; import net.xeoh.plugins.base.annotations.events.PluginLoaded; import net.xeoh.plugins.base.impl.PluginManagerFactory; import net.xeoh.plugins.base.util.JSPFProperties; import net.xeoh.plugins.base.util.uri.ClassURI; /** * * @author thomas */ @PluginImplementation public class RobotControlImpl extends javax.swing.JFrame implements ByteRateUpdateHandler, RobotControl { private static final String USER_CONFIG_DIR = System.getProperty("user.home") + "/.naoth/robotcontrol/"; private final File userLayoutFile = new File(USER_CONFIG_DIR, "layout_df1.1.1.xml"); private final File userConfigFile = new File(USER_CONFIG_DIR, "config"); private final MessageServer messageServer; private final Properties config = new Properties(); private final PreferencesDialog preferencesDialog; private final ConnectionManager connectionManager; private final DialogRegistry dialogRegistry; // remember the window position and size to restore it later private Rectangle defaultWindowBounds = new Rectangle(); private static final Logger logger = Logger.getLogger(RobotControlImpl.class.getName()); private static Logger getLogger() { return logger; } private final GridBagConstraints statusPanelPluginsConstraints = new GridBagConstraints(); private final String RC_TITLE = ""; // HACK: set the path to the native libs static { // load the logger properties InputStream stream = RobotControlImpl.class.getResourceAsStream("logging.properties"); try { LogManager.getLogManager().readConfiguration(stream); } catch (IOException e) { e.printStackTrace(); } try { // we need an absolute path to import native libs // in netbeans we can use the relative execution path File bin = new File("./bin"); if (!bin.isDirectory()) { // with a jar file, we need to determine the correct path relative to the jar file File jar = new File(RobotControlImpl.class.getProtectionDomain().getCodeSource().getLocation().toURI()); bin = new File(jar.getParent(), "bin"); } String arch = System.getProperty("os.arch").toLowerCase(); String name = System.getProperty("os.name").toLowerCase(); if("linux".equals(name)) { if("amd64".equals(arch)) { addLibraryPath(bin.getAbsolutePath() + "/linux64"); } else { addLibraryPath(bin.getAbsolutePath() + "/linux32"); } } else { if("amd64".equals(arch)) { addLibraryPath(bin.getAbsolutePath() + "/win64"); } else { addLibraryPath(bin.getAbsolutePath() + "/win32"); } addLibraryPath(bin.getAbsolutePath() + "/macos"); } System.getProperties().list(System.out); } catch (Throwable ex) { Logger.getLogger(RobotControlImpl.class.getName()).log(Level.SEVERE, null, ex); } } public static void addLibraryPath(String pathToAdd) throws Throwable { // Define black magic: IMPL_LOOKUP is "trusted" and can access prvae variables. final Lookup original = MethodHandles.lookup(); final Field internal = Lookup.class.getDeclaredField("IMPL_LOOKUP"); internal.setAccessible(true); final Lookup trusted = (Lookup) internal.get(original); // Invoke black magic. Get access to the private field usr_paths MethodHandle set = trusted.findStaticSetter(ClassLoader.class, "usr_paths", String[].class); MethodHandle get = trusted.findStaticGetter(ClassLoader.class, "usr_paths", String[].class); //get array of paths final String[] paths = (String[]) get.invoke(); //check if the path to add is already present for (String path : paths) { if (path.equals(pathToAdd)) { return; } } //add the new path final String[] newPaths = Arrays.copyOf(paths, paths.length + 1); newPaths[newPaths.length - 1] = pathToAdd; set.invoke(newPaths); } /** * Creates new form RobotControlGUI */ public RobotControlImpl() { splashScreenMessage("Welcome to RobotControl"); // load the configuration readConfigFromFile(); try { //UIManager.setLookAndFeel(new PlasticXPLookAndFeel()); UIManager.setLookAndFeel(new CustomNimbusLookAndFeel(RobotControlImpl.this)); // set explicitely the Nimbus colors to be used DockUI.getDefaultDockUI().registerColors("de.naoth.rc.CustomNimbusLookAndFeel", new Nimbus6u10()); } catch(UnsupportedLookAndFeelException ex) { getLogger().log(Level.SEVERE, null, ex); } // icon Image icon = Toolkit.getDefaultToolkit().getImage( this.getClass().getResource("res/RobotControlLogo128.png")); setIconImage(icon); initComponents(); // restore the bounds and the state of the frame from the config defaultWindowBounds = getBounds(); defaultWindowBounds.x = readValueFromConfig("frame.position.x", defaultWindowBounds.x); defaultWindowBounds.y = readValueFromConfig("frame.position.y", defaultWindowBounds.y); defaultWindowBounds.width = readValueFromConfig("frame.width", defaultWindowBounds.width); defaultWindowBounds.height = readValueFromConfig("frame.height", defaultWindowBounds.height); int extendedstate = readValueFromConfig("frame.extendedstate", getExtendedState()); setBounds(defaultWindowBounds); setExtendedState(extendedstate); // remember the bounds of the frame when not maximized this.addComponentListener(new ComponentAdapter() { @Override public void componentMoved(ComponentEvent event) { if ((getExtendedState() & JFrame.MAXIMIZED_BOTH) != JFrame.MAXIMIZED_BOTH) { defaultWindowBounds = getBounds(); } } }); // set up a list of all dialogs this.dialogRegistry = new DialogRegistry(this, this.mainMenuBar, this.dialogFastAccessPanel); // initialize the message server this.messageServer = new MessageServer(); this.messageServer.addConnectionStatusListener(new ConnectionStatusListener() { @Override public void connected(ConnectionStatusEvent event) { disconnectMenuItem.setEnabled(true); connectMenuItem.setEnabled(false); } @Override public void disconnected(ConnectionStatusEvent event) { disconnectMenuItem.setEnabled(false); connectMenuItem.setEnabled(true); if(event.getMessage() != null) { connectionManager.showConnectionDialog(event.getMessage()); } } }); this.connectionManager = new ConnectionManager(this, this.messageServer, this.getConfig()); this.disconnectMenuItem.setEnabled(false); // preference dialog this.preferencesDialog = new PreferencesDialog(this, this.getConfig()); this.preferencesDialog.setLocationRelativeTo(this); // set the constraints for the statusbar plugins statusPanelPluginsConstraints.fill = GridBagConstraints.VERTICAL; statusPanelPluginsConstraints.ipadx = 5; // dialog access dialogFastAccess.setLocationRelativeTo(this); dialogFastAccess.getRootPane().registerKeyboardAction( (e) -> {dialogFastAccess.setVisible(false); dialogFastAccessPanel.close(); }, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_IN_FOCUSED_WINDOW ); DefaultKeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventPostProcessor( (e) -> { if(e.getID() == KeyEvent.KEY_PRESSED && e.getKeyCode() == KeyEvent.VK_F && e.getModifiers() == InputEvent.ALT_MASK) { dialogFastAccess.setContentPane(dialogFastAccessPanel); dialogFastAccess.pack(); dialogFastAccess.setLocationRelativeTo(this); dialogFastAccess.setVisible(true); return true; } return false; }); // read & set the userdefined dialog configurations setMenuDialogConfiguration(); }//end constructor private int readValueFromConfig(String key, int default_value) { try { String value = getConfig().getProperty(key); if(value != null) { return Integer.parseInt(value); } } catch(NumberFormatException e){} return default_value; } private void splashScreenMessage(String message) { final SplashScreen splash = SplashScreen.getSplashScreen(); if(splash == null) { return; } Graphics2D g = splash.createGraphics(); if(g == null) { return; } int x = 120; int y = 140; g.setComposite(AlphaComposite.Clear); g.fillRect(x-10,y-10,290,100); g.setPaintMode(); g.setColor(Color.BLACK); g.drawString(message, x, y); splash.update(); } @PluginLoaded public void registerDialog(final Dialog dialog) { splashScreenMessage("Loading dialog " + dialog.getDisplayName() + "..."); this.dialogRegistry.registerDialog(dialog); } @Override public boolean checkConnected() { if(enforceConnection.isSelected() && !messageServer.isConnected()) { // NOTE: this call will block until the dialog is closed //connectionDialog.setVisible(true); this.connectionManager.showConnectionDialog(); return messageServer.isConnected(); } else { return true; } }//end checkConnected /** * Reads all user-defined dialog configurations and creates appropiate menu items. */ private void setMenuDialogConfiguration() { String suffix = "_" + userLayoutFile.getName(); Arrays.asList(userLayoutFile.getParentFile().listFiles((dir, name) -> { return name.endsWith(suffix); })).forEach((f) -> { String name = f.getName().substring(0, f.getName().length()-suffix.length()); createDialogConfigMenuItem(name); }); } /** * Returns the user dialog configuration file for the given configuration name. * * @param configName the name of the dialog configuration * @return the File object of this dialog configuraiton */ private File createUserDialogConfigFile(String configName) { return new File(userLayoutFile.getParent() + "/" + configName + "_" + userLayoutFile.getName()); } /** * Creates a new dialog configuration menu item and adds it to the restore menu. * * @param name the name of the dialog configuration item */ private void createDialogConfigMenuItem(String name) { JMenuItem item = new JMenuItem(name); item.setToolTipText("<html>Restores this dialog layout.<br>Use <i>Ctrl+Click</i> to delete this dialog layout.</html>"); item.addActionListener((e) -> { JMenuItem source = (JMenuItem) e.getSource(); if((e.getModifiers() & ActionEvent.CTRL_MASK) == ActionEvent.CTRL_MASK) { // delete requested if(JOptionPane.showConfirmDialog(this, "Do you want to remove the dialog layout '"+name+"'?", "Remove dialog layout", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) { if(createUserDialogConfigFile(name).delete()) { layout.remove(source); } } } else { // restore dialog configuration File f = createUserDialogConfigFile(source.getText()); if(f.isFile()) { try { dialogRegistry.loadFromFile(f); } catch (IOException ex) { Logger.getLogger(RobotControlImpl.class.getName()).log(Level.SEVERE, null, ex); } } else { JOptionPane.showMessageDialog(this, "The '"+source.getText()+"' dialog layout file doesn't exists!?", "Missing layout file", JOptionPane.ERROR_MESSAGE); } } }); layout.add(item); } /** * 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. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; dialogFastAccess = new javax.swing.JDialog(); dialogFastAccessPanel = new de.naoth.rc.DialogFastAccessPanel(); statusPanel = new javax.swing.JPanel(); btManager = new javax.swing.JButton(); lblReceivedBytesS = new javax.swing.JLabel(); jSeparator4 = new javax.swing.JSeparator(); lblSentBytesS = new javax.swing.JLabel(); jSeparator5 = new javax.swing.JSeparator(); lblFramesS = new javax.swing.JLabel(); statusPanelPlugins = new javax.swing.JPanel(); statusPanelSpacer = new javax.swing.Box.Filler(new java.awt.Dimension(0, 0), new java.awt.Dimension(0, 0), new java.awt.Dimension(32767, 0)); mainMenuBar = new de.naoth.rc.MainMenuBar(); mainControlMenu = new javax.swing.JMenu(); connectMenuItem = new javax.swing.JMenuItem(); disconnectMenuItem = new javax.swing.JMenuItem(); enforceConnection = new javax.swing.JCheckBoxMenuItem(); layout = new javax.swing.JMenu(); resetLayoutMenuItem = new javax.swing.JMenuItem(); miSaveDialogConfig = new javax.swing.JMenuItem(); jSeparator2 = new javax.swing.JPopupMenu.Separator(); preferences = new javax.swing.JMenuItem(); jSeparator1 = new javax.swing.JSeparator(); exitMenuItem = new javax.swing.JMenuItem(); helpMenu = new javax.swing.JMenu(); aboutMenuItem = new javax.swing.JMenuItem(); dialogFastAccess.setAlwaysOnTop(true); dialogFastAccess.setLocationByPlatform(true); dialogFastAccess.setModal(true); dialogFastAccess.setName("dialogFastAccessDialog"); // NOI18N dialogFastAccess.setUndecorated(true); dialogFastAccess.setPreferredSize(new java.awt.Dimension(600, 300)); dialogFastAccess.getContentPane().add(dialogFastAccessPanel, java.awt.BorderLayout.CENTER); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("RobotControl for NAO v2019"); addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent evt) { formWindowClosing(evt); } }); statusPanel.setBackground(java.awt.Color.lightGray); statusPanel.setPreferredSize(new java.awt.Dimension(966, 25)); btManager.setText("Running Manager btManager.setToolTipText("Shows the number of currently registered Manager"); btManager.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btManagerActionPerformed(evt); } }); lblReceivedBytesS.setText("Received (byte/s): "); jSeparator4.setOrientation(javax.swing.SwingConstants.VERTICAL); lblSentBytesS.setText("Sent (byte/s): "); jSeparator5.setOrientation(javax.swing.SwingConstants.VERTICAL); lblFramesS.setText("Update Loop (frame/s):"); statusPanelPlugins.setFocusable(false); statusPanelPlugins.setMaximumSize(new java.awt.Dimension(32767, 24)); statusPanelPlugins.setMinimumSize(new java.awt.Dimension(0, 24)); statusPanelPlugins.setOpaque(false); statusPanelPlugins.setPreferredSize(new java.awt.Dimension(100, 24)); statusPanelPlugins.setLayout(new java.awt.GridBagLayout()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; statusPanelPlugins.add(statusPanelSpacer, gridBagConstraints); javax.swing.GroupLayout statusPanelLayout = new javax.swing.GroupLayout(statusPanel); statusPanel.setLayout(statusPanelLayout); statusPanelLayout.setHorizontalGroup( statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(statusPanelLayout.createSequentialGroup() .addComponent(btManager, javax.swing.GroupLayout.PREFERRED_SIZE, 121, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(lblReceivedBytesS, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jSeparator4, javax.swing.GroupLayout.PREFERRED_SIZE, 1, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(lblSentBytesS, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jSeparator5) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(lblFramesS, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGap(63, 63, 63) .addComponent(statusPanelPlugins, javax.swing.GroupLayout.DEFAULT_SIZE, 464, Short.MAX_VALUE)) ); statusPanelLayout.setVerticalGroup( statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btManager, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(lblReceivedBytesS, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jSeparator5) .addComponent(lblSentBytesS, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(lblFramesS, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(statusPanelLayout.createSequentialGroup() .addComponent(statusPanelPlugins, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(statusPanelLayout.createSequentialGroup() .addComponent(jSeparator4, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE)) ); getContentPane().add(statusPanel, java.awt.BorderLayout.PAGE_END); mainControlMenu.setMnemonic('R'); mainControlMenu.setText("Main"); connectMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_K, java.awt.event.InputEvent.CTRL_MASK)); connectMenuItem.setMnemonic('c'); connectMenuItem.setText("Connect"); connectMenuItem.setToolTipText("Connect to robot"); connectMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { connectMenuItemActionPerformed(evt); } }); mainControlMenu.add(connectMenuItem); disconnectMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_D, java.awt.event.InputEvent.CTRL_MASK)); disconnectMenuItem.setMnemonic('d'); disconnectMenuItem.setText("Disconnect"); disconnectMenuItem.setToolTipText("Disconnect from robot"); disconnectMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { disconnectMenuItemActionPerformed(evt); } }); mainControlMenu.add(disconnectMenuItem); enforceConnection.setSelected(true); enforceConnection.setText("Enforce Connection"); enforceConnection.setToolTipText("Make sure that RobotControl is connected to a robot when dialogs try to receive data"); mainControlMenu.add(enforceConnection); layout.setText("Layout"); resetLayoutMenuItem.setText("Reset layout"); resetLayoutMenuItem.setToolTipText("Resets all layout information"); resetLayoutMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { resetLayoutMenuItemActionPerformed(evt); } }); layout.add(resetLayoutMenuItem); miSaveDialogConfig.setText("Save dialog layout"); miSaveDialogConfig.setToolTipText("Saves the current active dialog configuration."); miSaveDialogConfig.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { miSaveDialogConfigActionPerformed(evt); } }); layout.add(miSaveDialogConfig); layout.add(jSeparator2); mainControlMenu.add(layout); preferences.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_P, java.awt.event.InputEvent.CTRL_MASK)); preferences.setText("Preferences"); preferences.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { preferencesActionPerformed(evt); } }); mainControlMenu.add(preferences); mainControlMenu.add(jSeparator1); exitMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_X, java.awt.event.InputEvent.CTRL_MASK)); exitMenuItem.setMnemonic('e'); exitMenuItem.setText("Exit"); exitMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { exitMenuItemActionPerformed(evt); } }); mainControlMenu.add(exitMenuItem); mainMenuBar.add(mainControlMenu); helpMenu.setMnemonic('h'); helpMenu.setText("Help"); aboutMenuItem.setMnemonic('a'); aboutMenuItem.setText("About"); aboutMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { aboutMenuItemActionPerformed(evt); } }); helpMenu.add(aboutMenuItem); helpMenu.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT); mainMenuBar.add(javax.swing.Box.createHorizontalGlue()); mainMenuBar.add(helpMenu); setJMenuBar(mainMenuBar); setSize(new java.awt.Dimension(974, 626)); setLocationRelativeTo(null); }// </editor-fold>//GEN-END:initComponents private void connectMenuItemActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_connectMenuItemActionPerformed {//GEN-HEADEREND:event_connectMenuItemActionPerformed connectionManager.showConnectionDialog(); }//GEN-LAST:event_connectMenuItemActionPerformed private void disconnectMenuItemActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_disconnectMenuItemActionPerformed {//GEN-HEADEREND:event_disconnectMenuItemActionPerformed messageServer.disconnect(); }//GEN-LAST:event_disconnectMenuItemActionPerformed private void exitMenuItemActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_exitMenuItemActionPerformed {//GEN-HEADEREND:event_exitMenuItemActionPerformed beforeClose(); System.exit(0); }//GEN-LAST:event_exitMenuItemActionPerformed private void aboutMenuItemActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_aboutMenuItemActionPerformed {//GEN-HEADEREND:event_aboutMenuItemActionPerformed AboutDialog dlg = new AboutDialog(this, true); dlg.setLocationRelativeTo(this); dlg.setVisible(true); }//GEN-LAST:event_aboutMenuItemActionPerformed private void resetLayoutMenuItemActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_resetLayoutMenuItemActionPerformed {//GEN-HEADEREND:event_resetLayoutMenuItemActionPerformed this.dialogRegistry.setDefaultLayout(); }//GEN-LAST:event_resetLayoutMenuItemActionPerformed private void formWindowClosing(java.awt.event.WindowEvent evt)//GEN-FIRST:event_formWindowClosing {//GEN-HEADEREND:event_formWindowClosing beforeClose(); }//GEN-LAST:event_formWindowClosing private void preferencesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_preferencesActionPerformed preferencesDialog.setVisible(true); }//GEN-LAST:event_preferencesActionPerformed private void miSaveDialogConfigActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_miSaveDialogConfigActionPerformed // Ask for a name for this dialog configuration String inputName = JOptionPane.showInputDialog("Set a name for the current dialog layout"); // ignore canceled inputs if(inputName == null) { return; } // replace "invalid" characters String name = inputName.trim().replaceAll("[^A-Za-z0-9_-]", ""); // ignore empty inputs if(name.isEmpty()) { return; } // create layout file File f = createUserDialogConfigFile(name); // if configuration name already exists - ask to overwrite if(f.isFile() && JOptionPane.showConfirmDialog(this, "This dialog layout name already exists. Overwrite?", "Overwrite", JOptionPane.YES_NO_OPTION) != JOptionPane.YES_OPTION) { // don't overwrite! return; } // save configuration try { boolean exists = f.isFile(); dialogRegistry.saveToFile(f); // if this configuration already exists, don't create a new menu entry! if(!exists) { createDialogConfigMenuItem(name); } } catch (IOException ex) { Logger.getLogger(RobotControlImpl.class.getName()).log(Level.SEVERE, null, ex); } }//GEN-LAST:event_miSaveDialogConfigActionPerformed private void btManagerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btManagerActionPerformed TaskManager taskManager = new TaskManager(this, true); String str = "Currently registeres Manager:\n\n"; for(int i = 0; i < messageServer.getListeners().size(); i++) { String name = messageServer.getListeners().get(i).getClass().getSimpleName(); taskManager.addTask(name, "0", null); str += messageServer.getListeners().get(i).getClass().getSimpleName() + "\n"; }//end for str += "\n"; //taskManager.setVisible(true); JOptionPane.showMessageDialog(this, str); }//GEN-LAST:event_btManagerActionPerformed @Override public MessageServer getMessageServer() { return messageServer; } /** * @param args the command line arguments */ public static void main(final String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { @Override public void run() { // create the configlocation is not existing File configDir = new File(USER_CONFIG_DIR); if(!(configDir.exists() && configDir.isDirectory()) && !configDir.mkdirs()) { getLogger().log(Level.SEVERE, "Could not create the configuration path: \"{0}\".", USER_CONFIG_DIR); } final JSPFProperties props = new JSPFProperties(); props.setProperty(PluginManager.class, "cache.enabled", "false"); // props.setProperty(PluginManager.class, "cache.mode", "strong"); //optional // props.setProperty(PluginManager.class, "cache.file", configlocation+"robot-control.jspf.cache"); PluginManager pluginManager = PluginManagerFactory.createPluginManager(props); try { // make sure the main frame if loaded first pluginManager.addPluginsFrom(new ClassURI(RobotControlImpl.class).toURI()); File selfFile = new File(RobotControlImpl.class.getProtectionDomain().getCodeSource().getLocation().toURI()); // load all plugins from pluginManager.addPluginsFrom(selfFile.toURI()); // NOTE: this is very slow to search in the whole classpath
package org.ow2.proactive.scheduler.core.helpers; import org.ow2.proactive.db.DatabaseManagerException; import org.ow2.proactive.scheduler.common.exception.UnknownTaskException; import org.ow2.proactive.scheduler.common.job.JobType; import org.ow2.proactive.scheduler.common.task.TaskId; import org.ow2.proactive.scheduler.common.task.TaskLogs; import org.ow2.proactive.scheduler.common.task.TaskResult; import org.ow2.proactive.scheduler.core.db.SchedulerDBManager; import org.ow2.proactive.scheduler.descriptor.EligibleTaskDescriptor; import org.ow2.proactive.scheduler.descriptor.JobDescriptor; import org.ow2.proactive.scheduler.job.InternalJob; import org.ow2.proactive.scheduler.task.TaskResultImpl; import org.ow2.proactive.scheduler.task.internal.InternalTask; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; public class TaskResultCreator { private static TaskResultCreator instance = null; public TaskResultCreator() { } public static synchronized TaskResultCreator getInstance() { if (instance == null) { instance = new TaskResultCreator(); } return instance; } public TaskResultImpl getTaskResult(SchedulerDBManager dbManager, InternalJob job, InternalTask task) throws UnknownTaskException { return getTaskResult(dbManager, job, task, null, null); } public TaskResultImpl getTaskResult(SchedulerDBManager dbManager, InternalJob job, InternalTask task, Throwable exception, TaskLogs output) throws UnknownTaskException { if (task == null) { throw new UnknownTaskException(); } TaskResultImpl taskResult; JobDescriptor jobDescriptor = job.getJobDescriptor(); // try { // taskResult = (TaskResultImpl) dbManager.loadTasksResults(job.getId(), // Collections.singletonList(task.getId())).get(task.getId()); // } catch (DatabaseManagerException e) { taskResult = getEmptyTaskResultWithTaskIdAndExecutionTime(task, exception, output); EligibleTaskDescriptor etd = null; if (jobDescriptor.getPausedTasks().get(task.getId()) != null) { etd = (EligibleTaskDescriptor) jobDescriptor.getPausedTasks().get(task.getId()); } else if (jobDescriptor.getRunningTasks().get(task.getId()) != null) { etd = (EligibleTaskDescriptor) jobDescriptor.getRunningTasks().get(task.getId()); } if (etd != null) { taskResult.setPropagatedVariables(getPropagatedVariables(dbManager, etd, job, task)); } return taskResult; } public TaskResultImpl getEmptyTaskResultWithTaskIdAndExecutionTime(InternalTask task, Throwable exception, TaskLogs output) { return new TaskResultImpl(task.getId(), exception, output, System.currentTimeMillis() - task.getStartTime()); } private Map<String, byte[]> getPropagatedVariables(SchedulerDBManager dbManager, EligibleTaskDescriptor etd, InternalJob job, InternalTask task) throws UnknownTaskException { Map<String, byte[]> variables = new HashMap<>(); int numberOfParentTasks = etd.getParents().size(); if (job.getType() == JobType.TASKSFLOW) { // retrieve from the database the previous task results if available if ((numberOfParentTasks > 0) && task.handleResultsArguments()) { variables = extractTaskResultsAndMergeIntoMap(dbManager, etd, job); } else { variables = extractJobVariables(job); } } return variables; } private Map<String, byte[]> extractJobVariables(InternalJob job) { Map<String, byte[]> jobVariables = new HashMap<>(); // otherwise use the default job variables for (Entry<String, String> entry : job.getVariables().entrySet()) { jobVariables.put(entry.getKey(), entry.getValue().getBytes()); } return jobVariables; } private Map<String, byte[]> extractTaskResultsAndMergeIntoMap(SchedulerDBManager dbManager, EligibleTaskDescriptor etd, InternalJob job) { Map<String, byte[]> mergedVariables = new HashMap<>(); int numberOfParentTasks = etd.getParents().size(); List<TaskId> parentIds = new ArrayList<>(numberOfParentTasks); for (int i = 0; i < numberOfParentTasks; i++) { parentIds.add(etd.getParents().get(i).getTaskId()); } Map<TaskId, TaskResult> taskResults = dbManager .loadTasksResults( job.getId(), parentIds); for (TaskResult taskResult : taskResults.values()) { if (taskResult.getPropagatedVariables() != null) { mergedVariables.putAll(taskResult.getPropagatedVariables()); } } return mergedVariables; } }
package com.sothawo.trakxmap; import com.sothawo.trakxmap.generated.gpx.GpxType; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBElement; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; import java.nio.file.Path; import java.nio.file.Paths; /** * test program to read a gpx track file. * * @author P.J. Meisch (pj.meisch@sothawo.com). */ public class ReadGpx { public static void main(String[] args) { if (args.length > 0) { try { Unmarshaller unmarshaller = JAXBContext.newInstance(GpxType.class.getPackage().getName()).createUnmarshaller(); Path path = Paths.get(args[0]); @SuppressWarnings("unchecked") GpxType gpxType = ((JAXBElement<GpxType>) unmarshaller.unmarshal(path.toFile())).getValue(); System.out.println(gpxType); } catch (JAXBException e) { e.printStackTrace(); } } } }
package com.twistedplane.sealnote; import android.app.ActionBar; import android.app.Activity; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.WindowManager; import android.widget.EditText; import android.widget.ShareActionProvider; import android.widget.TextView; import android.widget.Toast; import com.twistedplane.sealnote.data.DatabaseHandler; import com.twistedplane.sealnote.data.Note; import com.twistedplane.sealnote.fragment.ColorDialogFragment; import com.twistedplane.sealnote.utils.*; //FIXME: Clean up code and update flag on settings changed. /** * NoteActivity implements activity to show and edit note in a full window view. */ public class NoteActivity extends Activity implements ColorDialogFragment.ColorChangedListener{ public final static String TAG = "NoteActivity"; private Note mNote; private Intent mShareIntent; private boolean mSaveButtonClicked = false; private boolean mAutoSaveEnabled; private boolean mLoadingNote = true; private boolean mTimedOut = false; private EditText mTitleView; private EditText mTextView; private TextView mEditedView; int mBackgroundColor; /** * Start a new NoteActivity with given note id. * * TODO: Take note object to make loading faster * * @param context Context to use * @param id Id of note. -1 for new note. */ public static void startForNoteId(Context context, int id) { Intent intent = new Intent(context, NoteActivity.class); intent.putExtra("NOTE_ID", id); context.startActivity(intent); } /** * TextWatcher for note text and title. Right now just updates share button intent. */ final private TextWatcher mNoteTextWatcher = new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) { // do nothing } @Override public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) { // do nothing } @Override public void afterTextChanged(Editable editable) { updateShareIntent(); } }; /** * Check if note is new or existing, and update views appropriately with values. * If note is existing an async task is started which shows progress dialog * and delays loading of note */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_note); mBackgroundColor = 0; mAutoSaveEnabled = PreferenceHandler.isAutosaveEnabled(NoteActivity.this); int id = -1; Note bundledNote = null; if (savedInstanceState != null) { id = savedInstanceState.getInt("NOTE_ID", -1); bundledNote = savedInstanceState.getParcelable("NOTE"); } if (id == -1) { Bundle extras = getIntent().getExtras(); id = extras.getInt("NOTE_ID", -1); } if (id != -1 && savedInstanceState != null && bundledNote != null) { Log.d(TAG, "Unsaved existing note being retrieved from bundle"); mLoadingNote = false; init(false); loadNote(bundledNote); } else if (id != -1) { // existing note. Start an async task to load from storage new NoteLoadTask().execute(id); } else { Log.d(TAG, "Creating new note"); mLoadingNote = false; init(true); // new note simply setup views getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE); } } /** * Initialize views, listeners and update references */ private void init(boolean isNewNote) { Misc.secureWindow(NoteActivity.this); mTitleView = (EditText) findViewById(R.id.note_activity_title); mTextView = (EditText) findViewById(R.id.note_activity_note); mEditedView = (TextView) findViewById(R.id.note_activity_edited); // TextWatcher to update share intent mTextView.addTextChangedListener(mNoteTextWatcher); mTitleView.addTextChangedListener(mNoteTextWatcher); mTitleView.setTypeface(FontCache.getFont(this, "RobotoSlab-Bold.ttf")); mTextView.setTypeface(FontCache.getFont(this, "RobotoSlab-Regular.ttf")); // set focus to text view //TODO: Only if id=-1 if (isNewNote) { mTextView.requestFocus(); } else { mTitleView.requestFocus(); } //NOTE: For ICS ActionBar actionBar = getActionBar(); actionBar.setHomeButtonEnabled(true); actionBar.setDisplayHomeAsUpEnabled(true); } /** * Update views with given note values */ private void loadNote(Note note) { mNote = note; mTitleView.setText(mNote.getTitle()); mTextView.setText(mNote.getNote()); EasyDate date = mNote.getEditedDate(); if (date == null) { mEditedView.setText("Edited " + EasyDate.now().friendly()); } else { mEditedView.setText("Edited " + mNote.getEditedDate().friendly()); } mBackgroundColor = mNote.getColor(); onColorChanged(mBackgroundColor); getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN); updateShareIntent(); if (mNote.getIsDeleted()) { mTitleView.setEnabled(false); mTextView.setEnabled(false); } } /** * When coming back from foreground check if timeout has expired and if * so load logout to password activity. Otherwise reset the timeout status. */ @Override public void onResume() { super.onResume(); if (TimeoutHandler.instance().resume(this)) { mTimedOut = true; return; } else { mTimedOut = false; } } /** * Schedules a delayed callback after configured password expiry timeout. */ @Override public void onPause() { super.onPause(); // makes sure that note is loaded. onPause is also called when // progress dialog is shown at which moment we haven't set our // content view // FIXME: This can be made simpler maybe by making better layout if (!mTimedOut && mAutoSaveEnabled && !mLoadingNote) { saveNote(); Log.d(TAG, "Note saved automatically due to activity pause."); } TimeoutHandler.instance().pause(this); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); //TODO: These bundles can be persistent and hence security hole if (mTimedOut || mLoadingNote) { // FIXME: After timeout user should be able to continue from where // they left off by giving password return; } int noteId = -1; if (mAutoSaveEnabled) { saveNote(); noteId = mNote.getId(); Log.d(TAG, "Note saved automatically due to activity pause."); } else { if (mNote != null && mNote.getId() != -1) { Log.d(TAG, "Save state in bundle for manual save"); noteId = mNote.getId(); outState.putParcelable("NOTE", mNote); } } outState.putInt("NOTE_ID", noteId); } /** * Inflate actionbar and add share button and intent */ @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.note_activity_actionbar, menu); MenuItem saveMenuItem = menu.findItem(R.id.action_save_note); MenuItem deleteMenuItem = menu.findItem(R.id.action_note_delete); MenuItem archiveMenuItem = menu.findItem(R.id.action_archive); MenuItem unarchiveMenuItem = menu.findItem(R.id.action_unarchive); MenuItem colorMenuItem = menu.findItem(R.id.action_color); MenuItem restoreMenuItem = menu.findItem(R.id.action_restore); MenuItem shareItem = menu.findItem(R.id.action_share); // check if autosave is enabled and set visibility of action saveMenuItem.setVisible(!mAutoSaveEnabled); // don't show delete action if note is newly created if (mNote == null || mNote.getId() == -1) { deleteMenuItem.setVisible(false); archiveMenuItem.setVisible(false); restoreMenuItem.setVisible(false); unarchiveMenuItem.setVisible(false); } else { saveMenuItem.setVisible(!mAutoSaveEnabled && !mNote.getIsDeleted()); deleteMenuItem.setVisible(!mNote.getIsDeleted()); archiveMenuItem.setVisible(mNote.getIsLive()); unarchiveMenuItem.setVisible(mNote.getIsArchived() && !mNote.getIsDeleted()); colorMenuItem.setVisible(!mNote.getIsDeleted()); shareItem.setVisible(!mNote.getIsDeleted()); restoreMenuItem.setVisible(mNote.getIsDeleted()); } // Fetch and store ShareActionProvider ShareActionProvider shareActionProvider = (ShareActionProvider) shareItem.getActionProvider(); mShareIntent = new Intent(Intent.ACTION_SEND); mShareIntent.setType("text/plain"); shareActionProvider.setShareIntent(mShareIntent); updateShareIntent(); return true; } /** * Update share intent with current note values */ private void updateShareIntent() { if (mShareIntent == null) { //FIX: crash when orientation is changed return; } final EditText titleView = (EditText) findViewById(R.id.note_activity_title); final EditText textView = (EditText) findViewById(R.id.note_activity_note); String shareText; if (textView != null && titleView != null) { shareText = titleView.getText().toString() + "\n\n" + textView.getText().toString(); } else { shareText = ""; } mShareIntent.putExtra(Intent.EXTRA_TEXT, shareText.trim()); } /** * An item on actionbar is selected. Dispatch appropriate action. */ @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle presses on the action bar items switch (item.getItemId()) { case R.id.action_save_note: doSave(); return true; case R.id.action_color: ColorDialogFragment cdf = new ColorDialogFragment(mBackgroundColor); cdf.show(getFragmentManager(), "ColorDialogFragment"); return true; case R.id.action_archive: doArchive(); return true; case R.id.action_note_delete: doDelete(); return true; case R.id.action_unarchive: doUnarchive(); return true; case R.id.action_restore: doRestore(); return true; case android.R.id.home: onBackPressed(); return true; default: return super.onOptionsItemSelected(item); } } /** * Save old or new note to database */ public void saveNote() { final DatabaseHandler handler = SealnoteApplication.getDatabase(); final String title = mTitleView.getText().toString(); final String text = mTextView.getText().toString(); if (title.equals("") && text.equals("")) { Toast.makeText(this, getResources().getString(R.string.empty_note), Toast.LENGTH_SHORT).show(); return; } final boolean noteContentChanged = title.equals(mNote.getTitle()) && text.equals(mNote.getNote()); final boolean onlyBackgroundChanged = (noteContentChanged && mBackgroundColor != mNote.getColor()); if (mNote == null) { // this is a new note mNote = new Note(); } else if (mAutoSaveEnabled && noteContentChanged && mBackgroundColor == mNote.getColor()) { // Also avoid unnecessarily updating the edit timestamp of note Log.d(TAG, "Note didn't change. No need to autosave"); return; } mNote.setTitle(title); mNote.setNote(text); mNote.setColor(mBackgroundColor); if (mNote.getId() == -1) { mNote.setPosition(-1); int newNoteId = (int) handler.addNote(mNote); mNote.setId(newNoteId); } else { // don't update timestamp when only background has changed handler.updateNote(mNote, !onlyBackgroundChanged); } } /** * Delete current note */ public void doDelete() { final DatabaseHandler handler = SealnoteApplication.getDatabase(); handler.trashNote(mNote.getId(), true); mNote = null; Toast.makeText(this, getResources().getString(R.string.note_deleted), Toast.LENGTH_SHORT).show(); // to disable saving when activity is finished when its // done in onPause() mAutoSaveEnabled = false; finish(); } /** * Un-archive a note */ public void doUnarchive() { final DatabaseHandler handler = SealnoteApplication.getDatabase(); handler.archiveNote(mNote.getId(), false); mNote = null; Toast.makeText(this, getResources().getString(R.string.note_unarchived), Toast.LENGTH_SHORT).show(); // to disable saving when activity is finished when its // done in onPause() mAutoSaveEnabled = false; finish(); } /** * Archive current note */ public void doArchive() { final DatabaseHandler handler = SealnoteApplication.getDatabase(); handler.archiveNote(mNote.getId(), true); mNote = null; Toast.makeText(this, getResources().getString(R.string.note_archived), Toast.LENGTH_SHORT).show(); // to disable saving when activity is finished when its // done in onPause() mAutoSaveEnabled = false; finish(); } /** * Restores note from trash */ public void doRestore() { final DatabaseHandler handler = SealnoteApplication.getDatabase(); handler.trashNote(mNote.getId(), false); mNote = null; Toast.makeText(this, getResources().getString(R.string.note_restored), Toast.LENGTH_SHORT).show(); // to disable saving when activity is finished when its // done in onPause() mAutoSaveEnabled = false; finish(); } /** * Called when save action is invoked by click */ public void doSave() { if (mSaveButtonClicked) return; else mSaveButtonClicked = true; //FIXME: Hack. Avoids double saving saveNote(); Toast.makeText(this, getResources().getString(R.string.note_saved), Toast.LENGTH_SHORT).show(); finish(); } /** * Callback used when color is changed using ColorDialogFragment * * @param color New background color to use */ public void onColorChanged(int color) { mBackgroundColor = color; if (color == -1) { return; } View view = findViewById(R.id.note_activity_title).getRootView(); view.setBackgroundColor(Misc.getColorForCode(this, color)); } /** * Asynchronous Task to load note */ private class NoteLoadTask extends AsyncTask<Integer, Void, Note> { ProgressDialog mProgressDialog; /** * Before task starts, create and show a progress dialog */ @Override protected void onPreExecute() { super.onPreExecute(); mProgressDialog = new ProgressDialog(NoteActivity.this); mProgressDialog.setMessage("Loading"); mProgressDialog.setIndeterminate(true); mProgressDialog.show(); } /** * Fetch note from database in background */ @Override protected Note doInBackground(Integer... integers) { DatabaseHandler db = SealnoteApplication.getDatabase(); return db.getNote(integers[0]); } /** * Initialize the views and show data on it */ @Override protected void onPostExecute(Note note) { super.onPostExecute(note); mProgressDialog.dismiss(); init(false); loadNote(note); mLoadingNote = false; } } }
package org.csveed.row; import static junit.framework.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import java.io.IOException; import java.io.Reader; import java.io.StringReader; import java.util.List; import org.csveed.api.Header; import org.csveed.api.Row; import org.csveed.common.Column; import org.csveed.report.CsvException; import org.csveed.report.RowReport; import org.junit.Test; public class RowReaderTest { @Test public void emptyLines() { Reader reader = new StringReader( "\n"+ "\n"+ "\n"+ "alpha;beta;gamma\n"+ "\"row 1, cell 1\";\"row 1, cell 2\";\"row 1, cell 3\"\n"+ "\n"+ "\"row 1, cell 1\";\"row 1, cell 2\";\"row 1, cell 3\"" ); RowReaderImpl lineReader = new RowReaderImpl(reader); assertEquals(2, lineReader.readRows().size()); } @Test public void doNotSkipEmptyLines() { Reader reader = new StringReader( "alpha\n"+ "\n"+ "word\n"+ "\n"+ "\n" ); RowReaderImpl lineReader = new RowReaderImpl(reader, new RowReaderInstructionsImpl() .skipEmptyLines(false) ); assertEquals(5, lineReader.readRows().size()); } @Test(expected = CsvException.class) public void getColumnIndexAt0() { Reader reader = new StringReader( "alpha;beta;gamma" ); RowReaderImpl rowReader = new RowReaderImpl(reader); HeaderImpl header = rowReader.getHeader(); assertEquals("alpha", header.getName(0)); } @Test public void commentLine() { Reader reader = new StringReader( "# lots of text\n"+ "# bla...\n"+ "# more bla...\n"+ "alpha;beta;gamma\n"+ "\"row 1, cell 1\";\"row 1, cell 2\";\"row 1, cell 3\"\n"+ "# this line must be ignored!\n"+ "\"row 1, cell 1\";\"row 1, cell 2\";\"row 1, cell 3\"" ); RowReaderImpl rowReader = new RowReaderImpl(reader); assertEquals(2, rowReader.readRows().size()); HeaderImpl header = rowReader.getHeader(); assertEquals("alpha", header.getName(1)); } @Test(expected = CsvException.class) public void dissimilarNumberOfColumns() { Reader reader = new StringReader( "\"row 1, cell 1\";\"row 1, cell 2\";\"row 1, cell 3\"\n"+ "\"row 2, cell 1\";\"row 2, cell 2\";\"row 2, cell 3\"\n"+ "\"row 3, cell 1\";\"row 3, cell 2\"" ); RowReaderImpl lineReader = new RowReaderImpl(reader); lineReader.readRows(); } @Test public void readUnmapped() { Reader reader = new StringReader( "alpha;beta;gamma\n"+ "\"row 1, cell 1\";\"row 1, cell 2\";\"row 1, cell 3\"\n"+ "\"row 2, cell 1\";\"row 2, cell 2\";\"row 2, cell 3\"\n"+ "\"row 3, cell 1\";\"row 3, cell 2\";\"row 3, cell 3\"" ); RowReaderImpl lineReader = new RowReaderImpl(reader); List<Row> rows = lineReader.readRows(); assertEquals(3, rows.size()); } @Test public void nonContentBeforeLines() { Reader reader = new StringReader( "# line 1\n"+ "# line 2\n"+ "# line 3\n"+ "alpha;beta;gamma\n"+ "\"row 1, cell 1\";\"row 1, cell 2\";\"row 1, cell 3\"\n"+ "\"row 2, cell 1\";\"row 2, cell 2\";\"row 2, cell 3\"\n" ); RowReaderImpl lineReader = new RowReaderImpl( reader, new RowReaderInstructionsImpl() .setStartRow(4) .setUseHeader(true) ); List<Row> rows = lineReader.readRows(); assertEquals(2, rows.size()); } @Test public void roughRide() throws IOException { Reader reader = new StringReader("\"alpha\";\"\";;\"beta\";gamma;\"een \"\"echte\"\" test\";\"1\n2\n3\n\"\"regels\"\"\""); RowReaderImpl lineReader = new RowReaderImpl(reader); Line cells = lineReader.readBareLine(); assertEquals(7, cells.size()); assertEquals("alpha", cells.get(0)); assertEquals("", cells.get(1)); assertEquals("", cells.get(2)); assertEquals("beta", cells.get(3)); assertEquals("gamma", cells.get(4)); assertEquals("een \"echte\" test", cells.get(5)); assertEquals("1\n2\n3\n\"regels\"", cells.get(6)); } @Test public void doubleQuotesAsEscape() throws IOException { Reader reader = new StringReader("\"\"\"very literal\"\"\";\"a\"\"b\"\"c\"\n\"abc\";\"first this, \"\"then that\"\"\""); RowReaderImpl lineReader = new RowReaderImpl( reader, new RowReaderInstructionsImpl() .setUseHeader(false) ); checkEscapedStrings(lineReader.readRows()); } @Test public void backSlashesAsEscape() throws IOException { Reader reader = new StringReader("\"\\\"very literal\\\"\";\"a\\\"b\\\"c\"\n\"abc\";\"first this, \\\"then that\\\"\""); RowReaderImpl lineReader = new RowReaderImpl( reader, new RowReaderInstructionsImpl() .setUseHeader(false) .setEscape('\\') ); checkEscapedStrings(lineReader.readRows()); } private void checkEscapedStrings(List<Row> lines) { Row row = lines.get(0); assertEquals("\"very literal\"", row.get(0)); assertEquals("a\"b\"c", row.get(1)); row = lines.get(1); assertEquals("abc", row.get(0)); assertEquals("first this, \"then that\"", row.get(1)); } @Test public void readAllLines() throws IOException { Reader reader = new StringReader(";;;\n;;;\n;;;\n"); RowReaderImpl lineReader = new RowReaderImpl( reader, new RowReaderInstructionsImpl() .setUseHeader(false) ); List<Row> allLines = lineReader.readRows(); assertEquals(3, allLines.size()); } @Test public void allNumbers() throws IOException { Reader reader = new StringReader("17.51;23.19;-100.23;"); RowReaderImpl lineReader = new RowReaderImpl(reader); Line row = lineReader.readBareLine(); assertEquals(4, row.size()); assertEquals("17.51", row.get(0)); assertEquals("23.19", row.get(1)); assertEquals("-100.23", row.get(2)); assertEquals("", row.get(3)); } @Test public void spacesBeforeAndAfter() { Reader reader = new StringReader(" \"alpha\" ; \"beta\" ; \"gamma\" "); RowReaderImpl lineReader = new RowReaderImpl(reader); Line row = lineReader.readBareLine(); assertEquals(3, row.size()); assertEquals("alpha", row.get(0)); assertEquals("beta", row.get(1)); assertEquals("gamma", row.get(2)); } @Test public void spaceWithoutQuotesFields() { Reader reader = new StringReader(" alpha one ; beta ; gamma "); RowReaderImpl lineReader = new RowReaderImpl(reader); Line row = lineReader.readBareLine(); assertEquals(3, row.size()); assertEquals("alpha one", row.get(0)); assertEquals("beta", row.get(1)); assertEquals("gamma", row.get(2)); } @Test public void reportSimple() { Reader reader = new StringReader("17.51;23.19;-100.23"); RowReaderImpl lineReader = new RowReaderImpl(reader); Line row = lineReader.readBareLine(); RowReport report = row.reportOnColumn(new Column(3)); assertEquals("17.51;23.19;-100.23[EOF]", report.getPrintableLines().get(0)); assertEquals(" ^ } @Test public void reportEscapingAndQuotes() { Reader reader = new StringReader("\"alpha\";\"\";;\"b\te\tt\ta\";gamma;\"een \"\"echte\"\" test\";\"1\n2\n3\n\"\"regels\"\"\""); RowReaderImpl lineReader = new RowReaderImpl(reader); Line row = lineReader.readBareLine(); RowReport report = row.reportOnColumn(new Column(4)); assertEquals("\"alpha\";\"\";;\"b\\te\\tt\\ta\";gamma;\"een \"\"echte\"\" test\";\"1\\n2\\n3\\n\"\"regels\"\"\"[EOF]", report.getPrintableLines().get(0)); assertEquals(" ^ report = row.reportOnColumn(new Column(3)); assertEquals(" ^ ", report.getPrintableLines().get(1)); } @Test public void readHeader() { Reader reader = new StringReader("alpha;beta;gamma"); RowReader rowReader = new RowReaderImpl(reader); HeaderImpl header = rowReader.readHeader(); assertNotNull(header); assertEquals(3, header.size()); } @Test public void readHeaderSecondLine() { Reader reader = new StringReader("alpha;beta;gamma\nalpha2;beta2"); RowReader rowReader = new RowReaderImpl( reader, new RowReaderInstructionsImpl() .setStartRow(2) ); HeaderImpl header = rowReader.readHeader(); assertNotNull(header); assertEquals(2, header.size()); } @Test public void readHeaderWithoutUseHeader() { Reader reader = new StringReader("alpha;beta;gamma"); RowReader rowReader = new RowReaderImpl( reader, new RowReaderInstructionsImpl() .setUseHeader(false) ); Header header = rowReader.readHeader(); assertNotNull(header); assertEquals(3, header.size()); } }
package com.sharefile.api.https; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.ProtocolException; import java.net.URL; import java.net.URLConnection; import java.util.List; import javax.net.ssl.HttpsURLConnection; import org.apache.http.NameValuePair; import android.util.Base64; import com.sharefile.api.V3Error; import com.sharefile.api.authentication.SFOAuth2Token; import com.sharefile.api.constants.SFKeywords; import com.sharefile.api.enumerations.SFHttpMethod; import com.sharefile.api.enumerations.SFProvider; import com.sharefile.api.utils.SFLog; import com.sharefile.api.utils.Utils; public class SFHttpsCaller { private static final String TAG = "-SFHttpCaller"; private static final String NO_AUTH_CHALLENGES = "No authentication challenges found"; private static final String OUT_OF_MEMORY = "memory"; //private static CookieManager m_cookieManager = null; public static void setBasicAuth(URLConnection conn,String username,String password) { String combinepass = username +SFKeywords.COLON + password; String basicAuth = "Basic " + new String(Base64.encode(combinepass.getBytes(),Base64.NO_WRAP )); conn.setRequestProperty ("Authorization", basicAuth); } public static void postBody(URLConnection conn, String body) throws IOException { OutputStream os = conn.getOutputStream(); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, SFKeywords.UTF_8)); writer.write(body); writer.flush(); writer.close(); os.close(); } public static URLConnection getURLConnection(URL url) throws IOException { //trustAll(); return url.openConnection(); } /** grant_type=authorization_code&code=CvJ4LMgMDHuZGLXgJgJdDYR17Hd3b5&client_id=3fTJB2mjJ7KaNflPWJ8MylHos&client_secret=Y8LzHuYvxjxc8FE7s1HNe96s0xGVM4 */ public static String getBodyForWebLogin(List<NameValuePair> params) throws UnsupportedEncodingException { StringBuilder result = new StringBuilder(); boolean first = true; for (NameValuePair pair : params) { if (first) { first = false; } else { result.append(SFKeywords.CHAR_AMPERSAND); } result.append(pair.getName()); result.append(SFKeywords.EQUALS); result.append(pair.getValue()); } return result.toString(); } public static void setAcceptLanguage(URLConnection conn) { conn.setRequestProperty("Accept-Language", Utils.getAcceptLanguageString()); } private static void setRequestMethod(URLConnection conn, String method) throws ProtocolException { if(conn instanceof HttpsURLConnection) { ((HttpsURLConnection) conn).setRequestMethod(method); } else if(conn instanceof HttpURLConnection) { ((HttpURLConnection) conn).setRequestMethod(method); } } public static void setPostMethod(URLConnection conn) throws ProtocolException { setRequestMethod(conn,SFHttpMethod.POST.toString()); conn.setDoInput(true); conn.setDoOutput(true); } public static void setMethod(URLConnection conn,String methodName) throws ProtocolException { if(methodName.equalsIgnoreCase(SFHttpMethod.POST.toString())) { setPostMethod(conn); } else if(methodName.equalsIgnoreCase(SFHttpMethod.DELETE.toString())) { setDeleteMethod(conn); } else if(methodName.equalsIgnoreCase(SFHttpMethod.GET.toString())) { setRequestMethod(conn, methodName); } } private static void setDeleteMethod(URLConnection conn) throws ProtocolException { setRequestMethod(conn,SFHttpMethod.DELETE.toString()); conn.setDoInput(true); } public static int catchIfAuthException(IOException e) throws IOException { String errMessage = e.getLocalizedMessage(); if(errMessage!=null) { if(errMessage.contains(NO_AUTH_CHALLENGES)) { return HttpsURLConnection.HTTP_UNAUTHORIZED; } else { throw e; } } else { throw e; } //return 0; } public static int catchIfOutOfMemoryException(Exception e,int origcode) { String errMessage = e.getLocalizedMessage(); if(errMessage!=null) { if(errMessage.contains(OUT_OF_MEMORY)) { SFLog.d2(TAG, "Gracefull catching out of memmory"); return 500; } } return origcode; } /** * The http functions sometimes respond with 401 error or sometimes throw and exception * <p> depending on what the server returns. So we need a generic way to get the error code. * @throws IOException * */ public static synchronized int safeGetResponseCode(URLConnection conn) throws Exception { int httpErrorCode = HttpsURLConnection.HTTP_INTERNAL_ERROR; try { if(conn instanceof HttpsURLConnection) { httpErrorCode = ((HttpsURLConnection) conn).getResponseCode(); } else { httpErrorCode = ((HttpURLConnection) conn).getResponseCode(); } } catch (IOException e) //on wrong creds this throws exeption { httpErrorCode = catchIfAuthException(e); } SFLog.d2(TAG,"ERR_CODE: " + httpErrorCode); return httpErrorCode; } /** * if responsecode != HTTP_OK * * <p> handle it appropriately by trying to read the error stream and constructing the * <p> error message. Auth errors may require reading the credentials and retrying. * * if responsecode == HTTP_OK then read the cookies. * * <p>This function always returns a valid V3Error in any non-success case or NULL if HTTP_OK * @throws IOException */ public static V3Error handleErrorAndCookies(URLConnection conn, int httpErrorCode,URL url,SFCookieManager cookieManager) throws IOException { V3Error v3Error = null; if(httpErrorCode == HttpsURLConnection.HTTP_OK || httpErrorCode == HttpsURLConnection.HTTP_NO_CONTENT) { getAndStoreCookies(conn,url,cookieManager); return v3Error; } try { String inputLine = readErrorResponse(conn); SFLog.d2(TAG, "ERR PAGE: %s" , inputLine); v3Error = new V3Error(httpErrorCode,inputLine); } catch (Exception e) { //try constructing the error from the exception. v3Error = new V3Error(httpErrorCode, e.getLocalizedMessage()); } return v3Error; } public static synchronized void getAndStoreCookies(URLConnection conn, URL url,SFCookieManager cookieManager) throws IOException { if(cookieManager!=null) { cookieManager.readCookiesFromConnection(conn); } } public static String readResponse(URLConnection conn) throws IOException { StringBuilder sb = new StringBuilder(); InputStream is = conn.getInputStream(); BufferedReader urlstream = new BufferedReader(new InputStreamReader(is)); String inputLine; try { while ((inputLine = urlstream.readLine()) != null) { sb.append(inputLine); } } catch (OutOfMemoryError e) { SFLog.d2(TAG, "Error: %s" , e.getLocalizedMessage()); throw new IOException("Out of memory"); } String response = sb.toString(); SFLog.d2(TAG, "SUCCESS RESPONSE size: %d" , response.length()); SFLog.d2(TAG, "SUCCESS RESPONSE: %s" , response.toString()); urlstream.close(); return response; } public static String readErrorResponse(URLConnection conn) throws IOException { StringBuilder sb = new StringBuilder(); BufferedReader urlstream = null; //type cast correctly. if(conn instanceof HttpsURLConnection) { urlstream = new BufferedReader(new InputStreamReader(((HttpsURLConnection) conn).getErrorStream())); } else if(conn instanceof HttpURLConnection) { urlstream = new BufferedReader(new InputStreamReader(((HttpURLConnection) conn).getErrorStream())); } else { return ""; } String inputLine; while ((inputLine = urlstream.readLine()) != null) { sb.append(inputLine); } SFLog.d2(TAG, "ERROR RESPONSE: %s",sb.toString()); urlstream.close(); return sb.toString(); } public static void disconnect(URLConnection conn) { if(conn!=null) { if(conn instanceof HttpsURLConnection) { ((HttpsURLConnection) conn).disconnect(); } else if(conn instanceof HttpURLConnection) { ((HttpURLConnection) conn).disconnect(); } } } public static void addBearerAuthorizationHeader(URLConnection connection,SFOAuth2Token token) { connection.addRequestProperty("Authorization",String.format("Bearer %s", token.getAccessToken())); } /** * TODO: This needs a major revamp. We need User specific cookies to be set and CIFS/SharePoint specific authentication to be handled We need a separate auth manager here to handle the setting of correct auth header based on the provider type and well as the user. * @throws IOException */ public static void addAuthenticationHeader(URLConnection connection,SFOAuth2Token token,String userName,String password, SFCookieManager cookieManager) throws IOException { String path = connection.getURL().getPath(); if(cookieManager!=null) { cookieManager.setCookies(connection); } switch(SFProvider.getProviderTypeFromString(path)) { case PROVIDER_TYPE_SF: SFHttpsCaller.addBearerAuthorizationHeader(connection, token); break; default: if(userName!=null && password!=null) { setBasicAuth(connection, userName, password); } break; } } }
package uk.co.jeeni.siren; import org.codehaus.jackson.map.ObjectMapper; import org.junit.Test; public class SwiberTest { @Test public void creatKevinSwiberExampleUsingBaseDomainTest(){ // Create the parent 'Order' entity final Entity entity = new Entity(new String[] {"order"}, "http://api.x.io/", "/orders/42"); // Create parent entity properties entity.addProperty("orderNumber", 42) .addProperty("itemCount", 3) .addProperty("status", "pending") // Add Sub entity for Collection .addSubEntity(new SubEntity(new String[] {"items", "collection"}, "/orders/42/items", new String[] {"/rels/order-items"})); // Add the 'next' and 'previous' links entity.addLink(new Link(new String[] {"previous"}, "/orders/41")) .addLink(new Link(new String[] {"next"}, "/orders/43")); // THIS ENTITY DOES NOT KNOW ABOUT THE PARENT DOMAIN /* The CustomerInfo Entity */ SubEntity customerInfo = new SubEntity(new String[] {"info", "customer"}, new String[] {"rels/customer"}); // Add Customer properties customerInfo.addProperty("customerId", "pj123") .addProperty("name", "Peter Joseph") // Add 'self' link for Customer .addLink(new Link("customers/pj123")); // Add Sub entity for Customer entity.addSubEntity(customerInfo); // Create action link entity and fields ActionLink actionLink = new ActionLink("add-item", "Add Item", "orders/42/items", HttpMethod.POST); actionLink.setFormType("application/x-www-form-urlencoded") .addDataField(new DataField("orderNumber", InputTypes.HIDDEN, "42")) .addDataField(new DataField("productCode", InputTypes.TEXT)) .addDataField(new DataField("quantity", InputTypes.NUMBER)); // Add action to parent entity. entity.addAction(actionLink); // Build and check all links entity.buildUrls(); // Output the JSON String ObjectMapper mapper = new ObjectMapper(); try { System.out.println(mapper.writeValueAsString(entity)); } catch (Exception e) { e.printStackTrace(); } } @Test public void creatKevinSwiberExampleTest(){ // Create the parent 'Order' entity final Entity entity = new Entity(new String[] {"order"}, "http://api.x.io/orders/42"); // Create parent entity properties entity.addProperty("orderNumber", 42) .addProperty("itemCount", 3) .addProperty("status", "pending") // Add Sub entity for Collection .addSubEntity(new SubEntity(new String[] {"items", "collection"}, "http: // Add Sub entity for Customer SubEntity customerInfo = new SubEntity(new String[] {"info", "customer"}, new String[] {"http://x.io/rels/customer"}); // Add Customer properties customerInfo.addProperty("customerId", "pj123") .addProperty("name", "Peter Joseph") // Add 'self' link for Customer .addLink(new Link("http://api.x.io/customers/pj123")); // Add Sub entity for Customer entity.addSubEntity(customerInfo); // Create action link entity and fields ActionLink action = new ActionLink("add-item", "Add Item", "http://api.x.io/orders/42/items", HttpMethod.POST); action.setFormType("application/x-www-form-urlencoded") .addDataField(new DataField("orderNumber", InputTypes.HIDDEN, "42")) .addDataField(new DataField("productCode", InputTypes.TEXT)) .addDataField(new DataField("quantity", InputTypes.NUMBER)); // Add action to parent entity. entity.addAction(action); // Add the 'next' and 'previous' links entity.addLink(new Link(new String[] {"previous"}, "http://api.x.io/orders/41")) .addLink(new Link(new String[] {"next"}, "http://api.x.io/orders/43")); // Build and check all links entity.buildUrls(); // Output the JSON String ObjectMapper mapper = new ObjectMapper(); try { System.out.println(mapper.writeValueAsString(entity)); } catch (Exception e) { e.printStackTrace(); } } }
package micromod; public class Macro { private Scale scale; private int rootKey, speed; private Pattern notes; public Macro( String scale, String rootKey, Pattern notes, int speed ) { this.scale = new Scale( scale != null ? scale : Scale.CHROMATIC ); this.rootKey = Note.parseKey( rootKey != null ? rootKey : "C-2" ); this.notes = new Pattern( 1, notes ); this.speed = ( speed > 0 ) ? speed : 6; } /* Expand macro into the specified pattern until end or an instrument is set. */ public int expand( Module module, int patternIdx, int channelIdx, int rowIdx ) { return expand( module, new int[] { patternIdx }, channelIdx, rowIdx ); } /* Treat the specified patterns as a single large pattern and expand macro until the end or an instrument is set. The final row index is returned. */ public int expand( Module module, int[] patterns, int channelIdx, int rowIdx ) { int macroRowIdx = 0, srcKey = rootKey, dstKey = rootKey, distance = 0, amplitude = 64; int volume = 0, fineTune = 0, period = 0, portaPeriod = 0, portaSpeed = 0; int sampleOffset = 0, sampleLength = 0, delta; Note note = new Note(); while( macroRowIdx < Pattern.NUM_ROWS ) { int patternsIdx = rowIdx / Pattern.NUM_ROWS; if( patternsIdx >= patterns.length ) { break; } Pattern pattern = module.getPattern( patterns[ patternsIdx ] ); pattern.getNote( rowIdx % Pattern.NUM_ROWS, channelIdx, note ); if( note.instrument > 0 ) { break; } if( note.key > 0 ) { distance = scale.getDistance( rootKey, note.key ); } int effect = note.effect; int param = note.parameter; notes.getNote( macroRowIdx++, 0, note ); if( effect > 0 ) { if( effect == 0xC ) { amplitude = param; } if( effect != 0xC || param == 0 ) { /* Ensure C00 is passed through to empty notes. */ note.effect = effect; note.parameter = param; } } if( note.instrument > 0 ) { Instrument instrument = module.getInstrument( note.instrument ); volume = instrument.getVolume() * 64; fineTune = instrument.getFineTune(); sampleLength = instrument.getLoopStart() + instrument.getLoopLength(); if( amplitude < 64 && note.effect != 0xC ) { /* Setting an instrument sets the volume. */ note.effect = 0xC; note.parameter = instrument.getVolume(); } } if( note.effect == 0xE && ( note.parameter & 0xF0 ) == 0x50 ) { fineTune = ( note.parameter & 0x7 ) - ( note.parameter & 0x8 ); } if( note.key > 0 ) { srcKey = note.key; dstKey = scale.transpose( srcKey, distance ); note.key = dstKey; portaPeriod = Note.keyToPeriod( note.key, fineTune ); if( note.effect != 0x3 && note.effect != 0x5 ) { period = portaPeriod; } if( note.effect != 0x9 ) { sampleOffset = 0; } } if( volume < 0 ) { volume = 0; } if( volume > 4096 ) { volume = 4096; } if( period < 7 ) { period = 6848; } if( note.effect == 0 && note.parameter != 0 ) { /* Arpeggio.*/ delta = scale.getDistance( srcKey, srcKey + ( ( note.parameter >> 4 ) & 0xF ) ); delta = scale.transpose( dstKey, delta ) - dstKey; if( delta < 0 ) delta = 0; if( delta > 15 ) delta = ( delta - 3 ) % 12 + 3; note.parameter = ( delta << 4 ) + ( note.parameter & 0xF ); delta = scale.getDistance( srcKey, srcKey + ( note.parameter & 0xF ) ); delta = scale.transpose( dstKey, delta ) - dstKey; if( delta < 0 ) delta = 0; if( delta > 15 ) delta = ( delta - 3 ) % 12 + 3; note.parameter = ( note.parameter & 0xF0 ) + delta; } else if( note.effect == 0x1 || ( note.effect == 0xE && ( note.parameter & 0xF0 ) == 0x10 ) ) { if( note.effect == 0x1 ) { /* Portamento up. */ if( note.parameter > 0xF0 && note.parameter < 0xFE ) { delta = period - note.transpose( period, note.parameter & 0xF ); } else { delta = note.transpose( note.parameter * ( speed - 1 ), dstKey - srcKey ); } if( speed > 1 && delta >= speed ) { note.parameter = divide( delta, speed - 1, 0xFF ); period = period - note.parameter * ( speed - 1 ); } else { note.effect = 0xE; note.parameter = 0x10 + ( delta & 0xF ); period = period - ( delta & 0xF ); } } else { /* Fine portamento up. */ note.parameter = 0x10 + transpose( note.parameter & 0xF, dstKey - srcKey, 0xF ); period = period - ( note.parameter & 0xF ); } } else if( note.effect == 0x2 || ( note.effect == 0xE && ( note.parameter & 0xF0 ) == 0x20 ) ) { if( note.effect == 0x2 ) { /* Portamento down. */ if( note.parameter > 0xF0 && note.parameter < 0xFE ) { delta = note.transpose( period, -( note.parameter & 0xF ) ) - period; } else { delta = note.transpose( note.parameter * ( speed - 1 ), dstKey - srcKey ); } if( speed > 1 && delta >= speed ) { note.parameter = divide( delta, speed - 1, 0xFF ); period = period + note.parameter * ( speed - 1 ); } else { note.effect = 0xE; note.parameter = 0x20 + ( delta & 0xF ); period = period + ( delta & 0xF ); } } else { /* Fine portamento down. */ note.parameter = 0x20 + transpose( note.parameter & 0xF, dstKey - srcKey, 0xF ); period = period + ( note.parameter & 0xF ); } } else if( note.effect == 0x3 || note.effect == 0x5 ) { /* Tone portamento. */ if( note.effect == 0x3 && note.parameter > 0 ) { if( note.parameter > 0xF0 && note.parameter < 0xFE ) { if( portaPeriod < period ) { delta = period - note.transpose( period, note.parameter & 0xF ); } else { delta = note.transpose( period, -( note.parameter & 0xF ) ) - period; } note.parameter = divide( delta, ( speed > 1 ) ? ( speed - 1 ) : 1, 0xFF ); } else { note.parameter = transpose( note.parameter & 0xFF, dstKey - srcKey, 0xFF ); } if( note.parameter < 1 ) { note.parameter = 1; } portaSpeed = note.parameter; } if( period < portaPeriod ) { period = period + portaSpeed * ( speed - 1 ); if( period > portaPeriod ) { period = portaPeriod; } } else { period = period - portaSpeed * ( speed - 1 ); if( period < portaPeriod ) { period = portaPeriod; } } } else if( note.effect == 0x9 ) { /* Set sample offset. */ if( note.parameter >= 0xF0 ) { sampleOffset = sampleOffset + sampleLength * ( note.parameter & 0xF ) / 16; note.parameter = ( ( sampleOffset + ( sampleOffset & 0x80 ) ) >> 8 ) & 0xFF; } else { sampleOffset = ( note.parameter & 0xFF ) << 8; } } if( note.effect == 0x4 || note.effect == 0x6 ) { /* Vibrato. */ note.parameter = ( note.parameter & 0xF0 ) + transpose( note.parameter & 0xF, dstKey - srcKey, 0xF ); } else if( note.effect == 0x7 ) { /* Tremolo. */ note.parameter = ( note.parameter & 0xF0 ) + divide( ( note.parameter & 0xF ) * amplitude, 64, 0xF ); } if( note.effect == 0x5 || note.effect == 0x6 || note.effect == 0xA ) { /* Volume slide. */ if( ( note.parameter & 0xF ) == 0xF ) { delta = ( note.parameter & 0xF0 ) >> 4; delta = sqrt( volume << 12 ) + 1024 / ( 16 - delta ); delta = ( ( delta * delta ) >> 12 ) - volume; } else if( ( note.parameter & 0xF0 ) == 0xF0 ) { delta = note.parameter & 0xF; delta = sqrt( volume << 12 ) - 1024 / ( 16 - delta ); if( delta < 0 ) { delta = 0; } delta = ( ( delta * delta ) >> 12 ) - volume; } else { delta = divide( ( ( note.parameter & 0xF0 ) >> 4 ) * ( speed - 1 ) * 64 * amplitude, 64, 32768 ); delta = delta - divide( ( note.parameter & 0xF ) * ( speed - 1 ) * 64 * amplitude, 64, 32768 ); } note.parameter = 0; if( speed > 1 ) { if( delta > 0 ) { note.parameter = divide( delta, ( speed - 1 ) * 64, 15 ) << 4; } else { note.parameter = divide( -delta, ( speed - 1 ) * 64, 15 ); } } if( note.parameter == 0 && delta != 0 ) { volume += delta; note.effect = 0xC; note.parameter = divide( volume, 64, 64 ); } else { volume = volume + ( ( note.parameter & 0xF0 ) >> 4 ) * ( speed - 1 ) * 64; volume = volume - ( note.parameter & 0xF ) * ( speed - 1 ) * 64; } } else if( note.effect == 0xC ) { /* Set volume. */ note.parameter = divide( note.parameter * amplitude, 64, 64 ); volume = note.parameter * 64; } else if( note.effect == 0xE && ( note.parameter & 0xF0 ) == 0xA0 ) { /* Fine volume slide up. */ note.parameter = 0xA0 + divide( ( note.parameter & 0xF ) * amplitude, 64, 0xF ); volume = volume + ( note.parameter & 0xF ) * 64; } else if( note.effect == 0xE && ( note.parameter & 0xF0 ) == 0xB0 ) { /* Fine volume slide down. */ note.parameter = 0xB0 + divide( ( note.parameter & 0xF ) * amplitude, 64, 0xF ); volume = volume - ( note.parameter & 0xF ) * 64; } pattern.setNote( ( rowIdx++ ) % pattern.NUM_ROWS, channelIdx, note ); } return rowIdx; } private static int transpose( int period, int semitones, int maximum ) { period = Note.transpose( period, semitones ); return period < maximum ? period : maximum; } private static int divide( int dividend, int divisor, int maximum ) { /* Divide positive integers with rounding and clipping. */ int quotient = 0; if( dividend > 0 ) { quotient = ( dividend << 1 ) / divisor; quotient = ( quotient >> 1 ) + ( quotient & 1 ); if( quotient > maximum ) { quotient = maximum; } } return quotient; } private static int sqrt( int y ) { int x = 4096; for( int n = 0; n < 12; n++ ) { x = ( x + y / x ); x = ( x >> 1 ) + ( x & 1 ); } return x; } }
package uk.co.plogic.gwt.lib.utils; import java.util.logging.Logger; import com.google.gwt.i18n.client.NumberFormat; public class StringUtils { static final Logger logger = Logger.getLogger("StringUtils"); public StringUtils() {} public static boolean isAlphaNumericWithHyphensUnderscores(String testString) { String t2 = testString.replace("-", "").replace("_", ""); for(char c : t2.toCharArray()) { if( ! Character.isLetterOrDigit(c) ) return false; } return true; } /** * The template contains placeholders in the format {{field_name}} where 'field_name' * is a key in the AttributeDictionary. * * If the corresponding value is a number, formatting for use with NumberFormat can * be specified. e.g. {{number_of|#}} - meaning no decimal places. * * @param htmlTemplate * @param values * @return */ public static String renderHtml(String htmlTemplate, AttributeDictionary values) { if( htmlTemplate == null || values == null ) return null; // find all tags, could be done with regex int currentPos = 0; int tagStart = -1; String html = htmlTemplate; while( (tagStart = htmlTemplate.indexOf("{{", currentPos) ) > 0 ) { int tagEnd = htmlTemplate.indexOf("}}", tagStart); String fullTag = htmlTemplate.substring(tagStart, tagEnd+2); int tagLen = fullTag.length(); int formatPos = -1; String replacement; String fieldName; if( (formatPos = fullTag.indexOf("|")) > 0 ) { String format = fullTag.substring(formatPos+1, tagLen-2); fieldName = fullTag.substring(2, formatPos); NumberFormat numberFormat = NumberFormat.getFormat(format); if( values.get(fieldName) == null ) logger.warning("Field not found:"+fieldName); else if( ! values.isType(AttributeDictionary.DataType.dtDouble, fieldName) ) logger.warning("Not a number for number formatted field:"+fieldName); replacement = numberFormat.format(values.getDouble(fieldName)); logger.finer("Formatted field:"+fieldName+" as "+format); } else { fieldName = fullTag.substring(2, tagLen-2); if( values.isType(AttributeDictionary.DataType.dtDouble, fieldName) ) { // cast to String replacement = ""+values.getDouble(fieldName); logger.finer("field:"+fieldName+" is number and replacement found."); } else if( values.isType(AttributeDictionary.DataType.dtString, fieldName) ) { replacement = values.get(fieldName); logger.finer("field:"+fieldName+" is string and replacement found."); } else { replacement = ""; logger.finer("field:"+fieldName+" no replacement found."); } } //System.out.println("Replacing:"+fullTag+" with:"+replacement); html = html.replace(fullTag, replacement); currentPos=tagEnd+2; } return html; } }
package graphic; import java.awt.Color; import java.awt.EventQueue; import java.awt.Toolkit; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.LineBorder; import javax.swing.JLabel; import javax.swing.SwingConstants; import java.awt.Font; import java.rmi.ServerException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.Locale; import java.util.ResourceBundle; import java.util.Set; import javax.swing.DefaultListModel; import javax.swing.ImageIcon; import javax.swing.JList; import javax.swing.JOptionPane; import javax.swing.JScrollPane; import javax.swing.JTextField; import javax.swing.JButton; import javax.swing.ListSelectionModel; import controllers.Application; import controllers.CurrentProfileController; import controllers.GroupController; import controllers.MyGroupController; import controllers.MyTripController; import controllers.ProfileController; import controllers.TripController; import domain.ControllerNotLoadedException; import domain.InvalidPermissionException; import domain.RequestStatus; import controllers.Session; import domain.SessionNotActiveException; import domain.UserNameAlreadyExistsException; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.awt.event.WindowEvent; import java.awt.Choice; public class Group extends JFrame { private static JPanel panel; private JTextField tFName; private JTextField tFCap; private JTextField tFAdmin; private JButton btnBack; private JTextField tFFAge; private JTextField tFFCity; private CurrentProfileController currentProfile; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { Group frame = new Group(0,null, null,null,null, null,null,true); frame.setVisible(true); frame.pack(); frame.setSize(900, 602); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the Frame * @param choice * @param myTrip * @param trip * @param auxText * @param instance * @param session * @param groupController * @param language */ // choice = 0 creando, choice = 1 viendo el propio, choice = 2 viendo el de otro public Group(final Integer choice, final MyTripController myTrip, final TripController trip, final ArrayList<String> auxText, final Application instance, final Session session, final GroupController groupController, final boolean language){ if(instance != null){ try { currentProfile = instance.getCurrentProfileController(); } catch (SessionNotActiveException e1) { e1.printStackTrace(); } } Locale currentLocale; if(language){ currentLocale = new Locale("en","US"); //$NON-NLS-1$ //$NON-NLS-2$ }else{ currentLocale = new Locale("es","AR"); //$NON-NLS-1$ //$NON-NLS-2$ } final ResourceBundle messages = ResourceBundle.getBundle("MessagesBundle", currentLocale); //$NON-NLS-1$ setTitle("TrekApp"); //$NON-NLS-1$ setBounds(0, 0, 902, 602); setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); panel = new ImagePanel(new ImageIcon("Group.jpg").getImage()); //$NON-NLS-1$ panel.setBackground(new Color(25, 25, 112)); panel.setBorder(new LineBorder(new Color(0, 0, 0), 1, true)); setContentPane(panel); panel.setLayout(null); final JLabel lblGroupName = new JLabel(); lblGroupName.setForeground(Color.BLACK); lblGroupName.setFont(new Font("Tahoma", Font.PLAIN, 19)); //$NON-NLS-1$ lblGroupName.setHorizontalAlignment(SwingConstants.LEFT); lblGroupName.setBounds(200, 58, 173, 34); panel.add(lblGroupName); tFName = new JTextField(); tFName.setFont(new Font("Tahoma", Font.PLAIN, 17)); //$NON-NLS-1$ tFName.setDisabledTextColor(new Color(0, 0, 0)); tFName.setBounds(408, 64, 185, 25); panel.add(tFName); tFName.setColumns(10); final JLabel lblCapacity = new JLabel(); lblCapacity.setFont(new Font("Tahoma", Font.PLAIN, 19)); //$NON-NLS-1$ lblCapacity.setForeground(Color.BLACK); lblCapacity.setBounds(200, 103, 159, 34); panel.add(lblCapacity); tFCap = new JTextField(); tFCap.setForeground(Color.BLACK); tFCap.setDisabledTextColor(new Color(0, 0, 0)); tFCap.setFont(new Font("Tahoma", Font.PLAIN, 17)); //$NON-NLS-1$ tFCap.setHorizontalAlignment(SwingConstants.CENTER); tFCap.setBounds(408, 105, 43, 30); panel.add(tFCap); tFCap.setColumns(10); tFFAge = new JTextField(); tFFCity = new JTextField(); final Object[] fields = { messages.getString("Group.9"), tFFAge, //$NON-NLS-1$ messages.getString("Group.10"), tFFCity //$NON-NLS-1$ }; final Object[] options = {messages.getString("Group.0"),messages.getString("Group.1")}; //$NON-NLS-1$ //$NON-NLS-2$ JButton btnFilters = new JButton(); btnFilters.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { int confirm = JOptionPane.showOptionDialog(null, fields, messages.getString("Group.11"), JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE,null,options,options[1]); //$NON-NLS-1$ if(confirm == JOptionPane.OK_OPTION){ while( (!isIntNumeric(tFFAge.getText()) && !tFFAge.getText().isEmpty())){ JOptionPane.showMessageDialog(null, messages.getString("Group.12"), "ERROR", JOptionPane.ERROR_MESSAGE); //$NON-NLS-1$ //$NON-NLS-2$ confirm = JOptionPane.showOptionDialog(null, fields, messages.getString("Group.11"), JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE,null,options,options[1]); //$NON-NLS-1$ } } } }); btnFilters.setBounds(430, 423, 145, 23); panel.add(btnFilters); final JButton btnTrip = new JButton(); if(choice == 0){ btnTrip.setBounds(430, 386, 145, 23); }else{ btnTrip.setBounds(240, 386, 145, 23); } panel.add(btnTrip); final JLabel lblMembers = new JLabel(); lblMembers.setFont(new Font("Tahoma", Font.PLAIN, 19)); //$NON-NLS-1$ lblMembers.setForeground(Color.BLACK); lblMembers.setHorizontalAlignment(SwingConstants.LEFT); lblMembers.setBounds(200, 208, 203, 34); panel.add(lblMembers); final DefaultListModel members = new DefaultListModel(); HashSet<ProfileController> auxMembers = new HashSet<>(); if(instance != null && groupController != null){ try { auxMembers = groupController.getMembers(); for(ProfileController each : auxMembers){ members.addElement(each.getUserName() + " " + each.getSurname() + " - " + each.getUsername()); //$NON-NLS-1$ //$NON-NLS-2$ } } catch (SessionNotActiveException e1) { e1.printStackTrace(); } catch (ControllerNotLoadedException e1) { e1.printStackTrace(); } } JScrollPane scrollPane = new JScrollPane(); scrollPane.setViewportBorder(null); scrollPane.setBounds(408, 206, 202, 169); panel.add(scrollPane); JList<String> list = new JList<String>(members); scrollPane.setViewportView(list); list.setForeground(Color.BLACK); list.setFont(new Font("Tahoma", Font.PLAIN, 15)); //$NON-NLS-1$ list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); list.setBorder(null); list.setValueIsAdjusting(true); list.setEnabled(false); final Choice requests = new Choice(); requests.setVisible(false); requests.setBounds(233, 457, 200, 30); HashMap<ProfileController, RequestStatus> requestsTrip = null; if(instance != null && choice == 1){ try { requestsTrip = ((MyGroupController)groupController).getMemberRequests(); for (ProfileController key : requestsTrip.keySet()) { requests.add(key.getUserName() + " " + key.getSurname() + " - " + key.getUsername()); //$NON-NLS-1$ //$NON-NLS-2$ } } catch (SessionNotActiveException e1) { e1.printStackTrace(); } catch (ControllerNotLoadedException e1) { e1.printStackTrace(); } } panel.add(requests); final JButton btnReject = new JButton(); final JButton btnAccept = new JButton(); final HashMap<ProfileController, RequestStatus> requestsTripaux = requestsTrip; btnAccept.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { try { ProfileController profile = getKey(requestsTripaux.keySet(),requests.getSelectedIndex()); members.addElement(requests.getSelectedItem()); ((MyGroupController)groupController).addMember(profile); requestsTripaux.remove(profile); } catch (SessionNotActiveException e) { e.printStackTrace(); } catch (ControllerNotLoadedException e) { e.printStackTrace(); } catch (InvalidPermissionException e) { e.printStackTrace(); } requests.remove(requests.getSelectedItem()); if((requests.getItemCount()) < 1){ btnReject.setEnabled(false); btnAccept.setEnabled(false); } } }); btnAccept.setBounds(476, 457, 123, 20); btnAccept.setVisible(false); panel.add(btnAccept); btnReject.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { ProfileController profile = getKey(requestsTripaux.keySet(),requests.getSelectedIndex()); ((MyGroupController)groupController).rejectAMemberRequest(profile); requestsTripaux.remove(profile); } catch (SessionNotActiveException e1) { e1.printStackTrace(); } catch (ControllerNotLoadedException e1) { e1.printStackTrace(); } requests.remove(requests.getSelectedItem()); if((requests.getItemCount()) < 1){ btnReject.setEnabled(false); btnAccept.setEnabled(false); } } }); btnReject.setVisible(false); btnReject.setBounds(637, 457, 123, 20); panel.add(btnReject); final JLabel lblNewRequest = new JLabel(); lblNewRequest.setVisible(false); lblNewRequest.setForeground(Color.WHITE); lblNewRequest.setFont(new Font("Tahoma", Font.PLAIN, 18)); //$NON-NLS-1$ lblNewRequest.setBounds(26, 448, 185, 34); panel.add(lblNewRequest); final JButton btnDelete = new JButton(); btnDelete.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if(instance != null && choice == 1){ try { ((MyGroupController)groupController).deleteGroup(); } catch (SessionNotActiveException e1) { e1.printStackTrace(); } catch (ControllerNotLoadedException e1) { e1.printStackTrace(); } } } }); btnDelete.setBounds(397, 386, 145, 23); panel.add(btnDelete); if(requests.countItems() < 1){ btnAccept.setEnabled(false); btnReject.setEnabled(false); } final JButton btnCalif = new JButton(); btnCalif.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Calif frame = new Calif(instance, session, groupController, language); frame.setVisible(true); frame.pack(); frame.setSize(900, 602); close(); } }); btnCalif.setBounds(69, 257, 250, 23); btnCalif.setVisible(false); panel.add(btnCalif); try { if(groupController != null && groupController.getTripStatus().equals(groupController.getTripStatus().CLOSED)){ btnCalif.setVisible(true); } } catch (SessionNotActiveException e3) { e3.printStackTrace(); } catch (ControllerNotLoadedException e3) { e3.printStackTrace(); } final JButton btnRequestcheck = new JButton(); btnRequestcheck.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { if(choice == 1){ lblNewRequest.setVisible(true); btnAccept.setVisible(true); btnReject.setVisible(true); requests.setVisible(true); } } }); btnRequestcheck.setBounds(552, 386, 150, 23); panel.add(btnRequestcheck); final JLabel lblAdmin = new JLabel(); lblAdmin.setForeground(Color.BLACK); lblAdmin.setFont(new Font("Tahoma", Font.PLAIN, 19)); //$NON-NLS-1$ lblAdmin.setBounds(200, 148, 200, 34); panel.add(lblAdmin); tFAdmin = new JTextField(); tFAdmin.setFont(new Font("Tahoma", Font.PLAIN, 17)); //$NON-NLS-1$ tFAdmin.setBounds(408, 152, 185, 25); panel.add(tFAdmin); tFAdmin.setColumns(10); btnBack = new JButton(); btnBack.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Options frame = new Options(instance, session,language); frame.setVisible(true); frame.pack(); frame.setSize(900, 620); close(); } }); btnBack.setBounds(26, 530, 150, 23); panel.add(btnBack); final JButton btnCreatetrip = new JButton(); btnCreatetrip.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { if(choice == 0){ Integer flag = 0; //flag=1 corresponde a que no hay error //flag=2 no introdujo el nombre del grupo //flag=3 no introdujo la capacidad maxima del viaje planeado //flag=4 no se creo un viaje //flag=5 no introdujo una capacidad correcta //flag=6 no introdujo filtros if(tFName.getText().isEmpty()){ flag = 2; } else if(tFCap.getText().isEmpty()){ flag = 3; }else if(myTrip == null){ flag = 4; }else if(!isIntNumeric(tFCap.getText())){ flag = 5; }else if (isIntNumeric(tFCap.getText()) && Integer.parseInt(tFCap.getText()) < 1){ flag = 5; }else if(tFFAge.getText().trim().isEmpty() || tFFCity.getText().trim().isEmpty()){ flag = 6; }else{ flag = 1; } switch(flag){ case 1: int confirm = JOptionPane.showConfirmDialog(null, messages.getString("Group.22"), messages.getString("Group.23"), JOptionPane.YES_NO_OPTION); //$NON-NLS-1$ //$NON-NLS-2$ if(confirm == JOptionPane.YES_OPTION){ try { MyGroupController group; group = instance.registerGroup(tFName.getText(), currentProfile, Integer.parseInt(tFCap.getText()), Integer.parseInt(tFFAge.getText()), tFFCity.getText()); //$NON-NLS-1$ group.addGroupTrip(myTrip); } catch (SessionNotActiveException e) { e.printStackTrace(); } catch (ControllerNotLoadedException e) { e.printStackTrace(); } catch (InvalidPermissionException e) { e.printStackTrace(); }catch (NumberFormatException e) { e.printStackTrace(); } catch (UserNameAlreadyExistsException e) { e.printStackTrace(); }catch (ServerException e) { e.printStackTrace(); }catch (IllegalArgumentException e){ e.printStackTrace(); } Options frame = new Options(instance, session,language); frame.setVisible(true); frame.pack(); frame.setSize(900, 602); close(); } break; case 2: JOptionPane.showMessageDialog(null, messages.getString("Group.25"), "ERROR", JOptionPane.ERROR_MESSAGE); //$NON-NLS-1$ //$NON-NLS-2$ break; case 3: JOptionPane.showMessageDialog(null, messages.getString("Group.27"), "ERROR", JOptionPane.ERROR_MESSAGE); //$NON-NLS-1$ //$NON-NLS-2$ break; case 4: JOptionPane.showMessageDialog(null, messages.getString("Group.29"), "ERROR", JOptionPane.ERROR_MESSAGE); //$NON-NLS-1$ //$NON-NLS-2$ break; case 5: JOptionPane.showMessageDialog(null, messages.getString("Group.4"), "ERROR", JOptionPane.ERROR_MESSAGE); //$NON-NLS-1$ //$NON-NLS-2$ break; case 6: JOptionPane.showMessageDialog(null, "No introdujo los filtros", "ERROR", JOptionPane.ERROR_MESSAGE); //$NON-NLS-1$ //$NON-NLS-2$ break; } } } }); btnCreatetrip.setBounds(651, 530, 150, 23); panel.add(btnCreatetrip); JButton btnLeaveGroup = new JButton(); btnLeaveGroup.setBounds(637, 260, 145, 23); panel.add(btnLeaveGroup); if( choice == 1 && instance != null){ tFName.setEditable(false); tFCap.setEditable(true); tFAdmin.setEditable(false); try { tFName.setText(groupController.getGroupName()); tFCap.setText(new Integer((groupController.getMaxGroupSize() - groupController.groupSize())).toString()); tFAdmin.setText(groupController.getAdmin().getUsername()); //$NON-NLS-1$ } catch (SessionNotActiveException e2) { e2.printStackTrace(); } catch (ControllerNotLoadedException e2) { e2.printStackTrace(); } btnFilters.setVisible(false); btnTrip.setText(messages.getString("Group.32")); //$NON-NLS-1$ btnTrip.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { Trip frame = null; try { frame = new Trip(1, null, (MyTripController)groupController.getTripController() ,null, instance, session, groupController,language); } catch (SessionNotActiveException e) { e.printStackTrace(); } catch (ControllerNotLoadedException e) { e.printStackTrace(); } frame.setVisible(true); frame.pack(); frame.setSize(900, 602); close(); } }); btnCreatetrip.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { if(isIntNumeric(tFCap.getText())){ if(Integer.parseInt(tFCap.getText()) < 1){ JOptionPane.showMessageDialog(null, messages.getString("Group.4"), "ERROR", JOptionPane.ERROR_MESSAGE); //$NON-NLS-1$ //$NON-NLS-2$ }else{ try { ((MyGroupController)groupController).changeGroupCapacity(Integer.parseInt(tFCap.getText())); } catch (NumberFormatException e) { e.printStackTrace(); } catch (SessionNotActiveException e) { e.printStackTrace(); } catch (ControllerNotLoadedException e) { e.printStackTrace(); } catch (IllegalArgumentException e){ } Options frame = new Options(instance, session,true); frame.setVisible(true); frame.pack(); frame.setSize(900, 602); close(); } }else{ JOptionPane.showMessageDialog(null, messages.getString("Group.4"), "ERROR", JOptionPane.ERROR_MESSAGE); //$NON-NLS-1$ //$NON-NLS-2$ } } }); btnLeaveGroup.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { if(instance != null){ try { currentProfile.leaveGroup(groupController); Group frame = new Group(choice,myTrip,trip,auxText,instance,session,groupController,language); frame.setVisible(true); frame.pack(); frame.setSize(900, 602); close(); } catch (SessionNotActiveException e) { e.printStackTrace(); } catch (ControllerNotLoadedException e) { e.printStackTrace(); } } } }); btnRequestcheck.setText(messages.getString("Group.33")); //$NON-NLS-1$ btnDelete.setVisible(true); }else if(choice == 2 && instance != null){ tFName.setEditable(false); tFCap.setEditable(false); tFAdmin.setEditable(false); btnCreatetrip.setVisible(false); try { tFName.setText(groupController.getGroupName()); tFCap.setText(groupController.groupSize().toString()); tFAdmin.setText(groupController.getAdmin().getUsername()); //$NON-NLS-1$ } catch (SessionNotActiveException e2) { e2.printStackTrace(); } catch (ControllerNotLoadedException e2) { e2.printStackTrace(); } btnFilters.setVisible(false); btnTrip.setText(messages.getString("Group.35")); //$NON-NLS-1$ btnTrip.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { Trip frame = new Trip(2,trip, null,null, instance, session,groupController,language); frame.setVisible(true); frame.pack(); frame.setSize(900, 602); close(); } }); btnDelete.setVisible(false); btnRequestcheck.setText(messages.getString("Group.36")); //$NON-NLS-1$ btnRequestcheck.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if(requestsTripaux.containsKey(currentProfile)){ btnRequestcheck.setText((requestsTripaux.get(currentProfile).toString())); btnRequestcheck.setEnabled(false); }else{ try { groupController.sendMemberRequest(); } catch (SessionNotActiveException e1) { e1.printStackTrace(); } catch (ControllerNotLoadedException e1) { e1.printStackTrace(); } catch (InvalidPermissionException e1) { e1.printStackTrace(); } } } }); try { if(! groupController.getMembers().contains(currentProfile)){ btnLeaveGroup.setVisible(false); } } catch (SessionNotActiveException e1) { e1.printStackTrace(); } catch (ControllerNotLoadedException e1) { e1.printStackTrace(); } }else if(choice == 0){ if(auxText != null){ tFName.setText(auxText.get(0)); tFCap.setText(auxText.get(1)); tFAdmin.setText(auxText.get(2)); } tFAdmin.setEditable(false); if(instance != null){ try { tFAdmin.setText(currentProfile.getUsername()); } catch (SessionNotActiveException e1) { e1.printStackTrace(); } catch (ControllerNotLoadedException e1) { e1.printStackTrace(); } } btnLeaveGroup.setVisible(false); btnFilters.setVisible(true); btnCreatetrip.setVisible(true); btnTrip.setText(messages.getString("Group.37")); //$NON-NLS-1$ btnTrip.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { ArrayList<String> aux = new ArrayList<String>(); aux.add(tFName.getText()); aux.add(tFCap.getText()); aux.add(tFAdmin.getText()); if(myTrip != null){ Trip frame = new Trip(0,myTrip,null,aux, instance, session, groupController,language); frame.setVisible(true); frame.pack(); frame.setSize(900, 602); close(); }else{ Trip frame = new Trip(0,null,null,aux, instance, session, groupController, language); frame.setVisible(true); frame.pack(); frame.setSize(900, 602); close(); } } }); btnDelete.setVisible(false); btnRequestcheck.setVisible(false); } JButton img = new JButton(); img.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { Group frame = new Group(choice,myTrip, trip,auxText,instance, session,groupController,false); frame.setVisible(true); frame.pack(); frame.setSize(900, 602); close(); } }); ImageIcon imageS = new ImageIcon("SpanishFlag.jpg"); //$NON-NLS-1$ panel.add(img); img.setIcon(imageS); img.setSize(22,18); img.setLocation(796,11); img.setVisible(true); JButton img2 = new JButton(); img2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Group frame = new Group(choice,myTrip, trip,auxText,instance, session,groupController,true); frame.setVisible(true); frame.pack(); frame.setSize(900, 602); close(); } }); ImageIcon imageE = new ImageIcon("EnglishFlag.jpg"); //$NON-NLS-1$ panel.add(img2); img2.setIcon(imageE); img2.setSize(22,18); img2.setLocation(760,11); img2.setVisible(true); if( choice == 1){ btnCreatetrip.setText(messages.getString("Group.2")); //$NON-NLS-1$ }else if(choice == 0){ btnCreatetrip.setText(messages.getString("Group.41")); //$NON-NLS-1$ } btnCalif.setText(messages.getString("Group.5")); //$NON-NLS-1$ btnDelete.setText(messages.getString("Group.40")); //$NON-NLS-1$ btnBack.setText(messages.getString("Group.42")); //$NON-NLS-1$ lblAdmin.setText(messages.getString("Group.43")); //$NON-NLS-1$ btnAccept.setText(messages.getString("Group.44")); //$NON-NLS-1$ lblNewRequest.setText(messages.getString("Group.45")); //$NON-NLS-1$ btnReject.setText(messages.getString("Group.46")); //$NON-NLS-1$ lblMembers.setText(messages.getString("Group.47")); //$NON-NLS-1$ lblGroupName.setText(messages.getString("Group.48")); //$NON-NLS-1$ lblCapacity.setText(messages.getString("Group.49")); //$NON-NLS-1$ btnFilters.setText(messages.getString("Group.50")); //$NON-NLS-1$ btnLeaveGroup.setText(messages.getString("Group.3")); //$NON-NLS-1$ } /** * Closes a frame after an event */ public void close(){ WindowEvent winClosingEvent = new WindowEvent(this,WindowEvent.WINDOW_CLOSING); Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(winClosingEvent); } /** * Checks if the string is a number * @param str * @return true str is number, false str is not a number */ public static boolean isNumeric(String str){ try { Double.parseDouble(str); } catch(NumberFormatException nfe){ return false; } return true; } /** * Checks if the str is a Integer * @param str * @return true str is Integer, false str is not a Integer */ public static boolean isIntNumeric(String str){ try { Integer.parseInt(str); } catch(NumberFormatException nfe){ return false; } return true; } /** * Searchs the user selected * @param keys * @param value * @return the ProfileController selected */ private ProfileController getKey(Set<ProfileController> keys, Integer value){ for(ProfileController each : keys){ if(value == 0){ return each; } } return null; } }
package us.corenetwork.moblimiter; import java.util.HashSet; import java.util.List; import org.bukkit.Bukkit; import org.bukkit.World; import org.bukkit.entity.Creature; import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; import org.bukkit.entity.LivingEntity; import org.bukkit.event.Listener; import org.bukkit.inventory.EntityEquipment; public class OldMobKiller implements Listener { private static HashSet<String> affectedMobs = new HashSet<String>(); private static int killTreshold; private static int nearMobsCount; private static int nearMobsSearchRange; public static void init() { loadConfig(); Bukkit.getPluginManager().registerEvents(new OldMobKiller(), MobLimiter.instance); Bukkit.getScheduler().runTaskTimer(MobLimiter.instance, new MobKillerTimer(), 20, Settings.getInt(Setting.OLD_MOB_KILLER_INTERVAL)); } public static void loadConfig() { for (String mobName : (List<String>) Settings.getList(Setting.OLD_MOB_KILLER_AFFECTED_MOBS)) { affectedMobs.add(mobName.toLowerCase()); } killTreshold = Settings.getInt(Setting.OLD_MOB_KILLER_TRESHOLD); nearMobsSearchRange = Settings.getInt(Setting.OLD_MOB_KILLER_NEAR_MOBS_SEARCH_RANGE); nearMobsCount = Settings.getInt(Setting.OLD_MOB_KILLER_NEAR_MOBS_COUNT); } private static int getNumberOfNearbyMobs(Entity mob) { int count = 0; for (Entity e : mob.getNearbyEntities(nearMobsSearchRange, nearMobsSearchRange, nearMobsSearchRange)) { EntityType type = e.getType(); if (type.getName() != null && affectedMobs.contains(type.getName().toLowerCase())) count++; } return count; } private static boolean hasStolenArmor(LivingEntity mob) { EntityEquipment equipment = mob.getEquipment(); return equipment.getBootsDropChance() >= 1 || equipment.getChestplateDropChance() >= 1 || equipment.getHelmetDropChance() >= 1 || equipment.getItemInHandDropChance() >= 1 || equipment.getLeggingsDropChance() >= 1; } private static class MobKillerTimer implements Runnable { @Override public void run() { for (World world : Bukkit.getWorlds()) { for (Entity mob : world.getEntities()) { if (!(mob instanceof Creature)) continue; EntityType type = mob.getType(); if (type.getName() == null || !affectedMobs.contains(type.getName().toLowerCase())) continue; int age = mob.getTicksLived(); if (age > killTreshold) { Creature creature = (Creature) mob; if (creature.getTarget() == null || (!hasStolenArmor(creature) && getNumberOfNearbyMobs(mob) >= nearMobsCount)) { mob.remove(); } } } } } } }
package grouplab; import grouplab.Checkers.Side; import grouplab.heuristics.*; import java.util.LinkedList; import java.util.Scanner; import java.util.concurrent.CompletionService; import java.util.concurrent.ExecutorCompletionService; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; /** * Game handles setting up all of the initial game variables and user * interface. No checkers logic should ever make its way in here. * * @author Nick Care (2014) * @author Sam Goree (2014) * @author Andrew Amis (2014) * @author Gabe Appleby (2014) */ public class Game { public static int GAME_MODE = 0; //0 is checkers, 1 is suicide checkers public static boolean silent; public static void main(String[] args) { boolean op_nerf_plox = false; if (op_nerf_plox == true) { silent = true; LinkedList<ComputerPlayer> playersB = new LinkedList<ComputerPlayer>(); int depth = 6; //for (int depth = 2; depth < 9; depth+=6) { playersB.add(new NaivePlayer(Side.BLACK, depth )); playersB.add(new WeightedCountCheckersPlayer(Side.BLACK, 1, 2, depth)); playersB.add(new BetterCountCheckersPlayer(Side.BLACK, depth)); playersB.add(new WeightedCountCheckersPlayer(Side.BLACK, 1, 3, depth)); playersB.add(new CenterWeightedCountCheckersPlayer(Side.BLACK, 1, 3, depth)); playersB.add(new NaiveCountCheckersPlayer(Side.BLACK, depth)); LinkedList<ComputerPlayer> playersR = new LinkedList<ComputerPlayer>(); //for (int depth = 2; depth < 9; depth+=6) { playersR.add(new NaivePlayer(Side.RED, depth )); playersR.add(new WeightedCountCheckersPlayer(Side.RED, 1, 2, depth)); playersR.add(new BetterCountCheckersPlayer(Side.RED, depth)); playersR.add(new WeightedCountCheckersPlayer(Side.RED, 1, 3, depth)); playersR.add(new CenterWeightedCountCheckersPlayer(Side.RED, 1, 3, depth)); playersR.add(new NaiveCountCheckersPlayer(Side.RED, depth)); ExecutorService executor = Executors.newFixedThreadPool(4); CompletionService<String> compService = new ExecutorCompletionService<>(executor); for (ComputerPlayer player1Q : playersB) { for (ComputerPlayer player2Q : playersR) { compService.submit(new CheckersTask(player1Q, player2Q, 8)); compService.submit(new CheckersTask(player1Q, player2Q, 12)); compService.submit(new CheckersTask(player1Q, player2Q, 13)); compService.submit(new CheckersTask(player1Q, player2Q, 14)); /*System.out.println(player1Q.getName() + ", " + player1Q.s + ", depth " + player1Q.depth + ". Against " + player2Q.getName() + ", " + player2Q.s + ", depth " + player2Q.depth + "." + " Board " + 8); Checkers.play(player1Q, player2Q, 8); System.out.println(player1Q.getName() + ", " + player1Q.s + ", depth " + player1Q.depth + ". Against " + player2Q.getName() + ", " + player2Q.s + ", depth " + player2Q.depth + "." + " Board " + 12); Checkers.play(player1Q, player2Q, 12); System.out.println(player1Q.getName() + ", " + player1Q.s + ", depth " + player1Q.depth + ". Against " + player2Q.getName() + ", " + player2Q.s + ", depth " + player2Q.depth + "." + " Board " + 15); Checkers.play(player1Q, player2Q, 13); System.out.println(player1Q.getName() + ", " + player1Q.s + ", depth " + player1Q.depth + ". Against " + player2Q.getName() + ", " + player2Q.s + ", depth " + player2Q.depth + "." + " Board " + 14); Checkers.play(player1Q, player2Q, 14);*/ } } while(true) { try { Future<String> future = compService.take(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } else { //silent = true; // player objects Player player1 = null; Player player2 = null; Scanner input = new Scanner(System.in); LinkedList<String> controllers = new LinkedList<String>(); controllers.add(0, "HumanPlayer"); controllers.add(1, "NaivePlayer"); //naive - all moves are 0 controllers.add(2, "CCPlayer"); //counts checkers weighted for kings controllers.add(3, "BCCPlayer"); //same as CCPlayer with set weights controllers.add(4, "WCCPlayer"); //I don't know what this does - please let me know controllers.add(5, "CWCCPlayer"); //I don't know what this does - please let me know controllers.add(6, "NCCPlayer"); //counts checkers weighted all the same // setup players int result = 0; // player1 result = InputHelper.queryMenu(input, "Who should play on the black side?", controllers); // if its a human player if (result == 0) { player1 = new HumanPlayer(); String name = InputHelper.queryStr(input, "Enter your name: "); player1.setName(name); } else { int depth = InputHelper.queryMenu(input, "Depth?"); switch (result) { case 1: player1 = new NaivePlayer(Side.BLACK, depth); break; case 2: player1 = new WeightedCountCheckersPlayer(Side.BLACK, 1, 2, depth); break; case 3: player1 = new BetterCountCheckersPlayer(Side.BLACK, depth); break; case 4: player1 = new WeightedCountCheckersPlayer(Side.BLACK, 1, 3, depth); break; case 5: player1 = new CenterWeightedCountCheckersPlayer(Side.BLACK, 1, 3, depth); break; case 6: player1 = new NaiveCountCheckersPlayer(Side.BLACK, depth); break; } } // player2 result = InputHelper.queryMenu(input, "Who should play on the red side?", controllers); if (result == 0) { player2 = new HumanPlayer(); String name = InputHelper.queryStr(input, "Enter your name: "); player2.setName(name); } else { int depth = InputHelper.queryMenu(input, "Depth?"); switch (result) { case 1: player2 = new NaivePlayer(Side.RED, depth); break; case 2: player2 = new WeightedCountCheckersPlayer(Side.RED, 1, 2, depth); break; case 3: player2 = new BetterCountCheckersPlayer(Side.RED, depth); break; case 4: player2 = new WeightedCountCheckersPlayer(Side.RED, 1, 3, depth); break; case 5: player2 = new CenterWeightedCountCheckersPlayer(Side.RED, 1, 3, depth); break; case 6: player2 = new NaiveCountCheckersPlayer(Side.RED, depth); break; } } int size = InputHelper.queryMenu(input, "What should the board size be?"); Checkers.play(player1, player2, size); } } }
package gui; import data.AllTracks; import data.CustomerTracks; import data.TrackedTimeItem; import java.awt.Color; import java.awt.Desktop; import java.awt.HeadlessException; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.net.URI; import java.net.URISyntaxException; import java.text.ParseException; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.Timer; import java.util.TimerTask; import java.util.TreeMap; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeModel; import logic.Export; import java.util.concurrent.TimeUnit; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.KeyStroke; import javax.swing.SwingUtilities; import javax.swing.filechooser.FileNameExtensionFilter; import javax.swing.tree.TreeNode; import logic.AutoCompletion; import logic.AutoSave; /** * * @author Lars */ public class MainFrame extends javax.swing.JFrame { private Date createdDate = new Date(); private Timer timer; private JLabel jLTemplatePath = new JLabel(); private String title = ("Timesheet Generator"); private final AutoSave as; /** * Creates new form MainFrame */ public MainFrame() { System.setProperty("apple.eawt.quitStrategy", "CLOSE_ALL_WINDOWS"); initComponents(); AutoCompletion.enable(jcbKindOfAction); if (readSaveState()) { buildTree(); } //Save the Status every 100 seconds this.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent windowEvent) { Object[] options = {"Nicht speichern", "Abbrechen", "Speichern"}; int n = JOptionPane.showOptionDialog(null, "Möchtest du die Änderungen speichern? ", "Speichern", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[2]); switch (n) { case 0: //Nicht speichern System.exit(0); break; case 1: //Abbrechen break; case 2: //Sichern.. if (as.save()) { System.exit(0); } else { JOptionPane.showMessageDialog(null, "Fehler beim Speichern", "Speichern", JOptionPane.ERROR_MESSAGE); } break; } } }); as = new AutoSave(); as.autoSave(); } /** * 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. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPMenue = new javax.swing.JPanel(); jBnewCustomer = new javax.swing.JButton(); jBSave = new javax.swing.JButton(); jBExport = new javax.swing.JButton(); jBTamplate = new javax.swing.JButton(); jBDeleteTreeleafs = new javax.swing.JButton(); jBMail = new javax.swing.JButton(); jPCustomers = new javax.swing.JPanel(); jScrollPane1 = new javax.swing.JScrollPane(); jTreeCustomer = new javax.swing.JTree(); jPanel1 = new javax.swing.JPanel(); jPCustomorMenue = new javax.swing.JPanel(); jLKlient = new javax.swing.JLabel(); jBStartTimeTrack = new javax.swing.JButton(); jBStopTimeTrack = new javax.swing.JButton(); jLTime = new javax.swing.JLabel(); jBDeleteCustomer = new javax.swing.JButton(); jPTrackItem = new javax.swing.JPanel(); jPanel2 = new javax.swing.JPanel(); jTAction = new javax.swing.JTextField(); jPanel3 = new javax.swing.JPanel(); jcbKindOfAction = new javax.swing.JComboBox<>(); jSStartTime = new javax.swing.JSpinner(); jSStopTime = new javax.swing.JSpinner(); jBSaveTaskChange = new javax.swing.JButton(); jBDublicateTask = new javax.swing.JButton(); jBDeleteTrack = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE); setTitle("Timesheet Generator"); setMinimumSize(new java.awt.Dimension(990, 640)); getContentPane().setLayout(new javax.swing.BoxLayout(getContentPane(), javax.swing.BoxLayout.PAGE_AXIS)); jPMenue.setBackground(new java.awt.Color(169, 1, 0)); jPMenue.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); jPMenue.setMaximumSize(new java.awt.Dimension(32767, 82)); jPMenue.setMinimumSize(new java.awt.Dimension(960, 41)); jPMenue.setPreferredSize(new java.awt.Dimension(960, 63)); jPMenue.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 25, 15)); jBnewCustomer.setBackground(new java.awt.Color(169, 1, 0)); jBnewCustomer.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/plus.png"))); // NOI18N jBnewCustomer.setToolTipText("neuer Mandant anlegen"); jBnewCustomer.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); jBnewCustomer.setBorderPainted(false); jBnewCustomer.setContentAreaFilled(false); jBnewCustomer.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseExited(java.awt.event.MouseEvent evt) { jBnewCustomerMouseExited(evt); } public void mouseEntered(java.awt.event.MouseEvent evt) { jBnewCustomerMouseEntered(evt); } }); jBnewCustomer.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jBnewCustomerActionPerformed(evt); } }); jPMenue.add(jBnewCustomer); jBSave.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/floppydisk.png"))); // NOI18N jBSave.setToolTipText("Save "); jBSave.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); jBSave.setBorderPainted(false); jBSave.setMargin(new java.awt.Insets(0, 10, 0, 10)); jBSave.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseExited(java.awt.event.MouseEvent evt) { jBSaveMouseExited(evt); } public void mouseEntered(java.awt.event.MouseEvent evt) { jBSaveMouseEntered(evt); } }); jBSave.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jBSaveActionPerformed(evt); } }); jPMenue.add(jBSave); jBExport.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/glyphicons-416-disk-open.png"))); // NOI18N jBExport.setToolTipText("Export to .xls"); jBExport.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); jBExport.setBorderPainted(false); jBExport.setContentAreaFilled(false); jBExport.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseExited(java.awt.event.MouseEvent evt) { jBExportMouseExited(evt); } public void mouseEntered(java.awt.event.MouseEvent evt) { jBExportMouseEntered(evt); } }); jBExport.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jBExportActionPerformed(evt); } }); jPMenue.add(jBExport); jBTamplate.setBackground(new java.awt.Color(252, 252, 252)); jBTamplate.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/glyphicons-511-duplicate.png"))); // NOI18N jBTamplate.setToolTipText("Template"); jBTamplate.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); jBTamplate.setBorderPainted(false); jBTamplate.setContentAreaFilled(false); jBTamplate.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseExited(java.awt.event.MouseEvent evt) { jBTamplateMouseExited(evt); } public void mouseEntered(java.awt.event.MouseEvent evt) { jBTamplateMouseEntered(evt); } }); jBTamplate.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jBTamplateActionPerformed(evt); } }); jPMenue.add(jBTamplate); jBDeleteTreeleafs.setBackground(new java.awt.Color(252, 252, 252)); jBDeleteTreeleafs.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/glyphicons-17-bin.png"))); // NOI18N jBDeleteTreeleafs.setToolTipText("Formular leeren"); jBDeleteTreeleafs.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); jBDeleteTreeleafs.setBorderPainted(false); jBDeleteTreeleafs.setContentAreaFilled(false); jBDeleteTreeleafs.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseExited(java.awt.event.MouseEvent evt) { jBDeleteTreeleafsMouseExited(evt); } public void mouseEntered(java.awt.event.MouseEvent evt) { jBDeleteTreeleafsMouseEntered(evt); } }); jBDeleteTreeleafs.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jBDeleteTreeleafsActionPerformed(evt); } }); jPMenue.add(jBDeleteTreeleafs); jBMail.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/bug.png"))); // NOI18N jBMail.setToolTipText("Report Bug"); jBMail.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); jBMail.setBorderPainted(false); jBMail.setContentAreaFilled(false); jBMail.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseExited(java.awt.event.MouseEvent evt) { jBMailMouseExited(evt); } public void mouseEntered(java.awt.event.MouseEvent evt) { jBMailMouseEntered(evt); } }); jBMail.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jBMailActionPerformed(evt); } }); jPMenue.add(jBMail); getContentPane().add(jPMenue); jPCustomers.setBackground(new java.awt.Color(204, 204, 204)); jPCustomers.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)), "Mandanten")); jPCustomers.setAutoscrolls(true); jPCustomers.setMinimumSize(new java.awt.Dimension(960, 540)); jPCustomers.setPreferredSize(new java.awt.Dimension(960, 560)); jPCustomers.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT)); jScrollPane1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); jScrollPane1.setAlignmentX(0.0F); jScrollPane1.setAlignmentY(0.0F); jScrollPane1.setMinimumSize(new java.awt.Dimension(19, 150)); jScrollPane1.setPreferredSize(new java.awt.Dimension(960, 350)); jTreeCustomer.setBackground(new java.awt.Color(252, 252, 252)); javax.swing.tree.DefaultMutableTreeNode treeNode1 = new javax.swing.tree.DefaultMutableTreeNode("Mandanten"); jTreeCustomer.setModel(new javax.swing.tree.DefaultTreeModel(treeNode1)); jTreeCustomer.setAlignmentX(0.0F); jTreeCustomer.setAlignmentY(0.0F); jTreeCustomer.setAutoscrolls(true); jTreeCustomer.setVisibleRowCount(2000); jTreeCustomer.addTreeSelectionListener(new javax.swing.event.TreeSelectionListener() { public void valueChanged(javax.swing.event.TreeSelectionEvent evt) { jTreeCustomerValueChanged(evt); } }); jScrollPane1.setViewportView(jTreeCustomer); jPCustomers.add(jScrollPane1); jPanel1.setBackground(new java.awt.Color(204, 204, 204)); jPanel1.setAlignmentX(0.0F); jPanel1.setAlignmentY(0.0F); jPanel1.setPreferredSize(new java.awt.Dimension(960, 140)); jPCustomorMenue.setBackground(new java.awt.Color(204, 204, 204)); jPCustomorMenue.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); jPCustomorMenue.setToolTipText(""); jPCustomorMenue.setAlignmentX(0.0F); jPCustomorMenue.setAlignmentY(0.0F); jPCustomorMenue.setMinimumSize(new java.awt.Dimension(960, 41)); jPCustomorMenue.setPreferredSize(new java.awt.Dimension(960, 50)); jLKlient.setText("Mandant: X"); jPCustomorMenue.add(jLKlient); jBStartTimeTrack.setBackground(new java.awt.Color(252, 252, 252)); jBStartTimeTrack.setText("Start"); jBStartTimeTrack.setEnabled(false); jBStartTimeTrack.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jBStartTimeTrackActionPerformed(evt); } }); jPCustomorMenue.add(jBStartTimeTrack); jBStopTimeTrack.setBackground(new java.awt.Color(252, 252, 252)); jBStopTimeTrack.setText("Stopp"); jBStopTimeTrack.setEnabled(false); jBStopTimeTrack.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jBStopTimeTrackActionPerformed(evt); } }); jPCustomorMenue.add(jBStopTimeTrack); jLTime.setText("Zeit: "); jPCustomorMenue.add(jLTime); jBDeleteCustomer.setBackground(new java.awt.Color(252, 252, 252)); jBDeleteCustomer.setText("Lösche Mandanten"); jBDeleteCustomer.setEnabled(false); jBDeleteCustomer.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jBDeleteCustomerActionPerformed(evt); } }); jPCustomorMenue.add(jBDeleteCustomer); jPTrackItem.setBackground(new java.awt.Color(204, 204, 204)); jPTrackItem.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); jPTrackItem.setAlignmentX(0.0F); jPTrackItem.setAlignmentY(0.0F); jPTrackItem.setMinimumSize(new java.awt.Dimension(14, 80)); jPTrackItem.setPreferredSize(new java.awt.Dimension(960, 100)); jPTrackItem.setLayout(new javax.swing.BoxLayout(jPTrackItem, javax.swing.BoxLayout.PAGE_AXIS)); jPanel2.setBackground(new java.awt.Color(204, 204, 204)); jPanel2.setPreferredSize(new java.awt.Dimension(960, 50)); jTAction.setMinimumSize(new java.awt.Dimension(100, 26)); jTAction.setPreferredSize(new java.awt.Dimension(200, 26)); jTAction.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTActionActionPerformed(evt); } }); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 958, Short.MAX_VALUE) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(jTAction, javax.swing.GroupLayout.PREFERRED_SIZE, 956, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE))) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 34, Short.MAX_VALUE) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(0, 4, Short.MAX_VALUE) .addComponent(jTAction, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 4, Short.MAX_VALUE))) ); jPTrackItem.add(jPanel2); jPanel3.setBackground(new java.awt.Color(204, 204, 204)); jPanel3.setPreferredSize(new java.awt.Dimension(960, 50)); jcbKindOfAction.setBackground(new java.awt.Color(252, 252, 252)); jcbKindOfAction.setEditable(true); jcbKindOfAction.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { " ", "Akquise", "Besprechung", "Büroorga", "diverse Korrespondenz", "Email", "Entwurf", "Marketing", "Recherche", "Review", "Review und Entwurf", "Telefonat", "Verfügung" })); jcbKindOfAction.setPreferredSize(new java.awt.Dimension(200, 26)); jPanel3.add(jcbKindOfAction); jSStartTime.setModel(new javax.swing.SpinnerDateModel(new java.util.Date(), null, null, java.util.Calendar.MINUTE)); jPanel3.add(jSStartTime); jSStopTime.setModel(new javax.swing.SpinnerDateModel(new java.util.Date(), null, null, java.util.Calendar.MINUTE)); jPanel3.add(jSStopTime); jBSaveTaskChange.setBackground(new java.awt.Color(252, 252, 252)); jBSaveTaskChange.setText("speichern"); jBSaveTaskChange.setEnabled(false); jBSaveTaskChange.setMaximumSize(new java.awt.Dimension(80, 29)); jBSaveTaskChange.setMinimumSize(new java.awt.Dimension(80, 29)); jBSaveTaskChange.setPreferredSize(new java.awt.Dimension(90, 29)); jBSaveTaskChange.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jBSaveTaskChangeActionPerformed(evt); } }); jPanel3.add(jBSaveTaskChange); jBDublicateTask.setBackground(new java.awt.Color(252, 252, 252)); jBDublicateTask.setText("duplizieren"); jBDublicateTask.setEnabled(false); jBDublicateTask.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jBDublicateTaskActionPerformed(evt); } }); jPanel3.add(jBDublicateTask); jBDeleteTrack.setBackground(new java.awt.Color(252, 252, 252)); jBDeleteTrack.setText("löschen"); jBDeleteTrack.setEnabled(false); jBDeleteTrack.setMaximumSize(new java.awt.Dimension(90, 29)); jBDeleteTrack.setMinimumSize(new java.awt.Dimension(90, 29)); jBDeleteTrack.setPreferredSize(new java.awt.Dimension(90, 29)); jBDeleteTrack.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jBDeleteTrackActionPerformed(evt); } }); jPanel3.add(jBDeleteTrack); jPTrackItem.add(jPanel3); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jPCustomorMenue, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE)) .addComponent(jPTrackItem, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addComponent(jPCustomorMenue, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPTrackItem, javax.swing.GroupLayout.DEFAULT_SIZE, 80, Short.MAX_VALUE) .addContainerGap()) ); jPCustomers.add(jPanel1); getContentPane().add(jPCustomers); pack(); }// </editor-fold>//GEN-END:initComponents /** * Creakte new Custemor when the name is unique * * @param evt */ private void jBnewCustomerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBnewCustomerActionPerformed String S = JOptionPane.showInputDialog("Bitte neuen Mandanten Eingeben!"); AllTracks instance = AllTracks.getInstance(); CustomerTracks get = instance.getAllCustomers().get(S); int bevor = instance.getAllCustomers().size(); if (get == null) { CustomerTracks ct = new CustomerTracks(S); instance.getAllCustomers().put(ct.getCustomername(), ct); DefaultTreeModel model = (DefaultTreeModel) jTreeCustomer.getModel(); DefaultMutableTreeNode root = (DefaultMutableTreeNode) model.getRoot(); model.insertNodeInto(new DefaultMutableTreeNode(ct), root, root.getChildCount()); } else { JOptionPane.showMessageDialog(null, "Mandant schon vorhanden!"); } if (bevor == 0) { jTreeCustomer.expandRow(0); jTreeCustomer.setRootVisible(false); jTreeCustomer.collapseRow(0); } setTieleUnsaved(true); buildTree(); }//GEN-LAST:event_jBnewCustomerActionPerformed private void jBSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBSaveActionPerformed if (as.save()) { JOptionPane.showMessageDialog(null, "Der Zustand wurde gespeichert."); setTieleUnsaved(false); } else { JOptionPane.showMessageDialog(null, "Fehler beim Speichern"); } }//GEN-LAST:event_jBSaveActionPerformed private void jTreeCustomerValueChanged(javax.swing.event.TreeSelectionEvent evt) {//GEN-FIRST:event_jTreeCustomerValueChanged DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) jTreeCustomer.getLastSelectedPathComponent(); try { String s = selectedNode.getUserObject().getClass().getName();// data.TrackedTimeItem Date now; switch (s) { case "data.CustomerTracks": CustomerTracks userObject = (CustomerTracks) selectedNode.getUserObject(); jLKlient.setText("Mandant: " + userObject.getCustomername()); jTAction.setText(""); jcbKindOfAction.setSelectedIndex(0); now = new java.util.Date(); jSStartTime.setValue(now); jSStopTime.setValue(now); jBDeleteTrack.setEnabled(false); jBSaveTaskChange.setEnabled(false); jBStartTimeTrack.setEnabled(true); jBDeleteCustomer.setEnabled(true); jBDublicateTask.setEnabled(false); break; case "data.TrackedTimeItem": TrackedTimeItem trackObject = (TrackedTimeItem) selectedNode.getUserObject(); jTAction.setText(trackObject.getKommand()); jcbKindOfAction.setSelectedItem(trackObject.getKindOfAction()); jSStartTime.setValue(trackObject.getStartTime()); jSStopTime.setValue(trackObject.getEndTime()); jBDeleteTrack.setEnabled(true); jBSaveTaskChange.setEnabled(true); jBDeleteCustomer.setEnabled(false); jBStartTimeTrack.setEnabled(false); jBStopTimeTrack.setEnabled(false); jBDublicateTask.setEnabled(true); break; case "java.lang.String": jLKlient.setText("Mandant: "); jTAction.setText(""); jcbKindOfAction.setSelectedIndex(0); now = new java.util.Date(); jSStartTime.setValue(now); jSStopTime.setValue(now); jBDeleteTrack.setEnabled(false); jBSaveTaskChange.setEnabled(false); jBDeleteCustomer.setEnabled(false); jBStartTimeTrack.setEnabled(false); jBStopTimeTrack.setEnabled(false); jBDublicateTask.setEnabled(false); break; } } catch (ClassCastException e) { JOptionPane.showMessageDialog(null, "Fehler:" + e.getMessage()); } }//GEN-LAST:event_jTreeCustomerValueChanged private void jBStopTimeTrackActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBStopTimeTrackActionPerformed if (jTAction.getText().isEmpty()) { JOptionPane.showMessageDialog(this, "Bitte einen Beschreibungstext eingeben und erneut Stopp betätigen"); return; } else { jTreeCustomer.setEnabled(true); java.util.Date now = new java.util.Date(); jSStopTime.setValue(now); TrackedTimeItem TTI; try { DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) jTreeCustomer.getLastSelectedPathComponent(); String name = selectedNode.getUserObject().getClass().getName(); if (name.equals("data.CustomerTracks")) { CustomerTracks CT = (CustomerTracks) selectedNode.getUserObject(); DefaultTreeModel model = (DefaultTreeModel) jTreeCustomer.getModel(); TTI = new TrackedTimeItem(createdDate, now, jTAction.getText(), jcbKindOfAction.getSelectedItem().toString()); model.insertNodeInto(new DefaultMutableTreeNode(TTI), selectedNode, selectedNode.getChildCount()); CT.getCustomeritems().add(TTI); Calendar cal = Calendar.getInstance(); cal.setTime(TTI.getEndTime()); jBDeleteCustomer.setEnabled(true); jBStartTimeTrack.setEnabled(true); jBStopTimeTrack.setEnabled(false); jBDeleteTrack.setEnabled(false); jBSaveTaskChange.setEnabled(false); jBDublicateTask.setEnabled(false); setTieleUnsaved(true); } else if (name.equals("data.TrackedTimeItem")) { DefaultMutableTreeNode selectedNodeParent = (DefaultMutableTreeNode) selectedNode.getParent(); CustomerTracks CT = (CustomerTracks) selectedNodeParent.getUserObject(); DefaultTreeModel model = (DefaultTreeModel) jTreeCustomer.getModel(); TTI = new TrackedTimeItem(createdDate, now, jTAction.getText(), jcbKindOfAction.getSelectedItem().toString()); model.insertNodeInto(new DefaultMutableTreeNode(TTI), selectedNodeParent, selectedNodeParent.getChildCount()); CT.getCustomeritems().add(TTI); Calendar cal = Calendar.getInstance(); cal.setTime(TTI.getEndTime()); jBDeleteCustomer.setEnabled(false); jBStartTimeTrack.setEnabled(false); jBStopTimeTrack.setEnabled(false); jBDeleteTrack.setEnabled(true); jBSaveTaskChange.setEnabled(true); jBDublicateTask.setEnabled(true); } jTAction.setText(""); jLTime.setText("Zeit"); jLTime.setForeground(Color.BLACK); timer.cancel(); timer = null; } catch (ClassCastException e) { JOptionPane.showMessageDialog(this, "Fehler bitte an Programmierer wenden"); } } }//GEN-LAST:event_jBStopTimeTrackActionPerformed private void jBStartTimeTrackActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBStartTimeTrackActionPerformed jBStartTimeTrack.setEnabled(false); jBDeleteCustomer.setEnabled(false); jBStopTimeTrack.setEnabled(true); jTreeCustomer.setEnabled(false); createdDate = new java.util.Date(); Calendar cal = Calendar.getInstance(); cal.setTime(createdDate); jSStartTime.setValue(createdDate); jLTime.setText("Zeit "); timer = new Timer(); /*timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { jLTime.setText("Zeit " + getAgeInSeconds()); } }, 1000, 1000); */ TimerTask tt = new TimerTask() { @Override public void run() { jLTime.setText("Zeit " + getAgeInSeconds()); } }; timer.scheduleAtFixedRate(tt, 10, 1000); jLTime.setForeground(Color.red); }//GEN-LAST:event_jBStartTimeTrackActionPerformed private void jTActionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTActionActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jTActionActionPerformed private void jBExportActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBExportActionPerformed if (jLTemplatePath.getText().equals("")) { JOptionPane.showMessageDialog(null, "Fehler kein Tamplate gefunden", "Export", JOptionPane.ERROR_MESSAGE); return; } JFileChooser fileChooser = new JFileChooser(); fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); FileNameExtensionFilter xlsxfilter = new FileNameExtensionFilter( "xlsx files (*.xlsx)", "xlsx"); fileChooser.setFileFilter(xlsxfilter); fileChooser.setDialogTitle("Speicherort"); fileChooser.showSaveDialog(this); fileChooser.setAcceptAllFileFilterUsed(false); if (fileChooser.getSelectedFile() != null) { Export exp = new Export(fileChooser, jLTemplatePath.getText()); try { boolean convertXls = exp.convertXls(); if (convertXls) { JOptionPane.showMessageDialog(this, "Erfolgreich Exportiert unter: " + fileChooser.getSelectedFile().toString()); //export entity delete } else { JOptionPane.showMessageDialog(this, "Leider nicht Erfolgreich Exportiert!"); } } catch (HeadlessException | IOException | IllegalArgumentException | ParseException ex) { JOptionPane.showMessageDialog(null, "Fehler: " + ex.getMessage(), "Export", JOptionPane.ERROR_MESSAGE); } } }//GEN-LAST:event_jBExportActionPerformed private void jBDeleteCustomerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBDeleteCustomerActionPerformed DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) jTreeCustomer.getLastSelectedPathComponent(); try { CustomerTracks CT = (CustomerTracks) selectedNode.getUserObject(); AllTracks instance = AllTracks.getInstance(); instance.getAllCustomers().remove(CT.getCustomername()); setTieleUnsaved(true); buildTree(); } catch (ClassCastException ex) { JOptionPane.showMessageDialog(null, "Fehler bitte einen Mandanten auswählen", "Fehler", JOptionPane.ERROR_MESSAGE); } }//GEN-LAST:event_jBDeleteCustomerActionPerformed private void jBTamplateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBTamplateActionPerformed JFileChooser fileChooser = new JFileChooser(); fileChooser.setFileFilter(new FileNameExtensionFilter(".xlsx", "xlsx")); fileChooser.setAcceptAllFileFilterUsed(false); fileChooser.showOpenDialog(this); if (fileChooser.getSelectedFile() != null) { AllTracks instance = AllTracks.getInstance(); instance.setTamplatePath(fileChooser.getSelectedFile().toString()); jLTemplatePath.setText(fileChooser.getSelectedFile().toString()); jLTemplatePath.setForeground(new java.awt.Color(252, 252, 252)); jPMenue.add(jLTemplatePath); SwingUtilities.updateComponentTreeUI(this); setTieleUnsaved(true); } }//GEN-LAST:event_jBTamplateActionPerformed private void jBDeleteTreeleafsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBDeleteTreeleafsActionPerformed AllTracks instance = AllTracks.getInstance(); Set set = instance.getAllCustomers().entrySet(); Iterator iterator = set.iterator(); while (iterator.hasNext()) { Map.Entry mentry = (Map.Entry) iterator.next(); CustomerTracks cusomer = (CustomerTracks) mentry.getValue(); ArrayList<TrackedTimeItem> customeritems = new ArrayList<TrackedTimeItem>(); cusomer.setCustomeritems(customeritems); } setTieleUnsaved(true); buildTree(); }//GEN-LAST:event_jBDeleteTreeleafsActionPerformed private void jBSaveTaskChangeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBSaveTaskChangeActionPerformed DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) jTreeCustomer.getLastSelectedPathComponent(); TrackedTimeItem TI = (TrackedTimeItem) selectedNode.getUserObject(); TI.setKommand(jTAction.getText()); TI.setKindOfAction(jcbKindOfAction.getSelectedItem().toString()); TI.setStartTime((Date) jSStartTime.getModel().getValue()); TI.setEndTime((Date) jSStopTime.getModel().getValue()); selectedNode.setUserObject(TI); DefaultMutableTreeNode selectedNode2 = (DefaultMutableTreeNode) jTreeCustomer.getLastSelectedPathComponent(); String s = selectedNode2.getUserObject().getClass().getName(); DefaultTreeModel model = (DefaultTreeModel) jTreeCustomer.getModel(); model.reload((TreeNode) selectedNode2); setTieleUnsaved(true); }//GEN-LAST:event_jBSaveTaskChangeActionPerformed private void jBDeleteTrackActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBDeleteTrackActionPerformed AllTracks instance = AllTracks.getInstance(); DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) jTreeCustomer.getLastSelectedPathComponent(); DefaultMutableTreeNode selectedNodeParent = (DefaultMutableTreeNode) selectedNode.getParent(); CustomerTracks CT = (CustomerTracks) selectedNodeParent.getUserObject(); CustomerTracks get = instance.getAllCustomers().get(CT.getCustomername()); TrackedTimeItem TI = (TrackedTimeItem) selectedNode.getUserObject(); get.getCustomeritems().remove(TI); DefaultTreeModel model = (DefaultTreeModel) jTreeCustomer.getModel(); jTreeCustomer.setSelectionRow(jTreeCustomer.getSelectionRows()[0] - 1); model.removeNodeFromParent(selectedNode); setTieleUnsaved(true); }//GEN-LAST:event_jBDeleteTrackActionPerformed private void jBDublicateTaskActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBDublicateTaskActionPerformed jBDeleteTrack.setEnabled(false); jBSaveTaskChange.setEnabled(false); jBStartTimeTrack.setEnabled(false); jBStopTimeTrack.setEnabled(false); jBDeleteCustomer.setEnabled(false); jBDublicateTask.setEnabled(false); jBStopTimeTrack.setEnabled(true); jTreeCustomer.setEnabled(false); createdDate = new java.util.Date(); Calendar cal = Calendar.getInstance(); cal.setTime(createdDate); jSStartTime.setValue(createdDate); jLTime.setText("Zeit "); timer = new Timer(); timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { jLTime.setText("Zeit " + getAgeInSeconds()); } }, 10, 1000); jLTime.setForeground(Color.red); // TODO add your handling code here: }//GEN-LAST:event_jBDublicateTaskActionPerformed private void jBMailActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBMailActionPerformed Desktop desktop; if (Desktop.isDesktopSupported() && (desktop = Desktop.getDesktop()).isSupported(Desktop.Action.MAIL)) { URI mailto = null; try { mailto = new URI("mailto:larslengersdorf@gmail.com?subject=Bug%20Timesheet"); } catch (URISyntaxException ex) { Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex); } try { desktop.mail(mailto); } catch (IOException ex) { Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex); } } else { // TODO fallback to some Runtime.exec(..) voodoo? throw new RuntimeException("desktop doesn't support mailto; mail is dead anyway ;)"); } }//GEN-LAST:event_jBMailActionPerformed private void jBnewCustomerMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jBnewCustomerMouseExited jBnewCustomer.setBorderPainted(false); }//GEN-LAST:event_jBnewCustomerMouseExited private void jBnewCustomerMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jBnewCustomerMouseEntered jBnewCustomer.setBorderPainted(true); }//GEN-LAST:event_jBnewCustomerMouseEntered private void jBSaveMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jBSaveMouseEntered jBSave.setBorderPainted(true); }//GEN-LAST:event_jBSaveMouseEntered private void jBSaveMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jBSaveMouseExited jBSave.setBorderPainted(false); }//GEN-LAST:event_jBSaveMouseExited private void jBExportMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jBExportMouseEntered jBExport.setBorderPainted(true); }//GEN-LAST:event_jBExportMouseEntered private void jBExportMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jBExportMouseExited jBExport.setBorderPainted(false); }//GEN-LAST:event_jBExportMouseExited private void jBMailMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jBMailMouseEntered jBMail.setBorderPainted(true); }//GEN-LAST:event_jBMailMouseEntered private void jBMailMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jBMailMouseExited jBMail.setBorderPainted(false); }//GEN-LAST:event_jBMailMouseExited private void jBTamplateMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jBTamplateMouseEntered jBTamplate.setBorderPainted(true); }//GEN-LAST:event_jBTamplateMouseEntered private void jBTamplateMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jBTamplateMouseExited jBTamplate.setBorderPainted(false); }//GEN-LAST:event_jBTamplateMouseExited private void jBDeleteTreeleafsMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jBDeleteTreeleafsMouseEntered jBDeleteTreeleafs.setBorderPainted(true); }//GEN-LAST:event_jBDeleteTreeleafsMouseEntered private void jBDeleteTreeleafsMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jBDeleteTreeleafsMouseExited jBDeleteTreeleafs.setBorderPainted(false); }//GEN-LAST:event_jBDeleteTreeleafsMouseExited public String getAgeInSeconds() { Calendar cal = Calendar.getInstance(); java.util.Date now = new java.util.Date(); cal.setTime(now); long diff = now.getTime() - createdDate.getTime();//as given String curTime = String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(diff) % 24, TimeUnit.MILLISECONDS.toMinutes(diff) % 60, TimeUnit.MILLISECONDS.toSeconds(diff) % 60); return curTime; } /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new MainFrame().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jBDeleteCustomer; private javax.swing.JButton jBDeleteTrack; private javax.swing.JButton jBDeleteTreeleafs; private javax.swing.JButton jBDublicateTask; private javax.swing.JButton jBExport; private javax.swing.JButton jBMail; private javax.swing.JButton jBSave; private javax.swing.JButton jBSaveTaskChange; private javax.swing.JButton jBStartTimeTrack; private javax.swing.JButton jBStopTimeTrack; private javax.swing.JButton jBTamplate; private javax.swing.JButton jBnewCustomer; private javax.swing.JLabel jLKlient; private javax.swing.JLabel jLTime; private javax.swing.JPanel jPCustomers; private javax.swing.JPanel jPCustomorMenue; private javax.swing.JPanel jPMenue; private javax.swing.JPanel jPTrackItem; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JSpinner jSStartTime; private javax.swing.JSpinner jSStopTime; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTextField jTAction; private javax.swing.JTree jTreeCustomer; private javax.swing.JComboBox<String> jcbKindOfAction; // End of variables declaration//GEN-END:variables private boolean readSaveState() { File state = new File(System.getProperty("user.dir") + "/saveState"); if (state.isFile()) { InputStream fis = null; try { fis = new FileInputStream(System.getProperty("user.dir") + "/saveState"); ObjectInputStream o = new ObjectInputStream(fis); AllTracks instance = AllTracks.getInstance(); // private TreeMap<String, CustomerTracks> allCustomers = new TreeMap<String, CustomerTracks>(String.CASE_INSENSITIVE_ORDER); TreeMap<String, CustomerTracks> allCustomers = new TreeMap<String, CustomerTracks>(String.CASE_INSENSITIVE_ORDER); Object confObjekt = o.readObject(); allCustomers = (TreeMap<String, CustomerTracks>) confObjekt; confObjekt = o.readObject(); jLTemplatePath.setText((String) confObjekt); // jLTemplatePath = (JLabel) confObjekt; jPMenue.add(jLTemplatePath); SwingUtilities.updateComponentTreeUI(this); instance.setAllCustomers(allCustomers); instance.setTamplatePath((String) confObjekt); return true; } catch (IOException | ClassNotFoundException e) { JOptionPane.showMessageDialog(null, "Fehler beim Laden der saveState Datei: \n" + e.getMessage() + "\n Version nicht kompatibel", "Fehler", JOptionPane.ERROR_MESSAGE); } finally { try { fis.close(); } catch (IOException e) { } } } return false; } private void buildTree() { AllTracks instance = AllTracks.getInstance(); DefaultTreeModel model = (DefaultTreeModel) jTreeCustomer.getModel(); DefaultMutableTreeNode root = (DefaultMutableTreeNode) model.getRoot(); root.removeAllChildren(); Set set = instance.getAllCustomers().entrySet(); Iterator iterator = set.iterator(); while (iterator.hasNext()) { Map.Entry mentry = (Map.Entry) iterator.next(); CustomerTracks cusomer = (CustomerTracks) mentry.getValue(); DefaultMutableTreeNode first = new DefaultMutableTreeNode(cusomer); model.insertNodeInto(first, root, root.getChildCount()); for (TrackedTimeItem ti : cusomer.getCustomeritems()) { model.insertNodeInto(new DefaultMutableTreeNode(ti), first, first.getChildCount()); } } if (instance.getAllCustomers().size() != 0) { jTreeCustomer.expandRow(0); jTreeCustomer.setRootVisible(false); jTreeCustomer.collapseRow(0); } jBDeleteTrack.setEnabled(false); jBSaveTaskChange.setEnabled(false); jBStartTimeTrack.setEnabled(false); jBStopTimeTrack.setEnabled(false); jBDeleteCustomer.setEnabled(false); jBDublicateTask.setEnabled(false); SwingUtilities.updateComponentTreeUI(this); } public void setTieleUnsaved(boolean b) { String title = this.getTitle(); title = title.replace("unsaved", ""); this.setTitle(title); if (b) { this.setTitle(title + " unsaved"); } } // public void setKeyshortcuts(){ // Action buttonAction = new AbstractAction("start") { // @Override // public void actionPerformed(ActionEvent evt) { // System.out.println("Refreshing..."); // String key = "start"; // jBSave.setAction(buttonAction); // //buttonAction.putValue(Action.MNEMONIC_KEY, KeyEvent.VK_R); // jBSave.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put( // KeyStroke.getKeyStroke(KeyEvent.VK_N, KeyEvent.CTRL_DOWN_MASK), key); // jBSave.getActionMap().put(key, buttonAction); }
package uk.ac.ebi.pride.archive.dataprovider.data.spectra; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class SpectrumNumberArrayDeserializerTest{ String spectraLine = "{\"usi\":\"mzspec:PRD000902:Rice_leaf_0h_phospho_test1:scan:3817:N[UNIMOD:7]NGSSIGS[UNIMOD:21]PGPGR/2\",\"spectraUsi\":\"mzspec:PXD002222:Rice_leaf_0h_phospho_test1:scan:3817\",\"assayAccession\":\"c0300332f12ec3420b966972b077cdb25520c0ba\",\"projectAccession\":\"PXD002222\",\"reanalysisAccession\":\"PRD000902\",\"proteinAccessions\":[\"Os07t0584500-01\"],\"peptideSequence\":\"NNGSSIGSPGPGR\",\"peptidoform\":\"N[UNIMOD:7]NGSSIGS[UNIMOD:21]PGPGR/2\",\"scores\":[{\"accession\":\"MS:1002257\",\"name\":\"Comet:expectation value\",\"value\":\"2.99E-8\"},{\"accession\":\"MS:1002354\",\"name\":\"PSM-level q-value\",\"value\":\"5.0E-6\"},{\"accession\":\"MS:1002357\",\"name\":\"PSM-level probability\",\"value\":\"1.0\"},{\"accession\":\"MS:1002355\",\"name\":\"PSM-level FDRScore\",\"value\":\"1.2510634038933093E-5\"}],\"sampleProperties\":[{\"accession\":\"EFO:0000324\",\"name\":\"cell type\",\"value\":\"not applicable\"},{\"accession\":\"OBI:0100026\",\"name\":\"organism\",\"value\":\"Oryza sativa\"},{\"accession\":\"EFO:0000635\",\"name\":\"organism part\",\"value\":\"Leaf\"},{\"accession\":\"EFO:0000408\",\"name\":\"disease\",\"value\":\"Xanthomonas oryzae pv. oryzae\"},{\"accession\":\"EFO:0002091\",\"name\":\"biological replicate\",\"value\":\"1\"}],\"isDecoy\":false,\"isValid\":true,\"precursorCharge\":2,\"precursorMz\":640.764810900142,\"bestSearchEngineScore\":{\"accession\":\"MS:1002354\",\"name\":\"PSM-level q-value\",\"value\":\"5.0E-6\"},\"numPeaks\":198,\"masses\":\"eJwllFtsVFUUhjdTi0JjiKiI5bbpxBdiH+TS2MbAYcolaRMCNTFC0Z5OKYp2gCktlpYpZ3pLsBRKJ/AwBjnTC2BJY2wjRAzkMBaMVDBgImGSMYdLjKQBgQolpeXSbz39WXuvy7/W+vdWShlNT+sN9QKbC0A34CnGbpmK7bRG5b7K7x9Hq8K3eRxVMF42jvZmf5C44mW12LF0C+zOAN08z2fYeQu5d1a0bR1HHX+fe5XVVg0mcvZSZ+b8Cvxn+74i/mb7bupO92Ob08p3kOfBujrsGXVf4D/p/xryDGWFyXOvgHtraBp1rDc64et42qvAkSrh9/IocfrRvK/FvsG9kYgXkt8Tp3/9LANezpREA3Ue+kq5H90TkPh+5mI/jpeA/3STx4z7TOp7T1DPWNgL6py78LQWT4Snzp5MXme5R3BlRhP+qxLwMvJypJ9V6Zy7+xuEX9uytfif6a3kvCvOPNz8ieQxYz72YxVkybxWH6Su830/fbsf+bDNI707qVNUXSdYB9r+uMSZtcKz9ALoNrxE38ahcuZifu4T/7IR6W9Lk+TZch50yuaDKuJnProiIXuK3tgAv9Bk0VttUnRS2bGd+52hasEe0NzqZa6qPEX4H07bAx4Iyzw3LkVf6suL9OP4W4izoz+S3/r2h0byBebiZwcuix5zU9YT13kN/uYKr+zN/hD9qaLwNvy7CrGN9hTqGh/3oUuVHxL9rW5EB3pRPfztRX2guSSAbu0LAy3Y/X+Cxm9j0velmMzrfCP7VtnNxLkfeNGt6b0OT+fKJtnXX5ky17+HmrEXn91I/ECgFfv3IGi80yFzessLTzv9E+ah36yhH/NWpeSZUS/22xH2aaQMloMjg+R356V+Cq9XFsi+R08Tp//1bsK+nYvunOGw3Kf+Ck91f6n0kbaNPs3hmOzjXoz5qjklzNH+r0POB/PZm/tkAv+QHg7Lu51Vg+719VzZa/9c/hWdLKE/4+oYujH/uMm71O9G8DcvJ0Ps8WqY+esrE9CfM5BGHv3LrF3wSBb7OV9QCB8dK8G2fhoj3jn1Kn669Rw6cfsyxT61n371mRjvzDnZhz71d4XUM4ty2bO1L5U4ozubc7f5XBH+Pcfln+g8DR+ryyv9H00KHlsj84sE2Y8T7RGdHcoU/8N36FtF7lPfKP1G/odAvui0uEPsg3dCErcGHbnRCP+FFX4PVDte34cdibFHtfs19q/rg/BzG36uMZ4DtkiqlQ==\",\"intensities\":\"eJwllHtMz3sYx7/Nco+Ve23tO8sOM3+g5fzyG9+jhMU5uS2X2Pc4OcOsMJEO85XNLUYZbc6vfJVbV7+Ewo6+1UmcTuYnlzL07WZGpJZx4o/j93r+evZ8nud5P+/n9lEURSlPyNe+C9Vxo9QrtdY119FjjGdeaTSHFKOv3+L2SssnvwA9xVXplbZnMfHK2sRH6N3Dm7AnT77M+7wR4Nnbh3wBb3NCEThNUbnYD8VcxL5vKbjmxgXnsccdvOuV+sSWWuI6vvJuLFwJrhr7C3aruwxe2tQ56GptGna7cl+H5P96CX226xx+peGFxDmyLoD389Zr5J3QCi+l+0/8lSfDsFvluehacC31WW9PuKVeP+zqlB9yJT70vvCOE36fMvGzI9rRDXVDFX6Xwp/g9+2yhZ/lIK+R7CP821rfIkOjpe6yPPpvhmTC01Y/taCn72ReyoNtMofo0+TT6/+ij9byHa/wC9qQA3//sIe8rzhwB3kytY48wZHgmPE1EnfVZ8BPXpwVzjbeXWnUre8wvyF3Ly9BPhxFPvXDO/D1gCp42vHvPNKHIPIpVh7xSoUbXa3OwN+uSrzKe8lKmU/dfPZDTYmROXycQb9UdzF9trv20EfrwS2Zu98smWPfdJlfeIX049Tvgn96Pf7asff0W4115vE+OBCeeuMq8R95QvZtdRR+SmEweEp7xz/I6psv8P/DHzzd7S/z3+JuAC9snPALHwMf5bccpBnpAc9w9ZLXCJhHPuP9SeE/ehB1W13lcg/t99kHLWia7N/QYu7CSveYyIGR8DL2K3Kf9X346Wdc7Il2pScLe3P8Pex1BczTPt9HvdqbtfRF60zl3UhpkP1w3mtErpsmc+339G/kxUHw1tc0Pgcvu1D6tPAA+Sz/X7GrWxfJnR9dBL6V1il+YZvgoSf1UofRlSH7l6AizVkR3KOZUijz/9wj+5DYJHOpSGKPNOd/3Jfhe5a8yt2Of8HxCRG8OzNlzpWOx9ivBb4m78C51KXHyd7by8bLfe3vesq7Y84V4goqaogLrEc3/HzJa28skf+uKKmauNSdveiTXsid3S6Cr5YdxN1rI9uJtwKGNoP3ciZztZccl/sfEyV7ED2YPhmZudLHYWN78G/olHk5jiCVjB+Rutmf/PoeJ/uozj7Mnui+6fTNCM3m/7VutYFnB3j4H/Tkg9Rv9y9jnlZpDfto7x0LHzMijr7oU3ZRv5bVwvy1Y74yzwn9aqRuHd5a8psq7X+A5tWt\",\"msLevel\":2,\"retentionTime\":753.2,\"missedCleavages\":0,\"modifications\":[{\"@type\":\"IdentifiedModification\",\"neutralLoss\":null,\"positionMap\":[{\"key\":1,\"value\":[{\"@type\":\"CvParam\",\"cvLabel\":\"MS\",\"accession\":\"MS:1003147\",\"name\":\"PTMProphet probability\",\"value\":\"0.3333\"}]}],\"modification\":{\"@type\":\"CvParam\",\"cvLabel\":\"UNIMOD\",\"accession\":\"UNIMOD:7\",\"name\":\"Deamidated\",\"value\":\"0.984016\"},\"attributes\":[]},{\"@type\":\"IdentifiedModification\",\"neutralLoss\":null,\"positionMap\":[{\"key\":8,\"value\":[{\"@type\":\"CvParam\",\"cvLabel\":\"MS\",\"accession\":\"MS:1003147\",\"name\":\"PTMProphet probability\",\"value\":\"0.774\"}]}],\"modification\":{\"@type\":\"CvParam\",\"cvLabel\":\"UNIMOD\",\"accession\":\"UNIMOD:21\",\"name\":\"Phospho\",\"value\":\"79.9663\"},\"attributes\":[]}],\"qualityEstimationMethods\":[{\"accession\":\"MS:1001194\",\"name\":\"quality estimation with decoy database\",\"value\":\"true\"}],\"properties\":[{\"accession\":\"PRIDE:0000511\",\"name\":\"Pass submitter threshold\",\"value\":\"true\"}]}"; String arrayLine = "{\"usi\":\"mzspec:PRD000902:Rice_leaf_0h_phospho_test1:scan:3817:N[UNIMOD:7]NGSSIGS[UNIMOD:21]PGPGR/2\",\"spectraUsi\":null,\"assayAccession\":null,\"projectAccession\":null,\"reanalysisAccession\":null,\"proteinAccessions\":null,\"peptideSequence\":null,\"peptidoform\":null,\"scores\":null,\"sampleProperties\":null,\"isDecoy\":null,\"isValid\":null,\"precursorCharge\":null,\"precursorMz\":null,\"bestSearchEngineScore\":null,\"numPeaks\":null,\"msLevel\":2,\"retentionTime\":753.2,\"missedCleavages\":0,\"modifications\":[{\"@type\":\"IdentifiedModification\",\"neutralLoss\":null,\"positionMap\":[{\"key\":1,\"value\":[{\"@type\":\"CvParam\",\"cvLabel\":\"MS\",\"accession\":\"MS:1003147\",\"name\":\"PTMProphet probability\",\"value\":\"0.3333\"}]}],\"modification\":{\"@type\":\"CvParam\",\"cvLabel\":\"UNIMOD\",\"accession\":\"UNIMOD:7\",\"name\":\"Deamidated\",\"value\":\"0.984016\"},\"attributes\":[]},{\"@type\":\"IdentifiedModification\",\"neutralLoss\":null,\"positionMap\":[{\"key\":8,\"value\":[{\"@type\":\"CvParam\",\"cvLabel\":\"MS\",\"accession\":\"MS:1003147\",\"name\":\"PTMProphet probability\",\"value\":\"0.774\"}]}],\"modification\":{\"@type\":\"CvParam\",\"cvLabel\":\"UNIMOD\",\"accession\":\"UNIMOD:21\",\"name\":\"Phospho\",\"value\":\"79.9663\"},\"attributes\":[]}],\"qualityEstimationMethods\":[{\"accession\":\"MS:1001194\",\"name\":\"quality estimation with decoy database\",\"value\":\"true\"}],\"properties\":[{\"accession\":\"PRIDE:0000511\",\"name\":\"Pass submitter threshold\",\"value\":\"true\"}],\"masses\":[639.8155517578125,618.3179931640625,136.07591247558594,610.3189697265625,627.3206787109375,147.07717895507812,242.07672119140625,230.0762939453125,278.1520080566406,484.2738952636719,515.3289184570312,516.3333129882812,184.07164001464844,483.2682189941406,265.14227294921875,519.0947875976562,425.13818359375,967.3564453125,323.13189697265625,372.1324768066406,820.3612670898438,374.1309814453125,407.1304626464844,587.3685302734375,212.0658416748047,447.2523498535156,550.86865234375,586.3673095703125,514.868896484375,229.12750244140625,394.12567138671875,527.1224365234375,447.7519226074219,837.3701782226562,398.1269226074219,111.04457092285156,632.2511596679688,322.1872863769531,667.2576904296875,170.0924072265625,236.4058074951172,246.15504455566406,158.0928497314453,394.6813049316406,130.0862274169922,534.767333984375,534.2755126953125,573.7783813476562,576.780517578125,641.2778930664062,640.2840576171875,708.2850341796875,859.2882080078125,583.2862548828125,707.288330078125,110.07140350341797,101.0714340209961,347.17156982421875,214.08274841308594,640.7870483398438,276.1643981933594,582.790283203125,562.7892456054688,444.29290771484375,552.2924194335938,459.1656188964844,591.2965087890625,592.2965087890625,600.2981567382812,591.7970581054688,601.2993774414062,232.14122009277344,327.16339111328125,584.3009643554688,543.3030395507812,592.8042602539062,600.8043212890625,582.3031005859375,155.0804443359375,571.3067016601562,167.08132934570312,609.311279296875,493.84344482421875,362.21624755859375,423.84283447265625,426.84283447265625,386.2149353027344,432.21533203125,897.4530639648438,560.1981811523438,260.0875244140625,460.838623046875,424.83660888671875,630.7005004882812,694.202392578125,258.08917236328125,269.0892639160156,112.05097198486328,539.205078125,129.1023406982422,810.453369140625,312.085693359375,811.4558715820312,896.4542236328125,379.20904541015625,439.830810546875,244.166015625,360.2004699707031,363.2005920410156,406.8279724121094,953.4739379882812,954.4708862304688,639.7232666015625,596.2259521484375,848.7218017578125,360.701416015625,225.10118103027344,270.0711364746094,557.2279052734375,581.7296752929688,894.4837646484375,182.0388641357422,1051.448486328125,1052.4495849609375,442.19659423828125,370.1933288574219,421.8190002441406,311.6926574707031,590.7365112304688,312.19427490234375,329.1936950683594,302.68829345703125,893.4971923828125,120.08074188232422,323.189453125,599.7482299804688,201.12208557128906,210.1222381591797,328.12298583984375,568.8776245117188,356.121337890625,622.3807983398438,426.1228942871094,133.0606231689453,908.39013671875,426.2460021972656,452.7450256347656,136.06199645996094,228.06141662597656,719.3895263671875,452.2424621582031,185.05526733398438,438.2414855957031,495.86505126953125,175.1190643310547,722.3965454101562,477.8636169433594,408.1151123046875,152.05690002441406,448.73724365234375,497.8601379394531,147.0582275390625,907.4002685546875,147.11341857910156,479.8577880859375,496.85809326171875,115.08692169189453,498.8564147949219,329.1079406738281,282.1089172363281,395.23236083984375,405.7287902832031,936.4215698242188,112.08688354492188,403.60406494140625,127.08666229248047,394.72991943359375,459.8526306152344,450.2279052734375,461.8534851074219,357.1037292480469,311.0986022949219,442.85028076171875,450.850830078125,494.8514404296875,287.098388671875,723.4244384765625,809.4286499023438,724.4224853515625,478.8493347167969,261.100830078125,345.2253112792969,339.0941162109375,994.43408203125,213.04925537109375,289.095947265625,391.0945129394531,443.7199401855469],\"intensities\":[3383.359375,5046.22314453125,5469.8837890625,24065.251953125,3858.4365234375,4208.39501953125,3541.00341796875,9016.9541015625,3368.909912109375,18877.46875,25663.779296875,3093.734619140625,5395.27734375,98487.3046875,3767.2119140625,2467.42529296875,2856.265625,3497.753662109375,2596.706298828125,11534.724609375,12226.3154296875,2685.9482421875,3116.6494140625,11422.6806640625,4279.9443359375,11396.384765625,3141.888916015625,44046.05859375,3069.638671875,2254.124755859375,3613.35009765625,2766.61279296875,5233.306640625,3825.073486328125,3021.970703125,2695.416015625,3025.86083984375,19228.47265625,4240.9169921875,2694.68359375,2451.588134765625,12904.2939453125,3118.18115234375,4247.95751953125,3186.132568359375,9424.25390625,21738.619140625,8529.974609375,3740.875244140625,11266.94140625,55063.09765625,11926.4072265625,3924.8583984375,5271.14306640625,36777.02734375,4983.56884765625,8933.609375,4246.29638671875,3550.901123046875,31193.33984375,2356.053955078125,16600.26953125,7814.3466796875,14085.154296875,4932.11767578125,3554.696533203125,188470.34375,39394.76171875,18990.447265625,117255.3984375,4437.48583984375,4117.81396484375,2421.965087890625,3937.035888671875,18349.576171875,16493.44921875,19111.0,17090.984375,2377.381103515625,4719.76123046875,2988.845703125,99468.7421875,3752.238525390625,9327.875,2775.343994140625,3134.968505859375,11637.615234375,3615.02685546875,5171.9794921875,5055.22900390625,2355.291015625,3122.794677734375,22454.20703125,3230.170166015625,3853.021240234375,4954.84521484375,2632.0390625,21785.43359375,5150.671875,13771.78125,29415.046875,3080.740966796875,4113.68896484375,20161.75,2700.607177734375,3595.614990234375,3665.193359375,22341.072265625,3322.3056640625,4935.072265625,11559.85546875,2948.54443359375,3804.46826171875,8595.787109375,2969.05322265625,2903.0234375,2152.78466796875,5188.0341796875,5376.513671875,3069.400634765625,12089.2060546875,1916.671142578125,12489.74609375,3541.896728515625,3965.322021484375,2351.45361328125,3521.46142578125,31565.9140625,25376.947265625,4402.38525390625,10668.0263671875,3204.824951171875,27489.458984375,2646.308837890625,12044.599609375,3248.53466796875,3110.720947265625,2342.7734375,2678.27294921875,12500.427734375,2938.229248046875,16971.7421875,16513.73046875,2209.622314453125,3030.239501953125,4850.96826171875,5081.43359375,17878.984375,2556.61767578125,12094.04296875,14795.546875,16528.02734375,3101.87255859375,20711.01953125,45269.625,24852.130859375,16601.443359375,11332.6630859375,23486.048828125,4001.112060546875,11135.337890625,4070.55078125,17428.2109375,4273.41357421875,9963.357421875,83832.1328125,4316.1630859375,4781.73193359375,12855.236328125,4082.03955078125,31792.29296875,3741.931640625,3143.661865234375,3235.0458984375,2309.1474609375,12103.18359375,74112.921875,3574.412109375,3525.113037109375,3484.28515625,9741.2529296875,13432.9794921875,8466.4931640625,3016.510498046875,3407.1025390625,12231.458984375,36488.58984375,25117.880859375,10606.0537109375,22294.80859375,3084.249755859375,16753.056640625,10994.3544921875,4577.6142578125,3074.77587890625,10758.2890625,3248.254150390625,9680.939453125]}"; private ObjectMapper objectMapper; @Before public void setUp() throws Exception { this.objectMapper = new ObjectMapper(); } @Test public void testDeserialize() { try { BinaryArchiveSpectrum spectrum = objectMapper.readValue(spectraLine, BinaryArchiveSpectrum.class); Assert.assertEquals("mzspec:PRD000902:Rice_leaf_0h_phospho_test1:scan:3817:N[UNIMOD:7]NGSSIGS[UNIMOD:21]PGPGR/2", spectrum.getUsi()); ArchiveSpectrum nonBinSpec = new ArchiveSpectrum(spectrum); String line = objectMapper.writeValueAsString(nonBinSpec); Assert.assertEquals(line, arrayLine); ArchiveSpectrum archiveSpectrum = objectMapper.readValue(arrayLine, ArchiveSpectrum.class); Assert.assertEquals("mzspec:PRD000902:Rice_leaf_0h_phospho_test1:scan:3817:N[UNIMOD:7]NGSSIGS[UNIMOD:21]PGPGR/2", archiveSpectrum.getUsi()); } catch (JsonProcessingException e) { throw new RuntimeException(e); } } }
package org.openmrs.module.xforms; import static org.openmrs.module.xforms.XformBuilder.ATTRIBUTE_BIND; import static org.openmrs.module.xforms.XformBuilder.ATTRIBUTE_CONCEPT_ID; import static org.openmrs.module.xforms.XformBuilder.ATTRIBUTE_CONSTRAINT; import static org.openmrs.module.xforms.XformBuilder.ATTRIBUTE_ID; import static org.openmrs.module.xforms.XformBuilder.ATTRIBUTE_MESSAGE; import static org.openmrs.module.xforms.XformBuilder.ATTRIBUTE_NODESET; import static org.openmrs.module.xforms.XformBuilder.ATTRIBUTE_OPENMRS_CONCEPT; import static org.openmrs.module.xforms.XformBuilder.ATTRIBUTE_TYPE; import static org.openmrs.module.xforms.XformBuilder.ATTRIBUTE_UUID; import static org.openmrs.module.xforms.XformBuilder.CONTROL_INPUT; import static org.openmrs.module.xforms.XformBuilder.CONTROL_REPEAT; import static org.openmrs.module.xforms.XformBuilder.CONTROL_SELECT; import static org.openmrs.module.xforms.XformBuilder.CONTROL_SELECT1; import static org.openmrs.module.xforms.XformBuilder.DATA_TYPE_BASE64BINARY; import static org.openmrs.module.xforms.XformBuilder.DATA_TYPE_BOOLEAN; import static org.openmrs.module.xforms.XformBuilder.DATA_TYPE_DATE; import static org.openmrs.module.xforms.XformBuilder.DATA_TYPE_DATETIME; import static org.openmrs.module.xforms.XformBuilder.DATA_TYPE_DECIMAL; import static org.openmrs.module.xforms.XformBuilder.DATA_TYPE_TEXT; import static org.openmrs.module.xforms.XformBuilder.DATA_TYPE_TIME; import static org.openmrs.module.xforms.XformBuilder.INSTANCE_ID; import static org.openmrs.module.xforms.XformBuilder.MODEL_ID; import static org.openmrs.module.xforms.XformBuilder.NAMESPACE_XFORMS; import static org.openmrs.module.xforms.XformBuilder.NAMESPACE_XML_INSTANCE; import static org.openmrs.module.xforms.XformBuilder.NAMESPACE_XML_SCHEMA; import static org.openmrs.module.xforms.XformBuilder.NODE_BIND; import static org.openmrs.module.xforms.XformBuilder.NODE_GROUP; import static org.openmrs.module.xforms.XformBuilder.NODE_HINT; import static org.openmrs.module.xforms.XformBuilder.NODE_INSTANCE; import static org.openmrs.module.xforms.XformBuilder.NODE_ITEM; import static org.openmrs.module.xforms.XformBuilder.NODE_LABEL; import static org.openmrs.module.xforms.XformBuilder.NODE_MODEL; import static org.openmrs.module.xforms.XformBuilder.NODE_VALUE; import static org.openmrs.module.xforms.XformBuilder.NODE_XFORMS; import static org.openmrs.module.xforms.XformBuilder.PREFIX_XFORMS; import static org.openmrs.module.xforms.XformBuilder.PREFIX_XML_INSTANCES; import static org.openmrs.module.xforms.XformBuilder.PREFIX_XML_SCHEMA; import static org.openmrs.module.xforms.XformBuilder.PREFIX_XML_SCHEMA2; import java.io.StringReader; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Hashtable; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.TreeMap; import java.util.TreeSet; import java.util.Vector; import org.apache.commons.lang.StringEscapeUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.kxml2.kdom.Document; import org.kxml2.kdom.Element; import org.kxml2.kdom.Node; import org.openmrs.Concept; import org.openmrs.ConceptAnswer; import org.openmrs.ConceptDatatype; import org.openmrs.ConceptName; import org.openmrs.ConceptNumeric; import org.openmrs.Field; import org.openmrs.Form; import org.openmrs.FormField; import org.openmrs.Location; import org.openmrs.Person; import org.openmrs.Provider; import org.openmrs.api.context.Context; import org.openmrs.hl7.HL7Constants; import org.openmrs.module.xforms.RelativeBuilder; import org.openmrs.module.xforms.XformConstants; import org.openmrs.module.xforms.formentry.FormEntryWrapper; import org.openmrs.module.xforms.formentry.FormSchemaFragment; import org.openmrs.module.xforms.util.XformsUtil; import org.openmrs.util.FormConstants; import org.openmrs.util.FormUtil; /** * This is a clone of the Xforms module XformBuilderEx class, allowing us to tinker with the view * creation code separately from the module itself. */ public class BuendiaXformBuilderEx { private static Log log = LogFactory.getLog(BuendiaXformBuilderEx.class); private final Map<String, Element> bindings = new HashMap<>(); private final Map<FormField, String> fieldTokens = new HashMap<>(); private final boolean useConceptIdAsHint; private BuendiaXformBuilderEx() { useConceptIdAsHint = "true".equalsIgnoreCase(Context.getAdministrationService().getGlobalProperty("xforms.useConceptIdAsHint")); } /** * Builds an xform for an given an openmrs form. This is the only * public member in the class; it constructs an instance (to avoid * nasty statics) and then invokes private methods appropriately. */ public static String buildXform(Form form) throws Exception { return new BuendiaXformBuilderEx().buildXformImpl(form); } private String buildXformImpl(Form form) throws Exception { boolean includeRelationshipNodes = false; /* * TODO(jonskeet): Reinstate this code when we're using a version of the * Xforms modules which has that property. (Or just don't reinstate...) * * !"false".equals(Context.getAdministrationService() * .getGlobalProperty(XformConstants.GLOBAL_PROP_KEY_INCLUDE_PATIENT_RELATIONSHIPS)); */ //String schemaXml = XformsUtil.getSchema(form); String templateXml = FormEntryWrapper.getFormTemplate(form); //Add relationship data node if (includeRelationshipNodes) { templateXml = templateXml.replace("</patient>", " <patient_relative>\n <patient_relative.person/>\n <patient_relative.relationship/>\n </patient_relative>\n </patient>"); } Document doc = new Document(); doc.setEncoding(XformConstants.DEFAULT_CHARACTER_ENCODING); Element xformsNode = appendElement(doc, NAMESPACE_XFORMS, NODE_XFORMS); xformsNode.setPrefix(PREFIX_XFORMS, NAMESPACE_XFORMS); xformsNode.setPrefix(PREFIX_XML_SCHEMA, NAMESPACE_XML_SCHEMA); xformsNode.setPrefix(PREFIX_XML_SCHEMA2, NAMESPACE_XML_SCHEMA); xformsNode.setPrefix(PREFIX_XML_INSTANCES, NAMESPACE_XML_INSTANCE); xformsNode.setPrefix("jr", "http://openrosa.org/javarosa"); Element modelNode = appendElement(xformsNode, NAMESPACE_XFORMS, NODE_MODEL); modelNode.setAttribute(null, ATTRIBUTE_ID, MODEL_ID); // All our UI nodes are appended directly into the xforms node. // Another alternative would be to create the HTML body node here, and append // everything under that. Element bodyNode = xformsNode; Element instanceNode = appendElement(modelNode, NAMESPACE_XFORMS, NODE_INSTANCE); instanceNode.setAttribute(null, ATTRIBUTE_ID, INSTANCE_ID); Element formNode = (Element) BuendiaXformBuilder.getDocument(new StringReader(templateXml)).getRootElement(); formNode.setAttribute(null, ATTRIBUTE_UUID, form.getUuid()); instanceNode.addChild(Element.ELEMENT, formNode); // (Note for comparison with XformBuilderEx: schema doc code removed here, as it wasn't actually used.) //TODO This block should be replaced with using database field items instead of // parsing the template document. Hashtable<String, String> problemList = new Hashtable<String, String>(); Hashtable<String, String> problemListItems = new Hashtable<String, String>(); BuendiaXformBuilder.parseTemplate(modelNode, formNode, formNode, bindings, problemList, problemListItems, 0); buildUInodes(form, bodyNode); //find all conceptId attributes in the document and replace their value with a mapped concept String prefSourceName = Context.getAdministrationService().getGlobalProperty( XformConstants.GLOBAL_PROP_KEY_PREFERRED_CONCEPT_SOURCE); //we only use the mappings if the global property is set if (StringUtils.isNotBlank(prefSourceName)) { for (int i = 0; i < formNode.getChildCount(); i++) { Element childElement = formNode.getElement(i); if (childElement != null) { for (int j = 0; j < childElement.getChildCount(); j++) { if (childElement.getElement(j) != null) { Element grandChildElement = childElement.getElement(j); String value = grandChildElement.getAttributeValue(null, ATTRIBUTE_OPENMRS_CONCEPT); if (StringUtils.isNotBlank(value)) BuendiaXformBuilder.addConceptMapAttributes(grandChildElement, value); } } } } } if (includeRelationshipNodes) { RelativeBuilder.build(modelNode, bodyNode, formNode); } return BuendiaXformBuilder.fromDoc2String(doc); } private void buildUInodes(Form form, Element bodyNode) { Locale locale = Context.getLocale(); TreeMap<Integer, TreeSet<FormField>> formStructure = FormUtil.getFormStructure(form); buildUInodes(form, formStructure, 0, locale, bodyNode); } private void buildUInodes(Form form, TreeMap<Integer, TreeSet<FormField>> formStructure, Integer sectionId, Locale locale, Element parentUiNode) { TreeSet<FormField> section = formStructure.get(sectionId); if (section == null) { return; } // Note: FormUtil.getTagList needs a Vector<String>. Urgh. Vector<String> tagList = new Vector<>(); for(FormField formField : section) { String sectionName = FormUtil.getXmlToken(formField.getField().getName()); String name = FormUtil.getNewTag(sectionName, tagList); if(formField.getParent() != null && fieldTokens.values().contains(name)){ String parentName = fieldTokens.get(formField.getParent()); String token = parentName + "_" + name; if(!bindings.containsKey(token)) { token = FormUtil.getNewTag(FormUtil.getXmlToken(formField.getParent().getField().getName()), new Vector<String>()); token = token + "_" + name; } name = token; } fieldTokens.put(formField, name); Field field = formField.getField(); boolean required = formField.isRequired(); Element fieldUiNode; int fieldTypeId = field.getFieldType().getFieldTypeId(); if (fieldTypeId == FormConstants.FIELD_TYPE_CONCEPT) { Concept concept = field.getConcept(); ConceptDatatype datatype = concept.getDatatype(); // TODO(jonskeet): Don't rely on names here? (Do we even need problem lists?) if ( (name.contains("problem_added") || name.contains("problem_resolved")) && formField.getParent() != null && (formField.getParent().getField().getName().contains("PROBLEM LIST")) ){ fieldUiNode = addProblemList(name, concept, required, locale, formField, parentUiNode); } else if (name.equals("problem_list")) { // TODO(jonskeet): Work out what we should do here. There won't be any bindings for this. // The child nodes will be covered by the case above, when we recurse down. fieldUiNode = parentUiNode; } else { switch (datatype.getHl7Abbreviation()) { case HL7Constants.HL7_BOOLEAN: fieldUiNode = addUiNode(name, concept, DATA_TYPE_BOOLEAN, CONTROL_INPUT, locale, parentUiNode); break; case HL7Constants.HL7_DATE: fieldUiNode = addUiNode(name, concept, DATA_TYPE_DATE, CONTROL_INPUT, locale, parentUiNode); break; case HL7Constants.HL7_DATETIME: fieldUiNode = addUiNode(name, concept, DATA_TYPE_DATETIME, CONTROL_INPUT, locale, parentUiNode); break; case HL7Constants.HL7_TIME: fieldUiNode = addUiNode(name, concept, DATA_TYPE_TIME, CONTROL_INPUT, locale, parentUiNode); break; case HL7Constants.HL7_TEXT: fieldUiNode = addUiNode(name, concept, DATA_TYPE_TEXT, CONTROL_INPUT, locale, parentUiNode); break; case HL7Constants.HL7_NUMERIC: ConceptNumeric conceptNumeric = Context.getConceptService().getConceptNumeric(concept.getConceptId()); fieldUiNode = addUiNode(name, conceptNumeric, DATA_TYPE_DECIMAL, CONTROL_INPUT, locale, parentUiNode); break; case HL7Constants.HL7_CODED: case HL7Constants.HL7_CODED_WITH_EXCEPTIONS: fieldUiNode = addCodedField(name, formField, field, required, concept, locale, parentUiNode); break; case "ED": // This isn't in HL7Constants as far as I can tell. fieldUiNode = addUiNode(name, concept, DATA_TYPE_BASE64BINARY, CONTROL_INPUT, locale, parentUiNode); break; default: // TODO(jonskeet): Remove this hack when we understand better... if (field.getName().equals("OBS")) { fieldUiNode = createGroupNode(formField, locale, parentUiNode); } else { // Don't understand this concept log.warn("Unhandled HL7 abbreviation " + datatype.getHl7Abbreviation() + " for field " + field.getName()); continue; // Skip recursion, go to next field } } } } else if (fieldTypeId == FormConstants.FIELD_TYPE_SECTION) { // TODO(jonskeet): Use the description for a hint? fieldUiNode = appendElement(parentUiNode, NAMESPACE_XFORMS, NODE_GROUP); Element label = appendElement(fieldUiNode, NAMESPACE_XFORMS, NODE_LABEL); label.addChild(Node.TEXT, getDisplayName(formField)); } else if (fieldTypeId == FormConstants.FIELD_TYPE_DATABASE) { fieldUiNode = addDatabaseElementUiNode(name, formField, parentUiNode); } else { // Don't understand this field type log.warn("Unhandled field type " + field.getFieldType().getName() + " for field " + field.getName()); continue; // Skip recursion, go to next field } // Recurse down to subnodes. buildUInodes(form, formStructure, formField.getFormFieldId(), locale, fieldUiNode); } } private Element addUiNode(String token, Concept concept, String dataType, String controlName, Locale locale, Element bodyNode) { String bindName = token; Element controlNode = appendElement(bodyNode, NAMESPACE_XFORMS, controlName); controlNode.setAttribute(null, ATTRIBUTE_BIND, bindName); Element bindNode = bindings.get(bindName); if (bindNode == null) { throw new IllegalArgumentException("No bind node for bindName " + bindName); } bindNode.setAttribute(null, ATTRIBUTE_TYPE, dataType); //create the label ConceptName name = concept.getName(locale, false); if (name == null) { name = concept.getName(); } Element labelNode = appendTextElement(controlNode, NAMESPACE_XFORMS, NODE_LABEL, name.getName()); addHintNode(labelNode, concept); if(concept instanceof ConceptNumeric) { ConceptNumeric numericConcept = (ConceptNumeric)concept; if(numericConcept.isPrecise()){ Double minInclusive = numericConcept.getLowAbsolute(); Double maxInclusive = numericConcept.getHiAbsolute(); if(!(minInclusive == null && maxInclusive == null)){ String lower = (minInclusive == null ? "" : FormSchemaFragment.numericToString(minInclusive, numericConcept.isPrecise())); String upper = (maxInclusive == null ? "" : FormSchemaFragment.numericToString(maxInclusive, numericConcept.isPrecise())); bindNode.setAttribute(null, ATTRIBUTE_CONSTRAINT, ". >= " + lower + " and . <= " + upper); bindNode.setAttribute(null, (XformsUtil.isJavaRosaSaveFormat() ? "jr:constraintMsg" : ATTRIBUTE_MESSAGE), "value should be between " + lower + " and " + upper + " inclusive"); } } } return controlNode; } private void addCodedUiNodes(boolean multiplSel, Element controlNode, Collection<ConceptAnswer> answerList, Concept concept, String dataType, String controlName, Locale locale){ for (ConceptAnswer answer : answerList) { String conceptName = answer.getAnswerConcept().getName(locale).getName(); String conceptValue; if (answer.getAnswerConcept().getConceptClass().getConceptClassId().equals(HL7Constants.CLASS_DRUG) && answer.getAnswerDrug() != null) { conceptName = answer.getAnswerDrug().getName(); if(multiplSel) conceptValue = FormUtil.getXmlToken(conceptName); else { conceptValue = FormUtil.conceptToString(answer.getAnswerConcept(), locale) + "^" + FormUtil.drugToString(answer.getAnswerDrug()); } } else { if(multiplSel) conceptValue = FormUtil.getXmlToken(conceptName); else conceptValue = FormUtil.conceptToString(answer.getAnswerConcept(), locale); } Element itemNode = appendElement(controlNode, NAMESPACE_XFORMS, NODE_ITEM); itemNode.setAttribute(null, ATTRIBUTE_CONCEPT_ID, concept.getConceptId().toString()); appendTextElement(itemNode, NAMESPACE_XFORMS, NODE_LABEL, conceptName); //TODO This will make sense after the form designer's OptionDef implements //the xforms hint. //addHintNode(itemLabelNode, answer.getAnswerConcept()); appendTextElement(itemNode, NAMESPACE_XFORMS, NODE_VALUE, conceptValue); } } private Element addProblemList(String token, Concept concept, boolean required, Locale locale, FormField formField, Node parentUiNode) { Element groupNode = appendElement(parentUiNode, NAMESPACE_XFORMS, NODE_GROUP); Element labelNode = appendTextElement(groupNode, NAMESPACE_XFORMS, NODE_LABEL, formField.getField().getConcept().getName(locale, false).getName()); addHintNode(labelNode, concept); Element repeatControl = appendElement(groupNode, NAMESPACE_XFORMS, CONTROL_REPEAT); repeatControl.setAttribute(null, ATTRIBUTE_BIND, token); //add the input node. Element controlNode = appendElement(repeatControl, NAMESPACE_XFORMS, CONTROL_INPUT); String nodeset = "problem_list/" + token + "/value"; String id = nodeset.replace('/', '_'); controlNode.setAttribute(null, ATTRIBUTE_BIND, id); //add the label. labelNode = appendTextElement(controlNode, NAMESPACE_XFORMS, NODE_LABEL, token + " value"); addHintNode(labelNode, concept); //create bind node Element bindNode = appendElement(bindings.get(token).getParent(), NAMESPACE_XFORMS, NODE_BIND); bindNode.setAttribute(null, ATTRIBUTE_ID, id); bindNode.setAttribute(null, ATTRIBUTE_NODESET, "/form/" + nodeset); bindNode.setAttribute(null, ATTRIBUTE_TYPE, DATA_TYPE_TEXT); return groupNode; } private Element createGroupNode(FormField formField, Locale locale, Element parentUiNode) { String token = fieldTokens.get(formField); Element groupNode = appendElement(parentUiNode, NAMESPACE_XFORMS, NODE_GROUP); Element labelNode = appendTextElement(groupNode, NAMESPACE_XFORMS, NODE_LABEL, formField.getField().getConcept().getName(locale, false).getName()); addHintNode(labelNode, formField.getField().getConcept()); if (formField.getMaxOccurs() != null && formField.getMaxOccurs() == -1) { Element repeatControl = appendElement(groupNode, NAMESPACE_XFORMS, CONTROL_REPEAT); repeatControl.setAttribute(null, ATTRIBUTE_BIND, token); return repeatControl; } else { groupNode.setAttribute(null, ATTRIBUTE_ID, token); return groupNode; } } private String getDisplayName(FormField formField) { String name = formField.getDescription(); if (StringUtils.isNotEmpty(name)) { return name; } name = formField.getName(); if (StringUtils.isNotEmpty(name)) { return name; } name = formField.getField().getDescription(); if (StringUtils.isNotEmpty(name)) { return name; } name = formField.getField().getName(); if (StringUtils.isNotEmpty(name)) { return name; } throw new IllegalArgumentException("No field name available"); } private Element addCodedField(String name, FormField formField, Field field, boolean required, Concept concept, Locale locale, Element parentUiNode) { if (formField.getMaxOccurs() != null && formField.getMaxOccurs().intValue() == -1) { return addProblemList(name, concept, required, locale, formField, parentUiNode); } else { List<ConceptAnswer> answers = new ArrayList<>(concept.getAnswers(false)); Collections.sort(answers); String controlName = field.getSelectMultiple() ? CONTROL_SELECT : CONTROL_SELECT1; Element controlNode = addUiNode(name, concept, DATA_TYPE_TEXT, controlName, locale, parentUiNode); addCodedUiNodes(field.getSelectMultiple(), controlNode, answers, concept, DATA_TYPE_TEXT, CONTROL_SELECT, locale); return controlNode; } } private void addHintNode(Element labelNode, Concept concept) { String hint = null; if(concept.getDescription() != null) { hint = concept.getDescription().getDescription(); } if(useConceptIdAsHint) { hint = (hint != null ? hint + " [" + concept.getConceptId() + "]" : concept.getConceptId().toString()); } if(hint != null) { appendTextElement(labelNode.getParent(), NAMESPACE_XFORMS, NODE_HINT, hint); } } private static Element appendElement(Node parent, String namespaceURI, String localName) { Element child = parent.createElement(namespaceURI, localName); parent.addChild(Element.ELEMENT, child); return child; } /** * Adds an element to the given parent, with the specified text as the element value */ private static Element appendTextElement(Node parent, String namespaceURI, String localName, String text) { Element child = appendElement(parent, namespaceURI, localName); child.addChild(Element.TEXT, text); return child; } // Code which was in XformBuilder, but is UI-based /** * Builds a UI control node for a table field. * * @param node - the node whose UI control to build. * @param bodyNode - the body node to add the UI control to. * @return - the created UI control node. */ private Element addDatabaseElementUiNode(String bindName, FormField formField, Element parentUiNode) { Element controlNode = appendElement(parentUiNode, NAMESPACE_XFORMS, CONTROL_INPUT); controlNode.setAttribute(null, ATTRIBUTE_BIND, bindName); // TODO: Set the data type on the bind node? It may already be done. // Handle encounter provider / location: these are multiple choice questions, and we populate // the options. Field field = formField.getField(); if ("encounter".equals(field.getTableName())) { if ("location_id".equals(field.getAttributeName())) { controlNode.setName(CONTROL_SELECT1); populateLocations(controlNode); } else if ("provider_id".equals(field.getAttributeName())) { controlNode.setName(CONTROL_SELECT1); populateProviders(controlNode); } } //create the label appendTextElement(controlNode, NAMESPACE_XFORMS, NODE_LABEL, getDisplayName(formField)); return controlNode; } /** * Populates a UI control node with providers. * * @param controlNode - the UI control node. */ private static void populateProviders(Element controlNode) { for (Provider provider : Context.getProviderService().getAllProviders()) { String name = provider.getName(); if (name == null) { Person person = provider.getPerson(); name = person.getPersonName().toString(); } String identifier = provider.getIdentifier(); Integer providerId = provider.getId(); Element itemNode = appendElement(controlNode, NAMESPACE_XFORMS, NODE_ITEM); appendTextElement(itemNode, NAMESPACE_XFORMS, NODE_LABEL, name + " [" + identifier + "]"); appendTextElement(itemNode, NAMESPACE_XFORMS, NODE_VALUE, providerId.toString()); } } /** * Populates a UI control node with locations. * * @param controlNode - the UI control node. */ private static void populateLocations(Element controlNode) { List<Location> locations = Context.getLocationService().getAllLocations(false); for (Location loc : locations) { Element itemNode = appendElement(controlNode, NAMESPACE_XFORMS, NODE_ITEM); appendTextElement(itemNode, NAMESPACE_XFORMS, NODE_LABEL, loc.getName() + " [" + loc.getLocationId() + "]"); appendTextElement(itemNode, NAMESPACE_XFORMS, NODE_VALUE, loc.getLocationId().toString()); } } }
package org.elasticsearch.xpack.sql.qa.mixed_node; import org.apache.http.HttpHost; import org.elasticsearch.Version; import org.elasticsearch.client.Request; import org.elasticsearch.client.Response; import org.elasticsearch.client.RestClient; import org.elasticsearch.common.xcontent.XContentHelper; import org.elasticsearch.common.xcontent.json.JsonXContent; import org.elasticsearch.core.internal.io.IOUtils; import org.elasticsearch.xpack.ql.TestNode; import org.elasticsearch.xpack.ql.TestNodes; import org.elasticsearch.xpack.sql.qa.rest.BaseRestSqlTestCase; import org.junit.AfterClass; import org.junit.Before; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import static org.elasticsearch.xpack.ql.TestUtils.buildNodeAndVersions; import static org.elasticsearch.xpack.ql.execution.search.QlSourceBuilder.INTRODUCING_MISSING_ORDER_IN_COMPOSITE_AGGS_VERSION; public class SqlCompatIT extends BaseRestSqlTestCase { private static RestClient newNodesClient; private static RestClient oldNodesClient; private static Version bwcVersion; @Before public void initBwcClients() throws IOException { if (newNodesClient == null) { assertNull(oldNodesClient); TestNodes nodes = buildNodeAndVersions(client()); bwcVersion = nodes.getBWCVersion(); newNodesClient = buildClient( restClientSettings(), nodes.getNewNodes().stream().map(TestNode::getPublishAddress).toArray(HttpHost[]::new) ); oldNodesClient = buildClient( restClientSettings(), nodes.getBWCNodes().stream().map(TestNode::getPublishAddress).toArray(HttpHost[]::new) ); } } @AfterClass public static void cleanUpClients() throws IOException { IOUtils.close(newNodesClient, oldNodesClient, () -> { newNodesClient = null; oldNodesClient = null; bwcVersion = null; }); } public void testNullsOrderBeforeMissingOrderSupportQueryingNewNode() throws IOException { testNullsOrderBeforeMissingOrderSupport(newNodesClient); } public void testNullsOrderBeforeMissingOrderSupportQueryingOldNode() throws IOException { testNullsOrderBeforeMissingOrderSupport(oldNodesClient); } private void testNullsOrderBeforeMissingOrderSupport(RestClient client) throws IOException { assumeTrue( "expected some nodes without support for missing_order but got none", bwcVersion.before(INTRODUCING_MISSING_ORDER_IN_COMPOSITE_AGGS_VERSION) ); List<Integer> result = runOrderByNullsLastQuery(client); assertEquals(3, result.size()); assertNull(result.get(0)); assertEquals(Integer.valueOf(1), result.get(1)); assertEquals(Integer.valueOf(2), result.get(2)); } public void testNullsOrderWithMissingOrderSupportQueryingNewNode() throws IOException { testNullsOrderWithMissingOrderSupport(newNodesClient); } public void testNullsOrderWithMissingOrderSupportQueryingOldNode() throws IOException { testNullsOrderWithMissingOrderSupport(oldNodesClient); } private void testNullsOrderWithMissingOrderSupport(RestClient client) throws IOException { assumeTrue( "expected all nodes with support for missing_order but got some without", bwcVersion.onOrAfter(INTRODUCING_MISSING_ORDER_IN_COMPOSITE_AGGS_VERSION) ); List<Integer> result = runOrderByNullsLastQuery(client); assertEquals(3, result.size()); assertEquals(Integer.valueOf(1), result.get(0)); assertEquals(Integer.valueOf(2), result.get(1)); assertNull(result.get(2)); } @SuppressWarnings("unchecked") private List<Integer> runOrderByNullsLastQuery(RestClient queryClient) throws IOException { Request putIndex = new Request("PUT", "/test"); putIndex.setJsonEntity("{\"settings\":{\"index\":{\"number_of_shards\":3}}}"); client().performRequest(putIndex); Request indexDocs = new Request("POST", "/test/_bulk"); indexDocs.addParameter("refresh", "true"); StringBuilder bulk = new StringBuilder(); for (String doc : Arrays.asList("{\"int\":1,\"kw\":\"foo\"}", "{\"int\":2,\"kw\":\"bar\"}", "{\"kw\":\"bar\"}")) { bulk.append("{\"index\":{}\n").append(doc).append("\n"); } indexDocs.setJsonEntity(bulk.toString()); client().performRequest(indexDocs); Request query = new Request("GET", "_sql"); query.setJsonEntity("{\"query\":\"SELECT int FROM test GROUP BY 1 ORDER BY 1 NULLS LAST\"}"); Response queryResponse = queryClient.performRequest(query); assertEquals(200, queryResponse.getStatusLine().getStatusCode()); InputStream content = queryResponse.getEntity().getContent(); Map<String, Object> result = XContentHelper.convertToMap(JsonXContent.jsonXContent, content, false); List<List<Object>> rows = (List<List<Object>>) result.get("rows"); return rows.stream().map(row -> (Integer) row.get(0)).collect(Collectors.toList()); } }
package org.xmlunit.exnm; import org.junit.Test; import org.xmlunit.XMLUnitException; import org.xmlunit.builder.DiffBuilder; import org.xmlunit.diff.*; import javax.xml.namespace.QName; import java.util.Iterator; import static junit.framework.TestCase.assertTrue; import static org.junit.Assert.*; public class PlaceholderDifferenceEvaluatorTest { @Test public void regression_NoPlaceholder_Equal() throws Exception { String control = "<elem1><elem11>123</elem11></elem1>"; String test = "<elem1><elem11>123</elem11></elem1>"; Diff diff = DiffBuilder.compare(control).withTest(test) .withDifferenceEvaluator(new PlaceholderDifferenceEvaluator()).build(); assertFalse(diff.hasDifferences()); } @Test public void regression_NoPlaceholder_Different() throws Exception { String control = "<elem1><elem11>123</elem11></elem1>"; String test = "<elem1><elem11>abc</elem11></elem1>"; Diff diff = DiffBuilder.compare(control).withTest(test) .withDifferenceEvaluator(new PlaceholderDifferenceEvaluator()).build(); assertTrue(diff.hasDifferences()); int count = 0; Iterator it = diff.getDifferences().iterator(); while (it.hasNext()) { count++; Difference difference = (Difference) it.next(); assertEquals(ComparisonResult.DIFFERENT, difference.getResult()); } assertEquals(1, count); } @Test public void regression_NoPlaceholder_Different_EmptyExpectedElement() throws Exception { String control = "<elem1><elem11/></elem1>"; String test = "<elem1><elem11>abc</elem11></elem1>"; Diff diff = DiffBuilder.compare(control).withTest(test) .withDifferenceEvaluator(new PlaceholderDifferenceEvaluator()).build(); assertTrue(diff.hasDifferences()); int count = 0; Iterator it = diff.getDifferences().iterator(); while (it.hasNext()) { count++; Difference difference = (Difference) it.next(); assertEquals(ComparisonResult.DIFFERENT, difference.getResult()); Comparison comparison = difference.getComparison(); if (count == 1) { String xpath = "/elem1[1]/elem11[1]"; assertEquals(ComparisonType.CHILD_NODELIST_LENGTH, comparison.getType()); assertEquals(xpath, comparison.getControlDetails().getXPath()); assertEquals(0, comparison.getControlDetails().getValue()); assertEquals(xpath, comparison.getTestDetails().getXPath()); assertEquals(1, comparison.getTestDetails().getValue()); } else { assertEquals(ComparisonType.CHILD_LOOKUP, comparison.getType()); assertEquals(null, comparison.getControlDetails().getXPath()); assertEquals(null, comparison.getControlDetails().getValue()); assertEquals("/elem1[1]/elem11[1]/text()[1]", comparison.getTestDetails().getXPath()); assertEquals(QName.valueOf("#text"), comparison.getTestDetails().getValue()); } } assertEquals(2, count); } @Test public void hasIgnorePlaceholder_Equal_NoWhitespaceInPlaceholder() throws Exception { String control = "<elem1><elem11>${xmlunit.ignore}</elem11></elem1>"; String test = "<elem1><elem11>abc</elem11></elem1>"; Diff diff = DiffBuilder.compare(control).withTest(test) .withDifferenceEvaluator(new PlaceholderDifferenceEvaluator()).build(); assertFalse(diff.hasDifferences()); } @Test public void hasIgnorePlaceholder_Equal_StartAndEndWhitespacesInPlaceholder() throws Exception { String control = "<elem1><elem11>${ xmlunit.ignore }</elem11></elem1>"; String test = "<elem1><elem11>abc</elem11></elem1>"; Diff diff = DiffBuilder.compare(control).withTest(test) .withDifferenceEvaluator(new PlaceholderDifferenceEvaluator()).build(); assertFalse(diff.hasDifferences()); } @Test public void hasIgnorePlaceholder_Equal_EmptyActualElement() throws Exception { String control = "<elem1><elem11>${xmlunit.ignore}</elem11></elem1>"; String test = "<elem1><elem11/></elem1>"; Diff diff = DiffBuilder.compare(control).withTest(test) .withDifferenceEvaluator(new PlaceholderDifferenceEvaluator()).build(); assertFalse(diff.hasDifferences()); } @Test public void hasIgnorePlaceholder_Exception_ExclusivelyOccupy() throws Exception { String control = "<elem1><elem11> ${xmlunit.ignore}abc</elem11></elem1>"; String test = "<elem1><elem11>abc</elem11></elem1>"; DiffBuilder diffBuilder = DiffBuilder.compare(control).withTest(test) .withDifferenceEvaluator(new PlaceholderDifferenceEvaluator()); try { diffBuilder.build(); fail(); } catch (XMLUnitException e) { assertEquals("${xmlunit.ignore} must exclusively occupy the text node.", e.getCause().getMessage()); } } }
package org.xwiki.job.internal.script.safe; import java.util.Date; import java.util.List; import org.xwiki.job.Request; import org.xwiki.job.event.status.JobProgress; import org.xwiki.job.event.status.JobStatus; import org.xwiki.logging.LogLevel; import org.xwiki.logging.LogQueue; import org.xwiki.logging.event.LogEvent; import org.xwiki.script.internal.safe.AbstractSafeObject; import org.xwiki.script.internal.safe.ScriptSafeProvider; /** * Provide a public script access to a job status. * * @param <J> the type of the job status * @version $Id$ * @since 4.0M2 */ public class SafeJobStatus<J extends JobStatus> extends AbstractSafeObject<J> implements JobStatus { /** * @param status the wrapped job status * @param safeProvider the provider of instances safe for public scripts */ public SafeJobStatus(J status, ScriptSafeProvider<?> safeProvider) { super(status, safeProvider); } @Override public State getState() { return getWrapped().getState(); } @Override public Request getRequest() { return getWrapped().getRequest(); } @Override public LogQueue getLog() { return getWrapped().getLog(); } @Override @Deprecated public List<LogEvent> getLog(LogLevel level) { return getWrapped().getLog(level); } @Override public JobProgress getProgress() { return getWrapped().getProgress(); } @Override public void ask(Object question) throws InterruptedException { getWrapped().ask(question); } @Override public Object getQuestion() { return getWrapped().getQuestion(); } @Override public void answered() { getWrapped().answered(); } @Override public Date getStartDate() { return getWrapped().getStartDate(); } @Override public Date getEndDate() { return getWrapped().getEndDate(); } }
package com.heavyplayer.audioplayerrecorder.util; import android.content.Context; import android.media.AudioManager; import android.media.MediaPlayer; import android.net.Uri; import android.os.Handler; import android.util.Log; import android.view.View; import android.widget.SeekBar; import com.heavyplayer.audioplayerrecorder.widget.AudioPlayerLayout; import com.heavyplayer.audioplayerrecorder.widget.PlayPauseImageButton; import com.heavyplayer.audioplayerrecorder.widget.interface_.OnDetachListener; import java.io.IOException; public class AudioPlayerHandler implements SafeMediaPlayer.OnStartListener, MediaPlayer.OnCompletionListener, MediaPlayer.OnBufferingUpdateListener, MediaPlayer.OnErrorListener { public static final String TAG = AudioPlayerHandler.class.getSimpleName(); private final static long PROGRESS_UPDATE_INTERVAL_MS = 200; private AudioManager mAudioManager; private AudioFocusChangeListener mAudioFocusChangeListener; private Uri mFileUri; private boolean mShowBufferIfPossible; private Handler mHandler; private ProgressUpdater mProgressUpdater; private SafeMediaPlayer mMediaPlayer; private AudioPlayerLayout mView; private PlayPauseImageButton mButton; private SeekBar mSeekBar; private Integer mBufferingCurrentPosition; public AudioPlayerHandler(Context context, Uri fileUri, boolean showBufferIfPossible, Handler handler) { mAudioManager = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE); mFileUri = fileUri; mShowBufferIfPossible = showBufferIfPossible; mHandler = handler; mProgressUpdater = new ProgressUpdater(); createMediaPlayer(); } protected void createMediaPlayer() { mMediaPlayer = new SafeMediaPlayer(); mMediaPlayer.setOnStartListener(this); mMediaPlayer.setOnCompletionListener(this); mMediaPlayer.setOnBufferingUpdateListener(this); mMediaPlayer.setOnErrorListener(this); } public void destroy() { destroyMediaPlayer(); abandonAudioFocus(); } protected void destroyMediaPlayer() { if(mMediaPlayer != null) { try { mMediaPlayer.setOnStartListener(null); mMediaPlayer.setOnCompletionListener(null); mMediaPlayer.setOnBufferingUpdateListener(null); mMediaPlayer.setOnErrorListener(null); mMediaPlayer.stop(); mMediaPlayer.reset(); mMediaPlayer.release(); mMediaPlayer = null; } catch(Exception e) { Log.w(TAG, e); } } mBufferingCurrentPosition = null; } protected void start(boolean gainAudioFocus, boolean updateButton) { if(gainAudioFocus) gainAudioFocus(); if(!mMediaPlayer.isPrepared()) { try { mMediaPlayer.setDataSource(mFileUri.toString()); mMediaPlayer.prepare(); } catch (IOException e) { Log.w(TAG, e); } } mMediaPlayer.start(); if(updateButton) updateButton(true); } protected void pause(boolean abandonAudioFocus, boolean updateButton) { mMediaPlayer.pause(); if(updateButton) updateButton(false); if(abandonAudioFocus) abandonAudioFocus(); } protected void seekTo(int msec) { mMediaPlayer.seekTo(msec); } protected void updateButton(boolean isPlaying) { if(mButton != null) mButton.setIsPlaying(isPlaying); } @Override public void onStart(MediaPlayer mp) { if(mView != null) mView.setTimeDuration(mp.getDuration()); if(mSeekBar != null) { if(mSeekBar.getMax() != mp.getDuration()) { mSeekBar.setMax(mp.getDuration()); mSeekBar.setProgress(mp.getCurrentPosition()); } else if(mSeekBar.getProgress() != mp.getCurrentPosition()) { mSeekBar.setProgress(mp.getCurrentPosition()); } } // Update seek bar. startSeekBarUpdate(); } public void startSeekBarUpdate() { // Update seek bar. mHandler.removeCallbacks(mProgressUpdater); mHandler.post(mProgressUpdater); } @Override public void onCompletion(MediaPlayer mp) { // Updates seek bar. if(mSeekBar != null) mSeekBar.setProgress(mp.getDuration()); updateButton(false); abandonAudioFocus(); } @Override public void onBufferingUpdate(MediaPlayer mp, int percent) { if(mShowBufferIfPossible) { mBufferingCurrentPosition = (int)(mp.getDuration() * (percent / 100f)); if(mSeekBar != null) mSeekBar.setSecondaryProgress(mBufferingCurrentPosition); } } @Override public boolean onError(MediaPlayer mp, int what, int extra) { if(what == MediaPlayer.MEDIA_ERROR_SERVER_DIED) { // Recreate media player. destroyMediaPlayer(); createMediaPlayer(); if(mView != null) registerView(mView); } abandonAudioFocus(); return false; } public void registerView(AudioPlayerLayout view) { mView = view; mView.setOnDetachListener(new OnDetachListener() { @Override public void onStartTemporaryDetach(View v) { clearView(); } @Override public void onDetachedFromWindow(View v) { clearView(); } }); // Resume duration. // Don't worry about current position as it will // always be correlated with the seek bar position. mView.setTimeDuration(mMediaPlayer.getDuration()); registerButton(view.getButton()); registerSeekBar(view.getSeekBar()); // Resume updater. startSeekBarUpdate(); } protected void registerButton(PlayPauseImageButton button) { mButton = button; mButton.setOnPlayPauseListener(new PlayPauseImageButton.OnPlayPauseListener() { @Override public void onPlay(View v) { start(true, false); } @Override public void onPause(View v) { pause(true, false); } }); // Resume button state. mButton.setIsPlaying(mMediaPlayer.isGoingToPlay()); } protected void registerSeekBar(SeekBar seekBar) { mSeekBar = seekBar; mSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onStartTrackingTouch(SeekBar seekBar) { mHandler.removeCallbacks(mProgressUpdater); } @Override public void onStopTrackingTouch(SeekBar seekBar) { seekTo(seekBar.getProgress()); mHandler.post(mProgressUpdater); } @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { mView.setTimeCurrentPosition(progress); } }); // Resume progress. mSeekBar.setMax(mMediaPlayer.getDuration()); mSeekBar.setProgress(mMediaPlayer.getCurrentPosition()); mSeekBar.setSecondaryProgress(mBufferingCurrentPosition != null ? mBufferingCurrentPosition : 0); } protected void clearView() { mView.setOnDetachListener(null); mView = null; mButton.setOnClickListener(null); mButton = null; mSeekBar.setOnSeekBarChangeListener(null); mSeekBar = null; } protected void gainAudioFocus() { if(mAudioFocusChangeListener == null) mAudioFocusChangeListener = new AudioFocusChangeListener(); // Request audio focus for playback mAudioManager.requestAudioFocus( mAudioFocusChangeListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT); } protected void abandonAudioFocus() { // Abandon audio focus when playback complete. if(mAudioFocusChangeListener != null) mAudioManager.abandonAudioFocus(mAudioFocusChangeListener); } private class AudioFocusChangeListener implements AudioManager.OnAudioFocusChangeListener { @Override public void onAudioFocusChange(int focusChange) { switch(focusChange) { case AudioManager.AUDIOFOCUS_LOSS: pause(true, true); break; case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT: case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK: pause(false, true); break; case AudioManager.AUDIOFOCUS_GAIN: start(false, true); break; } } } protected class ProgressUpdater implements Runnable { @Override public void run() { if(mSeekBar != null && mMediaPlayer != null && mMediaPlayer.isPlaying()) { mSeekBar.setProgress(mMediaPlayer.getCurrentPosition()); mHandler.postDelayed(this, PROGRESS_UPDATE_INTERVAL_MS); } } } }
package com.groupon.seleniumgridextras.grid.servlets; import com.google.gson.GsonBuilder; import com.google.gson.JsonObject; import org.openqa.grid.internal.ProxySet; import org.openqa.grid.internal.Registry; import org.openqa.grid.internal.RemoteProxy; import org.openqa.grid.internal.TestSlot; import org.openqa.grid.web.servlet.RegistryBasedServlet; import java.io.IOException; import java.net.URL; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @Deprecated public class ProxyStatusJsonServlet extends RegistryBasedServlet { private static final long serialVersionUID = -1975392591408983229L; public ProxyStatusJsonServlet() { this(null); } public ProxyStatusJsonServlet(Registry registry) { super(registry); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { process(req, resp); } protected void process(HttpServletRequest request, HttpServletResponse response) throws IOException { response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); response.setStatus(200); response.getWriter().print(new GsonBuilder().setPrettyPrinting().create() .toJson(getResponse())); response.getWriter().close(); } private Map getResponse() { Map error = new HashMap(); error.put("message", "This servlet is currently disabled and will be deprecated soon."); return error; // ProxySet proxies = this.getRegistry().getAllProxies(); // Iterator<RemoteProxy> iterator = proxies.iterator(); // while (iterator.hasNext()) { // RemoteProxy currentProxy = iterator.next(); // Iterator<TestSlot> proxyIterator = currentProxy.getTestSlots().iterator(); // while (proxyIterator.hasNext()) { // Map testMachine = new HashMap(); // TestSlot currentTestSlot = proxyIterator.next(); // testMachine.put("browserName", currentTestSlot.getCapabilities().get("browserName").toString()); // String version = ""; // if (currentTestSlot.getCapabilities().containsKey("version")) { // version = currentTestSlot.getCapabilities().get("version").toString(); // testMachine.put("version", version); // testMachine.put("session", ""); // if (currentTestSlot.getSession() != null) { // testMachine.put("session", currentTestSlot.getSession().getExternalKey().getKey()); // testMachine.put("host", currentProxy.getRemoteHost().getHost()); // Proxies.put(currentProxy.getOriginalRegistrationRequest().getAssociatedJSON()); // requestJSON.put("Proxies", ProxyStatus); // requestJSON.put("TotalProxies", Proxies); // return requestJSON; } }
package com.hubspot.singularity.data.zkmigrations; import com.google.inject.Inject; import com.google.inject.Singleton; import com.hubspot.singularity.config.SingularityConfiguration; import com.hubspot.singularity.data.ShuffleConfigurationManager; @Singleton public class ShuffleBlacklistMigration extends ZkDataMigration { private final SingularityConfiguration configuration; private final ShuffleConfigurationManager manager; @Inject public ShuffleBlacklistMigration(SingularityConfiguration configuration, ShuffleConfigurationManager manager) { super(16); this.configuration = configuration; this.manager = manager; } @Override public void applyMigration() { for (String requestId : configuration.getDoNotShuffleRequests()) { manager.addToShuffleBlacklist(requestId); } } } a
package io.doist.recyclerviewext.sticky_headers; import android.content.Context; import android.graphics.PointF; import android.os.Build; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; import java.util.ArrayList; import java.util.List; /** * Adds sticky headers capabilities to your {@link RecyclerView.Adapter}. It must implement {@link StickyHeaders} to * indicate which items are headers. */ public class StickyHeadersLinearLayoutManager<T extends RecyclerView.Adapter & StickyHeaders> extends LinearLayoutManager { private T mAdapter; private float mTranslationX; private float mTranslationY; // Header positions for the currently displayed list and their observer. private List<Integer> mHeaderPositions = new ArrayList<>(0); private RecyclerView.AdapterDataObserver mHeaderPositionsObserver = new HeaderPositionsAdapterDataObserver(); // Sticky header's ViewHolder and dirty state. protected View mStickyHeader; public StickyHeadersLinearLayoutManager(Context context) { super(context); } public StickyHeadersLinearLayoutManager(Context context, int orientation, boolean reverseLayout) { super(context, orientation, reverseLayout); } /** * Offsets the vertical location of the sticky header relative to the its default position. */ public void setStickyHeaderTranslationY(float translationY) { mTranslationY = translationY; } /** * Offsets the horizontal location of the sticky header relative to the its default position. */ public void setStickyHeaderTranslationX(float translationX) { mTranslationX = translationX; } @Override public void onAttachedToWindow(RecyclerView view) { super.onAttachedToWindow(view); setAdapter(view.getAdapter()); } @Override public void onAdapterChanged(RecyclerView.Adapter oldAdapter, RecyclerView.Adapter newAdapter) { super.onAdapterChanged(oldAdapter, newAdapter); setAdapter(newAdapter); } @SuppressWarnings("unchecked") private void setAdapter(RecyclerView.Adapter adapter) { if (mAdapter != null) { mAdapter.unregisterAdapterDataObserver(mHeaderPositionsObserver); } if (adapter instanceof StickyHeaders) { mAdapter = (T) adapter; mAdapter.registerAdapterDataObserver(mHeaderPositionsObserver); mHeaderPositionsObserver.onChanged(); } else if (adapter == null) { mAdapter = null; mHeaderPositions.clear(); } else { throw new IllegalStateException("StickyHeadersLinearLayoutManager must be used with an Adapter that " + "implements StickyHeaders"); } } @Override public int scrollVerticallyBy(int dy, RecyclerView.Recycler recycler, RecyclerView.State state) { detachStickyHeader(); int scrolled = super.scrollVerticallyBy(dy, recycler, state); attachStickyHeader(); if (scrolled != 0) { updateStickyHeader(recycler, false); } return scrolled; } @Override public int scrollHorizontallyBy(int dx, RecyclerView.Recycler recycler, RecyclerView.State state) { detachStickyHeader(); int scrolled = super.scrollHorizontallyBy(dx, recycler, state); attachStickyHeader(); if (scrolled != 0) { updateStickyHeader(recycler, false); } return scrolled; } @Override public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) { detachStickyHeader(); super.onLayoutChildren(recycler, state); attachStickyHeader(); if (!state.isPreLayout()) { updateStickyHeader(recycler, true); } } @Override public int computeVerticalScrollExtent(RecyclerView.State state) { detachStickyHeader(); int extent = super.computeVerticalScrollExtent(state); attachStickyHeader(); return extent; } @Override public int computeVerticalScrollOffset(RecyclerView.State state) { detachStickyHeader(); int offset = super.computeVerticalScrollOffset(state); attachStickyHeader(); return offset; } @Override public int computeVerticalScrollRange(RecyclerView.State state) { detachStickyHeader(); int range = super.computeVerticalScrollRange(state); attachStickyHeader(); return range; } @Override public int computeHorizontalScrollExtent(RecyclerView.State state) { detachStickyHeader(); int extent = super.computeHorizontalScrollExtent(state); attachStickyHeader(); return extent; } @Override public int computeHorizontalScrollOffset(RecyclerView.State state) { detachStickyHeader(); int offset = super.computeHorizontalScrollOffset(state); attachStickyHeader(); return offset; } @Override public int computeHorizontalScrollRange(RecyclerView.State state) { detachStickyHeader(); int range = super.computeHorizontalScrollRange(state); attachStickyHeader(); return range; } @Override public PointF computeScrollVectorForPosition(int targetPosition) { detachStickyHeader(); PointF vector = super.computeScrollVectorForPosition(targetPosition); attachStickyHeader(); return vector; } @Override public View onFocusSearchFailed(View focused, int focusDirection, RecyclerView.Recycler recycler, RecyclerView.State state) { detachStickyHeader(); View view = super.onFocusSearchFailed(focused, focusDirection, recycler, state); attachStickyHeader(); return view; } private void detachStickyHeader() { if (mStickyHeader != null) { detachView(mStickyHeader); } } private void attachStickyHeader() { if (mStickyHeader != null) { attachView(mStickyHeader); } } /** * Updates the sticky header state (creation, binding, display), to be called whenever there's a layout or scroll */ private void updateStickyHeader(RecyclerView.Recycler recycler, boolean layout) { int headerCount = mHeaderPositions.size(); int childCount = getChildCount(); if (headerCount > 0 && childCount > 0) { // Find first valid child. View anchorView = null; int anchorIndex = -1; int anchorPos = -1; for (int i = 0; i < childCount; i++) { View child = getChildAt(i); RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams(); if (isViewValidAnchor(child, params)) { anchorView = child; anchorIndex = i; anchorPos = params.getViewLayoutPosition(); break; } } if (anchorView != null) { int headerIndex = findHeaderIndexOrBefore(anchorPos); int headerPos = headerIndex != -1 ? mHeaderPositions.get(headerIndex) : -1; int nextHeaderPos = headerCount > headerIndex + 1 ? mHeaderPositions.get(headerIndex + 1) : -1; // Show sticky header if: // - there's one to show; // - it's on the edge or it's not the anchor view; // - isn't followed by another sticky header. if (headerPos != -1 && (headerPos != anchorPos || isViewOnBoundary(anchorView)) && nextHeaderPos != headerPos + 1) { // Ensure existing sticky header, if any, is of correct type. if (mStickyHeader != null && getItemViewType(mStickyHeader) != mAdapter.getItemViewType(headerPos)) { // A sticky header was shown before but is not of the correct type. Scrap it. scrapStickyHeader(recycler); } // Ensure sticky header is created, if absent, or bound, if being laid out or the position changed. if (mStickyHeader == null) { createStickyHeader(recycler, headerPos); } if(layout || getPosition(mStickyHeader) != headerPos) { bindStickyHeader(recycler, headerPos); } // Draw the sticky header using translation values which depend on orientation, direction and // position of the next header view. View nextHeaderView = null; if (nextHeaderPos != -1) { nextHeaderView = getChildAt(anchorIndex + (nextHeaderPos - anchorPos)); // The header view itself is added to the RecyclerView. Discard it if it comes up. if (nextHeaderView == mStickyHeader) { nextHeaderView = null; } } mStickyHeader.setTranslationX(getX(mStickyHeader, nextHeaderView)); mStickyHeader.setTranslationY(getY(mStickyHeader, nextHeaderView)); return; } } } if (mStickyHeader != null) { scrapStickyHeader(recycler); } } /** * Creates {@link RecyclerView.ViewHolder} for {@code position}, including measure / layout, and assigns it to * {@link #mStickyHeader}. */ protected void createStickyHeader(RecyclerView.Recycler recycler, int position) { mStickyHeader = recycler.getViewForPosition(position); // Setup sticky header if the adapter requires it. if (mAdapter instanceof StickyHeaders.ViewSetup) { ((StickyHeaders.ViewSetup) mAdapter).setupStickyHeaderView(mStickyHeader); } // Add sticky header as a child view, to be detached / reattached whenever LinearLayoutManager#fill() is called, // which happens on layout and scroll (see overrides). addView(mStickyHeader); measureChildWithMargins(mStickyHeader, 0, 0); if (getOrientation() == VERTICAL) { mStickyHeader.layout(getPaddingLeft(), 0, getWidth() - getPaddingRight(), mStickyHeader.getMeasuredHeight()); } else { mStickyHeader.layout(0, getPaddingTop(), mStickyHeader.getMeasuredWidth(), getHeight() - getPaddingBottom()); } } /** * Binds the {@link #mStickyHeader} for the given {@code position}. */ @SuppressWarnings("unchecked") protected void bindStickyHeader(RecyclerView.Recycler recycler, int position) { // Bind the sticky header. recycler.bindViewToPosition(mStickyHeader, position); } /** * Returns {@link #mStickyHeader} to the {@link RecyclerView}'s {@link RecyclerView.RecycledViewPool}, assigning it * to {@code null}. */ protected void scrapStickyHeader(RecyclerView.Recycler recycler) { // Revert translation values. mStickyHeader.setTranslationX(0); mStickyHeader.setTranslationY(0); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { mStickyHeader.setTranslationZ(0); } // Teardown holder if the adapter requires it. if (mAdapter instanceof StickyHeaders.ViewSetup) { ((StickyHeaders.ViewSetup) mAdapter).teardownStickyHeaderView(mStickyHeader); } removeAndRecycleView(mStickyHeader, recycler); mStickyHeader = null; } /** * Returns true when {@code view} is a valid anchor, ie. the first view to be valid and visible. */ private boolean isViewValidAnchor(View view, RecyclerView.LayoutParams params) { if (!params.isItemRemoved() && !params.isViewInvalid()) { if (getOrientation() == VERTICAL) { if (getReverseLayout()) { return view.getTop() <= getHeight() + mTranslationY; } else { return view.getBottom() >= mTranslationY; } } else { if (getReverseLayout()) { return view.getLeft() <= getWidth() + mTranslationX; } else { return view.getRight() >= mTranslationX; } } } else { return false; } } /** * Returns true when the {@code view} is at the edge of the parent {@link RecyclerView}. */ private boolean isViewOnBoundary(View view) { if (getOrientation() == VERTICAL) { if (getReverseLayout()) { return view.getBottom() - view.getTranslationY() > getHeight() + mTranslationY; } else { return view.getTop() + view.getTranslationY() < mTranslationY; } } else { if (getReverseLayout()) { return view.getRight() - view.getTranslationX() > getWidth() + mTranslationX; } else { return view.getLeft() + view.getTranslationX() < mTranslationX; } } } /** * Returns the position in the Y axis to position the header appropriately, depending on orientation, direction and * {@link android.R.attr#clipToPadding}. */ private float getY(View headerView, View nextHeaderView) { if (getOrientation() == VERTICAL) { float y = mTranslationY; if (getReverseLayout()) { y += getHeight() - headerView.getHeight(); } if (nextHeaderView != null) { if (getReverseLayout()) { y = Math.max(nextHeaderView.getBottom(), y); } else { y = Math.min(nextHeaderView.getTop() - headerView.getHeight(), y); } } return y; } else { return mTranslationY; } } /** * Returns the position in the X axis to position the header appropriately, depending on orientation, direction and * {@link android.R.attr#clipToPadding}. */ private float getX(View headerView, View nextHeaderView) { if (getOrientation() != VERTICAL) { float x = mTranslationX; if (getReverseLayout()) { x += getWidth() - headerView.getWidth(); } if (nextHeaderView != null) { if (getReverseLayout()) { x = Math.max(nextHeaderView.getRight(), x); } else { x = Math.min(nextHeaderView.getLeft() - headerView.getWidth(), x); } } return x; } else { return mTranslationX; } } /** * Finds the header index of {@code position} in {@code mHeaderPositions}. */ private int findHeaderIndex(int position) { int low = 0; int high = mHeaderPositions.size() - 1; while (low <= high) { int middle = (low + high) / 2; if (mHeaderPositions.get(middle) > position) { high = middle - 1; } else if(mHeaderPositions.get(middle) < position) { low = middle + 1; } else { return middle; } } return -1; } /** * Finds the header index of {@code position} or the one before it in {@code mHeaderPositions}. */ private int findHeaderIndexOrBefore(int position) { int low = 0; int high = mHeaderPositions.size() - 1; while (low <= high) { int middle = (low + high) / 2; if (mHeaderPositions.get(middle) > position) { high = middle - 1; } else if (middle < mHeaderPositions.size() - 1 && mHeaderPositions.get(middle + 1) <= position) { low = middle + 1; } else { return middle; } } return -1; } /** * Finds the header index of {@code position} or the one next to it in {@code mHeaderPositions}. */ private int findHeaderIndexOrNext(int position) { int low = 0; int high = mHeaderPositions.size() - 1; while (low <= high) { int middle = (low + high) / 2; if (middle > 0 && mHeaderPositions.get(middle - 1) >= position) { high = middle - 1; } else if(mHeaderPositions.get(middle) < position) { low = middle + 1; } else { return middle; } } return -1; } /** * Handles header positions while adapter changes occur. * * This is used in detriment of {@link RecyclerView.LayoutManager}'s callbacks to control when they're received. */ private class HeaderPositionsAdapterDataObserver extends RecyclerView.AdapterDataObserver implements Runnable { @Override public void run() { int itemCount = mAdapter.getItemCount(); for (int i = 0; i < itemCount; i++) { if (mAdapter.isStickyHeader(i)) { mHeaderPositions.add(i); } } } @Override public void onChanged() { // There's no hint at what changed, so go through the adapter. mHeaderPositions.clear(); int itemCount = mAdapter.getItemCount(); for (int i = 0; i < itemCount; i++) { if (mAdapter.isStickyHeader(i)) { mHeaderPositions.add(i); } } } @Override public void onItemRangeInserted(int positionStart, int itemCount) { // Shift headers below down. int headerCount = mHeaderPositions.size(); if (headerCount > 0) { for (int i = findHeaderIndexOrNext(positionStart); i != -1 && i < headerCount; i++) { mHeaderPositions.set(i, mHeaderPositions.get(i) + itemCount); } } // Add new headers. for (int i = positionStart; i < positionStart + itemCount; i++) { if (mAdapter.isStickyHeader(i)) { int headerIndex = findHeaderIndexOrNext(i); if (headerIndex != -1) { mHeaderPositions.add(headerIndex, i); } else { mHeaderPositions.add(i); } } } } @Override public void onItemRangeRemoved(int positionStart, int itemCount) { int headerCount = mHeaderPositions.size(); if (headerCount > 0) { // Remove headers. for (int i = positionStart + itemCount - 1; i >= positionStart; i int index = findHeaderIndex(i); if (index != -1) { mHeaderPositions.remove(index); headerCount } } // Shift headers below up. for (int i = findHeaderIndexOrNext(positionStart + itemCount); i != -1 && i < headerCount; i++) { mHeaderPositions.set(i, mHeaderPositions.get(i) - itemCount); } } } @Override public void onItemRangeMoved(int fromPosition, int toPosition, int itemCount) { // Shift moved headers by toPosition - fromPosition. // Shift headers in-between by -itemCount (reverse if upwards). int headerCount = mHeaderPositions.size(); if (headerCount > 0) { if (fromPosition < toPosition) { for (int i = findHeaderIndexOrNext(fromPosition); i != -1 && i < headerCount; i++) { int headerPos = mHeaderPositions.get(i); if (headerPos >= fromPosition && headerPos < fromPosition + itemCount) { mHeaderPositions.set(i, headerPos + (toPosition - fromPosition)); sortHeaderAtIndex(i); } else if (headerPos >= fromPosition + itemCount && headerPos < toPosition) { mHeaderPositions.set(i, headerPos - itemCount); sortHeaderAtIndex(i); } else if (headerPos > toPosition) { break; } } } else { for (int i = findHeaderIndexOrNext(toPosition); i != -1 && i < headerCount; i++) { int headerPos = mHeaderPositions.get(i); if (headerPos >= fromPosition && headerPos < fromPosition + itemCount) { mHeaderPositions.set(i, headerPos + (toPosition - fromPosition)); sortHeaderAtIndex(i); } else if (headerPos >= toPosition && headerPos < fromPosition) { mHeaderPositions.set(i, headerPos + itemCount); sortHeaderAtIndex(i); } else if (headerPos > toPosition) { break; } } } } } private void sortHeaderAtIndex(int index) { int headerPos = mHeaderPositions.remove(index); int headerIndex = findHeaderIndexOrNext(headerPos); if (headerIndex != -1) { mHeaderPositions.add(headerIndex, headerPos); } else { mHeaderPositions.add(headerPos); } } } }
package ar.com.tzulberti.archerytraining.fragments.tournament; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.PorterDuff; import android.graphics.PorterDuffColorFilter; import android.os.Build; import android.os.Bundle; import android.support.annotation.RequiresApi; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.ViewTreeObserver; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import org.w3c.dom.Text; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import ar.com.tzulberti.archerytraining.MainActivity; import ar.com.tzulberti.archerytraining.R; import ar.com.tzulberti.archerytraining.helper.TournamentHelper; import ar.com.tzulberti.archerytraining.model.tournament.TournamentConfiguration; import ar.com.tzulberti.archerytraining.model.tournament.TournamentSerie; import ar.com.tzulberti.archerytraining.model.tournament.TournamentSerieArrow; public class ViewSerieInformationFragment extends BaseTournamentFragment implements View.OnTouchListener, View.OnLongClickListener { public static final float IMAGE_WIDTH = 512; public static final float ARROW_IMPACT_RADIUS = 5; private static final int Y_PADDING = -80; private ImageView targetImageView; private TextView[] currentScoreText; private TextView totalSerieScoreText; private Button previousSerieButton; private Button nextSerieButton; private float targetCenterX = -1; private float targetCenterY = -1; private float imageScale = -1; private float pointWidth = -1; private Bitmap imageBitmap; private Paint currentImpactPaint; private Paint finalImpactPaint; private TournamentSerie tournamentSerie; public static ViewSerieInformationFragment createInstance(TournamentSerie tournamentSerie) { ViewSerieInformationFragment res = new ViewSerieInformationFragment(); res.tournamentSerie = tournamentSerie; return res; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.tournament_view_serie_arrow, container, false); this.targetImageView = (ImageView) view.findViewById(R.id.photo_view); this.setObjects(); this.targetImageView.setOnTouchListener(this); this.targetImageView.setOnLongClickListener(this); this.currentImpactPaint = new Paint(); this.currentImpactPaint.setAntiAlias(true); this.currentImpactPaint.setColor(Color.MAGENTA); this.finalImpactPaint = new Paint(); this.finalImpactPaint.setAntiAlias(true); this.finalImpactPaint.setColor(Color.LTGRAY); this.currentScoreText = new TextView[6]; this.currentScoreText[0] = (TextView) view.findViewById(R.id.current_score1); this.currentScoreText[1] = (TextView) view.findViewById(R.id.current_score2); this.currentScoreText[2] = (TextView) view.findViewById(R.id.current_score3); this.currentScoreText[3] = (TextView) view.findViewById(R.id.current_score4); this.currentScoreText[4] = (TextView) view.findViewById(R.id.current_score5); this.currentScoreText[5] = (TextView) view.findViewById(R.id.current_score6); this.nextSerieButton = (Button) view.findViewById(R.id.btn_serie_next); this.previousSerieButton = (Button) view.findViewById(R.id.btn_serie_previous); this.nextSerieButton.setEnabled(false); this.previousSerieButton.setEnabled(false); ViewTreeObserver vto = this.targetImageView.getViewTreeObserver(); vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() { @Override public boolean onPreDraw() { targetImageView.getViewTreeObserver().removeOnPreDrawListener(this); initializeValues(); return true; } }); ((TextView) view.findViewById(R.id.serie_index)).setText("Serie " + this.tournamentSerie.index); ((TextView) view.findViewById(R.id.total_tournament_score)).setText(String.format("%s / %s", this.tournamentSerie.tournament.totalScore, TournamentConfiguration.MAX_SCORE_FOR_TOURNAMENT)); this.totalSerieScoreText = (TextView) view.findViewById(R.id.total_serie_score); return view; } protected void initializeValues() { this.imageScale = Math.min(this.targetImageView.getWidth(), this.targetImageView.getHeight()) / IMAGE_WIDTH; this.targetCenterX = this.targetImageView.getWidth() / (2 * this.imageScale); this.targetCenterY = this.targetImageView.getHeight() / (2 * this.imageScale); this.pointWidth = Math.min(this.targetCenterX, this.targetCenterY) / 10; BitmapFactory.Options myOptions = new BitmapFactory.Options(); myOptions.inScaled = false; myOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;// important Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.complete_archery_target, myOptions); Paint paint = new Paint(); paint.setAntiAlias(true); paint.setColor(Color.BLUE); this.imageBitmap = Bitmap.createBitmap(bitmap); int arrowIndex = 0; for (TournamentSerieArrow serieArrow : this.tournamentSerie.arrows) { this.addTargetImpact(serieArrow.xPosition, serieArrow.yPosition, true, true, arrowIndex); arrowIndex += 1; } if (this.tournamentSerie.arrows.size() == TournamentConfiguration.MAX_ARROW_PER_SERIES) { this.nextSerieButton.setEnabled(true); this.previousSerieButton.setEnabled(this.tournamentSerie.index > 1); } if (this.tournamentSerie.index == TournamentConfiguration.MAX_SERIES) { this.nextSerieButton.setText("Terminar"); } } @Override public boolean onTouch(View v, MotionEvent event) { if (this.tournamentSerie.arrows.size() == TournamentConfiguration.MAX_ARROW_PER_SERIES) { // already got the max number of arrows so there is nothing specific to do return false; } int eventAction = event.getAction(); boolean isFinal = false; if (eventAction == MotionEvent.ACTION_DOWN || eventAction == MotionEvent.ACTION_MOVE || eventAction == MotionEvent.ACTION_UP) { isFinal = (eventAction == MotionEvent.ACTION_UP); this.addTargetImpact(event.getX() / this.imageScale, event.getY() / this.imageScale, isFinal, false, this.tournamentSerie.arrows.size()); } if (isFinal && this.tournamentSerie.arrows.size() == TournamentConfiguration.MAX_ARROW_PER_SERIES) { // enable the buttons to save the current serie if (this.tournamentSerie.index > 1) { this.previousSerieButton.setEnabled(true); } System.err.println("Entro en el ouTouch con el maximo cantidad de flechas"); this.nextSerieButton.setEnabled(true); // update the series information after updating the arrows by it's score // so it can be showed on that order Collections.sort(this.tournamentSerie.arrows, new Comparator<TournamentSerieArrow>() { @Override public int compare(TournamentSerieArrow o1, TournamentSerieArrow o2) { return Integer.compare(o1.score, o2.score) * -1; } }); this.tournamentDAO.saveTournamentSerieInformation(this.tournamentSerie); } return false; } private void addTargetImpact(float x, float y, boolean isFinal, boolean showingExisting, int arrowIndex) { Bitmap mutableBitmap = this.imageBitmap.copy(Bitmap.Config.ARGB_8888, true); Paint paint = this.finalImpactPaint; if (isFinal) { this.imageBitmap = mutableBitmap; } else { paint = this.currentImpactPaint; } Canvas canvas = new Canvas(mutableBitmap); y = y + Y_PADDING; canvas.drawCircle(x, y, ARROW_IMPACT_RADIUS, paint); double distance = Math.sqrt(Math.pow(x - this.targetCenterX, 2) + Math.pow(y - this.targetCenterY, 2)); int score = (int) (10 - Math.floor(distance / this.pointWidth)); if (score < 0) { score = 0; } this.targetImageView.setAdjustViewBounds(true); this.targetImageView.setImageBitmap(mutableBitmap); TextView scoreText = this.currentScoreText[arrowIndex]; scoreText.getBackground().setColorFilter(new PorterDuffColorFilter(TournamentHelper.getBackground(score), PorterDuff.Mode.SRC_IN)); scoreText.setText(TournamentHelper.getUserScore(score)); scoreText.setTextColor(TournamentHelper.getFontColor(score)); if (isFinal && ! showingExisting) { TournamentSerieArrow serieArrow = new TournamentSerieArrow(); serieArrow.xPosition = x; serieArrow.yPosition = y; serieArrow.score = score; this.tournamentSerie.totalScore += score; this.tournamentSerie.arrows.add(serieArrow); } if (isFinal) { this.totalSerieScoreText.setText(String.format("%s / %s", this.tournamentSerie.totalScore, TournamentConfiguration.MAX_SCORE_PER_SERIES)); } } @Override public void handleClick(View v) { final MainActivity activity = (MainActivity) getActivity(); if (v.getId() == R.id.btn_serie_previous || v.getId() == R.id.btn_serie_next) { TournamentSerie transitionSerie = null; if (v.getId() == R.id.btn_serie_previous) { // -2 is required because the first index is 1. transitionSerie = this.tournamentSerie.tournament.series.get(this.tournamentSerie.index - 2); } else { // same here... there isn't any need to add +1 because the serie already starts at 1 System.err.println(String.format("SerieIndex: %s, MaxSeries: %s", this.tournamentSerie.index, TournamentConfiguration.MAX_SERIES)); if (this.tournamentSerie.index == TournamentConfiguration.MAX_SERIES) { // return to the tournament view because all the series for the tournament have been loaded Bundle bundle = new Bundle(); bundle.putLong("tournamentId", this.tournamentSerie.tournament.id); ViewTournamentSeriesFragment tournamentSeriesFragment = new ViewTournamentSeriesFragment(); tournamentSeriesFragment.setArguments(bundle); FragmentManager fragmentManager = getActivity().getSupportFragmentManager(); fragmentManager.beginTransaction() .replace(R.id.container, tournamentSeriesFragment) .commit(); return; } else if (this.tournamentSerie.tournament.series.size() > this.tournamentSerie.index) { transitionSerie = this.tournamentSerie.tournament.series.get(this.tournamentSerie.index); } else { // creating a new serie for the tournament transitionSerie = this.tournamentDAO.createNewSerie(this.tournamentSerie.tournament); } } ViewSerieInformationFragment practiceTestingFragment = ViewSerieInformationFragment.createInstance(transitionSerie); FragmentManager fragmentManager = activity.getSupportFragmentManager(); fragmentManager.beginTransaction() .replace(R.id.container, practiceTestingFragment) .commit(); } else { throw new RuntimeException("Unknown click button"); } } @Override public boolean onLongClick(View v) { System.out.println("On long click"); return false; } }
package com.itachi1706.cheesecakeutilities.Features.FingerprintAuth; import android.annotation.SuppressLint; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.util.Log; import android.widget.Toast; import com.google.firebase.analytics.FirebaseAnalytics; import com.itachi1706.cheesecakeutilities.R; import java.util.concurrent.Executor; import androidx.annotation.NonNull; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import androidx.biometrics.BiometricConstants; import androidx.biometrics.BiometricPrompt; public class AuthenticationActivity extends AppCompatActivity { SharedPreferences sp; FirebaseAnalytics mFirebaseAnalytics; Context mContext; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_authentication); mFirebaseAnalytics = FirebaseAnalytics.getInstance(this); mContext = this; sp = PreferenceManager.getDefaultSharedPreferences(this); PasswordHelper.migrateToBiometric(sp); if (BiometricCompatHelper.isBiometricFPRegistered(this) && BiometricCompatHelper.requireFPAuth(sp)) { // Has Fingerprint and requested for fingerprint auth Executor executor = BiometricCompatHelper.getBiometricExecutor(); BiometricPrompt p = new BiometricPrompt(this, executor, callback); BiometricPrompt.PromptInfo promptInfo = BiometricCompatHelper.createPromptObject(); p.authenticate(promptInfo); } else { // No fingerprints setResult(RESULT_OK); finish(); } } private BiometricPrompt.AuthenticationCallback callback = new BiometricPrompt.AuthenticationCallback() { @SuppressLint("SwitchIntDef") @Override public void onAuthenticationError(int errorCode, @NonNull CharSequence errString) { super.onAuthenticationError(errorCode, errString); runOnUiThread(() -> { Intent intent = new Intent(); switch (errorCode) { case BiometricConstants.ERROR_NEGATIVE_BUTTON: case BiometricConstants.ERROR_USER_CANCELED: case BiometricConstants.ERROR_CANCELED: Toast.makeText(mContext, R.string.dialog_cancelled, Toast.LENGTH_SHORT).show(); Log.i("Authentication", "User Cancelled Authentication"); intent.putExtra("message", "Dialog Cancelled"); setResult(RESULT_CANCELED, intent); finish(); return; case BiometricConstants.ERROR_LOCKOUT: case BiometricConstants.ERROR_LOCKOUT_PERMANENT: Toast.makeText(mContext, R.string.dialog_cancelled, Toast.LENGTH_SHORT).show(); Log.i("Authentication", "User Lock out"); intent.putExtra("message", "Lockout"); new AlertDialog.Builder(mContext).setTitle("Fingerprint sensor disabled (Locked out)") .setMessage("You have scanned an invalid fingerprint too many times and your fingerprint sensor has been disabled. \n\n" + "Please re-authenticate by unlocking or rebooting your phone again or disable fingerprints on your device") .setCancelable(false).setPositiveButton(R.string.dialog_action_positive_close, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { setResult(RESULT_CANCELED, intent); finish(); } }).show(); return; default: Toast.makeText(mContext, R.string.dialog_cancelled, Toast.LENGTH_SHORT).show(); Log.e("Authentication", "Authentication Error (" + errorCode + "): " + errString); intent.putExtra("message", "Authentication Error: " + errString); setResult(RESULT_CANCELED, intent); finish(); } }); } @Override public void onAuthenticationSucceeded(@NonNull BiometricPrompt.AuthenticationResult result) { super.onAuthenticationSucceeded(result); runOnUiThread(() -> { Toast.makeText(mContext, R.string.dialog_authenticated, Toast.LENGTH_LONG).show(); Log.i("Authentication", "User Authenticated"); setResult(RESULT_OK); mFirebaseAnalytics.logEvent(FirebaseAnalytics.Event.LOGIN, null); finish(); }); } @Override public void onAuthenticationFailed() { super.onAuthenticationFailed(); Log.i("Authentication", "Wrong Biometric detected"); } }; }
package nodomain.freeyourgadget.gadgetbridge.service.devices.miband; import android.support.annotation.NonNull; import java.util.Arrays; import nodomain.freeyourgadget.gadgetbridge.impl.GBDevice; public abstract class AbstractMiFirmwareInfo { public static @NonNull AbstractMiFirmwareInfo determineFirmwareInfoFor(byte[] wholeFirmwareBytes) { AbstractMiFirmwareInfo[] candidates = getFirmwareInfoCandidatesFor(wholeFirmwareBytes); if (candidates.length == 0) { throw new IllegalArgumentException("Unsupported data (maybe not even a firmware?)."); } if (candidates.length == 1) { return candidates[0]; } throw new IllegalArgumentException("don't know for which device the firmware is, matches multiple devices"); } private static AbstractMiFirmwareInfo[] getFirmwareInfoCandidatesFor(byte[] wholeFirmwareBytes) { AbstractMiFirmwareInfo[] candidates = new AbstractMiFirmwareInfo[3]; int i = 0; Mi1FirmwareInfo mi1Info = Mi1FirmwareInfo.getInstance(wholeFirmwareBytes); if (mi1Info != null) { candidates[i++] = mi1Info; } Mi1AFirmwareInfo mi1aInfo = Mi1AFirmwareInfo.getInstance(wholeFirmwareBytes); if (mi1aInfo != null) { candidates[i++] = mi1aInfo; } Mi1SFirmwareInfo mi1sInfo = Mi1SFirmwareInfo.getInstance(wholeFirmwareBytes); if (mi1sInfo != null) { candidates[i++] = mi1sInfo; } return Arrays.copyOfRange(candidates, 0, i); } @NonNull protected byte[] wholeFirmwareBytes; public AbstractMiFirmwareInfo(@NonNull byte[] wholeFirmwareBytes) { this.wholeFirmwareBytes = wholeFirmwareBytes; } public abstract int getFirmwareOffset(); public abstract int getFirmwareLength(); public abstract int getFirmwareVersion(); protected abstract boolean isGenerallySupportedFirmware(); public abstract boolean isGenerallyCompatibleWith(GBDevice device); public @NonNull byte[] getFirmwareBytes() { return Arrays.copyOfRange(wholeFirmwareBytes, getFirmwareOffset(), getFirmwareOffset() + getFirmwareLength()); } public int getFirmwareVersionMajor() { int version = getFirmwareVersion(); if (version > 0) { return (version >> 24); } throw new IllegalArgumentException("bad firmware version: " + version); } public boolean isSingleMiBandFirmware() { // TODO: not sure if this is a correct check! if ((wholeFirmwareBytes[7] & 255) != 1) { return true; } return false; } public AbstractMiFirmwareInfo getFirst() { if (isSingleMiBandFirmware()) { return this; } throw new UnsupportedOperationException(getClass().getName() + " must override getFirst() and getSecond()"); } public AbstractMiFirmwareInfo getSecond() { if (isSingleMiBandFirmware()) { throw new UnsupportedOperationException(getClass().getName() + " only supports on firmware"); } throw new UnsupportedOperationException(getClass().getName() + " must override getFirst() and getSecond()"); } }
package com.philliphsu.bottomsheetpickers.view.numberpad; import android.os.Parcel; import android.os.Parcelable; import android.support.annotation.Nullable; import android.view.View; import java.util.Arrays; /** * Model that encapsulates data pertaining to the inputted time in a number pad time picker. */ final class DigitwiseTimeModel { private static final int UNMODIFIED = -1; static final int MAX_DIGITS = 4; private final int[] mDigits = new int[MAX_DIGITS]; private final @Nullable OnInputChangeListener mListener; private int mCount; /** * Informs clients of new digit insertion and deletion events. */ interface OnInputChangeListener { /** * @param digit The stored digit. */ void onDigitStored(int digit); /** * @param digit The removed digit. */ void onDigitRemoved(int digit); void onDigitsCleared(); } // TODO: Delete this! @Deprecated DigitwiseTimeModel() { this(null); } DigitwiseTimeModel(OnInputChangeListener listener) { mListener = listener; // TOneverDO: Call clearDigits() to do this, otherwise we'll // end up calling back to the listener with an unintended // onDigitsCleared() event. Arrays.fill(mDigits, UNMODIFIED); mCount = 0; } void storeDigit(int digit) { if (mCount < MAX_DIGITS) { mDigits[mCount] = digit; mCount++; if (mListener != null) { mListener.onDigitStored(digit); } } } int getDigit(int at) { return mDigits[at]; } /** * @return a defensive copy of the internal array of inputted digits */ int[] getDigits() { return Arrays.copyOf(mDigits, mDigits.length); } void removeDigit() { if (mCount > 0) { mCount--; // move the cursor back int digit = mDigits[mCount]; mDigits[mCount] = UNMODIFIED; if (mListener != null) { mListener.onDigitRemoved(digit); } } } boolean clearDigits() { Arrays.fill(mDigits, UNMODIFIED); mCount = 0; if (mListener != null) { mListener.onDigitsCleared(); } return true; } int count() { return mCount; } /** * @return the integer represented by the inputted digits */ int getDigitsAsInteger() { if (mCount <= 0) return UNMODIFIED; int result = 0; for (int i = 0; i < mCount; i++) { result = result * 10 + mDigits[i]; } return result; } /** * Inserts as many of the digits in the given sequence * into the input as possible. */ void storeDigits(int... digits) { if (digits == null) return; for (int d : digits) { if (d < 0 || d > 9) throw new IllegalArgumentException("Not a digit " + d); if (mCount == MAX_DIGITS) break; storeDigit(d); } } static class SavedState extends View.BaseSavedState { private final int[] mDigits; private final int mCount; public SavedState(Parcelable superState, int[] digits, int count) { super(superState); mDigits = Arrays.copyOf(digits, digits.length); mCount = count; } private SavedState(Parcel in) { super(in); mDigits = in.createIntArray(); mCount = in.readInt(); } int[] getDigits() { return Arrays.copyOf(mDigits, mDigits.length); } int getCount() { return mCount; } @Override public void writeToParcel(Parcel dest, int flags) { super.writeToParcel(dest, flags); dest.writeIntArray(mDigits); dest.writeInt(mCount); } public static final Creator<SavedState> CREATOR = new Creator<SavedState>() { public SavedState createFromParcel(Parcel in) { return new SavedState(in); } public SavedState[] newArray(int size) { return new SavedState[size]; } }; } }
package gov.nih.nci.cagrid.data.cql.test; import gov.nih.nci.cagrid.data.cql.tools.CQLBuilder; import junit.framework.TestCase; import org.jdom.Element; /** * Generate multiple CQLs to get attributes from other objects * @testType unit * @author Srini Akkala */ public class CQLBuilderTest extends TestCase { public CQLBuilderTest(String sTestName) { super(sTestName); } protected void setUp() throws Exception { super.setUp(); } protected void tearDown() throws Exception { super.tearDown(); } /** * * Generate multiple CQLs , to get attributes from other objects */ public void testCQLGeneration() throws Exception{ } }
package org.codingmatters.value.objects.values.json; import com.fasterxml.jackson.core.JsonGenerator; import org.codingmatters.value.objects.values.ObjectValue; import org.codingmatters.value.objects.values.PropertyValue; import java.io.IOException; import java.time.format.DateTimeFormatter; public class ObjectValueWriter { public void write(JsonGenerator generator, ObjectValue value) throws IOException { this.writeObject(generator, value); } public void writeArray(JsonGenerator generator, ObjectValue[] values) throws IOException { if(values == null) { generator.writeNull(); } else { generator.writeStartArray(); for(ObjectValue value : values) { this.write(generator, value); } generator.writeEndArray(); } } private void writeValue(JsonGenerator generator, PropertyValue property) throws IOException { if(property.isNullValue()) { generator.writeNull(); } else if(PropertyValue.Cardinality.SINGLE.equals(property.cardinality())) { this.writeSingleValue(generator, property.single(), property.type()); } else if(PropertyValue.Cardinality.MULTIPLE.equals(property.cardinality())) { this.writeMultipleValue(generator, property.multiple(), property.type()); } } private void writeSingleValue(JsonGenerator generator, PropertyValue.Value value, PropertyValue.Type type) throws IOException { switch (type) { case STRING: generator.writeString(value.stringValue()); break; case LONG: generator.writeNumber(value.longValue()); break; case DOUBLE: generator.writeNumber(value.doubleValue()); break; case BOOLEAN: generator.writeBoolean(value.booleanValue()); break; case BYTES: generator.writeBinary(value.bytesValue()); break; case DATE: generator.writeString(value.dateValue().format(DateTimeFormatter.ISO_LOCAL_DATE)); break; case TIME: generator.writeString(value.timeValue().format(DateTimeFormatter.ISO_LOCAL_TIME)); break; case DATETIME: generator.writeString(value.datetimeValue().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME)); break; case OBJECT: this.writeObject(generator, value.objectValue()); break; } } private void writeObject(JsonGenerator generator, ObjectValue objectValue) throws IOException { generator.writeStartObject(); for (String property : objectValue.propertyNames()) { generator.writeFieldName(property); this.writeValue(generator, objectValue.property(property)); } generator.writeEndObject(); } private void writeMultipleValue(JsonGenerator generator, PropertyValue.Value[] multiple, PropertyValue.Type type) throws IOException { generator.writeStartArray(); for (PropertyValue.Value value : multiple) { this.writeSingleValue(generator, value, value.type()); } generator.writeEndArray(); } }
package com.yahoo.vespa.hosted.controller.application.pkg; import com.google.common.hash.Hashing; import com.yahoo.component.Version; import com.yahoo.config.application.FileSystemWrapper; import com.yahoo.config.application.FileSystemWrapper.FileWrapper; import com.yahoo.config.application.XmlPreProcessor; import com.yahoo.config.application.api.DeploymentSpec; import com.yahoo.config.application.api.ValidationId; import com.yahoo.config.application.api.ValidationOverrides; import com.yahoo.config.provision.Environment; import com.yahoo.config.provision.InstanceName; import com.yahoo.config.provision.RegionName; import com.yahoo.security.X509CertificateUtils; import com.yahoo.slime.Inspector; import com.yahoo.slime.Slime; import com.yahoo.slime.SlimeUtils; import com.yahoo.vespa.hosted.controller.deployment.ZipBuilder; import com.yahoo.yolean.Exceptions; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.InputStreamReader; import java.nio.file.NoSuchFileException; import java.nio.file.Path; import java.nio.file.Paths; import java.security.cert.X509Certificate; import java.time.Duration; import java.time.Instant; import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.concurrent.ConcurrentSkipListMap; import java.util.function.Function; import static java.nio.charset.StandardCharsets.UTF_8; import static java.util.stream.Collectors.toMap; /** * A representation of the content of an application package. * Only meta-data content can be accessed as anything other than compressed data. * A package is identified by a hash of the content. * * This is immutable. * * @author bratseth * @author jonmv */ public class ApplicationPackage { private static final String trustedCertificatesFile = "security/clients.pem"; private static final String buildMetaFile = "build-meta.json"; private static final String deploymentFile = "deployment.xml"; private static final String validationOverridesFile = "validation-overrides.xml"; private static final String servicesFile = "services.xml"; private final String contentHash; private final byte[] zippedContent; private final DeploymentSpec deploymentSpec; private final ValidationOverrides validationOverrides; private final ZipArchiveCache files; private final Optional<Version> compileVersion; private final Optional<Instant> buildTime; private final List<X509Certificate> trustedCertificates; /** * Creates an application package from its zipped content. * This <b>assigns ownership</b> of the given byte array to this class; * it must not be further changed by the caller. */ public ApplicationPackage(byte[] zippedContent) { this(zippedContent, false); } /** * Creates an application package from its zipped content. * This <b>assigns ownership</b> of the given byte array to this class; * it must not be further changed by the caller. * If 'requireFiles' is true, files needed by deployment orchestration must be present. */ public ApplicationPackage(byte[] zippedContent, boolean requireFiles) { this.zippedContent = Objects.requireNonNull(zippedContent, "The application package content cannot be null"); this.contentHash = Hashing.sha1().hashBytes(zippedContent).toString(); this.files = new ZipArchiveCache(zippedContent, Set.of(deploymentFile, validationOverridesFile, servicesFile, buildMetaFile, trustedCertificatesFile)); Optional<DeploymentSpec> deploymentSpec = files.get(deploymentFile).map(bytes -> new String(bytes, UTF_8)).map(DeploymentSpec::fromXml); if (requireFiles && deploymentSpec.isEmpty()) throw new IllegalArgumentException("Missing required file '" + deploymentFile + "'"); this.deploymentSpec = deploymentSpec.orElse(DeploymentSpec.empty); this.validationOverrides = files.get(validationOverridesFile).map(bytes -> new String(bytes, UTF_8)).map(ValidationOverrides::fromXml).orElse(ValidationOverrides.empty); Optional<Inspector> buildMetaObject = files.get(buildMetaFile).map(SlimeUtils::jsonToSlime).map(Slime::get); this.compileVersion = buildMetaObject.flatMap(object -> parse(object, "compileVersion", field -> Version.fromString(field.asString()))); this.buildTime = buildMetaObject.flatMap(object -> parse(object, "buildTime", field -> Instant.ofEpochMilli(field.asLong()))); this.trustedCertificates = files.get(trustedCertificatesFile).map(bytes -> X509CertificateUtils.certificateListFromPem(new String(bytes, UTF_8))).orElse(List.of()); } /** Returns a copy of this with the given certificate appended. */ public ApplicationPackage withTrustedCertificate(X509Certificate certificate) { List<X509Certificate> trustedCertificates = new ArrayList<>(this.trustedCertificates); trustedCertificates.add(certificate); byte[] certificatesBytes = X509CertificateUtils.toPem(trustedCertificates).getBytes(UTF_8); ByteArrayOutputStream modified = new ByteArrayOutputStream(zippedContent.length + certificatesBytes.length); ZipStreamReader.transferAndWrite(modified, new ByteArrayInputStream(zippedContent), trustedCertificatesFile, certificatesBytes); return new ApplicationPackage(modified.toByteArray()); } /** Returns a hash of the content of this package */ public String hash() { return contentHash; } /** Returns the content of this package. The content <b>must not</b> be modified. */ public byte[] zippedContent() { return zippedContent; } /** * Returns the deployment spec from the deployment.xml file of the package content. * This is the DeploymentSpec.empty instance if this package does not contain a deployment.xml file. */ public DeploymentSpec deploymentSpec() { return deploymentSpec; } /** * Returns the validation overrides from the validation-overrides.xml file of the package content. * This is the ValidationOverrides.empty instance if this package does not contain a validation-overrides.xml file. */ public ValidationOverrides validationOverrides() { return validationOverrides; } /** Returns the platform version which package was compiled against, if known. */ public Optional<Version> compileVersion() { return compileVersion; } /** Returns the time this package was built, if known. */ public Optional<Instant> buildTime() { return buildTime; } /** Returns the list of certificates trusted by this application, or an empty list if no trust configured. */ public List<X509Certificate> trustedCertificates() { return trustedCertificates; } private static <Type> Optional<Type> parse(Inspector buildMetaObject, String fieldName, Function<Inspector, Type> mapper) { if ( ! buildMetaObject.field(fieldName).valid()) throw new IllegalArgumentException("Missing value '" + fieldName + "' in '" + buildMetaFile + "'"); try { return Optional.of(mapper.apply(buildMetaObject.field(fieldName))); } catch (RuntimeException e) { throw new IllegalArgumentException("Failed parsing \"" + fieldName + "\" in '" + buildMetaFile + "': " + Exceptions.toMessageString(e)); } } /** Creates a valid application package that will remove all application's deployments */ public static ApplicationPackage deploymentRemoval() { return new ApplicationPackage(filesZip(Map.of(validationOverridesFile, allValidationOverrides().xmlForm().getBytes(UTF_8), deploymentFile, DeploymentSpec.empty.xmlForm().getBytes(UTF_8)))); } /** Returns a zip containing meta data about deployments of this package by the given job. */ public byte[] metaDataZip() { preProcessAndPopulateCache(); return cacheZip(); } private void preProcessAndPopulateCache() { FileWrapper servicesXml = files.wrapper().wrap(Paths.get(servicesFile)); if (servicesXml.exists()) try { new XmlPreProcessor(files.wrapper().wrap(Paths.get("./")), new InputStreamReader(new ByteArrayInputStream(servicesXml.content()), UTF_8), InstanceName.defaultName(), Environment.prod, RegionName.defaultName()) .run(); // Populates the zip archive cache with files that would be included. } catch (Exception e) { throw new RuntimeException(e); } } private byte[] cacheZip() { return filesZip(files.cache.entrySet().stream() .filter(entry -> entry.getValue().isPresent()) .collect(toMap(entry -> entry.getKey().toString(), entry -> entry.getValue().get()))); } static byte[] filesZip(Map<String, byte[]> files) { try (ZipBuilder zipBuilder = new ZipBuilder(files.values().stream().mapToInt(bytes -> bytes.length).sum() + 512)) { files.forEach(zipBuilder::add); zipBuilder.close(); return zipBuilder.toByteArray(); } } private static ValidationOverrides allValidationOverrides() { String until = DateTimeFormatter.ISO_LOCAL_DATE.format(Instant.now().plus(Duration.ofDays(25)).atZone(ZoneOffset.UTC)); StringBuilder validationOverridesContents = new StringBuilder(1000); validationOverridesContents.append("<validation-overrides version=\"1.0\">\n"); for (ValidationId validationId: ValidationId.values()) validationOverridesContents.append("\t<allow until=\"").append(until).append("\">").append(validationId.value()).append("</allow>\n"); validationOverridesContents.append("</validation-overrides>\n"); return ValidationOverrides.fromXml(validationOverridesContents.toString()); } /** Maps normalized paths to cached content read from a zip archive. */ private static class ZipArchiveCache { /** Max size of each extracted file */ private static final int maxSize = 10 << 20; // 10 Mb // TODO: Vespa 8: Remove application/ directory support private static final String applicationDir = "application/"; private static String withoutLegacyDir(String name) { if (name.startsWith(applicationDir)) return name.substring(applicationDir.length()); return name; } private final byte[] zip; private final Map<Path, Optional<byte[]>> cache; public ZipArchiveCache(byte[] zip, Collection<String> prePopulated) { this.zip = zip; this.cache = new ConcurrentSkipListMap<>(); this.cache.putAll(read(prePopulated)); } public Optional<byte[]> get(String path) { return get(Paths.get(path)); } public Optional<byte[]> get(Path path) { return cache.computeIfAbsent(path.normalize(), read(List.of(path.normalize().toString()))::get); } public FileSystemWrapper wrapper() { return FileSystemWrapper.ofFiles(path -> get(path).isPresent(), // Assume content asked for will also be read ... path -> get(path).orElseThrow(() -> new NoSuchFileException(path.toString()))); } private Map<Path, Optional<byte[]>> read(Collection<String> names) { var entries = new ZipStreamReader(new ByteArrayInputStream(zip), name -> names.contains(withoutLegacyDir(name)), maxSize, true) .entries().stream() .collect(toMap(entry -> Paths.get(withoutLegacyDir(entry.zipEntry().getName())).normalize(), ZipStreamReader.ZipEntryWithContent::content)); names.stream().map(Paths::get).forEach(path -> entries.putIfAbsent(path.normalize(), Optional.empty())); return entries; } } }
package org.csstudio.platform.libs.dal.epics; import org.eclipse.core.runtime.Plugin; import org.osgi.framework.BundleContext; /** * The activator class controls the plug-in life cycle */ public class Activator extends Plugin { XXXXXXXXXXXXXXXXXXXXXXXXXXXXX Error to test nightly build // The plug-in ID public static final String PLUGIN_ID = "org.csstudio.platform.libs.dal.epics"; // The shared instance private static Activator plugin; /** * The constructor */ public Activator() { plugin = this; } /* * (non-Javadoc) * @see org.eclipse.core.runtime.Plugins#start(org.osgi.framework.BundleContext) */ public void start(BundleContext context) throws Exception { super.start(context); } /* * (non-Javadoc) * @see org.eclipse.core.runtime.Plugin#stop(org.osgi.framework.BundleContext) */ public void stop(BundleContext context) throws Exception { plugin = null; super.stop(context); } /** * Returns the shared instance * * @return the shared instance */ public static Activator getDefault() { return plugin; } }
package org.xwalk.embedding.base; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.HashSet; import java.util.Map; import java.util.List; import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.FutureTask; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import java.util.Timer; import java.util.TimerTask; import junit.framework.Assert; import org.chromium.content.browser.test.util.CallbackHelper; import org.chromium.content.browser.test.util.Criteria; import org.chromium.content.browser.test.util.CriteriaHelper; import org.chromium.net.test.util.TestWebServer; import org.chromium.ui.gfx.DeviceDisplayInfo; import org.xwalk.core.JavascriptInterface; import org.xwalk.core.XWalkCookieManager; import org.xwalk.core.XWalkDownloadListener; import org.xwalk.core.XWalkFindListener; import org.xwalk.core.XWalkNavigationHistory; import org.xwalk.core.XWalkNavigationItem; import org.xwalk.core.XWalkResourceClient; import org.xwalk.core.XWalkUIClient; import org.xwalk.core.XWalkView; import org.xwalk.core.XWalkSettings; import org.xwalk.embedding.MainActivity; import org.xwalk.core.XWalkWebResourceResponse; import com.test.server.ActivityInstrumentationTestCase2; import android.content.Context; import android.content.res.AssetManager; import android.os.Bundle; import android.test.MoreAsserts; import android.util.Log; import android.util.Pair; import android.graphics.Bitmap; import android.net.http.SslCertificate; import android.net.http.SslError; import android.webkit.ValueCallback; import android.webkit.WebResourceResponse; public class XWalkViewTestBase extends ActivityInstrumentationTestCase2<MainActivity> { public XWalkViewTestBase(Class<MainActivity> activityClass) { super(activityClass); } protected static final int FIND_ALL = 3; protected static final int FIND = 2; protected final static String PASS_STRING = "Pass"; protected static final String EMPTY_PAGE = "<!doctype html>" + "<title>Set User Agent String Test</title><p>Set User Agent String Test.</p>"; protected static final String USER_AGENT = "Set User Agent String Test Mozilla/5.0 Apple Webkit Cosswalk Mobile Safari"; protected static final String EXPECTED_USER_AGENT = "\"Set User Agent String Test Mozilla/5.0 Apple Webkit Cosswalk Mobile Safari\""; protected static final int NUM_OF_CONSOLE_CALL = 10; protected static final String REDIRECT_TARGET_PATH = "/redirect_target.html"; protected static final String TITLE = "TITLE"; protected final String mExpectedStr = "xwalk"; protected final String mDefaultTitle = "Add JS Interface"; protected static final String DATA_URL = "data:text/html,<div/>"; protected final static int WAIT_TIMEOUT_SECONDS = 15; protected final static long WAIT_TIMEOUT_MS = 2000; private final static int CHECK_INTERVAL = 100; private Timer mTimer = new Timer(); protected XWalkView mXWalkView; protected XWalkView mXWalkViewTexture; protected XWalkView mRestoreXWalkView; protected MainActivity mainActivity; protected TestWebServer mWebServer; protected TestWebServer mWebServerSsl; protected TestXWalkResourceClient mTestXWalkResourceClient; protected XWalkCookieManager mCookieManager; protected boolean mAllowSslError = true; protected final TestHelperBridge mTestHelperBridge = new TestHelperBridge(); private String mUrls[]=new String[3]; protected static final int NUM_NAVIGATIONS = 3; public static final String TITLES[] = { "page 1 title foo", "page 2 title bar", "page 3 title baz" }; private static final String PATHS[] = { "/p1foo.html", "/p2bar.html", "/p3baz.html", }; protected final String ALERT_TEXT = "Hello World!"; protected final String PROMPT_TEXT = "How do you like your eggs in the morning?"; protected final String PROMPT_DEFAULT = "Scrambled"; protected final String PROMPT_RESULT = "I like mine with a kiss"; final String CONFIRM_TEXT = "Would you like a cookie?"; protected final AtomicBoolean callbackCalled = new AtomicBoolean(false); final CallbackHelper jsBeforeUnloadHelper = new CallbackHelper(); boolean flagForConfirmCancelled = false; public XWalkViewTestBase() { super(MainActivity.class); } @Override protected void setUp() throws Exception { super.setUp(); mainActivity = (MainActivity) getActivity(); mWebServer = TestWebServer.start(); mWebServerSsl = TestWebServer.startSsl(); while(!mainActivity.isXWalkReady()) { try{ waitForTimerFinish(200); }catch(Exception e){} } getInstrumentation().runOnMainSync(new Runnable() { @Override public void run() { mRestoreXWalkView = new XWalkView(getActivity(), getActivity()); mXWalkView = mainActivity.getXWalkView(); mXWalkViewTexture = mainActivity.getXWalkViewTexture(); mXWalkView.setUIClient(new TestXWalkUIClient()); mTestXWalkResourceClient = new TestXWalkResourceClient(); mXWalkView.setResourceClient(mTestXWalkResourceClient); } }); } public void waitForTimerFinish(int timer) throws Exception { Object notify = new Object(); synchronized (notify) { NotifyTask testTask = new NotifyTask(notify); mTimer.schedule(testTask, timer); notify.wait(); } } public class NotifyTask extends TimerTask { private Object mObj; public NotifyTask(Object obj) { super(); mObj = obj; } @Override public void run() { synchronized (mObj) { mObj.notify(); } } } protected void loadUrlAsync(final String url) throws Exception { getInstrumentation().runOnMainSync(new Runnable() { @Override public void run() { mXWalkView.load(url, null); } }); } protected void loadUrlAsync(final String url,final String content) throws Exception { getInstrumentation().runOnMainSync(new Runnable() { @Override public void run() { mXWalkView.load(url, content); } }); } protected void loadDataAsync(final String url, final String data, final String mimeType, final boolean isBase64Encoded) throws Exception { getInstrumentation().runOnMainSync(new Runnable() { @Override public void run() { mXWalkView.load(url, data); } }); } protected String getTitleOnUiThread() throws Exception { return runTestOnUiThreadAndGetResult(new Callable<String>() { @Override public String call() throws Exception { return mXWalkView.getTitle(); } }); } protected <R> R runTestOnUiThreadAndGetResult(Callable<R> callable) throws Exception { FutureTask<R> task = new FutureTask<R>(callable); getInstrumentation().waitForIdleSync(); getInstrumentation().runOnMainSync(task); return task.get(); } protected String getFileContent(String fileName) { try { Context context = getInstrumentation().getContext(); InputStream inputStream = context.getAssets().open(fileName); int size = inputStream.available(); byte buffer[] = new byte[size]; inputStream.read(buffer); inputStream.close(); String fileContent = new String(buffer); return fileContent; } catch (IOException e) { throw new RuntimeException(e); } } protected XWalkView getXWalkView() { return mXWalkView; } protected boolean canGoBackOnUiThread() throws Throwable { return runTestOnUiThreadAndGetResult(new Callable<Boolean>() { @Override public Boolean call() { return mXWalkView.getNavigationHistory().canGoBack(); } }); } protected boolean hasEnteredFullScreenOnUiThread() throws Throwable { return runTestOnUiThreadAndGetResult(new Callable<Boolean>() { @Override public Boolean call() { return mXWalkView.hasEnteredFullscreen(); } }); } protected void leaveFullscreenOnUiThread() throws Throwable { getInstrumentation().runOnMainSync(new Runnable() { @Override public void run() { mXWalkView.leaveFullscreen(); } }); } protected boolean canGoForwardOnUiThread() throws Throwable { return runTestOnUiThreadAndGetResult(new Callable<Boolean>() { @Override public Boolean call() { return mXWalkView.getNavigationHistory().canGoForward(); } }); } protected XWalkNavigationItem getCurrentItemOnUiThread() throws Throwable { return runTestOnUiThreadAndGetResult(new Callable<XWalkNavigationItem>() { @Override public XWalkNavigationItem call() { return mXWalkView.getNavigationHistory().getCurrentItem(); } }); } protected String executeJavaScriptAndWaitForResult(final String code) throws Exception { final OnEvaluateJavaScriptResultHelper helper = mTestHelperBridge.getOnEvaluateJavaScriptResultHelper(); getInstrumentation().runOnMainSync(new Runnable() { @Override public void run() { helper.evaluateJavascript(mXWalkView, code); } }); helper.waitUntilHasValue(); Assert.assertTrue("Failed to retrieve JavaScript evaluation results.", helper.hasValue()); return helper.getJsonResultAndClear(); } protected String getUrlOnUiThread() throws Exception { return runTestOnUiThreadAndGetResult(new Callable<String>() { @Override public String call() throws Exception { return mXWalkView.getUrl(); } }); } protected String getRemoteDebuggingUrlOnUiThread() throws Exception { return runTestOnUiThreadAndGetResult(new Callable<String>() { @Override public String call() throws Exception { if(mXWalkView.getRemoteDebuggingUrl() == null) { return ""; } return mXWalkView.getRemoteDebuggingUrl().getPath(); } }); } protected String getCurrentItemUrlOnUiThread() throws Exception { return runTestOnUiThreadAndGetResult(new Callable<String>() { @Override public String call() throws Exception { return mXWalkView.getNavigationHistory().getCurrentItem().getUrl(); } }); } protected String getNavigationUrlOnUiThread() throws Exception { return runTestOnUiThreadAndGetResult(new Callable<String>() { @Override public String call() throws Exception { return mXWalkView.getNavigationHistory().getCurrentItem().getUrl(); } }); } protected String getNavigationOriginalUrlOnUiThread() throws Exception { return runTestOnUiThreadAndGetResult(new Callable<String>() { @Override public String call() throws Exception { return mXWalkView.getNavigationHistory().getCurrentItem().getOriginalUrl(); } }); } protected String getNavigationTitleOnUiThread() throws Exception { return runTestOnUiThreadAndGetResult(new Callable<String>() { @Override public String call() throws Exception { return mXWalkView.getNavigationHistory().getCurrentItem().getTitle(); } }); } protected String getSizeOnUiThread() throws Exception { return runTestOnUiThreadAndGetResult(new Callable<String>() { @Override public String call() throws Exception { return String.valueOf(mXWalkView.getNavigationHistory().size()); } }); } protected String hasItemAtOnUiThread() throws Exception { return runTestOnUiThreadAndGetResult(new Callable<String>() { @Override public String call() throws Exception { return String.valueOf(mXWalkView.getNavigationHistory().hasItemAt(1)); } }); } protected String getOriginalUrlOnUiThread() throws Exception { return runTestOnUiThreadAndGetResult(new Callable<String>() { @Override public String call() throws Exception { return mXWalkView.getOriginalUrl(); } }); } protected void clearCacheOnUiThread(final boolean includeDiskFiles) throws Exception { getInstrumentation().runOnMainSync(new Runnable() { @Override public void run() { mXWalkView.clearCache(includeDiskFiles); } }); } protected String getAPIVersionOnUiThread() throws Exception { return runTestOnUiThreadAndGetResult(new Callable<String>() { @Override public String call() throws Exception { return mXWalkView.getAPIVersion(); } }); } protected String getXWalkVersionOnUiThread() throws Exception { return runTestOnUiThreadAndGetResult(new Callable<String>() { @Override public String call() throws Exception { return mXWalkView.getXWalkVersion(); } }); } private String getAssetsFileContent(AssetManager assetManager, String fileName) throws IOException { String result = ""; InputStream inputStream = null; try { inputStream = assetManager.open(fileName); int size = inputStream.available(); byte[] buffer = new byte[size]; inputStream.read(buffer); result = new String(buffer); } finally { if (inputStream != null) { inputStream.close(); } } return result; } public class PerformExecute implements Runnable { protected StringBuffer urlBuf; public PerformExecute(StringBuffer url) { urlBuf = url; } @Override public void run() { } } public static class EmptyInputStream extends InputStream { @Override public int available() { return 0; } @Override public int read() throws IOException { return -1; } @Override public int read(byte b[]) throws IOException { return -1; } @Override public int read(byte b[], int off, int len) throws IOException { return -1; } @Override public long skip(long n) throws IOException { if (n < 0) throw new IOException("skipping negative number of bytes"); return 0; } } class TestXWalkFindListener extends XWalkFindListener { @Override public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) { mTestHelperBridge.onFindResultReceived(activeMatchOrdinal, numberOfMatches, isDoneCounting); } } protected void setFindListener() { getInstrumentation().runOnMainSync(new Runnable() { @Override public void run() { getXWalkView().setFindListener(new TestXWalkFindListener()); } }); } protected void goBackSync(final int n) throws Throwable { runTestWaitPageFinished(new Runnable(){ @Override public void run() { getInstrumentation().runOnMainSync(new Runnable() { @Override public void run() { mXWalkView.getNavigationHistory().navigate( XWalkNavigationHistory.Direction.BACKWARD, n); } }); } }); } protected void goForwardSync(final int n) throws Throwable { runTestWaitPageFinished(new Runnable(){ @Override public void run() { getInstrumentation().runOnMainSync(new Runnable() { @Override public void run() { mXWalkView.getNavigationHistory().navigate( XWalkNavigationHistory.Direction.FORWARD, n); } }); } }); } protected void setServerResponseAndLoad(int upto) throws Throwable { for (int i = 0; i < upto; ++i) { String html = "<html><head><title>" + TITLES[i] + "</title></head></html>"; mUrls[i] = mWebServer.setResponse(PATHS[i], html, null); loadUrlSync(mUrls[i]); } } protected void saveAndRestoreStateOnUiThread() throws Throwable { getInstrumentation().runOnMainSync(new Runnable() { @Override public void run() { Bundle bundle = new Bundle(); mXWalkView.saveState(bundle); mRestoreXWalkView.restoreState(bundle); } }); } protected boolean pollOnUiThread(final Callable<Boolean> callable) throws Exception { return CriteriaHelper.pollForCriteria(new Criteria() { @Override public boolean isSatisfied() { try { return runTestOnUiThreadAndGetResult(callable); } catch (Throwable e) { return false; } } }); } protected void checkHistoryItemList(XWalkView restoreXWalkView) throws Throwable { XWalkNavigationHistory history = getNavigationHistoryOnUiThread(restoreXWalkView); assertEquals(NUM_NAVIGATIONS, history.size()); assertEquals(NUM_NAVIGATIONS - 1, history.getCurrentIndex()); for (int i = 0; i < NUM_NAVIGATIONS; ++i) { assertEquals(mUrls[i], history.getItemAt(i).getUrl()); assertEquals(TITLES[i], history.getItemAt(i).getTitle()); } } private XWalkNavigationHistory getNavigationHistoryOnUiThread( final XWalkView content) throws Throwable{ return runTestOnUiThreadAndGetResult(new Callable<XWalkNavigationHistory>() { @Override public XWalkNavigationHistory call() throws Exception { return content.getNavigationHistory(); } }); } @Override protected void tearDown() throws Exception { if (mWebServer != null) { mWebServer.shutdown(); } if (mWebServerSsl != null) { mWebServerSsl.shutdown(); } if(mainActivity != null) { mainActivity.finish(); } super.tearDown(); } public class TestJavascriptInterface { @JavascriptInterface public String getTextWithoutAnnotation() { return mExpectedStr; } @JavascriptInterface public String getText() { return mExpectedStr; } @JavascriptInterface public String getDateText() { return new Date().toString(); } } protected void addJavascriptInterface() { getInstrumentation().runOnMainSync(new Runnable() { @Override public void run() { getXWalkView().addJavascriptInterface(new TestJavascriptInterface(), "testInterface"); } }); } protected void removeJavascriptInterface() { getInstrumentation().runOnMainSync(new Runnable() { @Override public void run() { getXWalkView().removeJavascriptInterface("testInterface"); } }); } protected void raisesExceptionAndSetTitle(String script) throws Throwable { executeJavaScriptAndWaitForResult("try { var title = " + script + ";" + " document.title = title;" + "} catch (exception) {" + " document.title = \"error\";" + "}"); } public class TestXWalkUIClient extends TestXWalkUIClientBase { public TestXWalkUIClient() { super(mTestHelperBridge, mXWalkView, callbackCalled); } } class TestXWalkResourceClient extends TestXWalkResourceClientBase { public TestXWalkResourceClient() { super(mTestHelperBridge,mXWalkView); } @Override public void onReceivedSslError(XWalkView view, ValueCallback<Boolean> callback, SslError error) { if(error.getUrl().endsWith("html")){ callback.onReceiveValue(mAllowSslError); mTestHelperBridge.onReceivedSsl(); } } } protected void loadUrlSync(final String url) throws Exception { CallbackHelper pageFinishedHelper = mTestHelperBridge.getOnPageFinishedHelper(); int currentCallCount = pageFinishedHelper.getCallCount(); loadUrlAsync(url); pageFinishedHelper.waitForCallback(currentCallCount, 1, WAIT_TIMEOUT_SECONDS, TimeUnit.SECONDS); } protected void loadUrlSync(final String url, final String content) throws Exception { CallbackHelper pageFinishedHelper = mTestHelperBridge.getOnPageFinishedHelper(); int currentCallCount = pageFinishedHelper.getCallCount(); loadUrlAsync(url, content); pageFinishedHelper.waitForCallback(currentCallCount, 1, WAIT_TIMEOUT_SECONDS, TimeUnit.SECONDS); } protected void loadJavaScriptSync(final String url, final String code) throws Exception { CallbackHelper pageFinishedHelper = mTestHelperBridge.getOnPageFinishedHelper(); int currentCallCount = pageFinishedHelper.getCallCount(); loadUrlAsync(url); loadUrlAsync(code); pageFinishedHelper.waitForCallback(currentCallCount, 1, WAIT_TIMEOUT_SECONDS, TimeUnit.SECONDS); } protected void loadFromManifestSync(final String path, final String name) throws Exception { CallbackHelper pageFinishedHelper = mTestHelperBridge.getOnPageFinishedHelper(); int currentCallCount = pageFinishedHelper.getCallCount(); loadFromManifestAsync(path, name); pageFinishedHelper.waitForCallback(currentCallCount, 1, WAIT_TIMEOUT_SECONDS, TimeUnit.SECONDS); } protected void loadFromManifestAsync(final String path, final String name) throws Exception { getInstrumentation().runOnMainSync(new Runnable() { @Override public void run() { String manifestContent = ""; try { manifestContent = getAssetsFileContent(mainActivity.getAssets(), name); } catch (IOException e) { e.printStackTrace(); } mXWalkView.loadAppFromManifest(path, manifestContent); } }); } protected void loadAssetFile(String fileName) throws Exception { CallbackHelper pageFinishedHelper = mTestHelperBridge.getOnPageFinishedHelper(); int currentCallCount = pageFinishedHelper.getCallCount(); String fileContent = getFileContent(fileName); loadDataAsync(fileName, fileContent, "text/html", false); pageFinishedHelper.waitForCallback(currentCallCount, 1, WAIT_TIMEOUT_SECONDS, TimeUnit.SECONDS); } protected void runTestWaitPageFinished(Runnable runnable) throws Exception{ CallbackHelper pageFinishedHelper = mTestHelperBridge.getOnPageFinishedHelper(); int currentCallCount = pageFinishedHelper.getCallCount(); runnable.run(); pageFinishedHelper.waitForCallback(currentCallCount, 1, WAIT_TIMEOUT_SECONDS, TimeUnit.SECONDS); } protected void reloadSync(final int mode) throws Exception { runTestWaitPageFinished(new Runnable(){ @Override public void run() { getInstrumentation().runOnMainSync(new Runnable() { @Override public void run() { mXWalkView.reload(mode); } }); } }); } protected void loadDataSync(final String url, final String data, final String mimeType, final boolean isBase64Encoded) throws Exception { CallbackHelper pageFinishedHelper = mTestHelperBridge.getOnPageFinishedHelper(); int currentCallCount = pageFinishedHelper.getCallCount(); loadDataAsync(url, data, mimeType, isBase64Encoded); pageFinishedHelper.waitForCallback(currentCallCount, 1, WAIT_TIMEOUT_SECONDS, TimeUnit.SECONDS); } public void loadAssetFileAndWaitForTitle(String fileName) throws Exception { CallbackHelper getTitleHelper = mTestHelperBridge.getOnTitleUpdatedHelper(); int currentCallCount = getTitleHelper.getCallCount(); String fileContent = getFileContent(fileName); loadDataSync(fileName, fileContent, "text/html", false); getTitleHelper.waitForCallback(currentCallCount, 1, WAIT_TIMEOUT_SECONDS, TimeUnit.SECONDS); } public boolean checkMethodInClass(Class<?> clazz, String methodName){ Method[] methods = clazz.getMethods(); for(Method method : methods) { if(method.getName().equals(methodName)){ return true; } } Method[] methods2 = clazz.getDeclaredMethods(); for(Method method : methods2) { if(method.getName().equals(methodName)){ return true; } } return false; } public void clickOnElementId_evaluateJavascript(final String id) throws Exception { Assert.assertTrue(CriteriaHelper.pollForCriteria(new Criteria() { @Override public boolean isSatisfied() { try { String idIsNotNull = executeJavaScriptAndWaitForResult( "document.getElementById('" + id + "') != null"); return idIsNotNull.equals("true"); } catch (Throwable t) { t.printStackTrace(); Assert.fail("Failed to check if DOM is loaded: " + t.toString()); return false; } } }, WAIT_TIMEOUT_MS, CHECK_INTERVAL)); try { executeJavaScriptAndWaitForResult( "var evObj = document.createEvent('Events'); " + "evObj.initEvent('click', true, false); " + "document.getElementById('" + id + "').dispatchEvent(evObj);" + "console.log('element with id [" + id + "] clicked');"); } catch (Throwable t) { t.printStackTrace(); } } public void clickOnElementId(final String id, String frameName) throws Exception { String str; if (frameName != null) { str = "top.window." + frameName + ".document.getElementById('" + id + "')"; } else { str = "document.getElementById('" + id + "')"; } final String script1 = str + " != null"; final String script2 = str + ".dispatchEvent(evObj);"; Assert.assertTrue(CriteriaHelper.pollForCriteria(new Criteria() { @Override public boolean isSatisfied() { try { String idIsNotNull = executeJavaScriptAndWaitForResult(script1); return idIsNotNull.equals("true"); } catch (Throwable t) { t.printStackTrace(); Assert.fail("Failed to check if DOM is loaded: " + t.toString()); return false; } } }, WAIT_TIMEOUT_MS, CHECK_INTERVAL)); try { loadJavaScriptUrl("javascript:var evObj = document.createEvent('Events'); " + "evObj.initEvent('click', true, false); " + script2 + "console.log('element with id [" + id + "] clicked');"); } catch (Throwable t) { t.printStackTrace(); } } protected String addPageToTestServer(TestWebServer webServer, String httpPath, String html) { List<Pair<String, String>> headers = new ArrayList<Pair<String, String>>(); headers.add(Pair.create("Content-Type", "text/html")); headers.add(Pair.create("Cache-Control", "no-store")); return webServer.setResponse(httpPath, html, headers); } protected void stopLoading() throws Exception { getInstrumentation().runOnMainSync(new Runnable() { @Override public void run() { mXWalkView.stopLoading(); } }); } protected void pauseTimers() throws Exception { getInstrumentation().runOnMainSync(new Runnable() { @Override public void run() { mXWalkView.pauseTimers(); } }); } protected void resumeTimers() throws Exception { getInstrumentation().runOnMainSync(new Runnable() { @Override public void run() { mXWalkView.resumeTimers(); } }); } protected void onHide() throws Exception { getInstrumentation().runOnMainSync(new Runnable() { @Override public void run() { mXWalkView.onHide(); } }); } protected void onShow() throws Exception { getInstrumentation().runOnMainSync(new Runnable() { @Override public void run() { mXWalkView.onShow(); } }); } protected void onDestroy() throws Exception { getInstrumentation().runOnMainSync(new Runnable() { @Override public void run() { mXWalkView.onDestroy(); } }); } protected void setDownloadListener() { getInstrumentation().runOnMainSync(new Runnable() { @Override public void run() { mXWalkView.setDownloadListener(new XWalkDownloadListener(getActivity()) { @Override public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) { // TODO Auto-generated method stub mTestHelperBridge.onDownloadStart(url, userAgent, contentDisposition, mimetype, contentLength); } }); } }); } protected boolean canZoomInOnUiThread() throws Exception { return runTestOnUiThreadAndGetResult(new Callable<Boolean>() { @Override public Boolean call() throws Exception { return mXWalkView.canZoomIn(); } }); } protected boolean canZoomOutOnUiThread() throws Exception { return runTestOnUiThreadAndGetResult(new Callable<Boolean>() { @Override public Boolean call() throws Exception { return mXWalkView.canZoomOut(); } }); } protected void zoomInOnUiThreadAndWait() throws Throwable { final double dipScale = DeviceDisplayInfo.create(getActivity()).getDIPScale() ; final float previousScale = mTestHelperBridge.getOnScaleChangedHelper().getNewScale() * (float)dipScale; assertTrue(runTestOnUiThreadAndGetResult(new Callable<Boolean>() { @Override public Boolean call() throws Exception { return mXWalkView.zoomIn(); } })); // The zoom level is updated asynchronously. pollOnUiThread(new Callable<Boolean>() { @Override public Boolean call() throws Exception { return previousScale != mTestHelperBridge.getOnScaleChangedHelper().getNewScale() * (float)dipScale; } }); } protected void zoomOutOnUiThreadAndWait() throws Throwable { final double dipScale = DeviceDisplayInfo.create(getActivity()).getDIPScale() ; final float previousScale = mTestHelperBridge.getOnScaleChangedHelper().getNewScale() * (float)dipScale; assertTrue(runTestOnUiThreadAndGetResult(new Callable<Boolean>() { @Override public Boolean call() throws Exception { return mXWalkView.zoomOut(); } })); // The zoom level is updated asynchronously. pollOnUiThread(new Callable<Boolean>() { @Override public Boolean call() throws Exception { return previousScale != mTestHelperBridge.getOnScaleChangedHelper().getNewScale() * (float)dipScale; } }); } protected void zoomByOnUiThreadAndWait(final float delta) throws Throwable { final double dipScale = DeviceDisplayInfo.create(getActivity()).getDIPScale() ; final float previousScale = mTestHelperBridge.getOnScaleChangedHelper().getNewScale() * (float)dipScale; getInstrumentation().runOnMainSync(new Runnable() { @Override public void run() { mXWalkView.zoomBy(delta); } }); // The zoom level is updated asynchronously. pollOnUiThread(new Callable<Boolean>() { @Override public Boolean call() throws Exception { return previousScale != mTestHelperBridge.getOnScaleChangedHelper().getNewScale() * (float)dipScale; } }); } protected void setAcceptLanguages(final String languages) { getInstrumentation().runOnMainSync(new Runnable() { @Override public void run() { mXWalkView.setAcceptLanguages(languages); } }); } protected void setUserAgent(final String userAgent) { getInstrumentation().runOnMainSync(new Runnable() { @Override public void run() { mXWalkView.setUserAgentString(userAgent); } }); } protected String getUserAgent() throws Exception { return runTestOnUiThreadAndGetResult(new Callable<String>() { @Override public String call() throws Exception { return mXWalkView.getUserAgentString(); } }); } protected void setCookie(final String name, final String value) throws Exception { String jsCommand = "javascript:void((function(){" + "var expirationDate = new Date();" + "expirationDate.setDate(expirationDate.getDate() + 5);" + "document.cookie='" + name + "=" + value + "; expires=' + expirationDate.toUTCString();" + "})())"; loadJavaScriptUrl(jsCommand); } protected void waitForCookie(final String url) throws InterruptedException { assertTrue(CriteriaHelper.pollForCriteria(new Criteria() { @Override public boolean isSatisfied() { return mCookieManager.getCookie(url) != null; } }, 6000, 50)); } protected void validateCookies(String responseCookie, String... expectedCookieNames) { String[] cookies = responseCookie.split(";"); Set<String> foundCookieNames = new HashSet<String>(); for (String cookie : cookies) { foundCookieNames.add(cookie.substring(0, cookie.indexOf("=")).trim()); } MoreAsserts.assertEquals( foundCookieNames, new HashSet<String>(Arrays.asList(expectedCookieNames))); } protected String makeExpiringCookie(String cookie, int secondsTillExpiry) { return makeExpiringCookieMs(cookie, secondsTillExpiry * 1000); } @SuppressWarnings("deprecation") protected String makeExpiringCookieMs(String cookie, int millisecondsTillExpiry) { Date date = new Date(); date.setTime(date.getTime() + millisecondsTillExpiry); return cookie + "; expires=" + date.toGMTString(); } protected boolean fileURLCanSetCookie(String suffix) throws Throwable { String value = "value" + suffix; String url = "file:///android_asset/cookie_test.html?value=" + value; loadUrlSync(url); String cookie = mCookieManager.getCookie(url); return cookie != null && cookie.contains("test=" + value); } public static final String ABOUT_TITLE = "About the Google"; protected String addAboutPageToTestServer(TestWebServer webServer) { return addPageToTestServer(webServer, "/" + "about.html", "<html><head><title>" + ABOUT_TITLE + "</title></head></html>"); } protected WebResourceResponse stringToWebResourceResponse(String input) throws Throwable { final String mimeType = "text/html"; final String encoding = "UTF-8"; return new WebResourceResponse( mimeType, encoding, new ByteArrayInputStream(input.getBytes(encoding))); } protected void loadJavaScriptUrl(final String url) throws Exception { if (!url.startsWith("javascript:")) { Log.w("Test", "loadJavascriptUrl only accepts javascript: url"); return; } loadUrlAsync(url); } protected void setInitialScale(final int scaleInPercent) { getInstrumentation().runOnMainSync(new Runnable() { @Override public void run() { mXWalkView.setInitialScale(scaleInPercent); } }); } protected double getDipScale() { return DeviceDisplayInfo.create(mXWalkView.getContext()).getDIPScale(); } protected float getScaleFactor() { return getPixelScale() / (float) getDipScale(); } public float getPixelScale() { return mTestHelperBridge.getOnScaleChangedHelper().getNewScale(); } protected void ensureScaleBecomes(final float targetScale) throws Throwable { pollOnUiThread(new Callable<Boolean>() { @Override public Boolean call() throws Exception { return targetScale == getScaleFactor(); } }); } protected void clearSingleCacheOnUiThread(final String url) throws Exception { getInstrumentation().runOnMainSync(new Runnable() { @Override public void run() { mXWalkView.clearCacheForSingleFile(url); } }); } protected XWalkSettings getXWalkSettingsOnUiThreadByXWalkView( final XWalkView view) throws Exception { return runTestOnUiThreadAndGetResult(new Callable<XWalkSettings>() { @Override public XWalkSettings call() throws Exception { return view.getSettings(); } }); } protected Bitmap getFaviconOnUiThread() throws Exception { return runTestOnUiThreadAndGetResult(new Callable<Bitmap>() { @Override public Bitmap call() throws Exception { return mXWalkView.getFavicon(); } }); } protected void setAllowSslError(boolean allow) { mAllowSslError = allow; } protected void clearSslPreferences() throws Exception { getInstrumentation().runOnMainSync(new Runnable() { @Override public void run() { mXWalkView.clearSslPreferences(); } }); } protected XWalkWebResourceResponse stringToWebResourceResponse2(String input) throws Throwable { final String mimeType = "text/html"; final String encoding = "UTF-8"; return mTestXWalkResourceClient.createXWalkWebResourceResponse( mimeType, encoding, new ByteArrayInputStream(input.getBytes(encoding))); } protected void loadUrlWithHeaders(final String url, final Map<String, String> headers) throws Exception { getInstrumentation().runOnMainSync(new Runnable() { @Override public void run() { mXWalkView.load(url, null, headers); } }); } protected SslCertificate getCertificateOnUiThread() throws Exception { return runTestOnUiThreadAndGetResult(new Callable<SslCertificate>() { @Override public SslCertificate call() throws Exception { return mXWalkView.getCertificate(); } }); } protected void findAllAsync(final String text) { getInstrumentation().runOnMainSync(new Runnable() { @Override public void run() { mXWalkView.findAllAsync(text); } }); } protected void findAllSync(CallbackHelper mOnFindResultReceivedHelper, int count, final String text) throws InterruptedException, TimeoutException { int currentCallCount = mOnFindResultReceivedHelper.getCallCount(); findAllAsync(text); mOnFindResultReceivedHelper.waitForCallback(currentCallCount, count); } protected void findNextAsync(final boolean forward) { getInstrumentation().runOnMainSync(new Runnable() { @Override public void run() { mXWalkView.findNext(forward); } }); } protected void runPerViewSettingsTest(XWalkSettingsTestHelper<?> helper0, XWalkSettingsTestHelper<?> helper1) throws Throwable { helper0.ensureSettingHasInitialValue(); helper1.ensureSettingHasInitialValue(); helper1.setAlteredSettingValue(); helper0.ensureSettingHasInitialValue(); helper1.ensureSettingHasAlteredValue(); helper1.setInitialSettingValue(); helper0.ensureSettingHasInitialValue(); helper1.ensureSettingHasInitialValue(); helper0.setAlteredSettingValue(); helper0.ensureSettingHasAlteredValue(); helper1.ensureSettingHasInitialValue(); helper0.setInitialSettingValue(); helper0.ensureSettingHasInitialValue(); helper1.ensureSettingHasInitialValue(); helper0.setAlteredSettingValue(); helper0.ensureSettingHasAlteredValue(); helper1.ensureSettingHasInitialValue(); helper1.setAlteredSettingValue(); helper0.ensureSettingHasAlteredValue(); helper1.ensureSettingHasAlteredValue(); helper0.setInitialSettingValue(); helper0.ensureSettingHasInitialValue(); helper1.ensureSettingHasAlteredValue(); helper1.setInitialSettingValue(); helper0.ensureSettingHasInitialValue(); helper1.ensureSettingHasInitialValue(); } protected XWalkView createXWalkViewContainerOnMainSync( final Context context, final XWalkUIClient uiClient, final XWalkResourceClient resourceClient) throws Exception { final AtomicReference<XWalkView> xWalkViewContainer = new AtomicReference<XWalkView>(); getInstrumentation().runOnMainSync(new Runnable() { @Override public void run() { xWalkViewContainer.set(new XWalkView(context, getActivity())); getActivity().addView(xWalkViewContainer.get()); xWalkViewContainer.get().setUIClient(uiClient); xWalkViewContainer.get().setResourceClient(resourceClient); } }); return xWalkViewContainer.get(); } public static class ViewPair { private final XWalkView view0; private final TestHelperBridge bridge0; private final XWalkView view1; private final TestHelperBridge bridge1; ViewPair(XWalkView view0, TestHelperBridge bridge0, XWalkView view1, TestHelperBridge bridge1) { this.view0 = view0; this.bridge0 = bridge0; this.view1 = view1; this.bridge1 = bridge1; } public XWalkView getView0() { return view0; } public TestHelperBridge getBridge0() { return bridge0; } public XWalkView getView1() { return view1; } public TestHelperBridge getBridge1() { return bridge1; } } protected ViewPair createViews() throws Throwable { TestHelperBridge helperBridge0 = new TestHelperBridge(); TestHelperBridge helperBridge1 = new TestHelperBridge(); TestXWalkUIClientBase uiClient0 = new TestXWalkUIClientBase(helperBridge0, mXWalkView, callbackCalled); TestXWalkUIClientBase uiClient1 = new TestXWalkUIClientBase(helperBridge1, mXWalkView, callbackCalled); TestXWalkResourceClientBase resourceClient0= new TestXWalkResourceClientBase(helperBridge0, mXWalkView); TestXWalkResourceClientBase resourceClient1 = new TestXWalkResourceClientBase(helperBridge1, mXWalkView); ViewPair viewPair = createViewsOnMainSync(helperBridge0, helperBridge1, uiClient0, uiClient1, resourceClient0, resourceClient1, getActivity()); return viewPair; } protected ViewPair createViewsOnMainSync(final TestHelperBridge helperBridge0, final TestHelperBridge helperBridge1, final XWalkUIClient uiClient0, final XWalkUIClient uiClient1, final XWalkResourceClient resourceClient0, final XWalkResourceClient resourceClient1, final Context context) throws Throwable { final XWalkView walkView0 = createXWalkViewContainerOnMainSync(context, uiClient0, resourceClient0); final XWalkView walkView1 = createXWalkViewContainerOnMainSync(context, uiClient1, resourceClient1); final AtomicReference<ViewPair> viewPair = new AtomicReference<ViewPair>(); getInstrumentation().runOnMainSync(new Runnable() { @Override public void run() { viewPair.set(new ViewPair(walkView0, helperBridge0, walkView1, helperBridge1)); } }); return viewPair.get(); } protected void loadDataAsyncWithXWalkView(final String data, final XWalkView view) throws Exception { getInstrumentation().runOnMainSync(new Runnable() { @Override public void run() { view.load(null, data); } }); } protected void findNextSync(CallbackHelper mOnFindResultReceivedHelper, int count, final boolean bool) throws InterruptedException, TimeoutException { int currentCallCount = mOnFindResultReceivedHelper.getCallCount(); findNextAsync(bool); mOnFindResultReceivedHelper.waitForCallback(currentCallCount, count); } protected void loadDataSyncWithXWalkView(final String data, final XWalkView view, final TestHelperBridge bridge) throws Exception { CallbackHelper pageFinishedHelper = bridge.getOnPageFinishedHelper(); int currentCallCount = pageFinishedHelper.getCallCount(); loadDataAsyncWithXWalkView(data, view); pageFinishedHelper.waitForCallback(currentCallCount, 1, WAIT_TIMEOUT_SECONDS, TimeUnit.SECONDS); } protected void setUseWideViewPortOnUiThreadByXWalkView(final boolean value, final XWalkView view) throws Exception { getInstrumentation().runOnMainSync(new Runnable() { @Override public void run() { view.getSettings().setUseWideViewPort(value); } }); } abstract class XWalkSettingsTestHelper<T> { protected final XWalkView mXWalkViewForHelper; protected final XWalkSettings mXWalkSettingsForHelper; XWalkSettingsTestHelper(XWalkView view) throws Throwable { mXWalkViewForHelper = view; mXWalkSettingsForHelper = getXWalkSettingsOnUiThreadByXWalkView(view); } void ensureSettingHasAlteredValue() throws Throwable { ensureSettingHasValue(getAlteredValue()); } void ensureSettingHasInitialValue() throws Throwable { ensureSettingHasValue(getInitialValue()); } void setAlteredSettingValue() throws Throwable { setCurrentValue(getAlteredValue()); } void setInitialSettingValue() throws Throwable { setCurrentValue(getInitialValue()); } protected abstract T getAlteredValue(); protected abstract T getInitialValue(); protected abstract T getCurrentValue(); protected abstract void setCurrentValue(T value) throws Throwable; protected abstract void doEnsureSettingHasValue(T value) throws Throwable; private void ensureSettingHasValue(T value) throws Throwable { assertEquals(value, getCurrentValue()); doEnsureSettingHasValue(value); } } private static final boolean ENABLED = true; private static final boolean DISABLED = false; private float getScaleFactorByXWalkViewAndHelperBridge(final XWalkView view, final TestHelperBridge bridge) { final float newScale = bridge.getOnScaleChangedHelper().getNewScale(); // If new scale is 0.0f, it means the page does not zoom, // return the default scale factior: 1.0f. if (Float.compare(newScale, 0.0f) == 0) return 1.0f; return newScale / (float) DeviceDisplayInfo.create(view.getContext()).getDIPScale(); } protected void setLoadWithOverviewModeOnUiThreadByXWalkView( final boolean value, final XWalkView view) throws Exception { getInstrumentation().runOnMainSync(new Runnable() { @Override public void run() { view.getSettings().setLoadWithOverviewMode(value); } }); } protected boolean getLoadWithOverviewModeOnUiThreadByXWalkView( final XWalkView view) throws Exception { return runTestOnUiThreadAndGetResult(new Callable<Boolean>() { @Override public Boolean call() throws Exception { return view.getSettings().getLoadWithOverviewMode(); } }); } public class XWalkSettingsLoadWithOverviewModeTestHelper extends XWalkSettingsTestHelper<Boolean> { private static final float DEFAULT_PAGE_SCALE = 1.0f; private final boolean mWithViewPortTag; private boolean mExpectScaleChange; private int mOnScaleChangedCallCount; XWalkView mView; TestHelperBridge mBridge; public XWalkSettingsLoadWithOverviewModeTestHelper( XWalkView view, TestHelperBridge bridge, boolean withViewPortTag) throws Throwable { super(view); mView = view; mBridge = bridge; mWithViewPortTag = withViewPortTag; setUseWideViewPortOnUiThreadByXWalkView(true, view); } @Override protected Boolean getAlteredValue() { return ENABLED; } @Override protected Boolean getInitialValue() { return DISABLED; } @Override protected Boolean getCurrentValue() { try { return getLoadWithOverviewModeOnUiThreadByXWalkView(mView); } catch (Exception e) { return false; } } @Override protected void setCurrentValue(Boolean value) { try { mExpectScaleChange = getLoadWithOverviewModeOnUiThreadByXWalkView(mView) != value; if (mExpectScaleChange) mOnScaleChangedCallCount = mBridge.getOnScaleChangedHelper().getCallCount(); setLoadWithOverviewModeOnUiThreadByXWalkView(value, mView); } catch (Exception e) { } } @Override protected void doEnsureSettingHasValue(Boolean value) throws Throwable { loadDataSyncWithXWalkView(getData(), mView, mBridge); if (mExpectScaleChange) { mBridge.getOnScaleChangedHelper().waitForCallback(mOnScaleChangedCallCount); mExpectScaleChange = false; } float currentScale = getScaleFactorByXWalkViewAndHelperBridge(mView, mBridge); if (value) { assertTrue("Expected: " + currentScale + " < " + DEFAULT_PAGE_SCALE, currentScale < DEFAULT_PAGE_SCALE); } else { assertEquals(DEFAULT_PAGE_SCALE, currentScale); } } private String getData() { return "<html><head>" + (mWithViewPortTag ? "<meta name='viewport' content='width=3000' />" : "") + "</head>" + "<body></body></html>"; } } public static final String SURFACE_VIEW = "SurfaceView"; public static final String TEXTURE_VIEW = "TextureView"; protected String getBackendTypeOnUiThread(final XWalkView view) throws Exception { return runTestOnUiThreadAndGetResult(new Callable<String>() { @Override public String call() throws Exception { //return view.getCompositingSurfaceType(); return ""; } }); } }
package org.eclipse.birt.report.engine.data.dte; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.eclipse.birt.data.engine.api.IBaseExpression; import org.eclipse.birt.data.engine.api.IBaseQueryDefn; import org.eclipse.birt.data.engine.api.IBaseTransform; import org.eclipse.birt.data.engine.api.IConditionalExpression; import org.eclipse.birt.data.engine.api.IFilterDefn; import org.eclipse.birt.data.engine.api.IGroupDefn; import org.eclipse.birt.data.engine.api.IInputParamBinding; import org.eclipse.birt.data.engine.api.ISortDefn; import org.eclipse.birt.data.engine.api.querydefn.BaseQueryDefn; import org.eclipse.birt.data.engine.api.querydefn.ConditionalExpression; import org.eclipse.birt.data.engine.api.querydefn.FilterDefn; import org.eclipse.birt.data.engine.api.querydefn.GroupDefn; import org.eclipse.birt.data.engine.api.querydefn.InputParamBinding; import org.eclipse.birt.data.engine.api.querydefn.JSExpression; import org.eclipse.birt.data.engine.api.querydefn.ReportQueryDefn; import org.eclipse.birt.data.engine.api.querydefn.SortDefn; import org.eclipse.birt.data.engine.api.querydefn.SubqueryDefn; import org.eclipse.birt.report.engine.executor.ExecutionContext; import org.eclipse.birt.report.engine.extension.ExtensionManager; import org.eclipse.birt.report.engine.extension.IReportItemGeneration; import org.eclipse.birt.report.engine.ir.ActionDesign; import org.eclipse.birt.report.engine.ir.CellDesign; import org.eclipse.birt.report.engine.ir.ColumnDesign; import org.eclipse.birt.report.engine.ir.DataItemDesign; import org.eclipse.birt.report.engine.ir.Expression; import org.eclipse.birt.report.engine.ir.ExtendedItemDesign; import org.eclipse.birt.report.engine.ir.FreeFormItemDesign; import org.eclipse.birt.report.engine.ir.GridItemDesign; import org.eclipse.birt.report.engine.ir.GroupDesign; import org.eclipse.birt.report.engine.ir.HighlightDesign; import org.eclipse.birt.report.engine.ir.HighlightRuleDesign; import org.eclipse.birt.report.engine.ir.ImageItemDesign; import org.eclipse.birt.report.engine.ir.LabelItemDesign; import org.eclipse.birt.report.engine.ir.ListBandDesign; import org.eclipse.birt.report.engine.ir.ListGroupDesign; import org.eclipse.birt.report.engine.ir.ListItemDesign; import org.eclipse.birt.report.engine.ir.ListingDesign; import org.eclipse.birt.report.engine.ir.MapDesign; import org.eclipse.birt.report.engine.ir.MapRuleDesign; import org.eclipse.birt.report.engine.ir.MultiLineItemDesign; import org.eclipse.birt.report.engine.ir.Report; import org.eclipse.birt.report.engine.ir.ReportItemDesign; import org.eclipse.birt.report.engine.ir.DefaultReportItemVisitorImpl; import org.eclipse.birt.report.engine.ir.RowDesign; import org.eclipse.birt.report.engine.ir.StyleDesign; import org.eclipse.birt.report.engine.ir.TableBandDesign; import org.eclipse.birt.report.engine.ir.TableGroupDesign; import org.eclipse.birt.report.engine.ir.TableItemDesign; import org.eclipse.birt.report.engine.ir.TextItemDesign; import org.eclipse.birt.report.engine.parser.DOMParser; import org.eclipse.birt.report.model.api.DataSetHandle; import org.eclipse.birt.report.model.api.ExtendedItemHandle; import org.eclipse.birt.report.model.api.FilterConditionHandle; import org.eclipse.birt.report.model.api.GroupHandle; import org.eclipse.birt.report.model.api.ListHandle; import org.eclipse.birt.report.model.api.ListingHandle; import org.eclipse.birt.report.model.api.ParamBindingHandle; import org.eclipse.birt.report.model.api.ReportItemHandle; import org.eclipse.birt.report.model.api.SlotHandle; import org.eclipse.birt.report.model.api.SortKeyHandle; import org.eclipse.birt.report.model.api.TableHandle; import org.eclipse.birt.report.model.elements.DesignChoiceConstants; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; public class ReportQueryBuilder { /** * constructor */ public ReportQueryBuilder( ) { } /** * @param report the entry point to the report design * @param context the execution context */ public void build( Report report, ExecutionContext context ) { new QueryBuilderVisitor( ).buildQuery( report, context ); } /** * The visitor class that actually builds the report query */ protected class QueryBuilderVisitor extends DefaultReportItemVisitorImpl { /** * for logging */ protected Log logger = LogFactory.getLog( QueryBuilderVisitor.class ); /** * a collection of all the queries */ protected Collection queries; /** * the query stack. The top stores the query that is currently prepared. * Needed because we could have nested queries */ protected LinkedList queryStack = new LinkedList( ); /** * the total number of queries created in this report */ protected int queryCount = 0; /** * a collection of the expressions on the CURRENT query */ protected Collection expressions; /** * the expression stack. This is a link list of collections, not a link-list * of individual expressions. */ protected LinkedList expressionStack = new LinkedList( ); /** * entry point to the report */ protected Report report; /** * the execution context */ protected ExecutionContext context; /** * create report query definitions for this report. * * @param report entry point to the report * @param context the execution context */ public void buildQuery( Report report, ExecutionContext context ) { this.report = report; this.context = context; queries = report.getQueries( ); // first clear the collection in case the caller call this function more than once. queries.clear( ); // visit report for ( int i = 0; i < report.getContentCount( ); i++ ) report.getContent( i ).accept( this ); } /** * Handles query creation and initialization with report-item related expressions * * @param item report item */ private BaseQueryDefn prepareVisit( ReportItemDesign item ) { BaseQueryDefn tempQuery = null; if (item instanceof ListingDesign) tempQuery = createQuery( (ListingDesign)item ); else tempQuery = createQuery( item ); if ( tempQuery != null ) { pushQuery( tempQuery ); pushExpressions( tempQuery.getRowExpressions( ) ); } handleReportItemExpressions( item ); return tempQuery; } /** * Clean up stack after visiting a report item */ private void finishVisit( BaseQueryDefn query ) { if (query != null) { popExpressions( ); popQuery( ); } } /* * (non-Javadoc) * * @see org.eclipse.birt.report.engine.ir.ReportItemVisitor#visitFreeFormItem(org.eclipse.birt.report.engine.ir.FreeFormItemDesign) */ public void visitFreeFormItem( FreeFormItemDesign container ) { BaseQueryDefn query = prepareVisit( container ); for ( int i = 0; i < container.getItemCount( ); i++ ) container.getItem( i ).accept( this ); finishVisit( query ); } /* * (non-Javadoc) * * @see org.eclipse.birt.report.engine.ir.ReportItemVisitor#visitGridItem(org.eclipse.birt.report.engine.ir.GridItemDesign) */ public void visitGridItem( GridItemDesign grid ) { BaseQueryDefn query = prepareVisit( grid ); for ( int i = 0; i < grid.getColumnCount( ); i++ ) { ColumnDesign column = grid.getColumn( i ); handleStyle( column.getStyle( ) ); } for ( int i = 0; i < grid.getRowCount( ); i++ ) handleRow( grid.getRow( i ) ); finishVisit( query ); } /* (non-Javadoc) * @see org.eclipse.birt.report.engine.ir.IReportItemVisitor#visitImageItem(org.eclipse.birt.report.engine.ir.ImageItemDesign) */ public void visitImageItem( ImageItemDesign image ) { BaseQueryDefn query = prepareVisit( image ); handleAction( image.getAction( ) ); if ( image.getImageSource( ) == ImageItemDesign.IMAGE_EXPRESSION ) { addExpression( image.getImageExpression( ) ); addExpression( image.getImageFormat( ) ); } finishVisit( query ); } /* * (non-Javadoc) * * @see org.eclipse.birt.report.engine.ir.ReportItemVisitor#visitLabelItem(org.eclipse.birt.report.engine.ir.LabelItemDesign) */ public void visitLabelItem( LabelItemDesign label ) { BaseQueryDefn query = prepareVisit( label ); handleAction( label.getAction( ) ); finishVisit( query ); } /* (non-Javadoc) * @see org.eclipse.birt.report.engine.ir.IReportItemVisitor#visitExtendedItem(org.eclipse.birt.report.engine.ir.ExtendedItemDesign) */ public void visitExtendedItem( ExtendedItemDesign item ) { //create user-defined generation-time helper object ExtendedItemHandle handle = (ExtendedItemHandle)item.getHandle(); String tagName = handle.getExtensionName(); // TODO: check in plugin registry whetherthe needQuery property is set to host or item. // Only do the following for "host" IReportItemGeneration itemGeneration = ExtensionManager.getInstance().createGenerationItem(tagName); if (itemGeneration == null) { // Add Log return; } else { // handle the parameters passed to extension writers HashMap parameters = new HashMap(); parameters.put(IReportItemGeneration.MODEL_OBJ, handle); // parameters.put(IReportItemGeneration.PARENT_QUERY, getParentQuery()); itemGeneration.initialize(parameters); IBaseQueryDefn query = null; IBaseQueryDefn parentQuery = getParentQuery(); boolean first = true; while ( (query = itemGeneration.nextQuery( parentQuery ) ) != null) { this.queries.add(query); item.setQuery(query); // Add other expressions only tot he first query if ( first ) { pushQuery( query ); pushExpressions( query.getRowExpressions()); handleReportItemExpressions(item); // handleActionExpressions(item.getAction()); popExpressions(); popQuery(); } } } } /* * (non-Javadoc) * * @see org.eclipse.birt.report.engine.ir.ReportItemVisitor#visitListItem(org.eclipse.birt.report.engine.ir.ListItemDesign) */ public void visitListItem( ListItemDesign list ) { BaseQueryDefn query = prepareVisit( list ); assert query != null; visitListBand( list.getHeader( ) ); popExpressions( ); SlotHandle groupsSlot = ( (ListHandle) list.getHandle( ) ).getGroups( ); for ( int i = 0; i < list.getGroupCount( ); i++ ) { handleListGroup( list.getGroup( i ), (GroupHandle) groupsSlot .get( i ) ); } if ( list.getDetail( ).getContentCount( ) != 0 ) { query.setUsesDetails( true ); } pushExpressions( query.getRowExpressions( ) ); visitListBand( list.getDetail( ) ); popExpressions( ); pushExpressions( query.getAfterExpressions( ) ); visitListBand( list.getFooter( ) ); finishVisit( query ); } /* * (non-Javadoc) * * @see org.eclipse.birt.report.engine.ir.ReportItemVisitor#visitTextItem(org.eclipse.birt.report.engine.ir.TextItemDesign) */ public void visitTextItem( TextItemDesign text ) { BaseQueryDefn query = prepareVisit( text ); if ( text.getDomTree( ) == null ) { String content = getLocalizedString( text.getContentKey( ), text.getContent( ) ); text.setDomTree( new DOMParser( ).parse( content, text .getContentType( ) ) ); } Document doc = text.getDomTree( ); if ( doc != null ) { getEmbeddedExpression( doc.getFirstChild( ), text ); } finishVisit( query ); } /* * (non-Javadoc) * * @see org.eclipse.birt.report.engine.ir.ReportItemVisitor#visitTableItem(org.eclipse.birt.report.engine.ir.TableItemDesign) */ public void visitTableItem( TableItemDesign table ) { BaseQueryDefn query = prepareVisit( table ); for ( int i = 0; i < table.getColumnCount( ); i++ ) { ColumnDesign column = table.getColumn( i ); handleStyle( column.getStyle( ) ); } pushExpressions( query.getBeforeExpressions() ); handleTableBand( table.getHeader( ) ); popExpressions( ); SlotHandle groupsSlot = ( (TableHandle) table.getHandle( ) ) .getGroups( ); for ( int i = 0; i < table.getGroupCount( ); i++ ) { handleTableGroup( table.getGroup( i ), (GroupHandle) groupsSlot .get( i ) ); } if ( table.getDetail( ).getRowCount( ) != 0 ) { query.setUsesDetails( true ); } pushExpressions( query.getRowExpressions( ) ); handleTableBand( table.getDetail( ) ); popExpressions( ); pushExpressions( query.getAfterExpressions( ) ); handleTableBand( table.getFooter( ) ); finishVisit( query ); } /* * (non-Javadoc) * * @see org.eclipse.birt.report.engine.ir.ReportItemVisitor#visitMultiLineItem(org.eclipse.birt.report.engine.ir.MultiLineItemDesign) */ public void visitMultiLineItem( MultiLineItemDesign multiLine ) { BaseQueryDefn query = prepareVisit( multiLine ); addExpression( multiLine.getContent( ) ); addExpression( multiLine.getContentType( ) ); finishVisit( query ); } /* (non-Javadoc) * @see org.eclipse.birt.report.engine.ir.IReportItemVisitor#visitDataItem(org.eclipse.birt.report.engine.ir.DataItemDesign) */ public void visitDataItem( DataItemDesign data ) { BaseQueryDefn query = prepareVisit( data ); handleReportItemExpressions( data ); handleAction( data.getAction( ) ); addExpression( data.getValue( ) ); finishVisit( query ); } /** * handle expressions common to all report items * * @param item a report item */ protected void handleReportItemExpressions( ReportItemDesign item ) { if ( item.getVisibility( ) != null ) { for ( int i = 0; i < item.getVisibility( ).count( ); i++ ) { addExpression( item.getVisibility( ).getRule( i ) .getExpression( ) ); } } addExpression( item.getBookmark( ) ); handleStyle( item.getStyle( ) ); handleHighlightExpressions(item.getHighlight()); handleMapExpressions(item.getMap()); } /** * @param band the list band */ protected void visitListBand( ListBandDesign band ) { for ( int i = 0; i < band.getContentCount( ); i++ ) { band.getContent( i ).accept( this ); } } /** * @param group a grouping in a list * @param handle handle to a grouping element */ protected void handleListGroup( ListGroupDesign group, GroupHandle handle ) { IGroupDefn groupDefn = handleGroup( group, handle ); pushQuery( groupDefn ); pushExpressions( groupDefn.getBeforeExpressions( ) ); visitListBand( group.getHeader( ) ); popExpressions( ); pushExpressions( groupDefn.getAfterExpressions( ) ); visitListBand( group.getFooter( ) ); popExpressions( ); popQuery( ); } /** * processes a table/list group */ protected IGroupDefn handleGroup( GroupDesign group, GroupHandle handle ) { GroupDefn groupDefn = new GroupDefn( group.getName( ) ); groupDefn.setKeyExpresion( handle.getKeyExpr( ) ); String interval = handle.getInterval( ); if ( interval != null ) { groupDefn.setInterval( parseInterval( interval ) ); } //inter-range groupDefn.setIntervalRange( handle.getIntervalRange( ) ); //sort-direction String direction = handle.getSortDirection( ); if ( direction != null ) { groupDefn.setSortDirection( parseSortDirection( direction ) ); } groupDefn.getSorts( ).addAll( createSorts( handle ) ); groupDefn.getFilters( ).addAll( createFilters( handle ) ); getParentQuery( ).getGroups( ).add( groupDefn ); return groupDefn; } /** * processes a band in a table */ protected void handleTableBand( TableBandDesign band ) { for ( int i = 0; i < band.getRowCount( ); i++ ) handleRow( band.getRow( i ) ); } /** * processes a table group */ protected void handleTableGroup( TableGroupDesign group, GroupHandle handle ) { IGroupDefn groupDefn = handleGroup( group, handle ); pushQuery( groupDefn ); pushExpressions( groupDefn.getBeforeExpressions( ) ); handleTableBand( group.getHeader( ) ); popExpressions( ); pushExpressions( groupDefn.getAfterExpressions( ) ); handleTableBand( group.getFooter( ) ); popExpressions( ); popQuery( ); } /** * handle style, which may contain highlight/mapping expressions * * @param style style design */ protected void handleStyle( StyleDesign style ) { /*if ( style != null ) { handleHighlight( style.getHighlight( ) ); handleMap( style.getMap( ) ); }*/ } /** * handle mapping expressions */ protected void handleMapExpressions( MapDesign map ) { if ( map != null ) { for ( int i = 0; i < map.getRuleCount( ); i++ ) { MapRuleDesign rule = map.getRule( i ); if ( rule != null ) addExpression(rule.getConditionExpr()); } } } /** * handle highlight expressions */ protected void handleHighlightExpressions( HighlightDesign highlight ) { if ( highlight != null ) { for ( int i = 0; i < highlight.getRuleCount( ); i++ ) { HighlightRuleDesign rule = highlight.getRule( i ); if ( rule != null ) addExpression(rule.getConditionExpr()); } } } /** * handles action expressions, i.e, book-mark and hyper-link expressions. */ protected void handleAction( ActionDesign action ) { if ( action != null ) { switch ( action.getActionType( ) ) { case ActionDesign.ACTION_BOOKMARK : addExpression( action.getBookmark( ) ); break; case ActionDesign.ACTION_DRILLTHROUGH : assert false; break; case ActionDesign.ACTION_HYPERLINK : addExpression( action.getHyperlink( ) ); break; default : assert false; } } } /** * visit content of a row */ protected void handleRow( RowDesign row ) { handleStyle( row.getStyle( ) ); if ( row.getVisibility( ) != null ) { for ( int i = 0; i < row.getVisibility( ).count( ); i++ ) addExpression( row.getVisibility( ).getRule( i ).getExpression( ) ); } addExpression( row.getBookmark( ) ); for ( int i = 0; i < row.getCellCount( ); i++ ) handleCell( row.getCell( i ) ); } /** * handles a cell in a row */ protected void handleCell( CellDesign cell ) { handleStyle( cell.getStyle( ) ); for ( int i = 0; i < cell.getContentCount( ); i++ ) cell.getContent( i ).accept( this ); } /** * A helper function for adding expression collection to stack */ protected void pushExpressions( Collection expressions ) { this.expressionStack.addLast( expressions ); this.expressions = expressions; } /** * A helper function for removing expression collection from stack */ protected void popExpressions( ) { assert !expressionStack.isEmpty( ); this.expressions = (Collection) expressionStack.removeLast( ); } /** * A helper function for adding a query to query stack */ protected void pushQuery( IBaseTransform query ) { this.queryStack.addLast( query ); } /** * A helper function for removing a query from query stack */ protected void popQuery( ) { assert !queryStack.isEmpty( ); queryStack.removeLast( ); } /** * add expression to the expression collection on top of the expressions stack * * @param expr expression to be added */ protected void addExpression( IBaseExpression expr ) { // expressions may be null, which means the expression is in the topmost // element, and has no data set associated with it. if ( expr != null && expressions != null ) expressions.add( expr ); } /** * @return topmost element on query stack */ protected IBaseTransform getTransform( ) { if ( queryStack.isEmpty( ) ) return null; return (IBaseTransform) queryStack.getLast( ); } /** * @return the parent query for the current report item */ protected BaseQueryDefn getParentQuery( ) { if ( queryStack.isEmpty( ) ) return null; for ( int i = queryStack.size( ) - 1; i >= 0; i { if ( queryStack.get( i ) instanceof BaseQueryDefn ) return (BaseQueryDefn) queryStack.get( i ); } return null; } /** * @return the expression collection */ protected Collection getExpressions( ) { return expressions; } /** * @return a unique query name, based on a simple integer counter */ protected String createUniqueQueryName( ) { queryCount++; return String.valueOf( queryCount ); } /** * create query for non-listing report item * * @param item report item * @return a report query */ protected BaseQueryDefn createQuery( ReportItemDesign item ) { DataSetHandle dsHandle = (DataSetHandle) ( (ReportItemHandle) item .getHandle( ) ).getDataSet( ); if ( dsHandle != null ) { ReportItemHandle riHandle =(ReportItemHandle)item.getHandle(); ReportQueryDefn query = new ReportQueryDefn( getParentQuery( ) ); query.setDataSetName( dsHandle.getName( ) ); query.getInputParamBindings( ).addAll( createParamBindings( riHandle.paramBindingsIterator() ) ); this.queries.add( query ); item.setQuery( query ); return query; } return null; } /** * create query for listing report item * * @param listing the listing item * @return a report query definition */ protected BaseQueryDefn createQuery( ListingDesign listing ) { // creates its own query BaseQueryDefn query = createQuery((ReportItemDesign)listing); if (query != null) { query.getSorts( ).addAll( createSorts( listing ) ); query.getFilters( ).addAll( createFilters( listing ) ); return query; } // creates a subquery, instead String name = createUniqueQueryName( ); SubqueryDefn subQuery = new SubqueryDefn( name ); listing.setQuery( subQuery ); subQuery.getSorts( ).addAll( createSorts( listing ) ); subQuery.getFilters( ).addAll( createFilters( listing ) ); getTransform( ).getSubqueries( ).add( subQuery ); return subQuery; } /** * get Localized string by the resouce key and * <code>Locale</code> object in <code>context</code> * * @param resourceKey the resource key * @param text the default value * @return the localized string if it is defined in report deign, else * return the default value */ protected String getLocalizedString( String resourceKey, String text ) { if ( resourceKey == null ) { return text; } String ret = report.getMessage( resourceKey, context.getLocale( ) ); if ( ret == null ) { if ( logger.isErrorEnabled( ) ) { logger.error( "get resource error, resource key:" // $NON-NLS-1$ + resourceKey + " Locale:" // $NON-NLS-1$ + context.getLocale( ).toString( ) ); } return text; } return ret; } /** * Walk through the DOM tree from a text item to collect the embedded * expressions and format expressions * * After evaluating, the second child node of the embedded expression node * holds the value if no error exists. * * @param node a node in the DOM tree * @param text the text object */ protected void getEmbeddedExpression( Node node, TextItemDesign text ) { if ( node.getNodeType( ) == Node.ELEMENT_NODE ) { Element ele = (Element) node; if ( node.getNodeName( ).equals( "value-of" ) ) // $NON-NLS-1$ { if ( !text.containExpr( node.getFirstChild( ) .getNodeValue( ) ) ) { Expression expr = new Expression( node.getFirstChild( ) .getNodeValue( ) ); this.addExpression( expr ); text.addExpression( node.getFirstChild( ) .getNodeValue( ), expr ); return; } } else if ( node.getNodeName( ).equals( "image" ) ) // $NON-NLS-1$ { String imageType = ( (Element) ( node ) ) .getAttribute( "type" ); // $NON-NLS-1$ if ( "expr".equals( imageType ) ) // $NON-NLS-1$ { if ( !text.containExpr( node.getFirstChild( ) .getNodeValue( ) ) ) { Expression expr = new Expression( node .getFirstChild( ).getNodeValue( ) ); this.addExpression( expr ); text.addExpression( node.getFirstChild( ) .getNodeValue( ), expr ); } } return; } //call recursively for ( Node child = node.getFirstChild( ); child != null; child = child .getNextSibling( ) ) { getEmbeddedExpression( child, text ); } } } /** * create one Filter given a filter condition handle * * @param handle a filter condition handle * @return the filter */ private IFilterDefn createFilter( FilterConditionHandle handle ) { String filterExpr = handle.getExpr( ); if ( filterExpr == null || filterExpr.length( ) == 0 ) return null; // no filter defined // converts to DtE exprFilter if there is no operator String filterOpr = handle.getOperator( ); if ( filterOpr == null || filterOpr.length( ) == 0 ) return new FilterDefn( new JSExpression( filterExpr ) ); /* * has operator defined, try to convert filter condition to * operator/operand style column filter with 0 to 2 operands */ String column = filterExpr; int dteOpr = toDteFilterOperator( filterOpr ); String operand1 = handle.getValue1( ); String operand2 = handle.getValue2( ); return new FilterDefn( new ConditionalExpression( column, dteOpr, operand1, operand2 ) ); } /** * create a filter array given a filter condition handle iterator * * @param iter the iterator * @return filter array */ private ArrayList createFilters( Iterator iter ) { ArrayList filters = new ArrayList( ); if ( iter != null ) { while ( iter.hasNext( ) ) { FilterConditionHandle filterHandle = (FilterConditionHandle) iter .next( ); IFilterDefn filter = createFilter( filterHandle ); filters.add( filter ); } } return filters; } /** * create filter array given a Listing design element * * @param listing the ListingDesign * @return the filter array */ public ArrayList createFilters( ListingDesign listing ) { return createFilters( ( (ListingHandle) listing.getHandle( ) ) .filtersIterator( ) ); } /** * create fileter array given a DataSetHandle * * @param dataSet the DataSetHandle * @return the filer array */ public ArrayList createFilters( DataSetHandle dataSet ) { return createFilters( dataSet.filtersIterator( ) ); } /** * create filter array given a GroupHandle * * @param group the GroupHandle * @return filter array */ public ArrayList createFilters( GroupHandle group ) { return createFilters( group.filtersIterator( ) ); } /** * create one sort condition * * @param handle the SortKeyHandle * @return the sort object */ private ISortDefn createSort( SortKeyHandle handle ) { SortDefn sort = new SortDefn( ); sort.setExpression( handle.getKey( ) ); sort.setSortDirection( handle.getDirection( ).equals( DesignChoiceConstants.SORT_DIRECTION_ASC ) ? 0 : 1 ); return sort; } /** * create all sort conditions given a sort key handle iterator * * @param iter the iterator * @return sort array */ private ArrayList createSorts( Iterator iter ) { ArrayList sorts = new ArrayList( ); if ( iter != null ) { while ( iter.hasNext( ) ) { SortKeyHandle handle = (SortKeyHandle) iter.next( ); sorts.add( createSort( handle ) ); } } return sorts; } /** * create all sort conditions in a listing element * * @param listing * ListingDesign * @return the sort array */ protected ArrayList createSorts( ListingDesign listing ) { return createSorts( ( (ListingHandle) listing.getHandle( ) ).sortsIterator( ) ); } /** * create sort array by giving GroupHandle * * @param group * the GroupHandle * @return the sort array */ protected ArrayList createSorts( GroupHandle group ) { return createSorts( group.sortsIterator( ) ); } /** * create input parameter binding * * @param handle * @return */ protected IInputParamBinding createParamBinding( ParamBindingHandle handle ) { if ( handle.getExpression( ) == null ) return null; // no expression is bound JSExpression expr = new JSExpression( handle.getExpression( ) ); // model provides binding by name only return new InputParamBinding( handle.getParamName( ), expr ); } /** * create input parameter bindings * * @param iter parameter bindings iterator * @return a list of input parameter bindings */ protected ArrayList createParamBindings(Iterator iter) { ArrayList list = new ArrayList(); if ( iter != null ) { while ( iter.hasNext() ) { ParamBindingHandle modelParamBinding = (ParamBindingHandle) iter.next(); IInputParamBinding binding = createParamBinding( modelParamBinding ); if(binding != null) list.add(binding); } } return list; } /** * converts interval string values to integer values */ protected int parseInterval( String interval ) { if ( DesignChoiceConstants.INTERVAL_YEAR.equals( interval ) ) { return IGroupDefn.YEAR_INTERVAL; } if ( DesignChoiceConstants.INTERVAL_MONTH.equals( interval ) ) { return IGroupDefn.MONTH_INTERVAL; } if ( DesignChoiceConstants.INTERVAL_WEEK.equals( interval ) ) { return IGroupDefn.WEEK_INTERVAL; } if ( DesignChoiceConstants.INTERVAL_QUARTER.equals( interval ) ) { return IGroupDefn.QUARTER_INTERVAL; } if ( DesignChoiceConstants.INTERVAL_DAY.equals( interval ) ) { return IGroupDefn.DAY_INTERVAL; } if ( DesignChoiceConstants.INTERVAL_HOUR.equals( interval ) ) { return IGroupDefn.HOUR_INTERVAL; } if ( DesignChoiceConstants.INTERVAL_MINUTE.equals( interval ) ) { return IGroupDefn.MINUTE_INTERVAL; } if ( DesignChoiceConstants.INTERVAL_PREFIX.equals( interval ) ) { return IGroupDefn.STRING_PREFIX_INTERVAL; } if ( DesignChoiceConstants.INTERVAL_SECOND.equals( interval ) ) { return IGroupDefn.SECOND_INTERVAL; } if ( DesignChoiceConstants.INTERVAL_INTERVAL.equals( interval ) ) { return IGroupDefn.NUMERIC_INTERVAL; } return IGroupDefn.NO_INTERVAL; } /** * @param direction "asc" or "desc" string * @return integer value defined in <code>ISortDefn</code> */ protected int parseSortDirection( String direction ) { if ( "asc".equals( direction ) ) // $NON-NLS-1$ return ISortDefn.SORT_ASC; if ( "desc".equals( direction ) ) // $NON-NLS-1$ return ISortDefn.SORT_DESC; assert false; return 0; } /** * converts model operator values to DtE IColumnFilter enum values */ protected int toDteFilterOperator( String modelOpr ) { if ( modelOpr.equals( DesignChoiceConstants.FILTER_OPERATOR_EQ ) ) return IConditionalExpression.OP_EQ; if ( modelOpr.equals( DesignChoiceConstants.FILTER_OPERATOR_NE ) ) return IConditionalExpression.OP_NE; if ( modelOpr.equals( DesignChoiceConstants.FILTER_OPERATOR_LT ) ) return IConditionalExpression.OP_LT; if ( modelOpr.equals( DesignChoiceConstants.FILTER_OPERATOR_LE ) ) return IConditionalExpression.OP_LE; if ( modelOpr.equals( DesignChoiceConstants.FILTER_OPERATOR_GE ) ) return IConditionalExpression.OP_GE; if ( modelOpr.equals( DesignChoiceConstants.FILTER_OPERATOR_GT ) ) return IConditionalExpression.OP_GT; if ( modelOpr.equals( DesignChoiceConstants.FILTER_OPERATOR_BETWEEN ) ) return IConditionalExpression.OP_BETWEEN; if ( modelOpr .equals( DesignChoiceConstants.FILTER_OPERATOR_NOT_BETWEEN ) ) return IConditionalExpression.OP_NOT_BETWEEN; if ( modelOpr.equals( DesignChoiceConstants.FILTER_OPERATOR_NULL ) ) return IConditionalExpression.OP_NULL; if ( modelOpr.equals( DesignChoiceConstants.FILTER_OPERATOR_NOT_NULL ) ) return IConditionalExpression.OP_NOT_NULL; if ( modelOpr.equals( DesignChoiceConstants.FILTER_OPERATOR_TRUE ) ) return IConditionalExpression.OP_TRUE; if ( modelOpr.equals( DesignChoiceConstants.FILTER_OPERATOR_FALSE ) ) return IConditionalExpression.OP_FALSE; if ( modelOpr.equals( DesignChoiceConstants.FILTER_OPERATOR_LIKE ) ) return IConditionalExpression.OP_LIKE; if ( modelOpr.equals( DesignChoiceConstants.FILTER_OPERATOR_TOP_N ) ) return IConditionalExpression.OP_TOP_N; if ( modelOpr.equals( DesignChoiceConstants.FILTER_OPERATOR_BOTTOM_N ) ) return IConditionalExpression.OP_BOTTOM_N; if ( modelOpr .equals( DesignChoiceConstants.FILTER_OPERATOR_TOP_PERCENT ) ) return IConditionalExpression.OP_TOP_PERCENT; if ( modelOpr .equals( DesignChoiceConstants.FILTER_OPERATOR_BOTTOM_PERCENT ) ) return IConditionalExpression.OP_BOTTOM_PERCENT; if ( modelOpr.equals( DesignChoiceConstants.FILTER_OPERATOR_ANY ) ) return IConditionalExpression.OP_ANY; return IConditionalExpression.OP_NONE; } } }
package org.hibernate.validator.internal.util.privilegedactions; import static org.hibernate.validator.internal.util.CollectionHelper.newHashMap; import java.io.Serializable; import java.lang.annotation.Annotation; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.security.PrivilegedAction; import java.util.Map; import org.hibernate.validator.internal.util.CollectionHelper; import org.hibernate.validator.internal.util.logging.Log; import org.hibernate.validator.internal.util.logging.LoggerFactory; import org.hibernate.validator.internal.util.privilegedactions.GetAnnotationParameters.AnnotationParameters; import org.hibernate.validator.internal.util.stereotypes.Immutable; /** * @author Guillaume Smet */ public final class GetAnnotationParameters implements PrivilegedAction<AnnotationParameters> { private static final Log LOG = LoggerFactory.make(); private final Annotation annotation; public static GetAnnotationParameters action(Annotation annotation) { return new GetAnnotationParameters( annotation ); } private GetAnnotationParameters(Annotation annotation) { this.annotation = annotation; } @Override public AnnotationParameters run() { final Method[] declaredMethods = annotation.annotationType().getDeclaredMethods(); Map<String, Object> parameters = newHashMap( declaredMethods.length ); for ( Method m : declaredMethods ) { // HV-1184 Exclude synthetic methods potentially introduced by jacoco if ( m.isSynthetic() ) { continue; } m.setAccessible( true ); String parameterName = m.getName(); try { parameters.put( m.getName(), m.invoke( annotation ) ); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { throw LOG.getUnableToGetAnnotationParameterException( parameterName, annotation.getClass(), e ); } } return new AnnotationParameters( parameters ); } public static class AnnotationParameters implements Serializable { @Immutable private final Map<String, Object> parameters; private AnnotationParameters(Map<String, Object> parameters) { this.parameters = CollectionHelper.toImmutableMap( parameters ); } public Map<String, Object> getParameters() { return parameters; } @SuppressWarnings("unchecked") public <T> T getMandatoryParameter(String parameterName, Class<T> type) { Object parameter = parameters.get( parameterName ); if ( parameter == null ) { throw LOG.getUnableToFindAnnotationParameterException( parameterName, null ); } if ( !type.isAssignableFrom( parameter.getClass() ) ) { throw LOG.getWrongParameterTypeException( type, parameter.getClass() ); } return (T) parameter; } @SuppressWarnings("unchecked") public <T> T getParameter(String parameterName, Class<T> type) { Object parameter = parameters.get( parameterName ); if ( parameter == null ) { return null; } if ( !type.isAssignableFrom( parameter.getClass() ) ) { throw LOG.getWrongParameterTypeException( type, parameter.getClass() ); } return (T) parameter; } @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append( this.getClass().getSimpleName() ); sb.append( '{' ); sb.append( "parameters=" ).append( parameters ); sb.append( '}' ); return sb.toString(); } } }
package org.grammaticalframework.examples.PhraseDroid; import android.app.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.speech.tts.TextToSpeech; import android.view.*; import android.widget.*; import java.util.Locale; import java.util.Arrays; public abstract class PhrasedroidActivity extends Activity implements TextToSpeech.OnInitListener, View.OnClickListener { // CONSTANTS public static final String PREFS_NAME = "PhrasedroidPrefs"; public static final String TLANG_PREF_KEY = "targetLanguageCode"; static final int MY_TTS_CHECK_CODE = 2347453; static final int MENU_CHANGE_LANGUAGE = 3634543; private boolean tts_ready = false; private TextToSpeech mTts; private Language sLang = Language.ENGLISH; private Language tLang = Language.FRENCH; protected PGFThread mPGFThread; String currentText = ""; // UI elements TextView resultView; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0); // Setup languages // FIXME : do Source language Locale l = Locale.getDefault(); Language source = Language.fromCode(l.getLanguage()); if (source == null) source = Language.ENGLISH; // Target language String tLangCode = settings.getString(TLANG_PREF_KEY, null); Language target = Language.fromCode(tLangCode); if (target == null || !Arrays.asList(source.getAvailableTargetLanguages()).contains(target)) target = source.getDefaultTargetLanguage(); this.setupLanguages(source, target); // Setup TTS startTTSInit(); // Setup UI setContentView(R.layout.main); // Get pointers to the ui elements resultView = (TextView) findViewById(R.id.result_view); // setup translate button ((Button) findViewById(R.id.translate_button)).setOnClickListener(this); // setup speak action ((Button) findViewById(R.id.speak_button)).setOnClickListener(this); } public void onDestroy() { super.onDestroy(); if (mTts != null) mTts.shutdown(); } public void setupLanguages(Language sLang, Language tLang) { this.sLang = sLang; this.tLang = tLang; // Setup the thread for the pgf // FIXME : localize the dialog... final ProgressDialog progress = ProgressDialog.show(this, "", "Loading Grammar. Please wait...", true); mPGFThread = new PGFThread(this, sLang, tLang); mPGFThread.onPGFReady(new Runnable() { public void run() { runOnUiThread(new Runnable() { public void run() { progress.dismiss(); }}); }}); mPGFThread.start(); if (this.tts_ready) mTts.setLanguage(this.tLang.locale); } public void changeTargetLanguage(Language l) { this.setupLanguages(this.sLang, l); } // needed by View.onClickListener public void onClick(View v) { if (v == findViewById(R.id.translate_button)) { setText("Translating...", false); String phrase = ((EditText)findViewById(R.id.phrase)).getText().toString(); mPGFThread.translate(phrase); } else if (v == findViewById(R.id.speak_button)) say(currentText); } public void setText(String t, boolean sayable) { final String text = t; if (sayable) this.currentText = text; else this.currentText = ""; runOnUiThread(new Runnable() { public void run() { resultView.setText(text); } }); } /* Creates the menu items */ public boolean onCreateOptionsMenu(Menu menu) { menu.add(0, MENU_CHANGE_LANGUAGE, 0, "Change Language"); return true; } /* Handles menu item selections */ public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case MENU_CHANGE_LANGUAGE: final Language[] tls = this.sLang.getAvailableTargetLanguages(); final String[] items = new String[tls.length]; int i = 0; for (Language l : tls) { items[i] = l.getName(); i++ ; } AlertDialog.Builder builder = new AlertDialog.Builder(this); // FIXME: localize... builder.setTitle("Pick a language"); builder.setItems(items, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { changeTargetLanguage(tls[item]); SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0); settings.edit().putString(TLANG_PREF_KEY, tls[item].locale.getLanguage()).commit(); } }); AlertDialog alert = builder.create(); alert.show(); return true; } return false; } public void say(String txt) { if (this.tts_ready) this.mTts.speak(txt, TextToSpeech.QUEUE_ADD, null); } // Text-To-Speech initialization is done in three (asychronous) steps coresponding // to the three methods below : // First : we check if the TTS data is present on the system public void startTTSInit() { Intent checkIntent = new Intent(); checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA); startActivityForResult(checkIntent, MY_TTS_CHECK_CODE); } // Second: if the data is present, we initialise the TTS engine // (otherwise we ask to install it) protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == MY_TTS_CHECK_CODE) { if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) { // success, create the TTS instance mTts = new TextToSpeech(this, this); } else { // missing data, install it Intent installIntent = new Intent(); installIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA); startActivity(installIntent); } } } // Finally: once the TTS engine is initialized, we set-up the language. public void onInit(int status) { if (status == TextToSpeech.SUCCESS) { this.tts_ready = true; mTts.setLanguage(this.tLang.locale); } } }
package de.saxsys.mvvmfx.examples.contacts.ui.detail; import static eu.lestard.advanced_bindings.api.ObjectBindings.map; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import javax.inject.Inject; import de.saxsys.mvvmfx.InjectScope; import de.saxsys.mvvmfx.ViewModel; import de.saxsys.mvvmfx.examples.contacts.model.Address; import de.saxsys.mvvmfx.examples.contacts.model.Contact; import de.saxsys.mvvmfx.examples.contacts.model.Repository; import de.saxsys.mvvmfx.examples.contacts.ui.scopes.ContactDialogScope; import de.saxsys.mvvmfx.examples.contacts.ui.scopes.MasterDetailScope; import de.saxsys.mvvmfx.utils.commands.Action; import de.saxsys.mvvmfx.utils.commands.Command; import de.saxsys.mvvmfx.utils.commands.DelegateCommand; import javafx.application.HostServices; import javafx.beans.binding.Bindings; import javafx.beans.binding.ObjectBinding; import javafx.beans.binding.StringBinding; import javafx.beans.property.ObjectProperty; import javafx.beans.property.ReadOnlyObjectProperty; import javafx.beans.property.ReadOnlyStringProperty; import javafx.beans.property.ReadOnlyStringWrapper; public class DetailViewModel implements ViewModel { public static final String OPEN_EDIT_CONTACT_DIALOG = "open_edit_contact"; private static final DateTimeFormatter BIRTHDAY_FORMATTER = DateTimeFormatter.ISO_DATE; private final ReadOnlyStringWrapper name = new ReadOnlyStringWrapper(); private final ReadOnlyStringWrapper birthday = new ReadOnlyStringWrapper(); private final ReadOnlyStringWrapper roleDepartment = new ReadOnlyStringWrapper(); private final ReadOnlyStringWrapper email = new ReadOnlyStringWrapper(); private final ReadOnlyStringWrapper phone = new ReadOnlyStringWrapper(); private final ReadOnlyStringWrapper mobile = new ReadOnlyStringWrapper(); private final ReadOnlyStringWrapper cityPostalcode = new ReadOnlyStringWrapper(); private final ReadOnlyStringWrapper street = new ReadOnlyStringWrapper(); private final ReadOnlyStringWrapper countrySubdivision = new ReadOnlyStringWrapper(); private DelegateCommand editCommand; private DelegateCommand removeCommand; private DelegateCommand emailLinkCommand; @Inject HostServices hostServices; @Inject Repository repository; @InjectScope MasterDetailScope mdScope; @InjectScope ContactDialogScope dialogscope; public void initialize() { ReadOnlyObjectProperty<Contact> contactProperty = getSelectedContactPropertyFromScope(); createBindingsForLabels(contactProperty); editCommand = new DelegateCommand(() -> new Action() { @Override protected void action() throws Exception { Contact selectedContact = getSelectedContactFromScope(); if (selectedContact != null) { dialogscope.setContactToEdit(selectedContact); publish(OPEN_EDIT_CONTACT_DIALOG); } } }, getSelectedContactPropertyFromScope().isNotNull()); removeCommand = new DelegateCommand(() -> new Action() { @Override protected void action() throws Exception { Contact selectedContact = getSelectedContactFromScope(); if (selectedContact != null) { repository.delete(getSelectedContactFromScope()); } } }, getSelectedContactPropertyFromScope().isNotNull()); emailLinkCommand = new DelegateCommand(() -> new Action() { @Override protected void action() throws Exception { if (email.get() != null && !email.get().trim().isEmpty()) { hostServices.showDocument("mailto:" + email.get()); } } }); } private void createBindingsForLabels(ReadOnlyObjectProperty<Contact> contactProperty) { name.bind(emptyStringOnNull(map(contactProperty, contact -> { StringBuilder result = new StringBuilder(); String title = contact.getTitle(); if (title != null && !title.trim().isEmpty()) { result.append(title); result.append(" "); } result.append(contact.getFirstname()); result.append(" "); result.append(contact.getLastname()); return result.toString(); }))); email.bind(emptyStringOnNull(map(contactProperty, Contact::getEmailAddress))); roleDepartment.bind(emptyStringOnNull(map(contactProperty, contact -> { StringBuilder result = new StringBuilder(); if (contact.getRole() != null && !contact.getRole().trim().isEmpty()) { result.append(contact.getRole()); if (contact.getDepartment() != null && !contact.getDepartment().trim().isEmpty()) { result.append(" / "); result.append(contact.getDepartment()); } } else if (contact.getDepartment() != null) { result.append(contact.getDepartment()); } return result.toString(); }))); birthday.bind(emptyStringOnNull(map(contactProperty, contact -> { LocalDate date = contact.getBirthday(); if (date == null) { return ""; } else { return BIRTHDAY_FORMATTER.format(date); } }))); phone.bind(emptyStringOnNull(map(contactProperty, Contact::getPhoneNumber))); mobile.bind(emptyStringOnNull(map(contactProperty, Contact::getMobileNumber))); ObjectBinding<Address> addressBinding = map(contactProperty, Contact::getAddress); cityPostalcode.bind(emptyStringOnNull(map(addressBinding, address -> { StringBuilder result = new StringBuilder(); if (address.getCity() != null) { result.append(address.getCity()); } if (address.getPostalcode() != null) { result.append(" ("); result.append(address.getPostalcode()); result.append(")"); } return result.toString(); }))); street.bind(emptyStringOnNull(map(addressBinding, Address::getStreet))); countrySubdivision.bind(emptyStringOnNull(map(addressBinding, address -> { StringBuilder result = new StringBuilder(); if (address.getCountry() != null) { result.append(address.getCountry().getName()); } if (address.getSubdivision() != null) { result.append(" / "); result.append(address.getSubdivision().getName()); } return result.toString(); }))); } /** * When the given source binding has a value of <code>null</code> an empty string is used for the returned binding. * Otherwise the value of the source binding is used. */ private StringBinding emptyStringOnNull(ObjectBinding<String> source) { return Bindings.createStringBinding(() -> { if (source.get() == null) { return ""; } else { return source.get(); } } , source); } public Command getEditCommand() { return editCommand; } public Command getRemoveCommand() { return removeCommand; } public Command getEmailLinkCommand() { return emailLinkCommand; } public ReadOnlyStringProperty nameLabelTextProperty() { return name.getReadOnlyProperty(); } public ReadOnlyStringProperty birthdayLabelTextProperty() { return birthday.getReadOnlyProperty(); } public ReadOnlyStringProperty roleDepartmentLabelTextProperty() { return roleDepartment.getReadOnlyProperty(); } public ReadOnlyStringProperty emailLabelTextProperty() { return email.getReadOnlyProperty(); } public ReadOnlyStringProperty phoneLabelTextProperty() { return phone.getReadOnlyProperty(); } public ReadOnlyStringProperty mobileLabelTextProperty() { return mobile.getReadOnlyProperty(); } public ReadOnlyStringProperty cityPostalcodeLabelTextProperty() { return cityPostalcode.getReadOnlyProperty(); } public ReadOnlyStringProperty streetLabelTextProperty() { return street.getReadOnlyProperty(); } public ReadOnlyStringProperty countrySubdivisionLabelTextProperty() { return countrySubdivision.getReadOnlyProperty(); } private String trimString(String string) { if (string == null || string.trim().isEmpty()) { return ""; } return string; } private String trimStringWithPostfix(String string, String append) { if (string == null || string.trim().isEmpty()) { return ""; } return string + append; } private Contact getSelectedContactFromScope() { return getSelectedContactPropertyFromScope().get(); } private ObjectProperty<Contact> getSelectedContactPropertyFromScope() { return mdScope.selectedContactProperty(); } }
package org.geomajas.gwt.client.util; import org.geomajas.configuration.client.UnitType; import org.geomajas.gwt.client.widget.MapWidget; import com.google.gwt.i18n.client.NumberFormat; /** * General formatter for distances and areas. * * @author Pieter De Graef */ public final class DistanceFormat { private static final double METERS_IN_MILE = 1609.344d; private static final double METERS_IN_YARD = 0.9144d; private static final double METERS_IN_KM = 1000; private DistanceFormat() { // Private default constructor. This is a utility class after all! } /** * Distance formatting method. Requires a length as parameter, expressed in the CRS units of the given map. * * @param map * The map for which a distance should be formatted. This map may be configured to use the metric system * or the English system. * @param length * The original length, expressed in the coordinate reference system of the given map. * @return Returns a string that is the formatted distance of the given length. Preference goes to meters or yards * (depending on the configured unit type), but when the number is larger than 10000, it will switch * automatically to kilometer/mile. */ public static String asMapLength(MapWidget map, double length) { double unitLength = map.getUnitLength(); double distance = length * unitLength; String unit = "m"; if (map.getMapModel().getMapInfo().getDisplayUnitType() == UnitType.METRIC) { // Right now, the distance is expressed in meter. Switch to km? if (distance > 10000) { distance /= METERS_IN_KM; unit = "km"; } } else if (map.getMapModel().getMapInfo().getDisplayUnitType() == UnitType.ENGLISH) { if (distance / METERS_IN_YARD > 10000) { // More than 10000 yard; switch to mile: distance = distance / METERS_IN_MILE; unit = "mi"; } else { distance /= METERS_IN_YARD; // use yards. unit = "yd"; } } else if (map.getMapModel().getMapInfo().getDisplayUnitType() == UnitType.CRS) { unit = "u"; } String formatted = NumberFormat.getDecimalFormat().format(distance); return formatted + unit; } /** * Area formatting method. Requires an area as parameter, expressed in the CRS units of the given map. * * @param map * The map for which an area should be formatted. This map may be configured to use the metric system or * the English system. * @param area * The original area, expressed in the coordinate reference system of the given map. * @return Returns a string that is the formatted area of the given area. Preference goes to meters or yards * (depending on the configured unit type), but when the number is larger than meters (or yards), it will * switch automatically to kilometers/miles. */ public static String asMapArea(MapWidget map, double area) { double unitLength = map.getUnitLength(); double distance = area * unitLength * unitLength; String unit = "m"; if (map.getMapModel().getMapInfo().getDisplayUnitType() == UnitType.METRIC) { // Right now, the distance is expressed in meter. Switch to km? if (distance > (METERS_IN_KM * METERS_IN_KM)) { distance /= (METERS_IN_KM * METERS_IN_KM); unit = "km"; } } else if (map.getMapModel().getMapInfo().getDisplayUnitType() == UnitType.ENGLISH) { if (distance > (METERS_IN_MILE * METERS_IN_MILE)) { // Switch to mile: distance = distance / (METERS_IN_MILE * METERS_IN_MILE); unit = "mi"; } else { distance /= (METERS_IN_YARD * METERS_IN_YARD); // use yards. unit = "yd"; } } else if (map.getMapModel().getMapInfo().getDisplayUnitType() == UnitType.CRS) { unit = "u"; } String formatted = NumberFormat.getDecimalFormat().format(distance); return formatted + unit + "&sup2;"; } }
package com.oracle.graal.phases.common.inlining.walker; import com.oracle.graal.api.code.Assumptions; import com.oracle.graal.api.code.BailoutException; import com.oracle.graal.api.meta.JavaTypeProfile; import com.oracle.graal.api.meta.ResolvedJavaMethod; import com.oracle.graal.api.meta.ResolvedJavaType; import com.oracle.graal.compiler.common.GraalInternalError; import com.oracle.graal.compiler.common.type.ObjectStamp; import com.oracle.graal.debug.Debug; import com.oracle.graal.debug.DebugMetric; import com.oracle.graal.graph.Graph; import com.oracle.graal.graph.Node; import com.oracle.graal.nodes.*; import com.oracle.graal.nodes.java.MethodCallTargetNode; import com.oracle.graal.phases.OptimisticOptimizations; import com.oracle.graal.phases.common.CanonicalizerPhase; import com.oracle.graal.phases.common.inlining.InliningUtil; import com.oracle.graal.phases.common.inlining.info.*; import com.oracle.graal.phases.common.inlining.info.elem.Inlineable; import com.oracle.graal.phases.common.inlining.info.elem.InlineableGraph; import com.oracle.graal.phases.common.inlining.info.elem.InlineableMacroNode; import com.oracle.graal.phases.common.inlining.policy.InliningPolicy; import com.oracle.graal.phases.graph.FixedNodeProbabilityCache; import com.oracle.graal.phases.tiers.HighTierContext; import com.oracle.graal.phases.util.Providers; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.List; import java.util.function.ToDoubleFunction; import static com.oracle.graal.compiler.common.GraalOptions.*; /** * Holds the data for building the callee graphs recursively: graphs and invocations (each * invocation can have multiple graphs). */ public class InliningData { private static final CallsiteHolder DUMMY_CALLSITE_HOLDER = new CallsiteHolder(null, 1.0, 1.0); // Metrics private static final DebugMetric metricInliningPerformed = Debug.metric("InliningPerformed"); private static final DebugMetric metricInliningRuns = Debug.metric("InliningRuns"); private static final DebugMetric metricInliningConsidered = Debug.metric("InliningConsidered"); /** * Call hierarchy from outer most call (i.e., compilation unit) to inner most callee. */ private final ArrayDeque<CallsiteHolder> graphQueue = new ArrayDeque<>(); private final ArrayDeque<MethodInvocation> invocationQueue = new ArrayDeque<>(); private final ToDoubleFunction<FixedNode> probabilities = new FixedNodeProbabilityCache(); private final HighTierContext context; private final int maxMethodPerInlining; private final CanonicalizerPhase canonicalizer; private final InliningPolicy inliningPolicy; private int maxGraphs; public InliningData(StructuredGraph rootGraph, HighTierContext context, int maxMethodPerInlining, CanonicalizerPhase canonicalizer, InliningPolicy inliningPolicy) { assert rootGraph != null; this.context = context; this.maxMethodPerInlining = maxMethodPerInlining; this.canonicalizer = canonicalizer; this.inliningPolicy = inliningPolicy; this.maxGraphs = 1; Assumptions rootAssumptions = context.getAssumptions(); invocationQueue.push(new MethodInvocation(null, rootAssumptions, 1.0, 1.0)); pushGraph(rootGraph, 1.0, 1.0); } private String checkTargetConditionsHelper(ResolvedJavaMethod method) { if (method == null) { return "the method is not resolved"; } else if (method.isNative() && (!Intrinsify.getValue() || !InliningUtil.canIntrinsify(context.getReplacements(), method))) { return "it is a non-intrinsic native method"; } else if (method.isAbstract()) { return "it is an abstract method"; } else if (!method.getDeclaringClass().isInitialized()) { return "the method's class is not initialized"; } else if (!method.canBeInlined()) { return "it is marked non-inlinable"; } else if (countRecursiveInlining(method) > MaximumRecursiveInlining.getValue()) { return "it exceeds the maximum recursive inlining depth"; } else if (new OptimisticOptimizations(method.getProfilingInfo()).lessOptimisticThan(context.getOptimisticOptimizations())) { return "the callee uses less optimistic optimizations than caller"; } else { return null; } } private boolean checkTargetConditions(Invoke invoke, ResolvedJavaMethod method) { final String failureMessage = checkTargetConditionsHelper(method); if (failureMessage == null) { return true; } else { InliningUtil.logNotInlined(invoke, inliningDepth(), method, failureMessage); return false; } } /** * Determines if inlining is possible at the given invoke node. * * @param invoke the invoke that should be inlined * @return an instance of InlineInfo, or null if no inlining is possible at the given invoke */ private InlineInfo getInlineInfo(Invoke invoke, Assumptions assumptions) { final String failureMessage = InliningUtil.checkInvokeConditions(invoke); if (failureMessage != null) { InliningUtil.logNotInlinedMethod(invoke, failureMessage); return null; } MethodCallTargetNode callTarget = (MethodCallTargetNode) invoke.callTarget(); ResolvedJavaMethod targetMethod = callTarget.targetMethod(); if (callTarget.invokeKind() == MethodCallTargetNode.InvokeKind.Special || targetMethod.canBeStaticallyBound()) { return getExactInlineInfo(invoke, targetMethod); } assert callTarget.invokeKind() == MethodCallTargetNode.InvokeKind.Virtual || callTarget.invokeKind() == MethodCallTargetNode.InvokeKind.Interface; ResolvedJavaType holder = targetMethod.getDeclaringClass(); if (!(callTarget.receiver().stamp() instanceof ObjectStamp)) { return null; } ObjectStamp receiverStamp = (ObjectStamp) callTarget.receiver().stamp(); if (receiverStamp.alwaysNull()) { // Don't inline if receiver is known to be null return null; } ResolvedJavaType contextType = invoke.getContextType(); if (receiverStamp.type() != null) { // the invoke target might be more specific than the holder (happens after inlining: // parameters lose their declared type...) ResolvedJavaType receiverType = receiverStamp.type(); if (receiverType != null && holder.isAssignableFrom(receiverType)) { holder = receiverType; if (receiverStamp.isExactType()) { assert targetMethod.getDeclaringClass().isAssignableFrom(holder) : holder + " subtype of " + targetMethod.getDeclaringClass() + " for " + targetMethod; ResolvedJavaMethod resolvedMethod = holder.resolveMethod(targetMethod, contextType); if (resolvedMethod != null) { return getExactInlineInfo(invoke, resolvedMethod); } } } } if (holder.isArray()) { // arrays can be treated as Objects ResolvedJavaMethod resolvedMethod = holder.resolveMethod(targetMethod, contextType); if (resolvedMethod != null) { return getExactInlineInfo(invoke, resolvedMethod); } } if (assumptions.useOptimisticAssumptions()) { ResolvedJavaType uniqueSubtype = holder.findUniqueConcreteSubtype(); if (uniqueSubtype != null) { ResolvedJavaMethod resolvedMethod = uniqueSubtype.resolveMethod(targetMethod, contextType); if (resolvedMethod != null) { return getAssumptionInlineInfo(invoke, resolvedMethod, new Assumptions.ConcreteSubtype(holder, uniqueSubtype)); } } ResolvedJavaMethod concrete = holder.findUniqueConcreteMethod(targetMethod); if (concrete != null) { return getAssumptionInlineInfo(invoke, concrete, new Assumptions.ConcreteMethod(targetMethod, holder, concrete)); } } // type check based inlining return getTypeCheckedInlineInfo(invoke, targetMethod); } private InlineInfo getTypeCheckedInlineInfo(Invoke invoke, ResolvedJavaMethod targetMethod) { JavaTypeProfile typeProfile; ValueNode receiver = invoke.callTarget().arguments().get(0); if (receiver instanceof TypeProfileProxyNode) { TypeProfileProxyNode typeProfileProxyNode = (TypeProfileProxyNode) receiver; typeProfile = typeProfileProxyNode.getProfile(); } else { InliningUtil.logNotInlined(invoke, inliningDepth(), targetMethod, "no type profile exists"); return null; } JavaTypeProfile.ProfiledType[] ptypes = typeProfile.getTypes(); if (ptypes == null || ptypes.length <= 0) { InliningUtil.logNotInlined(invoke, inliningDepth(), targetMethod, "no types in profile"); return null; } ResolvedJavaType contextType = invoke.getContextType(); double notRecordedTypeProbability = typeProfile.getNotRecordedProbability(); final OptimisticOptimizations optimisticOpts = context.getOptimisticOptimizations(); if (ptypes.length == 1 && notRecordedTypeProbability == 0) { if (!optimisticOpts.inlineMonomorphicCalls()) { InliningUtil.logNotInlined(invoke, inliningDepth(), targetMethod, "inlining monomorphic calls is disabled"); return null; } ResolvedJavaType type = ptypes[0].getType(); assert type.isArray() || !type.isAbstract(); ResolvedJavaMethod concrete = type.resolveMethod(targetMethod, contextType); if (!checkTargetConditions(invoke, concrete)) { return null; } return new TypeGuardInlineInfo(invoke, concrete, type); } else { invoke.setPolymorphic(true); if (!optimisticOpts.inlinePolymorphicCalls() && notRecordedTypeProbability == 0) { InliningUtil.logNotInlinedInvoke(invoke, inliningDepth(), targetMethod, "inlining polymorphic calls is disabled (%d types)", ptypes.length); return null; } if (!optimisticOpts.inlineMegamorphicCalls() && notRecordedTypeProbability > 0) { // due to filtering impossible types, notRecordedTypeProbability can be > 0 although // the number of types is lower than what can be recorded in a type profile InliningUtil.logNotInlinedInvoke(invoke, inliningDepth(), targetMethod, "inlining megamorphic calls is disabled (%d types, %f %% not recorded types)", ptypes.length, notRecordedTypeProbability * 100); return null; } // Find unique methods and their probabilities. ArrayList<ResolvedJavaMethod> concreteMethods = new ArrayList<>(); ArrayList<Double> concreteMethodsProbabilities = new ArrayList<>(); for (int i = 0; i < ptypes.length; i++) { ResolvedJavaMethod concrete = ptypes[i].getType().resolveMethod(targetMethod, contextType); if (concrete == null) { InliningUtil.logNotInlined(invoke, inliningDepth(), targetMethod, "could not resolve method"); return null; } int index = concreteMethods.indexOf(concrete); double curProbability = ptypes[i].getProbability(); if (index < 0) { index = concreteMethods.size(); concreteMethods.add(concrete); concreteMethodsProbabilities.add(curProbability); } else { concreteMethodsProbabilities.set(index, concreteMethodsProbabilities.get(index) + curProbability); } } if (concreteMethods.size() > maxMethodPerInlining) { InliningUtil.logNotInlinedInvoke(invoke, inliningDepth(), targetMethod, "polymorphic call with more than %d target methods", maxMethodPerInlining); return null; } // Clear methods that fall below the threshold. if (notRecordedTypeProbability > 0) { ArrayList<ResolvedJavaMethod> newConcreteMethods = new ArrayList<>(); ArrayList<Double> newConcreteMethodsProbabilities = new ArrayList<>(); for (int i = 0; i < concreteMethods.size(); ++i) { if (concreteMethodsProbabilities.get(i) >= MegamorphicInliningMinMethodProbability.getValue()) { newConcreteMethods.add(concreteMethods.get(i)); newConcreteMethodsProbabilities.add(concreteMethodsProbabilities.get(i)); } } if (newConcreteMethods.size() == 0) { // No method left that is worth inlining. InliningUtil.logNotInlinedInvoke(invoke, inliningDepth(), targetMethod, "no methods remaining after filtering less frequent methods (%d methods previously)", concreteMethods.size()); return null; } concreteMethods = newConcreteMethods; concreteMethodsProbabilities = newConcreteMethodsProbabilities; } // Clean out types whose methods are no longer available. ArrayList<JavaTypeProfile.ProfiledType> usedTypes = new ArrayList<>(); ArrayList<Integer> typesToConcretes = new ArrayList<>(); for (JavaTypeProfile.ProfiledType type : ptypes) { ResolvedJavaMethod concrete = type.getType().resolveMethod(targetMethod, contextType); int index = concreteMethods.indexOf(concrete); if (index == -1) { notRecordedTypeProbability += type.getProbability(); } else { assert type.getType().isArray() || !type.getType().isAbstract() : type + " " + concrete; usedTypes.add(type); typesToConcretes.add(index); } } if (usedTypes.size() == 0) { // No type left that is worth checking for. InliningUtil.logNotInlinedInvoke(invoke, inliningDepth(), targetMethod, "no types remaining after filtering less frequent types (%d types previously)", ptypes.length); return null; } for (ResolvedJavaMethod concrete : concreteMethods) { if (!checkTargetConditions(invoke, concrete)) { InliningUtil.logNotInlined(invoke, inliningDepth(), targetMethod, "it is a polymorphic method call and at least one invoked method cannot be inlined"); return null; } } return new MultiTypeGuardInlineInfo(invoke, concreteMethods, concreteMethodsProbabilities, usedTypes, typesToConcretes, notRecordedTypeProbability); } } private InlineInfo getAssumptionInlineInfo(Invoke invoke, ResolvedJavaMethod concrete, Assumptions.Assumption takenAssumption) { assert !concrete.isAbstract(); if (!checkTargetConditions(invoke, concrete)) { return null; } return new AssumptionInlineInfo(invoke, concrete, takenAssumption); } private InlineInfo getExactInlineInfo(Invoke invoke, ResolvedJavaMethod targetMethod) { assert !targetMethod.isAbstract(); if (!checkTargetConditions(invoke, targetMethod)) { return null; } return new ExactInlineInfo(invoke, targetMethod); } private void doInline(CallsiteHolder callerCallsiteHolder, MethodInvocation calleeInvocation, Assumptions callerAssumptions) { StructuredGraph callerGraph = callerCallsiteHolder.graph(); Graph.Mark markBeforeInlining = callerGraph.getMark(); InlineInfo callee = calleeInvocation.callee(); try { try (Debug.Scope scope = Debug.scope("doInline", callerGraph)) { List<Node> invokeUsages = callee.invoke().asNode().usages().snapshot(); callee.inline(new Providers(context), callerAssumptions); callerAssumptions.record(calleeInvocation.assumptions()); metricInliningRuns.increment(); Debug.dump(callerGraph, "after %s", callee); if (OptCanonicalizer.getValue()) { Graph.Mark markBeforeCanonicalization = callerGraph.getMark(); canonicalizer.applyIncremental(callerGraph, context, invokeUsages, markBeforeInlining); // process invokes that are possibly created during canonicalization for (Node newNode : callerGraph.getNewNodes(markBeforeCanonicalization)) { if (newNode instanceof Invoke) { callerCallsiteHolder.pushInvoke((Invoke) newNode); } } } callerCallsiteHolder.computeProbabilities(); metricInliningPerformed.increment(); } } catch (BailoutException bailout) { throw bailout; } catch (AssertionError | RuntimeException e) { throw new GraalInternalError(e).addContext(callee.toString()); } catch (GraalInternalError e) { throw e.addContext(callee.toString()); } } /** * @return true iff inlining was actually performed */ private boolean tryToInline(CallsiteHolder callerCallsiteHolder, MethodInvocation calleeInvocation, MethodInvocation parentInvocation, int inliningDepth) { InlineInfo calleeInfo = calleeInvocation.callee(); Assumptions callerAssumptions = parentInvocation.assumptions(); metricInliningConsidered.increment(); if (inliningPolicy.isWorthInlining(probabilities, context.getReplacements(), calleeInfo, inliningDepth, calleeInvocation.probability(), calleeInvocation.relevance(), true)) { doInline(callerCallsiteHolder, calleeInvocation, callerAssumptions); return true; } if (context.getOptimisticOptimizations().devirtualizeInvokes()) { calleeInfo.tryToDevirtualizeInvoke(context.getMetaAccess(), callerAssumptions); } return false; } /** * Process the next invoke and enqueue all its graphs for processing. */ private void processNextInvoke() { CallsiteHolder callsiteHolder = currentGraph(); Invoke invoke = callsiteHolder.popInvoke(); MethodInvocation callerInvocation = currentInvocation(); Assumptions parentAssumptions = callerInvocation.assumptions(); Assumptions calleeAssumptions = new Assumptions(parentAssumptions.useOptimisticAssumptions()); InlineInfo info = populateInlineInfo(invoke, parentAssumptions, calleeAssumptions); if (info != null) { double invokeProbability = callsiteHolder.invokeProbability(invoke); double invokeRelevance = callsiteHolder.invokeRelevance(invoke); MethodInvocation methodInvocation = new MethodInvocation(info, calleeAssumptions, invokeProbability, invokeRelevance); pushInvocation(methodInvocation); for (int i = 0; i < info.numberOfMethods(); i++) { Inlineable elem = info.inlineableElementAt(i); if (elem instanceof InlineableGraph) { pushGraph(((InlineableGraph) elem).getGraph(), invokeProbability * info.probabilityAt(i), invokeRelevance * info.relevanceAt(i)); } else { assert elem instanceof InlineableMacroNode; pushDummyGraph(); } } } } private InlineInfo populateInlineInfo(Invoke invoke, Assumptions parentAssumptions, Assumptions calleeAssumptions) { InlineInfo info = getInlineInfo(invoke, parentAssumptions); if (info == null) { return null; } for (int i = 0; i < info.numberOfMethods(); i++) { Inlineable elem = Inlineable.getInlineableElement(info.methodAt(i), info.invoke(), context.replaceAssumptions(calleeAssumptions), canonicalizer); info.setInlinableElement(i, elem); } return info; } public int graphCount() { return graphQueue.size(); } private void pushGraph(StructuredGraph graph, double probability, double relevance) { assert graph != null; assert !contains(graph); graphQueue.push(new CallsiteHolder(graph, probability, relevance)); assert graphQueue.size() <= maxGraphs; } private void pushDummyGraph() { graphQueue.push(DUMMY_CALLSITE_HOLDER); } public boolean hasUnprocessedGraphs() { return !graphQueue.isEmpty(); } private CallsiteHolder currentGraph() { return graphQueue.peek(); } private void popGraph() { graphQueue.pop(); assert graphQueue.size() <= maxGraphs; } private void popGraphs(int count) { assert count >= 0; for (int i = 0; i < count; i++) { graphQueue.pop(); } } private static final Object[] NO_CONTEXT = {}; /** * Gets the call hierarchy of this inlining from outer most call to inner most callee. */ private Object[] inliningContext() { if (!Debug.isDumpEnabled()) { return NO_CONTEXT; } Object[] result = new Object[graphQueue.size()]; int i = 0; for (CallsiteHolder g : graphQueue) { result[i++] = g.method(); } return result; } private MethodInvocation currentInvocation() { return invocationQueue.peekFirst(); } private void pushInvocation(MethodInvocation methodInvocation) { invocationQueue.addFirst(methodInvocation); maxGraphs += methodInvocation.callee().numberOfMethods(); assert graphQueue.size() <= maxGraphs; } private void popInvocation() { maxGraphs -= invocationQueue.peekFirst().callee().numberOfMethods(); assert graphQueue.size() <= maxGraphs; invocationQueue.removeFirst(); } public int countRecursiveInlining(ResolvedJavaMethod method) { int count = 0; for (CallsiteHolder callsiteHolder : graphQueue) { if (method.equals(callsiteHolder.method())) { count++; } } return count; } public int inliningDepth() { assert invocationQueue.size() > 0; return invocationQueue.size() - 1; } @Override public String toString() { StringBuilder result = new StringBuilder("Invocations: "); for (MethodInvocation invocation : invocationQueue) { if (invocation.callee() != null) { result.append(invocation.callee().numberOfMethods()); result.append("x "); result.append(invocation.callee().invoke()); result.append("; "); } } result.append("\nGraphs: "); for (CallsiteHolder graph : graphQueue) { result.append(graph.graph()); result.append("; "); } return result.toString(); } private boolean contains(StructuredGraph graph) { for (CallsiteHolder info : graphQueue) { if (info.graph() == graph) { return true; } } return false; } /** * @return true iff inlining was actually performed */ public boolean moveForward() { final MethodInvocation currentInvocation = currentInvocation(); final boolean backtrack = (!currentInvocation.isRoot() && !inliningPolicy.isWorthInlining(probabilities, context.getReplacements(), currentInvocation.callee(), inliningDepth(), currentInvocation.probability(), currentInvocation.relevance(), false)); if (backtrack) { int remainingGraphs = currentInvocation.totalGraphs() - currentInvocation.processedGraphs(); assert remainingGraphs > 0; popGraphs(remainingGraphs); popInvocation(); return false; } final boolean delve = currentGraph().hasRemainingInvokes() && inliningPolicy.continueInlining(currentGraph().graph()); if (delve) { processNextInvoke(); return false; } popGraph(); if (currentInvocation.isRoot()) { return false; } // try to inline assert currentInvocation.callee().invoke().asNode().isAlive(); currentInvocation.incrementProcessedGraphs(); if (currentInvocation.processedGraphs() == currentInvocation.totalGraphs()) { popInvocation(); final MethodInvocation parentInvoke = currentInvocation(); try (Debug.Scope s = Debug.scope("Inlining", inliningContext())) { return tryToInline(currentGraph(), currentInvocation, parentInvoke, inliningDepth() + 1); } catch (Throwable e) { throw Debug.handle(e); } } return false; } }
package com.mindthehippo.infrastructure.security; import com.fasterxml.jackson.databind.ObjectMapper; import com.mindthehippo.budget.aggregate.budget.Budget; import com.mindthehippo.budget.aggregate.budget.Item; import com.mindthehippo.budget.application.dto.BudgetDTO; import com.mindthehippo.budget.application.dto.ItemDTO; import java.io.IOException; import static java.util.Collections.singletonMap; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.modelmapper.ModelMapper; import org.modelmapper.PropertyMap; import org.modelmapper.TypeToken; import org.modelmapper.convention.MatchingStrategies; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.authentication.AuthenticationFailureHandler; import org.springframework.security.web.authentication.AuthenticationSuccessHandler; import org.springframework.security.web.csrf.CsrfFilter; /** * * @author Marcelo */ // TODO: CHANGE TO OAuth based authentication @Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter implements AuthenticationSuccessHandler, AuthenticationFailureHandler { @Value("${mock.account}") private String mockAccount; @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/").permitAll() .anyRequest().permitAll() .and() .formLogin() .loginProcessingUrl("/login") .successHandler(this) .failureHandler(this) .permitAll() .and() .logout() .permitAll() .and() .addFilterAfter(new CsrfHeaderFilter(), CsrfFilter.class); } @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth .inMemoryAuthentication() .withUser("user").password("password").roles("USER"); } @Override public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException { ObjectMapper mapper = new ObjectMapper(); response.setContentType("application/json"); Map m = new HashMap(); m.put("user", authentication.getName()); m.put("account", UUID.fromString(mockAccount)); mapper.writeValue(response.getWriter(), singletonMap("authenticated", m)); } @Override public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException { ObjectMapper mapper = new ObjectMapper(); response.setContentType("application/json"); mapper.writeValue(response.getWriter(), singletonMap("failure", exception.getMessage())); } @Bean public ModelMapper modelMapper() { ModelMapper modelMapper = new ModelMapper(); modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.LOOSE); PropertyMap<Item, ItemDTO> itemMap = new PropertyMap<Item, ItemDTO>() { @Override protected void configure() { map().setCategory(source.getCategory().getText()); } }; modelMapper.addMappings(itemMap); return modelMapper; } }
package com.alibaba.otter.canal.instance.manager.plain; import java.io.ByteArrayInputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.security.NoSuchAlgorithmException; import java.util.HashMap; import java.util.Map; import java.util.Properties; import org.apache.commons.lang.StringUtils; import com.alibaba.fastjson2.JSON; import com.alibaba.fastjson2.TypeReference; import com.alibaba.otter.canal.common.AbstractCanalLifeCycle; import com.alibaba.otter.canal.common.CanalException; import com.alibaba.otter.canal.common.CanalLifeCycle; import com.alibaba.otter.canal.protocol.SecurityUtil; import com.google.common.net.UrlEscapers; /** * * * @author rewerma 2019-01-25 05:20:16 * @author agapple 2019826 7:52:06 * @since 1.1.4 */ public class PlainCanalConfigClient extends AbstractCanalLifeCycle implements CanalLifeCycle { private final static Integer REQUEST_TIMEOUT = 5000; private String configURL; private String user; private String passwd; private HttpHelper httpHelper; private String localIp; private int adminPort; private boolean autoRegister; private String autoCluster; private String name; public PlainCanalConfigClient(String configURL, String user, String passwd, String localIp, int adminPort, boolean autoRegister, String autoCluster, String name){ this(configURL, user, passwd, localIp, adminPort); this.autoCluster = autoCluster; this.autoRegister = autoRegister; this.name = name; } public PlainCanalConfigClient(String configURL, String user, String passwd, String localIp, int adminPort){ this.configURL = configURL; if (!StringUtils.startsWithIgnoreCase(configURL, "http")) { this.configURL = "http://" + configURL; } else { this.configURL = configURL; } this.user = user; this.passwd = passwd; this.httpHelper = new HttpHelper(); if (StringUtils.isEmpty(localIp)) { this.localIp = "127.0.0.1"; } else { this.localIp = localIp; } this.adminPort = adminPort; } /** * canal.properties * * @return properties */ public PlainCanal findServer(String md5) { if (StringUtils.isEmpty(md5)) { md5 = ""; } String url = configURL + "/api/v1/config/server_polling?ip=" + localIp + "&port=" + adminPort + "&md5=" + md5 + "&register=" + (autoRegister ? 1 : 0) + "&cluster=" + autoCluster + "&name=" + name; return queryConfig(url); } /** * instance.properties */ public PlainCanal findInstance(String destination, String md5) { if (StringUtils.isEmpty(md5)) { md5 = ""; } String url = configURL + "/api/v1/config/instance_polling/" + UrlEscapers.urlPathSegmentEscaper().escape(destination) + "?md5=" + md5; return queryConfig(url); } /** * instance */ public String findInstances(String md5) { if (StringUtils.isEmpty(md5)) { md5 = ""; } String url = configURL + "/api/v1/config/instances_polling?md5=" + md5 + "&ip=" + localIp + "&port=" + adminPort; ResponseModel<CanalConfig> config = doQuery(url); if (config.data != null) { return config.data.content; } else { return null; } } private PlainCanal queryConfig(String url) { try { ResponseModel<CanalConfig> config = doQuery(url); return processData(config.data); } catch (Throwable e) { throw new CanalException("load manager config failed.", e); } } private ResponseModel<CanalConfig> doQuery(String url) { Map<String, String> heads = new HashMap<>(); heads.put("user", user); heads.put("passwd", passwd); String response = httpHelper.get(url, heads, REQUEST_TIMEOUT); ResponseModel<CanalConfig> resp = JSON.parseObject(response, new TypeReference<ResponseModel<CanalConfig>>() { }); if (!HttpHelper.REST_STATE_OK.equals(resp.code)) { throw new CanalException("requestGet for canal config error: " + resp.message); } return resp; } private PlainCanal processData(CanalConfig config) throws IOException, NoSuchAlgorithmException { Properties properties = new Properties(); String md5 = null; String status = null; if (config != null && StringUtils.isNotEmpty(config.content)) { md5 = SecurityUtil.md5String(config.content); status = config.status; properties.load(new ByteArrayInputStream(config.content.getBytes(StandardCharsets.UTF_8))); } else { // null return null; } return new PlainCanal(properties, status, md5); } private static class ResponseModel<T> { public Integer code; public String message; public T data; } private static class CanalConfig { public String content; public String status; } }
package org.javarosa.services.properties.view; import java.util.Enumeration; import java.util.Hashtable; import java.util.Vector; import javax.microedition.lcdui.ChoiceGroup; import javax.microedition.lcdui.Display; import javax.microedition.lcdui.Displayable; import javax.microedition.lcdui.Form; import javax.microedition.lcdui.Item; import javax.microedition.lcdui.StringItem; import javax.microedition.lcdui.TextField; import javax.microedition.rms.RecordStore; import javax.microedition.rms.RecordStoreException; import org.javarosa.core.JavaRosaServiceProvider; import org.javarosa.core.api.IView; import org.javarosa.core.services.PropertyManager; import org.javarosa.core.services.properties.IPropertyRules; import org.javarosa.core.services.storage.utilities.RMSUtility; public class PropertiesScreen extends Form implements IView{ Hashtable itemChoices; Hashtable changes; /** item -> String **/ Hashtable itemForPropertyName; Display currentDisplay; Displayable currentScreen; PropertyManager propertyManager; public PropertiesScreen(PropertyManager propertyManager) { super("Properties"); itemChoices = new Hashtable(); changes = new Hashtable(); itemForPropertyName = new Hashtable(); this.propertyManager = propertyManager; populateProperties(); addRMSInfoJ2MEOnly(); } public void showPropertiesScreen(Display currentDisplay, Displayable currentScreen) { this.currentDisplay = currentDisplay; this.currentScreen = currentScreen; currentDisplay.setCurrent(this); } private void populateProperties() { Vector readOnlys = new Vector(); Vector rulesSets = propertyManager .getRules(); Enumeration en = rulesSets.elements(); while (en.hasMoreElements()) { IPropertyRules rules = (IPropertyRules) en.nextElement(); Vector properties = rules.allowableProperties(); for (int i = 0; i < properties.size(); ++i) { String propertyName = (String) properties.elementAt(i); Vector options = rules.allowableValues(propertyName); // Check to see whether this property has a dynamic rules list if (options.size() == 1) { String option = (String) options.elementAt(0); if (rules.checkPropertyAllowed(option)) { // this is a Dynamic property list, replace options options = propertyManager.getProperty(option); } } // If there are no options, it is an internal system's variable. // Don't touch if (options.size() != 0) { Vector propValues = propertyManager.getProperty(propertyName); // We can easily add the functionality to use multiple // possible choices here but // for now, we'll stick with single-selection properties if (propValues == null || propValues.size() == 1) { // Pull the property's current value String currentSelection = ""; if(propValues != null) { currentSelection = (String) propValues.elementAt(0); } // Create the UI Elements ChoiceGroup newChoiceGroup = new ChoiceGroup( rules.getHumanReadableDescription(propertyName), ChoiceGroup.EXCLUSIVE); itemChoices.put(newChoiceGroup, options); itemForPropertyName.put(newChoiceGroup, propertyName); // Seek through to find the property in the list of // potentials int selindex = 0; for (int j = 0; j < options.size(); ++j) { String option = (String) options.elementAt(j); if (option.equals(currentSelection)) { selindex = j; } newChoiceGroup.append(rules.getHumanReadableValue(propertyName, option), null); } // Finish it all up newChoiceGroup.setSelectedIndex(selindex, true); this.append(newChoiceGroup); } } else { Vector propValues = propertyManager.getProperty(propertyName); // We can easily add the functionality to use multiple // possible choices here but // for now, we'll stick with single-selection properties if (propValues != null) { if (propValues.size() <= 1) { TextField input = new TextField( rules .getHumanReadableDescription(propertyName), (String) propValues.elementAt(0), 50, TextField.ANY); itemForPropertyName.put(input, propertyName); if (rules.checkPropertyUserReadOnly(propertyName)) { input.setConstraints(TextField.UNEDITABLE); readOnlys.addElement(input); } else { this.append(input); } } } else { TextField input = new TextField(rules.getHumanReadableDescription(propertyName), "", 50, TextField.ANY); itemForPropertyName.put(input, propertyName); if(rules.checkPropertyUserReadOnly(propertyName)) { input.setConstraints(TextField.UNEDITABLE); readOnlys.addElement(input); } else { this.append(input); } } } } } Enumeration enden = readOnlys.elements(); while(enden.hasMoreElements()) { Item currentElement = (Item)enden.nextElement(); this.append(currentElement); } } private void addRMSInfoJ2MEOnly () { try { String[] stores = RecordStore.listRecordStores(); for (int i = 0; i < stores.length; i++) { String rmsName = stores[i]; RecordStore rms = RecordStore.openRecordStore(rmsName, false); int size = rms.getSize(); int avail = rms.getSizeAvailable(); int numRecs = rms.getNumRecords(); int perRecord = (numRecs == 0 ? -1 : size / numRecs); this.append(new StringItem(null, rmsName)); this.append(new StringItem(null, "Used: " + formatBytes(size))); this.append(new StringItem(null, "Records: " + numRecs + (numRecs > 0 ? " (" + formatBytes(perRecord) + " per record)" : ""))); this.append(new StringItem(null, "Available: " + formatBytes(avail))); } } catch (RecordStoreException rse) { } } private void addRMSInfo() { Vector stores = JavaRosaServiceProvider.instance().getStorageManager().getRMSStorageProvider().getUtilityNames(); int consumedSpace[] = new int[stores.size()]; int availableSpace[] = new int[stores.size()]; Enumeration names = stores.elements(); int i = 0; while (names.hasMoreElements()) { String name = (String) names.nextElement(); RMSUtility utility = JavaRosaServiceProvider.instance() .getStorageManager().getRMSStorageProvider().getUtility( name); consumedSpace[i] = (int) utility.getConsumedSpace(); availableSpace[i] = (int) utility.getAvailableSpace(); ++i; } String devID = JavaRosaServiceProvider.instance().getPropertyManager() .getSingularProperty("DeviceID"); this.append(new StringItem(null, "Device ID: " + devID)); for (i = 0; i < stores.size(); i++) { this.append(new StringItem(null, (String) stores.elementAt(i) .toString())); this.append(new StringItem(null, "Available: " + formatBytes(availableSpace[i]))); this.append(new StringItem(null, "Used: " + formatBytes(consumedSpace[i]))); } } private String formatBytes (int bytes) { int NUM_DIGITS = 2; if (bytes <= 0) return "err"; double kb = bytes / 1024.; String str = String.valueOf(kb); if (str.indexOf(".") != -1) str = str.substring(0, Math.min(str.indexOf(".") + 1 + NUM_DIGITS, str.length())); return str + " KB"; } // private String formatBytes(int bytes) { // if (bytes == -1) // return "error"; // String kbytes = ""; // //Check for overflow // if(bytes*10 < bytes) { // //Handle this case with low precision // int kb = bytes / 1024; // kbytes = String.valueOf(kb); // else if(bytes*100 < bytes){ // int kb = (bytes*10)/1024; // kbytes = String.valueOf(kb); // if(kbytes.length() >= 2) { // kbytes = kbytes.substring(0,kbytes.length()-2) + "." + kbytes.charAt(kbytes.length()-1); // else { // kbytes = "0." + kbytes; // else { // int kb = (bytes*100)/1024; // kbytes = String.valueOf(kb); // if(kbytes.length() >= 3) { // kbytes = kbytes.substring(0,kbytes.length()-3) + "." + kbytes.substring(kbytes.length()-2, kbytes.length()-1); // else if(kbytes.length() >= 2) { // kbytes = "0." + kbytes; // else { // kbytes = "0.0" + kbytes; // return kbytes + " KB"; public Hashtable getItemChoices() { return itemChoices; } public String nameFromItem(Item item) { return (String)itemForPropertyName.get(item); } public Object getScreenObject() { return this; } }
package org.eclipse.kura.core.data.transport.mqtt; import java.io.UnsupportedEncodingException; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.net.ssl.SSLSocketFactory; import org.eclipse.kura.KuraConnectException; import org.eclipse.kura.KuraException; import org.eclipse.kura.KuraNotConnectedException; import org.eclipse.kura.KuraTimeoutException; import org.eclipse.kura.KuraTooManyInflightMessagesException; import org.eclipse.kura.configuration.ConfigurableComponent; import org.eclipse.kura.core.data.transport.mqtt.MqttClientConfiguration.PersistenceType; import org.eclipse.kura.core.util.ValidationUtil; import org.eclipse.kura.crypto.CryptoService; import org.eclipse.kura.data.DataTransportListener; import org.eclipse.kura.data.DataTransportService; import org.eclipse.kura.data.DataTransportToken; import org.eclipse.kura.ssl.SslManagerService; import org.eclipse.kura.ssl.SslServiceListener; import org.eclipse.kura.system.SystemService; import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken; import org.eclipse.paho.client.mqttv3.IMqttToken; import org.eclipse.paho.client.mqttv3.MqttAsyncClient; import org.eclipse.paho.client.mqttv3.MqttCallback; import org.eclipse.paho.client.mqttv3.MqttClientPersistence; import org.eclipse.paho.client.mqttv3.MqttConnectOptions; import org.eclipse.paho.client.mqttv3.MqttException; import org.eclipse.paho.client.mqttv3.MqttMessage; import org.eclipse.paho.client.mqttv3.MqttPersistenceException; import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence; import org.eclipse.paho.client.mqttv3.persist.MqttDefaultFilePersistence; import org.osgi.service.component.ComponentContext; import org.osgi.util.tracker.ServiceTracker; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class MqttDataTransport implements DataTransportService, MqttCallback, ConfigurableComponent, SslServiceListener { private static final Logger s_logger = LoggerFactory.getLogger(MqttDataTransport.class); private static final String ENV_JAVA_SECURITY= System.getProperty("java.security.manager"); private static final String ENV_OSGI_FRAMEWORK_SECURITY= System.getProperty("org.osgi.framework.security"); private static final String ENV_OSGI_SIGNED_CONTENT_SUPPORT= System.getProperty("osgi.signedcontent.support"); private static final String ENV_OSGI_FRAMEWORK_TRUST_REPOSITORIES= System.getProperty("org.osgi.framework.trust.repositories"); private static final String MQTT_SCHEME = "mqtt: private static final String MQTTS_SCHEME = "mqtts: // TODO: add mqtt+ssl for secure mqtt private static final String TOPIC_PATTERN = "#([^\\s/]+)"; // '#' followed // by one or // more // non-whitespace // but not the private static final Pattern s_topicPattern = Pattern.compile(TOPIC_PATTERN); private SystemService m_systemService; private SslManagerService m_sslManagerService; private MqttAsyncClient m_mqttClient; private DataTransportListeners m_dataTransportListeners; private MqttClientConfiguration m_clientConf; private boolean m_newSession; private String m_sessionId; PersistenceType m_persistenceType; MqttClientPersistence m_persistence; private Map<String, String> m_topicContext = new HashMap<String, String>(); private Map<String, Object> m_properties = new HashMap<String, Object>(); private CryptoService m_cryptoService; private static final String MQTT_BROKER_URL_PROP_NAME = "broker-url"; private static final String MQTT_USERNAME_PROP_NAME = "username"; private static final String MQTT_PASSWORD_PROP_NAME = "password"; private static final String MQTT_CLIENT_ID_PROP_NAME = "client-id"; private static final String MQTT_KEEP_ALIVE_PROP_NAME = "keep-alive"; private static final String MQTT_CLEAN_SESSION_PROP_NAME = "clean-session"; private static final String MQTT_TIMEOUT_PROP_NAME = "timeout"; // All // timeouts private static final String MQTT_DEFAULT_VERSION_PROP_NAME = "protocol-version"; private static final String MQTT_LWT_QOS_PROP_NAME = "lwt.qos"; private static final String MQTT_LWT_RETAIN_PROP_NAME = "lwt.retain"; private static final String MQTT_LWT_TOPIC_PROP_NAME = "lwt.topic"; private static final String MQTT_LWT_PAYLOAD_PROP_NAME = "lwt.payload"; private static final String CLOUD_ACCOUNT_NAME_PROP_NAME = "topic.context.account-name"; private static final String PERSISTENCE_TYPE_PROP_NAME = "in-flight.persistence"; private static final String TOPIC_ACCOUNT_NAME_CTX_NAME = "account-name"; private static final String TOPIC_DEVICE_ID_CTX_NAME = "client-id"; // Dependencies public void setSystemService(SystemService systemService) { this.m_systemService = systemService; } public void unsetSystemService(SystemService systemService) { this.m_systemService = null; } public void setSslManagerService(SslManagerService sslManagerService) { this.m_sslManagerService = sslManagerService; } public void unsetSslManagerService(SslManagerService sslManagerService) { this.m_sslManagerService = null; } public void setCryptoService(CryptoService cryptoService) { this.m_cryptoService = cryptoService; } public void unsetCryptoService(CryptoService cryptoService) { this.m_cryptoService = null; } // Activation APIs protected void activate(ComponentContext componentContext, Map<String, Object> properties) { s_logger.info("Activating..."); // We need to catch the configuration exception and activate anyway. // Otherwise the ConfigurationService will not be able to track us. HashMap<String, Object> decryptedPropertiesMap = new HashMap<String, Object>(); Iterator<String> keys = properties.keySet().iterator(); while (keys.hasNext()) { String key = keys.next(); Object value = properties.get(key); if (key.equals(MQTT_PASSWORD_PROP_NAME)) { try { char[] decryptedPassword = m_cryptoService.decryptAes(value.toString().toCharArray()); decryptedPropertiesMap.put(key, decryptedPassword); } catch (Exception e) { // e.printStackTrace(); decryptedPropertiesMap.put(key, value.toString().toCharArray()); } } else { decryptedPropertiesMap.put(key, value); } } m_properties.putAll(decryptedPropertiesMap); try { m_clientConf = buildConfiguration(m_properties); setupMqttSession(); } catch (RuntimeException e) { s_logger.error("Invalid client configuration. Service will not be able to connect until the configuration is updated", e); } ServiceTracker<DataTransportListener, DataTransportListener> listenersTracker = new ServiceTracker<DataTransportListener, DataTransportListener>( componentContext.getBundleContext(), DataTransportListener.class, null); // Deferred open of tracker to prevent // java.lang.Exception: Recursive invocation of // ServiceFactory.getService // on ProSyst m_dataTransportListeners = new DataTransportListeners(listenersTracker); // Do nothing waiting for the connect request from the upper layer. } protected void deactivate(ComponentContext componentContext) { s_logger.debug("Deactivating..."); // Before deactivating us, the OSGi container should have first // deactivated all dependent components. // They should be able to complete whatever is needed, // e.g. publishing a special last message, // synchronously in their deactivate method and disconnect us cleanly. // There shouldn't be anything to do here other then // perhaps forcibly disconnecting the MQTT client if not already done. if (isConnected()) { disconnect(0); } m_dataTransportListeners.close(); } public void updated(Map<String, Object> properties) { s_logger.info("Updating..."); m_properties.clear(); HashMap<String, Object> decryptedPropertiesMap = new HashMap<String, Object>(); Iterator<String> keys = properties.keySet().iterator(); while (keys.hasNext()) { String key = keys.next(); Object value = properties.get(key); if (key.equals(MQTT_PASSWORD_PROP_NAME)) { try { char[] decryptedPassword = m_cryptoService.decryptAes(value.toString().toCharArray()); decryptedPropertiesMap.put(key, decryptedPassword); } catch (Exception e) { // e.printStackTrace(); decryptedPropertiesMap.put(key, value.toString().toCharArray()); } } else { decryptedPropertiesMap.put(key, value); } } m_properties.putAll(decryptedPropertiesMap); // m_properties.putAll(properties); update(); } private void update() { boolean wasConnected = isConnected(); // First notify the Listeners // We do nothing other than notifying the listeners which may later // request to disconnect and reconnect again. m_dataTransportListeners.onConfigurationUpdating(wasConnected); // Then update the configuration // Throwing a RuntimeException here is fine. // Listeners will not be notified of an invalid configuration update. s_logger.info("Building new configuration..."); m_clientConf = buildConfiguration(m_properties); // We do nothing other than notifying the listeners which may later // request to disconnect and reconnect again. m_dataTransportListeners.onConfigurationUpdated(wasConnected); } // Service APIs public synchronized void connect() throws KuraConnectException { // We treat this as an application bug. if (isConnected()) { s_logger.error("Already connected"); throw new IllegalStateException("Already connected"); // TODO: define an KuraRuntimeException } // Attempt to setup the MQTT session setupMqttSession(); if (m_mqttClient == null) { s_logger.error("Invalid configuration"); throw new IllegalStateException("Invalid configuration"); // TODO: define an KuraRuntimeException } s_logger.info(" s_logger.info("# Connection Properties"); s_logger.info("# broker = " + m_clientConf.getBrokerUrl()); s_logger.info("# clientId = " + m_clientConf.getClientId()); s_logger.info("# username = " + m_clientConf.getConnectOptions().getUserName()); s_logger.info("# password = XXXXXXXXXXXXXX"); s_logger.info("# keepAlive = " + m_clientConf.getConnectOptions().getKeepAliveInterval()); s_logger.info("# timeout = " + m_clientConf.getConnectOptions().getConnectionTimeout()); s_logger.info("# cleanSession = " + m_clientConf.getConnectOptions().isCleanSession()); s_logger.info("# MQTT version = " + getMqttVersionLabel(m_clientConf.getConnectOptions().getMqttVersion())); s_logger.info("# willDestination = " + m_clientConf.getConnectOptions().getWillDestination()); s_logger.info("# willMessage = " + m_clientConf.getConnectOptions().getWillMessage()); s_logger.info(" s_logger.info("# Connecting..."); // connect try { IMqttToken connectToken = m_mqttClient.connect(m_clientConf.getConnectOptions()); connectToken.waitForCompletion(getTimeToWaitMillis() * 3); s_logger.info("# Connected!"); s_logger.info(" } catch (MqttException e) { s_logger.warn("xxxxx Connect failed. Forcing disconnect. xxxxx {}", e); try { // prevent callbacks from a zombie client m_mqttClient.setCallback(null); m_mqttClient.close(); } catch (Exception de) { s_logger.warn("Forced disconnect exception.", de); } finally { m_mqttClient = null; } throw new KuraConnectException(e, "Cannot connect"); } // notify the listeners m_dataTransportListeners.onConnectionEstablished(m_newSession); } public boolean isConnected() { if (m_mqttClient != null) { return m_mqttClient.isConnected(); } return false; } public String getBrokerUrl() { if (m_clientConf != null) { return m_clientConf.getBrokerUrl(); } return ""; } public String getAccountName() { if (m_clientConf != null) { return m_topicContext.get(TOPIC_ACCOUNT_NAME_CTX_NAME); } return ""; } public String getUsername() { if (m_clientConf != null) { return m_clientConf.getConnectOptions().getUserName(); } return ""; } @Override public String getClientId() { if (m_clientConf != null) { return m_clientConf.getClientId(); } return ""; } // TODO: java.lang.reflect.Proxy for every listener in order to catch // runtime exceptions thrown by listener implementor and log them. public synchronized void disconnect(long quiesceTimeout) { // Disconnect the client if it's connected. If it fails log the // exception. // Don't throw an exception because the caller would not // be able to handle it. if (isConnected()) { s_logger.info("Disconnecting..."); // notify the listeners m_dataTransportListeners.onDisconnecting(); try { IMqttToken token = m_mqttClient.disconnect(quiesceTimeout); token.waitForCompletion(getTimeToWaitMillis()); s_logger.info("Disconnected"); } catch (MqttException e) { s_logger.error("Disconnect failed", e); } // notify the listeners m_dataTransportListeners.onDisconnected(); } else { s_logger.warn("MQTT client already disconnected"); } } // Subscription Management Methods @Override public void subscribe(String topic, int qos) throws KuraTimeoutException, KuraException, KuraNotConnectedException { if (m_mqttClient == null || !m_mqttClient.isConnected()) { throw new KuraNotConnectedException("Not connected"); } topic = replaceTopicVariables(topic); s_logger.info("Subscribing to topic: {} with QoS: {}", topic, qos); try { IMqttToken token = m_mqttClient.subscribe(topic, qos); token.waitForCompletion(getTimeToWaitMillis()); } catch (MqttException e) { if (e.getReasonCode() == MqttException.REASON_CODE_CLIENT_TIMEOUT) { s_logger.warn("Timeout subscribing to topic: {}", topic); throw new KuraTimeoutException("Timeout subscribing to topic: " + topic, e); } else { s_logger.error("Cannot subscribe to topic: " + topic, e); throw KuraException.internalError(e, "Cannot subscribe to topic: " + topic); } } } @Override public void unsubscribe(String topic) throws KuraTimeoutException, KuraException, KuraNotConnectedException { if (m_mqttClient == null || !m_mqttClient.isConnected()) { throw new KuraNotConnectedException("Not connected"); } topic = replaceTopicVariables(topic); s_logger.info("Unsubscribing to topic: {}", topic); try { IMqttToken token = m_mqttClient.unsubscribe(topic); token.waitForCompletion(getTimeToWaitMillis()); } catch (MqttException e) { if (e.getReasonCode() == MqttException.REASON_CODE_CLIENT_TIMEOUT) { s_logger.warn("Timeout unsubscribing to topic: {}", topic); throw new KuraTimeoutException("Timeout unsubscribing to topic: " + topic, e); } else { s_logger.error("Cannot unsubscribe to topic: " + topic, e); throw KuraException.internalError(e, "Cannot unsubscribe to topic: " + topic); } } } /* * (non-Javadoc) * * @see org.eclipse.kura.data.DataPublisherService#publish(java.lang.String * , byte[], int, boolean) * * DataConnectException this can be easily recovered connecting the service. * TooManyInflightMessagesException the caller SHOULD retry publishing the * message at a later time. RuntimeException (unchecked) all other * unrecoverable faults that are not recoverable by the caller. */ @Override public DataTransportToken publish(String topic, byte[] payload, int qos, boolean retain) throws KuraTooManyInflightMessagesException, KuraException, KuraNotConnectedException { if (m_mqttClient == null || !m_mqttClient.isConnected()) { throw new KuraNotConnectedException("Not connected"); } topic = replaceTopicVariables(topic); s_logger.info("Publishing message on topic: {} with QoS: {}", topic, qos); MqttMessage message = new MqttMessage(); message.setPayload(payload); message.setQos(qos); message.setRetained(retain); Integer messageId = null; try { IMqttDeliveryToken token = m_mqttClient.publish(topic, message); // At present Paho ALWAYS allocates (gets and increments) internally // a message ID, // even for messages published with QoS == 0. // Of course, for QoS == 0 this "internal" message ID will not hit // the wire. // On top of that, messages published with QoS == 0 are confirmed // in the deliveryComplete callback. // Another implementation might behave differently // and only allocate a message ID for messages published with QoS > // We don't want to rely on this and only return and confirm IDs // of messages published with QoS > 0. s_logger.debug("Published message with ID: {}", token.getMessageId()); if (qos > 0) { messageId = Integer.valueOf(token.getMessageId()); } } catch (MqttPersistenceException e) { // This is probably an unrecoverable internal error s_logger.error("Cannot publish on topic: {}", topic, e); throw new IllegalStateException("Cannot publish on topic: " + topic, e); } catch (MqttException e) { if (e.getReasonCode() == MqttException.REASON_CODE_MAX_INFLIGHT) { s_logger.info("Too many inflight messages"); throw new KuraTooManyInflightMessagesException(e, "Too many in-fligh messages"); } else { s_logger.error("Cannot publish on topic: " + topic, e); throw KuraException.internalError(e, "Cannot publish on topic: " + topic); } } DataTransportToken token = null; if (messageId != null) { token = new DataTransportToken(messageId, m_sessionId); } return token; } // MqttCallback methods @Override public void connectionLost(final Throwable cause) { s_logger.warn("Connection Lost", cause); // notify the listeners m_dataTransportListeners.onConnectionLost(cause); } @Override public void deliveryComplete(IMqttDeliveryToken token) { if (token == null) { s_logger.error("null token"); return; } // Weird, tokens related to messages published with QoS > 0 have a null // nested message MqttMessage msg = null; try { msg = token.getMessage(); } catch (MqttException e) { s_logger.error("Cannot get message", e); return; } if (msg != null) { // Note that Paho call this also for messages published with QoS == // We don't want to rely on that and we drop asynchronous confirms // for QoS == 0. int qos = msg.getQos(); if (qos == 0) { s_logger.debug("Ignoring deliveryComplete for messages published with QoS == 0"); return; } } int id = token.getMessageId(); s_logger.debug("Delivery complete for message with ID: {}", id); // FIXME: We should be more selective here and only call the listener // that actually published the message. // Anyway we don't have such a mapping and so the publishers MUST track // their own // identifiers and filter confirms. // FIXME: it can happen that the listener that has published the message // has not come up yet. // This is the scenario: // * Paho has some in-flight messages. // * Kura gets stopped, crashes or the power is removed. // * Kura starts again, Paho connects and restores in-flight messages // from its persistence. // * These messages are delivered (this callback gets called) before the // publisher (also a DataPublisherListener) // * has come up (not yet tracked by the OSGi container). // These confirms will be lost! // notify the listeners DataTransportToken dataPublisherToken = new DataTransportToken(id, m_sessionId); m_dataTransportListeners.onMessageConfirmed(dataPublisherToken); } @Override public void messageArrived(String topic, MqttMessage message) throws Exception { s_logger.debug("Message arrived on topic: {}", topic); // FIXME: we should be more selective here and only call the listeners // actually subscribed to this topic. // Anyway we don't have such a mapping so the listeners are responsible // to filter messages. // FIXME: the same argument about lost confirms applies to arrived // messages. // notify the listeners m_dataTransportListeners.onMessageArrived(topic, message.getPayload(), message.getQos(), message.isRetained()); } private long getTimeToWaitMillis() { // We use the same value for every timeout long timeout = m_clientConf.getConnectOptions().getConnectionTimeout() * 1000L; return timeout; } // SslServiceListener Overrides @Override public void onConfigurationUpdated() { // The SSL service was update, build a new socket connection update(); } /* * This method builds an internal configuration option needed by the client * to connect. The configuration is assembled from various sources: * component configuration, SystemService, NetworkService, etc. The returned * configuration is valid so no further validation is needed. If a valid * configuration cannot be assembled the method throws a RuntimeException * (assuming that this error is unrecoverable). */ private MqttClientConfiguration buildConfiguration(Map<String, Object> properties) { MqttClientConfiguration clientConfiguration = null; MqttConnectOptions conOpt = new MqttConnectOptions(); String clientId = null; String brokerUrl = null; try { // Configure the client ID clientId = (String) properties.get(MQTT_CLIENT_ID_PROP_NAME); if (clientId == null || clientId.trim().length() == 0) { clientId = m_systemService.getPrimaryMacAddress(); } ValidationUtil.notEmptyOrNull(clientId, "clientId"); // replace invalid token in the client ID as it is used as part of // the topicname space clientId = clientId.replace('/', '-'); clientId = clientId.replace('+', '-'); clientId = clientId.replace(' /* // Configure the broker URL brokerUrl = (String) properties.get(MQTT_BROKER_URL_PROP_NAME); ValidationUtil.notEmptyOrNull(brokerUrl, MQTT_BROKER_URL_PROP_NAME); brokerUrl = brokerUrl.trim(); if( isSecuredEnvironment() && brokerUrl.contains(MQTT_SCHEME)){ s_logger.error("ESF requires a secure (mqtts) connection!"); throw KuraException.internalError("ESF requires a secure (mqtts) connection!"); } brokerUrl = brokerUrl.replaceAll("^" + MQTT_SCHEME, "tcp://"); brokerUrl = brokerUrl.replaceAll("^" + MQTTS_SCHEME, "ssl://"); */ // Configure the broker URL //only for demo use: for example with CIAB and auto-signed certificates brokerUrl = (String) properties.get(MQTT_BROKER_URL_PROP_NAME); ValidationUtil.notEmptyOrNull(brokerUrl, MQTT_BROKER_URL_PROP_NAME); brokerUrl = brokerUrl.trim(); brokerUrl = brokerUrl.replaceAll("^" + MQTT_SCHEME, "tcp: brokerUrl = brokerUrl.replaceAll("^" + MQTTS_SCHEME, "ssl: brokerUrl = brokerUrl.replaceAll("/$", ""); ValidationUtil.notEmptyOrNull(brokerUrl, "brokerUrl"); ValidationUtil.notEmptyOrNull((String) properties.get(MQTT_USERNAME_PROP_NAME), MQTT_USERNAME_PROP_NAME); ValidationUtil.notEmptyOrNull(new String((char[]) properties.get(MQTT_PASSWORD_PROP_NAME)), MQTT_PASSWORD_PROP_NAME); ValidationUtil.notNegative((Integer) properties.get(MQTT_KEEP_ALIVE_PROP_NAME), MQTT_KEEP_ALIVE_PROP_NAME); ValidationUtil.notNegative((Integer) properties.get(MQTT_TIMEOUT_PROP_NAME), MQTT_TIMEOUT_PROP_NAME); ValidationUtil.notNull((Boolean) properties.get(MQTT_CLEAN_SESSION_PROP_NAME), MQTT_CLEAN_SESSION_PROP_NAME); conOpt.setUserName((String) properties.get(MQTT_USERNAME_PROP_NAME)); conOpt.setPassword((char[]) properties.get(MQTT_PASSWORD_PROP_NAME)); conOpt.setKeepAliveInterval((Integer) properties.get(MQTT_KEEP_ALIVE_PROP_NAME)); conOpt.setConnectionTimeout((Integer) properties.get(MQTT_TIMEOUT_PROP_NAME)); conOpt.setCleanSession((Boolean) properties.get(MQTT_CLEAN_SESSION_PROP_NAME)); conOpt.setMqttVersion((Integer) properties.get(MQTT_DEFAULT_VERSION_PROP_NAME)); synchronized (m_topicContext) { m_topicContext.clear(); if (properties.get(CLOUD_ACCOUNT_NAME_PROP_NAME) != null) { m_topicContext.put(TOPIC_ACCOUNT_NAME_CTX_NAME, (String) properties.get(CLOUD_ACCOUNT_NAME_PROP_NAME)); } m_topicContext.put(TOPIC_DEVICE_ID_CTX_NAME, clientId); } String willTopic = (String) properties.get(MQTT_LWT_TOPIC_PROP_NAME); if (!(willTopic == null || willTopic.isEmpty())) { int willQos = 0; boolean willRetain = false; String willPayload = (String) properties.get(MQTT_LWT_PAYLOAD_PROP_NAME); if (properties.get(MQTT_LWT_QOS_PROP_NAME) != null) { willQos = (Integer) properties.get(MQTT_LWT_QOS_PROP_NAME); } if (properties.get(MQTT_LWT_RETAIN_PROP_NAME) != null) { willRetain = (Boolean) properties.get(MQTT_LWT_RETAIN_PROP_NAME); } willTopic = replaceTopicVariables(willTopic); byte[] payload = {}; if (willPayload != null && !willPayload.isEmpty()) { try { payload = willPayload.getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { s_logger.error("Unsupported encoding", e); } } conOpt.setWill(willTopic, payload, willQos, willRetain); } } catch (KuraException e) { s_logger.error("Invalid configuration"); throw new IllegalStateException("Invalid MQTT client configuration", e); } // SSL if (brokerUrl.startsWith("ssl")) { try { String alias = m_topicContext.get(TOPIC_ACCOUNT_NAME_CTX_NAME); SSLSocketFactory ssf = m_sslManagerService.getSSLSocketFactory(alias); conOpt.setSocketFactory(ssf); } catch (Exception e) { s_logger.error("SSL setup failed", e); throw new IllegalStateException("SSL setup failed", e); } } String sType = (String) properties.get(PERSISTENCE_TYPE_PROP_NAME); PersistenceType persistenceType = null; if (sType.equals("file")) { persistenceType = PersistenceType.FILE; } else if (sType.equals("memory")) { persistenceType = PersistenceType.MEMORY; } else { throw new IllegalStateException("Invalid MQTT client configuration: persistenceType: " + persistenceType); } clientConfiguration = new MqttClientConfiguration(brokerUrl, clientId, persistenceType, conOpt); return clientConfiguration; } private boolean isSecuredEnvironment() { boolean result = ENV_JAVA_SECURITY != null && ENV_OSGI_FRAMEWORK_SECURITY != null && ENV_OSGI_SIGNED_CONTENT_SUPPORT != null && ENV_OSGI_FRAMEWORK_TRUST_REPOSITORIES != null; return result; } private String replaceTopicVariables(String topic) { boolean found; Matcher topicMatcher = s_topicPattern.matcher(topic); StringBuffer sb = new StringBuffer(); do { found = topicMatcher.find(); if (found) { // By default replace #variable-name (group 0) with itself String replacement = topicMatcher.group(0); // TODO: Try to get variable-name (group 1) from the context String variableName = topicMatcher.group(1); synchronized (m_topicContext) { String value = m_topicContext.get(variableName); if (value != null) { replacement = value; } } // Replace #variable-name with the value of the variable topicMatcher.appendReplacement(sb, replacement); } } while (found); topicMatcher.appendTail(sb); String replacedTopic = sb.toString(); s_logger.debug("Replaced tokens in topic {} with: {}", topic, replacedTopic); return replacedTopic; } private String generateSessionId() { return m_clientConf.getClientId() + "-" + m_clientConf.getBrokerUrl(); } private void setupMqttSession() { if (m_clientConf == null) { throw new IllegalStateException("Invalid client configuration"); } // We need to construct a new client instance only if either the broker URL // or the client ID changes. // We also need to construct a new instance if the persistence type (file or memory) changes. // We MUST avoid to construct a new client instance every time because // in that case the MQTT message ID is reset to 1. if (m_mqttClient != null) { String brokerUrl = m_mqttClient.getServerURI(); String clientId = m_mqttClient.getClientId(); if (!(brokerUrl.equals(m_clientConf.getBrokerUrl()) && clientId.equals(m_clientConf.getClientId()) && m_persistenceType == m_clientConf .getPersistenceType())) { try { s_logger.info("Closing client..."); // prevent callbacks from a zombie client m_mqttClient.setCallback(null); m_mqttClient.close(); s_logger.info("Closed"); } catch (MqttException e) { s_logger.error("Cannot close client", e); } finally { m_mqttClient = null; } } } // Connecting with Clean Session flag set to true always starts // a new session. boolean newSession = m_clientConf.getConnectOptions().isCleanSession(); if (m_mqttClient == null) { s_logger.info("Creating a new client instance"); // Initialize persistence. This is only useful if the client // connects with // Clean Session flag set to false. // Note that when using file peristence, // Paho creates a subdirectory persistence whose name is encoded // like this: // cristiano-tcpbroker-stageeveryware-cloudcom1883/ // So the persistence is per client ID (cristiano) and broker URL. // If we are connecting to a different broker URL or with a // different client ID, // Paho will create a new subdirectory for this MQTT connection. // Closing the old client instance also deletes the associated // persistence subdirectory. // The lesson is: // Reconnecting to the same broker URL with the same client ID will // leverage // Paho persistence and the MQTT message ID is always increased (up // to the its maximum). // Connecting either to a different broker URL or with a different // client ID discards persisted // messages and the MQTT client ID is reset. // We have a problem here where the DataService needs to track // in-flight messages, possibly // across different MQTT connections. // These messages will never be confirmed on a different connection. // While we can assume that the client ID never changes because it's // typically auto-generated, // we cannot safely assume that the broker URL never changes. // The above leads to two problems: // The MQTT message ID alone is not sufficient to track an in-flight // message // because it can be reset on a different connection. // On a different connection the DataService should republish the // in-flight messages because // Paho won't do that. PersistenceType persistenceType = m_clientConf.getPersistenceType(); if (persistenceType == PersistenceType.MEMORY) { s_logger.info("Using memory persistence for in-flight messages"); m_persistence = new MemoryPersistence(); } else { StringBuffer sb = new StringBuffer(); sb.append(m_systemService.getKuraDataDirectory()).append(m_systemService.getFileSeparator()).append("paho-persistence"); String dir = sb.toString(); s_logger.info("Using file persistence for in-flight messages: {}", dir); // Look for "Close on CONNACK timeout" FIXME in this file. // Make sure persistence is closed. // This is needed if the previous connect attempt was // forcibly terminated by closing the client. if (m_persistence != null) { try { m_persistence.close(); } catch (MqttPersistenceException e) { s_logger.info("Failed to close persistence. Ignoring exception " + e.getMessage()); s_logger.debug("Failed to close persistence. Ignoring exception.", e); } } m_persistence = new MqttDefaultFilePersistence(dir); } // Construct the MqttClient instance MqttAsyncClient mqttClient = null; try { mqttClient = new MqttAsyncClient(m_clientConf.getBrokerUrl(), m_clientConf.getClientId(), m_persistence); } catch (MqttException e) { s_logger.error("Client instantiation failed", e); throw new IllegalStateException("Client instantiation failed", e); } mqttClient.setCallback(this); m_persistenceType = persistenceType; m_mqttClient = mqttClient; if (!m_clientConf.getConnectOptions().isCleanSession()) { // This is tricky. // The purpose of this code is to try to restore pending delivery tokens // from the MQTT client persistence and determine if the next connection // can be considered continuing an existing session. // This is needed to allow the upper layer deciding what to do with the // in-flight messages it is tracking (if any). // If pending delivery tokens are found we assume that the upper layer // is tracking them. In this case we set the newSession flag to false // and notify this in the onConnectionEstablished callback. // The upper layer shouldn't do anything special. // Otherwise the next upper layer should decide what to do with the // in-flight messages it is tracking (if any), either to republish or // drop them. IMqttDeliveryToken[] pendingDeliveryTokens = m_mqttClient.getPendingDeliveryTokens(); if (pendingDeliveryTokens != null && pendingDeliveryTokens.length != 0) { newSession = false; } } } m_newSession = newSession; m_sessionId = generateSessionId(); } private String getMqttVersionLabel(int MqttVersion) { switch (MqttVersion) { case MqttConnectOptions.MQTT_VERSION_3_1: return "3.1"; case MqttConnectOptions.MQTT_VERSION_3_1_1: return "3.1.1"; default: return String.valueOf(MqttVersion); } } }
package org.eclipse.kura.linux.net.modem; import java.util.Arrays; import java.util.List; import org.eclipse.kura.linux.net.util.KuraConstants; import org.eclipse.kura.net.modem.ModemTechnologyType; public enum SupportedUsbModemInfo { // device name, vendor, product, ttyDevs, blockDevs, AT Port, Data Port, GPS Port, technology types, device driver Telit_HE910_D ("HE910-D", "1bc7", "0021", 7, 0, 3, 0, 3, Arrays.asList(ModemTechnologyType.HSPA, ModemTechnologyType.UMTS), Arrays.asList(new UsbModemDriver("cdc_acm", "1bc7", "0021"))), Telit_GE910 ("GE910", "1bc7", "0022", 2, 0, 0, 1, 0, Arrays.asList(ModemTechnologyType.GSM_GPRS), Arrays.asList(new UsbModemDriver("cdc_acm", "1bc7", "0022"))), Telit_DE910_DUAL("DE910-DUAL", "1bc7", "1010", 4, 0, 2, 3, 1, Arrays.asList(ModemTechnologyType.EVDO, ModemTechnologyType.CDMA), Arrays.asList(new De910ModemDriver())), Telit_LE910 ("LE910", "1bc7", "1201", 5, 1, 2, 3, 1, Arrays.asList(ModemTechnologyType.LTE, ModemTechnologyType.HSPA, ModemTechnologyType.UMTS), Arrays.asList(new Le910ModemDriver())), Telit_CE910_DUAL("CE910-DUAL", "1bc7", "1011", 2, 0, 1, 1, -1, Arrays.asList(ModemTechnologyType.CDMA), Arrays.asList(new Ce910ModemDriver())), Sierra_MC8775 ("MC8775", "1199", "6812", 3, 0, 2, 0, -1, Arrays.asList(ModemTechnologyType.HSDPA), Arrays.asList(new UsbModemDriver("sierra", "1199", "6812"))), Sierra_MC8790 ("MC8790", "1199", "683c", 7, 0, 3, 4, -1, Arrays.asList(ModemTechnologyType.HSDPA), Arrays.asList(new UsbModemDriver("sierra", "1199", "683c"))), Sierra_USB598 ("USB598", "1199", "0025", 4, 1, 0, 0, -1, Arrays.asList(ModemTechnologyType.EVDO), Arrays.asList(new UsbModemDriver("sierra", "1199", "0025"))); private static final String TARGET_NAME = System.getProperty("target.device"); private String m_deviceName; private String m_vendorId; private String m_productId; private int m_numTtyDevs; private int m_numBlockDevs; private int m_atPort; private int m_dataPort; private int m_gpsPort; private List<ModemTechnologyType> m_technologyTypes; private List<? extends UsbModemDriver> m_deviceDrivers; private SupportedUsbModemInfo(String deviceName, String vendorId, String productId, int numTtyDevs, int numBlockDevs, int atPort, int dataPort, int gpsPort, List<ModemTechnologyType> modemTechnology, List<? extends UsbModemDriver> drivers) { m_deviceName = deviceName; m_vendorId = vendorId; m_productId = productId; m_numTtyDevs = numTtyDevs; m_numBlockDevs = numBlockDevs; m_atPort = atPort; m_dataPort = dataPort; m_gpsPort = gpsPort; m_technologyTypes = modemTechnology; m_deviceDrivers = drivers; } public String getDeviceName() { return m_deviceName; } public List<? extends UsbModemDriver> getDeviceDrivers() { return m_deviceDrivers; } public String getVendorId() { return m_vendorId; } public String getProductId() { return m_productId; } public int getNumTtyDevs() { int ret = m_numTtyDevs; if ((TARGET_NAME != null) && (TARGET_NAME.equals(KuraConstants.ReliaGATE_15_10.getTargetName()) || TARGET_NAME.equals(KuraConstants.ReliaGATE_50_21_Ubuntu.getTargetName())) && m_deviceName.equals(Telit_LE910.m_deviceName)) { ret = m_numTtyDevs+2; } return ret; } public int getNumBlockDevs() { return m_numBlockDevs; } public int getAtPort() { int ret = m_atPort; if ((TARGET_NAME != null) && (TARGET_NAME.equals(KuraConstants.ReliaGATE_15_10.getTargetName()) || TARGET_NAME.equals(KuraConstants.ReliaGATE_50_21_Ubuntu.getTargetName())) && m_deviceName.equals(Telit_LE910.m_deviceName)) { ret = m_atPort+2; } return ret; } public int getDataPort() { int ret = m_dataPort; if ((TARGET_NAME != null) && (TARGET_NAME.equals(KuraConstants.ReliaGATE_15_10.getTargetName()) || TARGET_NAME.equals(KuraConstants.ReliaGATE_50_21_Ubuntu.getTargetName())) && m_deviceName.equals(Telit_LE910.m_deviceName)) { ret = m_dataPort+2; } return ret; } public int getGpsPort() { int ret = m_gpsPort; if ((TARGET_NAME != null) && (TARGET_NAME.equals(KuraConstants.ReliaGATE_15_10.getTargetName()) || TARGET_NAME.equals(KuraConstants.ReliaGATE_50_21_Ubuntu.getTargetName())) && m_deviceName.equals(Telit_LE910.m_deviceName)) { ret = m_gpsPort+2; } return ret; } public List<ModemTechnologyType> getTechnologyTypes() { return m_technologyTypes; } }
package org.languagetool.tokenizers.uk; import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; import java.util.StringTokenizer; import org.languagetool.tokenizers.Tokenizer; /** * Tokenizes a sentence into words. * Punctuation and whitespace gets its own token. * Specific to Ukrainian: apostrophes (0x27 and U+2019) not in the list as they are part of the word * * @author Andriy Rysin */ public class UkrainianWordTokenizer implements Tokenizer { private static final String SPLIT_CHARS = "\u0020\u00A0\u115f\u1160\u1680" + "\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007" + "\u2008\u2009\u200A\u200B\u200c\u200d\u200e\u200f" + "\u2028\u2029\u202a\u202b\u202c\u202d\u202e\u202f" + "\u205F\u2060\u2061\u2062\u2063\u206A\u206b\u206c\u206d" + "\u206E\u206F\u3000\u3164\ufeff\uffa0\ufff9\ufffa\ufffb" + ",.;()[]{}<>!?:/|\\\"«»„”“`´‘‛′…¿¡\t\n\r"; // decimal comma between digits private static final Pattern DECIMAL_COMMA_PATTERN = Pattern.compile("([\\d]),([\\d])", Pattern.CASE_INSENSITIVE|Pattern.UNICODE_CASE); private static final char DECIMAL_COMMA_SUBST = '_'; // some unused character to hide comma in decimal number temporary for tokenizer run private static final Pattern DATE_PATTERN = Pattern.compile("([\\d]{2})\\.([\\d]{2})\\.([\\d]{4})", Pattern.CASE_INSENSITIVE|Pattern.UNICODE_CASE); private static final char DATE_DOT_SUBST = '\u0001'; // some unused character to hide dot in date temporary for tokenizer run public UkrainianWordTokenizer() { } @Override public List<String> tokenize(String text) { text = cleanup(text); text = DECIMAL_COMMA_PATTERN.matcher(text).replaceAll("$1" + DECIMAL_COMMA_SUBST + "$2"); text = DATE_PATTERN.matcher(text).replaceAll("$1" + DATE_DOT_SUBST + "$2" + DATE_DOT_SUBST + "$3"); List<String> tokenList = new ArrayList<>(); StringTokenizer st = new StringTokenizer(text, SPLIT_CHARS, true); while (st.hasMoreElements()) { String token = st.nextToken(); token = token.replace(DECIMAL_COMMA_SUBST, ','); token = token.replace(DATE_DOT_SUBST, '.'); tokenList.add( token ); } return tokenList; } private static String cleanup(String text) { text = text.replace('’', '\'').replace('ʼ', '\''); if( text.contains("\u0301") || text.contains("\u00AD") ) { text = text.replace("\u0301", "").replace("\u00AD", ""); } return text; } }
package org.sagebionetworks.repo.model.dbo.dao.table; import java.io.IOException; import java.util.Collection; import java.util.ConcurrentModificationException; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.sagebionetworks.repo.model.ConflictingUpdateException; import org.sagebionetworks.repo.model.dao.table.RowAccessor; import org.sagebionetworks.repo.model.dao.table.RowHandler; import org.sagebionetworks.repo.model.dao.table.RowSetAccessor; import org.sagebionetworks.repo.model.dao.table.TableRowCache; import org.sagebionetworks.repo.model.dbo.persistence.table.DBOTableIdSequence; import org.sagebionetworks.repo.model.dbo.persistence.table.DBOTableRowChange; import org.sagebionetworks.repo.model.table.ColumnModel; import org.sagebionetworks.repo.model.table.CurrentRowCacheStatus; import org.sagebionetworks.repo.model.table.Row; import org.sagebionetworks.repo.model.table.RowReference; import org.sagebionetworks.repo.model.table.RowReferenceSet; import org.sagebionetworks.repo.model.table.RowSet; import org.sagebionetworks.repo.model.table.TableRowChange; import org.sagebionetworks.repo.web.NotFoundException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.RowMapper; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import com.google.common.base.Predicate; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.HashMultimap; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Multimap; import com.google.common.collect.SetMultimap; import com.google.common.collect.Sets; /** * Basic S3 & RDS implementation of the TableRowTruthDAO. * * @author John * */ public class CachingTableRowTruthDAOImpl extends TableRowTruthDAOImpl { private static Logger log = LogManager.getLogger(CachingTableRowTruthDAOImpl.class); @Autowired private TableRowCache tableRowCache; /** * Check for a row level conflicts in the passed change sets, by scanning each row of each change set and looking * for the intersection with the passed row Ids. * * @param tableId * @param delta * @param coutToReserver * @throws ConflictingUpdateException when a conflict is found */ @Override public void checkForRowLevelConflict(String tableId, RowSet delta) throws IOException { if (checkAndUpdateCurrentRowCache(tableId)) { checkForRowLevelConflictUsingCache(tableId, delta); } else { // Validate that this update does not contain any row level conflicts. super.checkForRowLevelConflict(tableId, delta); } } private boolean checkAndUpdateCurrentRowCache(String tableId) { try { if (tableRowCache.isEnabled()) { // Lookup the version number for this update. CurrentRowCacheStatus currentStatus = tableRowCache.getLatestCurrentVersionNumber(tableId); // Check each version greater than the version for the etag (must do this in ascending order) List<TableRowChange> changes = currentStatus.getLatestCachedVersionNumber() == null ? listRowSetsKeysForTable(tableId) : listRowSetsKeysForTableGreaterThanVersion(tableId, currentStatus.getLatestCachedVersionNumber()); long newLastCurrentVersion = -1L; for (TableRowChange change : changes) { newLastCurrentVersion = Math.max(newLastCurrentVersion, change.getRowVersion()); final Map<Long, Long> rowIdVersionNumbers = Maps.newHashMap(); final List<Row> rows = Lists.newArrayListWithCapacity(change.getRowCount().intValue()); scanChange(new RowHandler() { @Override public void nextRow(Row row) { rowIdVersionNumbers.put(row.getRowId(), row.getVersionNumber()); rows.add(row); } }, change); tableRowCache.updateCurrentVersionNumbers(tableId, rowIdVersionNumbers); } if (newLastCurrentVersion >= 0) { try { tableRowCache.setLatestCurrentVersionNumber(currentStatus, newLastCurrentVersion); } catch (ConcurrentModificationException e) { // in the case of a concurrent update, we don't want to keep retrying. Instead, we fall back to // uncached behaviour for this call log.warn("Concurrent updates of cache: " + e.getMessage()); return false; } } return true; } } catch (Exception e) { log.error("Error updating cache: " + e.getMessage(), e); } return false; } /** * Check for a row level conflicts in the passed change sets, by checking the cache for the latest version of each * row * * @param tableId * @param delta * @param coutToReserver * @throws ConflictingUpdateException when a conflict is found */ private void checkForRowLevelConflictUsingCache(String tableId, RowSet delta) throws IOException { if (delta.getEtag() == null) throw new IllegalArgumentException("RowSet.etag cannot be null when rows are being updated."); // Lookup the version number for this update. long versionOfEtag = getVersionForEtag(tableId, delta.getEtag()); Iterable<Row> updatingRows = Iterables.filter(delta.getRows(), new Predicate<Row>() { @Override public boolean apply(Row row) { return !TableModelUtils.isNullOrInvalid(row.getRowId()); } }); Set<Long> rowToGetVersionsFor = Sets.newHashSet(); for (Row row : updatingRows) { if (!rowToGetVersionsFor.add(row.getRowId())) { // the row id is found twice int the same rowset throw new IllegalArgumentException("The row id " + row.getRowId() + " is included more than once in the rowset"); } } Map<Long, Long> rowIdVersions = tableRowCache.getCurrentVersionNumbers(tableId, rowToGetVersionsFor); for (Map.Entry<Long, Long> entry : rowIdVersions.entrySet()) { if (entry.getValue().longValue() > versionOfEtag) { throw new ConflictingUpdateException("Row id: " + entry.getKey() + " has been changes since last read. Please get the latest value for this row and then attempt to update it again."); } } } @Override public void truncateAllRowData() { super.truncateAllRowData(); if (tableRowCache.isEnabled()) { tableRowCache.truncateAllData(); } } /** * Get the RowSet original for each row referenced. * * @throws NotFoundException */ @Override public List<RowSet> getRowSetOriginals(RowReferenceSet ref) throws IOException, NotFoundException { if (ref == null) throw new IllegalArgumentException("RowReferenceSet cannot be null"); if (ref.getTableId() == null) throw new IllegalArgumentException( "RowReferenceSet.tableId cannot be null"); if (ref.getHeaders() == null) throw new IllegalArgumentException( "RowReferenceSet.headers cannot be null"); if (ref.getRows() == null) throw new IllegalArgumentException( "RowReferenceSet.rows cannot be null"); List<RowSet> results = getRowSetOriginalsFromCache(ref); if (results != null) { return results; } else { return super.getRowSetOriginals(ref); } } private List<RowSet> getRowSetOriginalsFromCache(RowReferenceSet ref) throws IOException, NotFoundException { if (!tableRowCache.isEnabled()) { return null; } SetMultimap<Long, Long> versions = createVersionToRowsMap(ref.getRows()); List<RowSet> results = new LinkedList<RowSet>(); for (Entry<Long, Collection<Long>> versionWithRows : versions.asMap().entrySet()) { Set<Long> rowsToGet = (Set<Long>) versionWithRows.getValue(); Long version = versionWithRows.getKey(); TableRowChange trc = getTableRowChange(ref.getTableId(), version); final Map<Long, Row> resultRows = tableRowCache.getRowsFromCache(ref.getTableId(), version, rowsToGet); if (resultRows.size() != rowsToGet.size()) { // we are still missing some (or all) rows here. Read them from S3 and add to cache final List<Row> rows = Lists.newArrayListWithCapacity(rowsToGet.size() - resultRows.size()); scanChange(new RowHandler() { @Override public void nextRow(Row row) { // Is this a row we are still looking for? if (!resultRows.containsKey(row.getRowId())) { // This is a match rows.add(row); } } }, trc); tableRowCache.putRowsInCache(ref.getTableId(), rows); for (Row row : rows) { if (rowsToGet.contains(row.getRowId())) { resultRows.put(row.getRowId(), row); } } } RowSet thisSet = new RowSet(); thisSet.setTableId(ref.getTableId()); thisSet.setEtag(trc.getEtag()); thisSet.setHeaders(trc.getHeaders()); thisSet.setRows(Lists.newArrayList(resultRows.values())); results.add(thisSet); } return results; } /** * Get the RowSet original for each row referenced. * * @throws NotFoundException */ @Override public Row getRowOriginal(String tableId, final RowReference ref, List<ColumnModel> columns) throws IOException, NotFoundException { if (ref == null) throw new IllegalArgumentException("RowReferenceSet cannot be null"); if (tableId == null) throw new IllegalArgumentException("RowReferenceSet.tableId cannot be null"); // first try to get the row from the cache Row rowResult = tableRowCache.getRowFromCache(tableId, ref.getRowId(), ref.getVersionNumber()); if (rowResult != null) { TableRowChange trc = getTableRowChange(tableId, ref.getVersionNumber()); Map<String, Integer> columnIndexMap = TableModelUtils.createColumnIdToIndexMap(trc); return TableModelUtils.convertToSchemaAndMerge(rowResult, columnIndexMap, columns); } else { return super.getRowOriginal(tableId, ref, columns); } } @Override @Transactional(readOnly = false, propagation = Propagation.REQUIRED) public RowSetAccessor getLatestVersions(String tableId, Set<Long> rowIds, String etag) throws IOException, NotFoundException { if (etag == null) { throw new IllegalArgumentException("A valid etag must be passed in"); } final Map<Long, RowAccessor> rowIdToRowMap; if (checkAndUpdateCurrentRowCache(tableId)) { rowIdToRowMap = getLatestVersionsFromCache(tableId, rowIds); return new RowSetAccessor() { @Override protected Map<Long, RowAccessor> getRowIdToRowMap() { return rowIdToRowMap; } }; } else { return super.getLatestVersions(tableId, rowIds, etag); } } private Map<Long, RowAccessor> getLatestVersionsFromCache(String tableId, Set<Long> rowIds) throws NotFoundException, IOException { Map<Long, Long> currentVersionNumbers = tableRowCache.getCurrentVersionNumbers(tableId, rowIds); Multimap<Long, Long> versions = createVersionToRowsMap(currentVersionNumbers); Map<Long, RowAccessor> rowIdToRowMap = Maps.newHashMap(); for (Entry<Long, Collection<Long>> versionWithRows : versions.asMap().entrySet()) { Collection<Long> rowsToGet = versionWithRows.getValue(); Long version = versionWithRows.getKey(); TableRowChange rowChange = getTableRowChange(tableId, versionWithRows.getKey()); List<String> rowChangeHeaders = rowChange.getHeaders(); for (Row row : tableRowCache.getRowsFromCache(tableId, version, rowsToGet).values()) { appendRowDataToMap(rowIdToRowMap, rowChangeHeaders, row); } } return rowIdToRowMap; } private SetMultimap<Long, Long> createVersionToRowsMap(Map<Long, Long> currentVersionNumbers) { // create a map from version to set of row ids map SetMultimap<Long, Long> versions = HashMultimap.create(); for (Entry<Long, Long> rowVersion : currentVersionNumbers.entrySet()) { versions.put(rowVersion.getValue(), rowVersion.getKey()); } return versions; } private SetMultimap<Long, Long> createVersionToRowsMap(Iterable<RowReference> refs) { // create a map from version to set of row ids map SetMultimap<Long, Long> versions = HashMultimap.create(); for (RowReference ref : refs) { versions.put(ref.getVersionNumber(), ref.getRowId()); } return versions; } }
package classycle; /** * Process command line arguments and options for the main application * {@link Analyser}. * * @author Franz-Josef Elmer */ public class AnalyserCommandLine extends CommandLine { private static final String XML_FILE = "-xmlFile="; private static final String CSV_FILE = "-csvFile="; private static final String TITLE = "-title="; private boolean _packagesOnly; private boolean _raw; private boolean _cycles; private boolean _strong; private String _title; private String _xmlFile; private String _csvFile; public AnalyserCommandLine(String[] args) { super(args); if (_title == null && _classFiles.length > 0) { _title = _classFiles[0]; } } protected void handleOption(String argument) { if (argument.equals("-raw")) { _raw = true; } else if (argument.equals("-packagesOnly")) { _packagesOnly = true; } else if (argument.equals("-cycles")) { _cycles = true; } else if (argument.equals("-strong")) { _strong = true; } else if (argument.startsWith(TITLE)) { _title = argument.substring(TITLE.length()); if (_title.length() == 0) { _valid = false; } } else if (argument.startsWith(XML_FILE)) { _xmlFile = argument.substring(XML_FILE.length()); if (_xmlFile.length() == 0) { _valid = false; } } else if (argument.startsWith(CSV_FILE)) { _csvFile = argument.substring(CSV_FILE.length()); if (_csvFile.length() == 0) { _valid = false; } } else { super.handleOption(argument); } } /** Returns the usage of correct command line arguments and options. */ public String getUsage() { return "[-raw] [-packagesOnly] [-cycles|-strong] " + "[" + XML_FILE + "<file>] [" + CSV_FILE + "<file>] " + "[" + TITLE + "<title>] " + super.getUsage(); } /** Returns <tt>true</tt> if the option <tt>-cycles</tt> has been set. */ public boolean isCycles() { return _cycles; } /** Returns <tt>true</tt> if the option <tt>-package</tt> has been set. */ public boolean isPackagesOnly() { return _packagesOnly; } /** Returns <tt>true</tt> if the option <tt>-raw</tt> has been set. */ public boolean isRaw() { return _raw; } /** Returns <tt>true</tt> if the option <tt>-strong</tt> has been set. */ public boolean isStrong() { return _strong; } /** * Returns the name of the CSV file as defined by the option * <tt>-csvFile</tt>. * @return <tt>null</tt> if undefined. */ public String getCsvFile() { return _csvFile; } /** * Returns the title by the option <tt>-title</tt>. * If undefined {@link #getClassFiles()}<tt>[0]</tt> will be used. * @return String */ public String getTitle() { return _title; } /** * Returns the name of the XML file as defined by the option * <tt>-xmlFile</tt>. * @return <tt>null</tt> if undefined. */ public String getXmlFile() { return _xmlFile; } }
package example; //-*- mode:java; encoding:utf-8 -*- // vim:set fileencoding=utf-8: //@homepage@ import java.awt.*; import java.awt.event.*; import java.beans.*; import java.util.Objects; import javax.swing.*; public final class MainPanel extends JPanel { private final JSplitPane leftPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT); private final JSplitPane rightPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT); private final JSplitPane centerPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT); public MainPanel() { super(new BorderLayout()); //leftPane.setContinuousLayout(true); //rightPane.setContinuousLayout(true); //centerPane.setContinuousLayout(true); leftPane.setTopComponent(new JScrollPane(new JTextArea("aaaaaaa"))); leftPane.setBottomComponent(new JScrollPane(new JTextArea("bbbb"))); rightPane.setTopComponent(new JScrollPane(new JTree())); rightPane.setBottomComponent(new JScrollPane(new JTree())); centerPane.setLeftComponent(leftPane); centerPane.setRightComponent(rightPane); leftPane.setResizeWeight(.5); rightPane.setResizeWeight(.5); centerPane.setResizeWeight(.5); PropertyChangeListener pcl = e -> { if (JSplitPane.DIVIDER_LOCATION_PROPERTY.equals(e.getPropertyName())) { JSplitPane source = (JSplitPane) e.getSource(); int location = ((Integer) e.getNewValue()).intValue(); JSplitPane target = Objects.equals(source, leftPane) ? rightPane : leftPane; if (location != target.getDividerLocation()) { target.setDividerLocation(location); } } }; leftPane.addPropertyChangeListener(pcl); rightPane.addPropertyChangeListener(pcl); add(new JCheckBox(new AbstractAction("setContinuousLayout") { @Override public void actionPerformed(ActionEvent e) { boolean flag = ((JCheckBox) e.getSource()).isSelected(); leftPane.setContinuousLayout(flag); rightPane.setContinuousLayout(flag); centerPane.setContinuousLayout(flag); } }), BorderLayout.NORTH); add(centerPane); setPreferredSize(new Dimension(320, 240)); } public static void main(String... args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { createAndShowGUI(); } }); } public static void createAndShowGUI() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { ex.printStackTrace(); } JFrame frame = new JFrame("@title@"); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.getContentPane().add(new MainPanel()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } }
package xal.tools.apputils.files; import xal.tools.StringJoiner; import java.util.*; import java.util.regex.Pattern; import java.util.regex.Matcher; import java.util.prefs.Preferences; import java.net.*; import java.io.File; import javax.swing.JFileChooser; /** * RecentFileTracker caches recently accessed files into the the user's preferences and has accessors * for getting the recent files and the most recent folder. * * @author tap */ public class RecentFileTracker { /** default buffer size for a tracker */ final static protected int DEFAULT_BUFFER_SIZE = 10; /** pattern for storing the URL spec in a string */ final static private Pattern URL_SPEC_STORE_PATTERN; /** buffer size for this tracker */ final protected int RECENT_URLS_BUFFER_SIZE; /** preferences storage */ final protected Preferences PREFS; /** ID for the preferences */ final protected String PREFERENCE_ID; // static initializer static { URL_SPEC_STORE_PATTERN = Pattern.compile( "\"[^\"]*\"" ); // specs are enclosed within quotes } /** * Primary constructor * @param bufferSize the buffer size of the recent URL specs to cache * @param prefs the preferences used to save the cache of recent URL specs * @param preferenceID the ID of the preference to save */ public RecentFileTracker(final int bufferSize, final Preferences prefs, final String preferenceID) { RECENT_URLS_BUFFER_SIZE = bufferSize; PREFERENCE_ID = preferenceID; PREFS = prefs; } /** * Constructor which generates the preferences from the specified preference node * @param bufferSize the buffer size of the recent URL specs to cache * @param preferenceNode the node used for saving the preference * @param preferenceID the ID of the preference to save */ public RecentFileTracker(final int bufferSize, final Class preferenceNode, final String preferenceID) { this(bufferSize, Preferences.userNodeForPackage(preferenceNode), preferenceID); } /** * Constructor with a default buffer size of 10 * @param preferenceNode the node used for saving the preference * @param preferenceID the ID of the preference to save */ public RecentFileTracker(final Class preferenceNode, final String preferenceID) { this(DEFAULT_BUFFER_SIZE, preferenceNode, preferenceID); } /** * Clear the cache of the recent URL specs */ public void clearCache() { PREFS.put(PREFERENCE_ID, ""); } /** * Cache the URL of the specified file. * @param file the file whose URL is to be cached. */ public void cacheURL(File file) { try { cacheURL( file.toURI().toURL() ); } catch(MalformedURLException exception) { final String message = "Exception translating the file: " + file + " to a URL."; throw new RuntimeException(message, exception); } } /** * Cache the URL. * @param url the URL to cache. */ public void cacheURL(URL url) { cacheURL( url.toString() ); } /** * Cache the URL * @param urlSpec the URL Spec to cache. */ public void cacheURL( final String urlSpec ) { final String[] recentURLSpecArray = getRecentURLSpecs(); // get the current list of specs final List<String> recentSpecs = new ArrayList<String>( RECENT_URLS_BUFFER_SIZE ); // hold the new list of specs recentSpecs.add( urlSpec ); // add the new spec as the first item // add the original specs expect for any spec matching the new one to avoid repetitions and don't exceed the buffer size for ( int index = 0 ; index < recentURLSpecArray.length && recentSpecs.size() < RECENT_URLS_BUFFER_SIZE ; index++ ) { final String recentURLSpec = recentURLSpecArray[index]; if ( !recentSpecs.contains( recentURLSpec ) ) { // make sure we don't repeat the new spec recentSpecs.add( recentURLSpec ); // add the spec } } // create a new array with the recent specs encoded final List<String> recentEncodedSpecs = new ArrayList<String>( recentSpecs.size() ); for ( final String spec : recentSpecs ) { recentEncodedSpecs.add( encodeItem( spec ) ); } // merge the specs into a single comma delimited string final StringJoiner joiner = new StringJoiner(","); joiner.append( recentEncodedSpecs.toArray() ); // record the preference PREFS.put( PREFERENCE_ID, joiner.toString() ); } /** encode the item for caching */ static private String encodeItem( final String item ) { return "\"" + item + "\""; // place quotes around the item } /** decode the encoded item */ static private String decodeItem( final String encodedItem ) { if ( encodedItem == null || encodedItem.length() == 0 ) return null; final int encodedLength = encodedItem.length(); if ( encodedLength > 2 && encodedItem.startsWith( "\"" ) && encodedItem.endsWith( "\"" ) ) { return encodedItem.substring( 1, encodedLength - 1 ); // strip the starting and ending quotes } else { return null; } } /** * Get the array of URLs corresponding to recently registered URLs. Fetch the recent items from the list saved in the user's preferences for the preference node. * @return The array of recent URLs. */ public String[] getRecentURLSpecs() { final String pathsStr = PREFS.get( PREFERENCE_ID, "" ); // check whether the paths are encoded using the new format ( quotes around each URL Spec ) if ( pathsStr != null && pathsStr.length() > 2 && pathsStr.startsWith( "\"" ) && pathsStr.endsWith( "\"" ) ) { final Matcher matcher = URL_SPEC_STORE_PATTERN.matcher( pathsStr ); final List<String> urlSpecs = new ArrayList<String>(); while ( matcher.find() ) { final String encodedItem = matcher.group(); urlSpecs.add( decodeItem( encodedItem ) ); } return urlSpecs.toArray( new String[urlSpecs.size()] ); } else { return getTokens( pathsStr, "," ); // old format uses comma delimited items } } /** * Get the folder corresponding to the most recently cached URL. * @return the most recent folder accessed */ public File getRecentFolder() { final File recentFile = getMostRecentFile(); return recentFile != null ? recentFile.getParentFile() : null; } /** * Get the folder path corresponding to the most recently cached URL. * @return path to the most recent folder accessed or null if none has been accessed */ public String getRecentFolderPath() { final File recentFolder = getRecentFolder(); return recentFolder != null ? recentFolder.getPath() : null; } /** * Get the most recent file * @return the most recently accessed file. */ public File getMostRecentFile() { final String[] recentURLSpecs = getRecentURLSpecs(); final String recentSpec = recentURLSpecs.length > 0 ? recentURLSpecs[0] : null; try { if ( recentSpec != null ) { final URL recentURL = new URL( recentSpec ); return new File( recentURL.toURI() ); } else { return null; } } catch( Exception exception ) { exception.printStackTrace(); return null; } } /** * Set the file chooser's current directory to the recent folder. * @param fileChooser the file chooser for which to set the current directory * @return the file chooser (same as the argument) */ public JFileChooser applyRecentFolder(final JFileChooser fileChooser) { final File recentFolder = getRecentFolder(); if ( recentFolder != null ) { fileChooser.setCurrentDirectory(recentFolder); } return fileChooser; } /** * Set the file chooser's selected file to the most recent file. * @param fileChooser the file chooser for which to set the current directory * @return the file chooser (same as the argument) */ public JFileChooser applyMostRecentFile( final JFileChooser fileChooser ) { final File recentFile = getMostRecentFile(); if ( recentFile != null && recentFile.exists() ) { fileChooser.setSelectedFile( recentFile ); } return fileChooser; } /** * Parse a string into tokens where whitespace is the delimiter. * @param string The string to parse. * @return The array of tokens. */ static protected String[] getTokens( final String string ) { return getTokens( string, " \t" ); } /** * Parse a string into tokens with the specified delimiter. * @param string The string to parse. * @param delim The delimiter * @return The array of tokens. */ static protected String[] getTokens( final String string, final String delim ) { final StringTokenizer tokenizer = new StringTokenizer(string, delim); final int numTokens = tokenizer.countTokens(); final String[] tokens = new String[ numTokens ]; for ( int index = 0 ; index < numTokens ; index++ ) { tokens[index] = tokenizer.nextToken(); } return tokens; } }
package com.uservoice.uservoicesdk.ui; import java.util.ArrayList; import java.util.List; import android.content.Context; import android.content.Intent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.TextView; import com.uservoice.uservoicesdk.Config; import com.uservoice.uservoicesdk.InitManager; import com.uservoice.uservoicesdk.R; import com.uservoice.uservoicesdk.Session; import com.uservoice.uservoicesdk.activity.ArticleActivity; import com.uservoice.uservoicesdk.activity.ForumActivity; import com.uservoice.uservoicesdk.activity.SuggestionActivity; import com.uservoice.uservoicesdk.activity.TopicActivity; import com.uservoice.uservoicesdk.model.Article; import com.uservoice.uservoicesdk.model.BaseModel; import com.uservoice.uservoicesdk.model.Forum; import com.uservoice.uservoicesdk.model.Suggestion; import com.uservoice.uservoicesdk.model.Topic; import com.uservoice.uservoicesdk.rest.Callback; public class WelcomeAdapter extends SearchAdapter<BaseModel> implements AdapterView.OnItemClickListener { private static int KB_HEADER = 0; private static int FORUM = 1; private static int TOPIC = 2; private static int LOADING = 3; private static int CONTACT = 4; private static int ARTICLE = 5; private static int SUGGESTION = 6; private List<Topic> topics; private List<Article> articles; private LayoutInflater inflater; private final Context context; private List<Integer> staticRows; public WelcomeAdapter(Context context) { this.context = context; inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); new InitManager(context, new Runnable() { @Override public void run() { notifyDataSetChanged(); // this has to be deferred only because we fall back to clientconfig forum_id loadForum(); } }).init(); loadTopics(); } private boolean shouldShowArticles() { return Session.getInstance().getConfig().getTopicId() != -1 || (topics != null && topics.isEmpty()); } private void loadForum() { Forum.loadForum(Session.getInstance().getConfig().getForumId(), new DefaultCallback<Forum>(context) { @Override public void onModel(Forum model) { Session.getInstance().setForum(model); notifyDataSetChanged(); } }); } private void loadTopics() { final DefaultCallback<List<Article>> articlesCallback = new DefaultCallback<List<Article>>(context) { @Override public void onModel(List<Article> model) { topics = new ArrayList<Topic>(); articles = model; notifyDataSetChanged(); } }; if (Session.getInstance().getConfig().getTopicId() != -1) { Article.loadForTopic(Session.getInstance().getConfig().getTopicId(), articlesCallback); } else { Topic.loadTopics(new DefaultCallback<List<Topic>>(context) { @Override public void onModel(List<Topic> model) { topics = model; if (topics.isEmpty()) { Article.loadAll(articlesCallback); } else { notifyDataSetChanged(); } } }); } } private void computeStaticRows() { if (staticRows == null) { staticRows = new ArrayList<Integer>(); Config config = Session.getInstance().getConfig(); if (config.shouldShowContactUs()) staticRows.add(CONTACT); if (config.shouldShowForum()) staticRows.add(FORUM); if (config.shouldShowKnowledgeBase()) staticRows.add(KB_HEADER); } } @Override public int getCount() { if (Session.getInstance().getClientConfig() == null) { return 1; } else if (searchActive) { return loading ? 1 : searchResults.size(); } else { computeStaticRows(); return staticRows.size() + (Session.getInstance().getConfig().shouldShowKnowledgeBase() ? (topics == null ? 1 : (shouldShowArticles() ? articles.size() : topics.size() + 1)) : 0); } } @Override public Object getItem(int position) { if (searchActive) return loading ? null : searchResults.get(position); computeStaticRows(); if (position < staticRows.size() && staticRows.get(position) == FORUM) return Session.getInstance().getForum(); else if (topics != null && !shouldShowArticles() && position >= staticRows.size() && position - staticRows.size() < topics.size()) return topics.get(position - staticRows.size()); else if (articles != null && shouldShowArticles() && position >= staticRows.size() && position - staticRows.size() < articles.size()) return articles.get(position - staticRows.size()); return null; } @Override public long getItemId(int position) { return position; } @Override public boolean isEnabled(int position) { if (searchActive) return !loading; if (Session.getInstance().getClientConfig() == null) return false; computeStaticRows(); if (position < staticRows.size()) { int type = staticRows.get(position); if (type == KB_HEADER || type == LOADING) return false; } return true; } @Override public View getView(int position, View convertView, ViewGroup parent) { View view = convertView; int type = getItemViewType(position); if (view == null) { if (type == LOADING) view = inflater.inflate(R.layout.loading_item, null); else if (type == FORUM) view = inflater.inflate(android.R.layout.simple_list_item_1, null); else if (type == KB_HEADER) view = inflater.inflate(R.layout.header_item, null); else if (type == TOPIC) view = inflater.inflate(R.layout.topic_item, null); else if (type == CONTACT) view = inflater.inflate(android.R.layout.simple_list_item_1, null); else if (type == ARTICLE) view = inflater.inflate(R.layout.article_item, null); else if (type == SUGGESTION) view = inflater.inflate(R.layout.suggestion_result_item, null); } if (type == FORUM) { TextView textView = (TextView) view.findViewById(android.R.id.text1); textView.setText("Feedback Forum"); } else if (type == KB_HEADER) { TextView textView = (TextView) view.findViewById(R.id.text); textView.setText("KNOWLEDGE BASE"); } else if (type == TOPIC) { Topic topic = (Topic) getItem(position); TextView textView = (TextView) view.findViewById(R.id.topic_name); textView.setText(topic == null ? "All Articles" : topic.getName()); textView = (TextView) view.findViewById(R.id.article_count); if (topic == null) { textView.setVisibility(View.GONE); } else { textView.setVisibility(View.VISIBLE); textView.setText(String.format("%d articles", topic.getNumberOfArticles())); } } else if (type == CONTACT) { TextView textView = (TextView) view.findViewById(android.R.id.text1); textView.setText("Contact Us"); } else if (type == ARTICLE) { TextView textView = (TextView) view.findViewById(R.id.article_name); Article article = (Article) getItem(position); textView.setText(searchActive ? highlightResult(article.getQuestion()) : article.getQuestion()); } else if (type == SUGGESTION) { TextView textView = (TextView) view.findViewById(R.id.suggestion_title); Suggestion suggestion = (Suggestion) getItem(position); textView.setText(highlightResult(suggestion.getTitle())); } return view; } @Override public int getViewTypeCount() { return 7; } @Override public int getItemViewType(int position) { if (Session.getInstance().getClientConfig() == null) return LOADING; if (searchActive) { if (loading) return LOADING; BaseModel model = searchResults.get(position); if (model instanceof Article) return ARTICLE; else if (model instanceof Suggestion) return SUGGESTION; else return LOADING; } computeStaticRows(); if (position < staticRows.size()) { int type = staticRows.get(position); if (type == FORUM && Session.getInstance().getForum() == null) return LOADING; return type; } return topics == null ? LOADING : (shouldShowArticles() ? ARTICLE : TOPIC); } @Override protected void search(String query, Callback<List<BaseModel>> callback) { currentQuery = query; Article.loadInstantAnswers(query, callback); } public void onItemClick(AdapterView<?> parent, View view, int position, long id) { int type = getItemViewType(position); if (type == FORUM) { context.startActivity(new Intent(context, ForumActivity.class)); } else if (type == TOPIC) { Session.getInstance().setTopic((Topic) getItem(position)); context.startActivity(new Intent(context, TopicActivity.class)); } else if (type == ARTICLE) { Session.getInstance().setArticle((Article) getItem(position)); context.startActivity(new Intent(context, ArticleActivity.class)); } else if (type == SUGGESTION) { Session.getInstance().setSuggestion((Suggestion) getItem(position)); context.startActivity(new Intent(context, SuggestionActivity.class)); } } }
package xal.tools.apputils; import java.awt.Color; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.BorderLayout; import java.awt.GridLayout; import java.awt.Frame; import javax.swing.*; import javax.swing.table.*; import java.util.*; import xal.model.probe.Probe; import xal.model.IAlgorithm; import xal.tools.bricks.*; import xal.tools.swing.*; import xal.tools.data.*; import java.beans.*; import java.lang.reflect.*; /** SimpleProbeEditor */ public class SimpleProbeEditor extends JDialog { /** Private serializable version ID */ private static final long serialVersionUID = 1L; /** Table model of ProbeProperty records */ final private KeyValueFilteredTableModel<PropertyRecord> PROPERTY_TABLE_MODEL; /** List of properties that appear in the properties table */ final private List<PropertyRecord> PROBE_PROPERTY_RECORDS; /** Probe that is being edited */ final private Probe PROBE; /* Constructor that takes a window parent * and a probe to fetch properties from */ public SimpleProbeEditor( final Frame owner, final Probe probe ) { super( owner, "Probe Editor", true ); //Set JDialog's owner, title, and modality PROBE = probe; // Set the probe to edit // generate the probe property tree final EditablePropertyContainer probePropertyTree = EditableProperty.getInstanceWithRoot( "Probe", probe ); //System.out.println( probePropertyTree ); PROBE_PROPERTY_RECORDS = PropertyRecord.toRecords( probePropertyTree ); PROPERTY_TABLE_MODEL = new KeyValueFilteredTableModel<>( PROBE_PROPERTY_RECORDS, "displayLabel", "value", "units" ); PROPERTY_TABLE_MODEL.setMatchingKeyPaths( "path" ); // match on the path PROPERTY_TABLE_MODEL.setColumnName( "displayLabel", "Property" ); PROPERTY_TABLE_MODEL.setColumnEditKeyPath( "value", "editable" ); // the value is editable if the record is editable setSize( 600, 600 ); // Set the window size initializeComponents(); // Set up each component in the editor pack(); // Fit the components in the window setLocationRelativeTo( owner ); // Center the editor in relation to the frame that constructed the editor setVisible(true); // Make the window visible } /** * Get the probe to edit * @return probe associated with this editor */ public Probe getProbe() { return PROBE; } /** publish record values to the probe */ private void publishToProbe() { for ( final PropertyRecord record : PROBE_PROPERTY_RECORDS ) { record.publishIfNeeded(); } } /** revert the record values from the probe */ private void revertFromProbe() { for ( final PropertyRecord record : PROBE_PROPERTY_RECORDS ) { record.revertIfNeeded(); } PROPERTY_TABLE_MODEL.fireTableDataChanged(); } /** Initialize the components of the probe editor */ public void initializeComponents() { //main view containing all components final Box mainContainer = new Box( BoxLayout.Y_AXIS ); // button to revert changes back to last saved state final JButton revertButton = new JButton( "Revert" ); revertButton.setToolTipText( "Revert values back to those in probe." ); revertButton.setEnabled( false ); // button to publish changes final JButton publishButton = new JButton( "Publish" ); publishButton.setToolTipText( "Publish values to the probe." ); publishButton.setEnabled( false ); // button to publish changes and dismiss the panel final JButton okayButton = new JButton( "Okay" ); okayButton.setToolTipText( "Publish values to the probe and dismiss the dialog." ); okayButton.setEnabled( true ); //Add the action listener as the ApplyButtonListener revertButton.addActionListener( new ActionListener() { public void actionPerformed( final ActionEvent event ) { revertFromProbe(); revertButton.setEnabled( false ); publishButton.setEnabled( false ); } }); //Add the action listener as the ApplyButtonListener publishButton.addActionListener( new ActionListener() { public void actionPerformed( final ActionEvent event ) { publishToProbe(); revertButton.setEnabled( false ); publishButton.setEnabled( false ); } }); //Add the action listener as the ApplyButtonListener okayButton.addActionListener( new ActionListener() { public void actionPerformed( final ActionEvent event ) { try { publishToProbe(); dispose(); } catch( Exception exception ) { JOptionPane.showMessageDialog( SimpleProbeEditor.this, exception.getMessage(), "Error Publishing", JOptionPane.ERROR_MESSAGE ); System.err.println( "Exception publishing values to probe: " + exception ); } } }); PROPERTY_TABLE_MODEL.addKeyValueRecordListener( new KeyValueRecordListener<KeyValueTableModel<PropertyRecord>,PropertyRecord>() { public void recordModified( final KeyValueTableModel<PropertyRecord> source, final PropertyRecord record, final String keyPath, final Object value ) { revertButton.setEnabled( true ); publishButton.setEnabled( true ); } }); //Table containing the properties that can be modified final JTable propertyTable = new JTable() { /** Serializable version ID */ private static final long serialVersionUID = 1L; /** renderer for a table section */ private final TableCellRenderer SECTION_RENDERER = makeSectionRenderer(); //Get the cell editor for the table @Override public TableCellEditor getCellEditor( final int row, final int col ) { //Value at [row, col] of the table final Object value = getValueAt( row, col ); if ( value == null ) { return super.getCellEditor( row, col ); } else { return getDefaultEditor( value.getClass() ); } } //Get the cell renderer for the table to change how values are displayed @Override public TableCellRenderer getCellRenderer( final int row, final int col ) { // index of the record in the model final int recordIndex = this.convertRowIndexToModel( row ); final PropertyRecord record = PROPERTY_TABLE_MODEL.getRecordAtRow( recordIndex ); final Object value = getValueAt( row, col ); //Set the renderer according to the property type (e.g. Boolean => checkbox display, numeric => right justified) if ( !record.isEditable() ) { return SECTION_RENDERER; } else if ( value == null ) { return super.getCellRenderer( row, col ); } else { return getDefaultRenderer( value.getClass() ); } } private TableCellRenderer makeSectionRenderer() { final DefaultTableCellRenderer renderer = new DefaultTableCellRenderer(); renderer.setBackground( Color.GRAY ); renderer.setForeground( Color.WHITE ); return renderer; } }; //Set the table to allow one-click edit ((DefaultCellEditor) propertyTable.getDefaultEditor(Object.class)).setClickCountToStart(1); //Resize the last column propertyTable.setAutoResizeMode( JTable.AUTO_RESIZE_LAST_COLUMN); //Allow single selection only propertyTable.setSelectionMode( ListSelectionModel.SINGLE_SELECTION ); //Set the model to the table propertyTable.setModel( PROPERTY_TABLE_MODEL ); //Configure the text field to filter the table final JTextField filterTextField = new JTextField(); filterTextField.setMaximumSize( new Dimension( 32000, filterTextField.getPreferredSize().height ) ); filterTextField.putClientProperty( "JTextField.variant", "search" ); filterTextField.putClientProperty( "JTextField.Search.Prompt", "Property Filter" ); PROPERTY_TABLE_MODEL.setInputFilterComponent( filterTextField ); mainContainer.add( filterTextField, BorderLayout.NORTH ); //Add the scrollpane to the table with a vertical scrollbar final JScrollPane scrollPane = new JScrollPane( propertyTable, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED ); mainContainer.add( scrollPane ); //Add the buttons to the bottom of the dialog final Box controlPanel = new Box( BoxLayout.X_AXIS ); controlPanel.add( revertButton ); controlPanel.add( Box.createHorizontalGlue() ); controlPanel.add( publishButton ); controlPanel.add( okayButton ); mainContainer.add( controlPanel ); //Add everything to the dialog add( mainContainer ); } } /** Wraps a property for display as a record in a table */ class PropertyRecord { /** wrapped property */ final private EditableProperty PROPERTY; /** current value which may be pending */ private Object _value; /** indicates that this record has unsaved changes */ private boolean _hasChanges; /** Constructor */ public PropertyRecord( final EditableProperty property ) { PROPERTY = property; // initialize the value and status from the underlying property revert(); } /** name of the property */ public String getName() { return PROPERTY.getName(); } /** Get the path to this property */ public String getPath() { return PROPERTY.getPath(); } /** Get the label for display. */ public String getDisplayLabel() { return isEditable() ? getName() : getPath(); } /** Get the property type */ public Class<?> getPropertyType() { return PROPERTY.getPropertyType(); } /** Get the value for this property */ public Object getValue() { return _value; } /** set the pending value */ public void setValueAsObject( final Object value ) { if ( isEditable() ) { _hasChanges = true; _value = value; } } /** set the pending value */ public void setValue( final boolean value ) { setValueAsObject( Boolean.valueOf( value ) ); } /** Set the pending string value. Most values (except for boolean) are set as string since the table cell editor does so. */ public void setValue( final String value ) { final Class<?> rawType = getPropertyType(); if ( rawType == String.class ) { setValueAsObject( value ); } else { try { final Class<?> type = rawType.isPrimitive() ? _value.getClass() : rawType; // convert to wrapper type (e.g. double.class to Double.class) if necessary final Object objectValue = toObjectOfType( value, type ); setValueAsObject( objectValue ); } catch( Exception exception ) { System.err.println( "Exception: " + exception ); System.err.println( "Error parsing the value: " + value + " as " + rawType ); } } } /** Convert the string to an Object of the specified type */ static private Object toObjectOfType( final String stringValue, final Class<?> type ) { try { // every wrapper class has a static method named "valueOf" that takes a String and returns a corresponding instance of the wrapper final Method converter = type.getMethod( "valueOf", String.class ); return converter.invoke( null, stringValue ); } catch ( Exception exception ) { throw new RuntimeException( "No match to parse string: " + stringValue + " as " + type ); } } /** synonym for isEditable so the table model will work */ public boolean getEditable() { return isEditable(); } /** only primitive properties are editable */ public boolean isEditable() { return PROPERTY.isPrimitive(); } /** indicates whether this record has unpublished changes */ public boolean hasChanges() { return _hasChanges; } /** revert to the property value if this record is editable and has unpublished changes */ public void revertIfNeeded() { if ( isEditable() && hasChanges() ) { revert(); } } /** revert back to the current value of the underlying property */ public void revert() { // the value is only meaningful for primitive properties (only thing we want to display) _value = PROPERTY.isPrimitive() ? PROPERTY.getValue() : null; _hasChanges = false; } /** publish the pending value to the underlying property if editable and marked with unpublished changes */ public void publishIfNeeded() { if ( isEditable() && hasChanges() ) { publish(); } } /** publish the pending value to the underlying property */ public void publish() { PROPERTY.setValue( _value ); _hasChanges = false; } /** Get the units */ public String getUnits() { return PROPERTY.getUnits(); } /** Generate a flat list of records from the given property tree */ static public List<PropertyRecord> toRecords( final EditablePropertyContainer propertyTree ) { final List<PropertyRecord> records = new ArrayList<>(); appendPropertiesToRecords( propertyTree, records ); return records; } /** append the properties in the given tree to the records nesting deeply */ static private void appendPropertiesToRecords( final EditablePropertyContainer propertyTree, final List<PropertyRecord> records ) { records.add( new PropertyRecord( propertyTree ) ); // add the container itself // add all the primitive properties final List<EditablePrimitiveProperty> properties = propertyTree.getChildPrimitiveProperties(); for ( final EditablePrimitiveProperty property : properties ) { records.add( new PropertyRecord( property ) ); } // navigate down through each container and append their sub trees final List<EditablePropertyContainer> containers = propertyTree.getChildPropertyContainers(); for ( final EditablePropertyContainer container : containers ) { appendPropertiesToRecords( container, records ); // add the containers descendents } } } /** base class for a editable property */ abstract class EditableProperty { /** array of classes for which the property can be edited directly */ final static protected Set<Class<?>> EDITABLE_PROPERTY_TYPES = new HashSet<>(); /** property name */ final protected String NAME; /** path to this property */ final protected String PATH; /** target object which is assigned the property */ final protected Object TARGET; /** property descriptor */ final protected PropertyDescriptor PROPERTY_DESCRIPTOR; // static initializer static { // cache the editable properties in a set for quick comparison later final Class<?>[] editablePropertyTypes = { Double.class, Double.TYPE, Float.class, Float.TYPE, Integer.class, Integer.TYPE, Short.class, Short.TYPE, Long.class, Long.TYPE, Boolean.class, Boolean.TYPE, String.class }; for ( final Class<?> type : editablePropertyTypes ) { EDITABLE_PROPERTY_TYPES.add( type ); } } /** Constructor */ protected EditableProperty( final String pathPrefix, final String name, final Object target, final PropertyDescriptor descriptor ) { NAME = name; PATH = pathPrefix != null && pathPrefix.length() > 0 ? pathPrefix + "." + name : name; TARGET = target; PROPERTY_DESCRIPTOR = descriptor; } /** Constructor */ protected EditableProperty( final String pathPrefix, final Object target, final PropertyDescriptor descriptor ) { this( pathPrefix, descriptor.getName(), target, descriptor ); } /** Get an instance starting at the root object */ static public EditablePropertyContainer getInstanceWithRoot( final String name, final Object root ) { return EditablePropertyContainer.getInstanceWithRoot( name, root ); } /** name of the property */ public String getName() { return NAME; } /** Get the path to this property */ public String getPath() { return PATH; } /** Get the property type */ public Class<?> getPropertyType() { return PROPERTY_DESCRIPTOR != null ? PROPERTY_DESCRIPTOR.getPropertyType() : null; } /** Get the value for this property */ public Object getValue() { if ( TARGET != null && PROPERTY_DESCRIPTOR != null ) { final Method getter = PROPERTY_DESCRIPTOR.getReadMethod(); try { return getter.invoke( TARGET ); } catch( Exception exception ) { System.err.println( exception ); return null; } } else { return null; } } /** set the value */ abstract public void setValue( final Object value ); /** Get the units */ public String getUnits() { return null; } /** determine whether the property is a container */ abstract public boolean isContainer(); /** determine whether the property is a primitive */ abstract public boolean isPrimitive(); /* * Get the property descriptors for the given bean info * @param target object for which to get the descriptors * @return the property descriptors for non-null beanInfo otherwise null */ static protected PropertyDescriptor[] getPropertyDescriptors( final Object target ) { if ( target != null ) { final BeanInfo beanInfo = getBeanInfo( target ); return getPropertyDescriptorsForBeanInfo( beanInfo ); } else { return null; } } /* * Get the property descriptors for the given bean info * @param beanInfo bean info * @return the property descriptors for non-null beanInfo otherwise null */ static private PropertyDescriptor[] getPropertyDescriptorsForBeanInfo( final BeanInfo beanInfo ) { return beanInfo != null ? beanInfo.getPropertyDescriptors() : null; } /** Convenience method to get the BeanInfo for an object's class */ static private BeanInfo getBeanInfo( final Object object ) { if ( object != null ) { return getBeanInfoForType( object.getClass() ); } else { return null; } } /** Convenience method to get the BeanInfo for the given type */ static private BeanInfo getBeanInfoForType( final Class<?> propertyType ) { if ( propertyType != null ) { try { return Introspector.getBeanInfo( propertyType ); } catch( IntrospectionException exception ) { return null; } } else { return null; } } /** Get a string represenation of this property */ public String toString() { return getPath(); } } /** editable property representing a primitive that is directly editable */ class EditablePrimitiveProperty extends EditableProperty { /** property's units */ final private String UNITS; /** Constructor */ protected EditablePrimitiveProperty( final String pathPrefix, final Object target, final PropertyDescriptor descriptor ) { super( pathPrefix, target, descriptor ); UNITS = fetchUnits(); } /** fetch the units */ private String fetchUnits() { // form the accessor as get<PropertyName>Units() replacing <PropertyName> with the property's name whose first character is upper case final char[] nameChars = getName().toCharArray(); nameChars[0] = Character.toUpperCase( nameChars[0] ); // capitalize the first character of the name final String propertyName = String.valueOf( nameChars ); // property name whose first character is upper case // first look for a method of the form get<PropertyName>Units() taking no arguments and returning a String final String unitsAccessorName = "get" + propertyName + "Units"; try { final Method unitsAccessor = TARGET.getClass().getMethod( unitsAccessorName ); if ( unitsAccessor.getReturnType() == String.class ) { return (String)unitsAccessor.invoke( TARGET ); } } catch ( NoSuchMethodException exception ) { // fallback look for a method of the form getUnitsForProperty( String name ) returning a String try { final Method unitsAccessor = TARGET.getClass().getMethod( "getUnitsForProperty", String.class ); if ( unitsAccessor.getReturnType() == String.class ) { return (String)unitsAccessor.invoke( TARGET, getName() ); } return ""; } catch( Exception fallbackException ) { return ""; } } catch( Exception exception ) { System.out.println( exception ); return ""; } return ""; } /** determine whether the property is a container */ public boolean isContainer() { return false; } /** determine whether the property is a primitive */ public boolean isPrimitive() { return true; } /** Set the value for this property */ public void setValue( final Object value ) { if ( TARGET != null && PROPERTY_DESCRIPTOR != null ) { final Method setter = PROPERTY_DESCRIPTOR.getWriteMethod(); try { setter.invoke( TARGET, value ); } catch( Exception exception ) { throw new RuntimeException( "Cannot set value " + value + " on target: " + TARGET + " with descriptor: " + PROPERTY_DESCRIPTOR.getName(), exception ); } } else { if ( TARGET == null && PROPERTY_DESCRIPTOR == null ) { throw new RuntimeException( "Cannot set value " + value + " on target because both the target and descriptor are null." ); } else if ( TARGET == null ) { throw new RuntimeException( "Cannot set value " + value + " on target with descriptor: " + PROPERTY_DESCRIPTOR.getName() + " because the target is null." ); } else if ( PROPERTY_DESCRIPTOR == null ) { throw new RuntimeException( "Cannot set value " + value + " on target: " + TARGET + " because the property descriptor is null." ); } } } /** Get the units */ public String getUnits() { return UNITS; } /** Get a string represenation of this property */ public String toString() { return getPath() + ": " + getValue() + " " + getUnits(); } } /** base class for a container of editable properties */ class EditablePropertyContainer extends EditableProperty { /** target for child properties */ final protected Object CHILD_TARGET; /** set of ancestors to reference to prevent cycles */ final private Set<Object> ANCESTORS; /** list of child primitive properties */ protected List<EditablePrimitiveProperty> _childPrimitiveProperties; /** list of child property containers */ protected List<EditablePropertyContainer> _childPropertyContainers; /** Primary Constructor */ protected EditablePropertyContainer( final String pathPrefix, final String name, final Object target, final PropertyDescriptor descriptor, final Object childTarget, final Set<Object> ancestors ) { super( pathPrefix, name, target, descriptor ); CHILD_TARGET = childTarget; ANCESTORS = ancestors; } /** Constructor */ protected EditablePropertyContainer( final String pathPrefix, final Object target, final PropertyDescriptor descriptor, final Object childTarget, final Set<Object> ancestors ) { this( pathPrefix, descriptor.getName(), target, descriptor, childTarget, ancestors ); } /** Constructor */ protected EditablePropertyContainer( final String pathPrefix, final Object target, final PropertyDescriptor descriptor, final Set<Object> ancestors ) { this( pathPrefix, target, descriptor, generateChildTarget( target, descriptor ), ancestors ); } /** Create an instance with the specified root Object */ static public EditablePropertyContainer getInstanceWithRoot( final String name, final Object rootObject ) { final Set<Object> ancestors = new HashSet<Object>(); return new EditablePropertyContainer( "", name, null, null, rootObject, ancestors ); } /** Generat the child target from the target and descriptor */ static private Object generateChildTarget( final Object target, final PropertyDescriptor descriptor ) { try { final Method readMethod = descriptor.getReadMethod(); return readMethod.invoke( target ); } catch( Exception exception ) { return null; } } /** determine whether the property is a container */ public boolean isContainer() { return true; } /** determine whether the property is a primitive */ public boolean isPrimitive() { return false; } /** set the value */ public void setValue( final Object value ) { throw new RuntimeException( "Usupported operation attempting to set the value of the editable property container: " + getPath() + " with value " + value ); } /** determine whether this container has any child properties */ public boolean isEmpty() { return getChildCount() == 0; } /** get the number of child properties */ public int getChildCount() { generateChildPropertiesIfNeeded(); return _childPrimitiveProperties.size() + _childPropertyContainers.size(); } /** Get the child properties */ public List<EditableProperty> getChildProperties() { generateChildPropertiesIfNeeded(); final List<EditableProperty> properties = new ArrayList<>(); properties.addAll( _childPrimitiveProperties ); properties.addAll( _childPropertyContainers ); return properties; } /** Get the list of child primitive properties */ public List<EditablePrimitiveProperty> getChildPrimitiveProperties() { generateChildPropertiesIfNeeded(); return _childPrimitiveProperties; } /** Get the list of child property containers */ public List<EditablePropertyContainer> getChildPropertyContainers() { generateChildPropertiesIfNeeded(); return _childPropertyContainers; } /** generate the child properties if needed */ protected void generateChildPropertiesIfNeeded() { if ( _childPrimitiveProperties == null ) { generateChildProperties(); } } /** Generate the child properties this container's child target */ protected void generateChildProperties() { _childPrimitiveProperties = new ArrayList<>(); _childPropertyContainers = new ArrayList<>(); final PropertyDescriptor[] descriptors = getPropertyDescriptors( CHILD_TARGET ); if ( descriptors != null ) { for ( final PropertyDescriptor descriptor : descriptors ) { if ( descriptor.getPropertyType() != Class.class ) { generateChildPropertyForDescriptor( descriptor ); } } } } /** Generate the child properties starting at the specified descriptor for this container's child target */ protected void generateChildPropertyForDescriptor( final PropertyDescriptor descriptor ) { final Class<?> propertyType = descriptor.getPropertyType(); if ( EDITABLE_PROPERTY_TYPES.contains( propertyType ) ) { // if the property is an editable primitive with both a getter and setter then return the primitive property instance otherwise null final Method getter = descriptor.getReadMethod(); final Method setter = descriptor.getWriteMethod(); if ( getter != null && setter != null ) { _childPrimitiveProperties.add( new EditablePrimitiveProperty( PATH, CHILD_TARGET, descriptor ) ); } return; // reached end of branch so we are done } else if ( propertyType == null ) { return; } else if ( propertyType.isArray() ) { // property is an array // System.out.println( "Property type is array for target: " + CHILD_TARGET + " with descriptor: " + descriptor.getName() ); return; } else { // property is a plain container if ( !ANCESTORS.contains( CHILD_TARGET ) ) { // only propagate down the branch if the targets are unique (avoid cycles) final Set<Object> ancestors = new HashSet<Object>( ANCESTORS ); ancestors.add( CHILD_TARGET ); final EditablePropertyContainer container = new EditablePropertyContainer( PATH, CHILD_TARGET, descriptor, ancestors ); if ( container.getChildCount() > 0 ) { // only care about containers that lead to editable properties _childPropertyContainers.add( container ); } } return; } } /** Get a string represenation of this property */ public String toString() { final StringBuilder buffer = new StringBuilder(); buffer.append( getPath() + ":\n" ); for ( final EditableProperty property : getChildProperties() ) { buffer.append( "\t" + property.toString() + "\n" ); } return buffer.toString(); } } /** container for an editable property that is an array */ class EditableArrayProperty extends EditablePropertyContainer { /** Constructor */ protected EditableArrayProperty( final String pathPrefix, final Object target, final PropertyDescriptor descriptor, final Set<Object> ancestors ) { super( pathPrefix, target, descriptor, ancestors ); } // TODO: complete implementation of array property }
import java.util.*; import java.io.*; public class TronBot { public static void main(String[] args) { //Initialize bot with respect to the Tron Environment. Tron.init(); //We'll want to keep track of the turn number to make debugging easier. int turnNumber = 0; // Execute loop forever (or until game ends) while (true) { //Update turn number: turnNumber++; /* Get an integer map of the field. Each int * can either be Tron.Tile.EMPTY, Tron.Tile.ME, * Tron.Tile.OPPONENT, Tron.Tile.TAKEN_BY_ME, * Tron.Tile.TAKEN_BY_OPPONENT, or Tron.Tile.WALL */ ArrayList<ArrayList<Tron.Tile>> mList = Tron.getMap(); int[][] m = new int[mList.size()][mList.get(0).size()]; for (int i = 0; i < mList.size(); i++) { for (int j = 0; j < mList.get(i).size(); j++) { m[i][j] = mList.get(i).get(j).ordinal(); } } //Let's figure out where we are: int myLocX = 0, myLocY = 0; for(int y = 0; y < 16; y++) { for(int x = 0; x < 16; x++) { //I want to note that this is a little bit of a disgusting way of doing this comparison, and that you should change it later, but Java makes this uglier than C++ if(Tron.Tile.values()[m[y][x]] == Tron.Tile.ME) { myLocX = x; myLocY = y; } } } //Let's find out which directions are safe to go in: boolean [] safe = emptyAdjacentSquares(m, myLocX, myLocY); //Let's look at the counts of empty squares around the possible squares to go to: int [] dirEmptyCount = new int[4]; for(int a = 0; a < 4; a++) { if(safe[a]) { //Get the location we would be in if we went in a certain direction (specified by a). int[] possibleSquare = getLocation(myLocX, myLocY, a); //Make sure that square exists: if(possibleSquare[0] != -1 && possibleSquare[1] != -1) { //Find the squares around that square: boolean [] around = emptyAdjacentSquares(m, possibleSquare[0], possibleSquare[1]); //Count the number of empty squares around that square and set it in our array: dirEmptyCount[a] = 0; for(int b = 0; b < 4; b++) if(around[b]) dirEmptyCount[a]++; } } else dirEmptyCount[a] = 5; //Irrelevant, but we must ensure it's as large as possible because we don't want to go there. } //Log some basic information. Tron.log("-----------------------------------------------------\nDebug for turn #" + turnNumber + ":\n"); for(int a = 0; a < 4; a++) Tron.log("Direction " + stringFromDirection(a) + " is " + (safe[a] ? "safe.\n" : "not safe.\n")); /* Send your move. This can be Tron.Direction.NORTH, * Tron.Direction.SOUTH, Tron.Direction.EAST, or * Tron.Direction.WEST. */ int minVal = 1000, minValLoc = 0; for(int a = 0; a < 4; a++) { if(dirEmptyCount[a] < minVal) { minVal = dirEmptyCount[a]; minValLoc = a; } } Tron.sendMove(Tron.Direction.values()[minValLoc]); } } //Little useful function for debugging, as it will tell us what direction, in words, an integer corresponds to. public static String stringFromDirection(int dir) { return dir == 0 ? "NORTH" : dir == 1 ? "EAST" : dir == 2 ? "SOUTH" : dir == 3 ? "WEST" : "NONSENSE"; } /*This function finds out which squares adjacent to location are empty. It returns in the standard order of NORTH, EAST, SOUTH, and WEST as booleans which are true if the square is empty. Note that this function DOES create dynamic memory. Make sure to delete it when you're done.*/ public static boolean [] emptyAdjacentSquares(int [][] map, int locX, int locY) { boolean [] empty = new boolean[4]; //0 has value empty. empty[0] = locY != 15 && map[locY + 1][locX] == 0; //North empty[1] = locX != 15 && map[locY][locX + 1] == 0; //East empty[2] = locY != 0 && map[locY - 1][locX] == 0; //South empty[3] = locX != 0 && map[locY][locX - 1] == 0; //West return empty; } //This will give us the square we'd get to if we tried to move in direction dir from location. public static int[] getLocation(int locX, int locY, int dir) { if(dir == 0) return locY == 15 ? new int[]{ -1, -1 } : new int[]{ locX, locY + 1 }; if(dir == 1) return locX == 15 ? new int[]{ -1, -1 } : new int[]{ locX + 1, locY }; if(dir == 2) return locY == 0 ? new int[]{ -1, -1 } : new int[]{ locX, locY - 1 }; if(dir == 3) return locX == 0 ? new int[]{ -1, -1 } : new int[]{ locX - 1, locY }; //I hate Java exceptions, so fuck it. Don't give this function anything but 0, 1, 2, or 3. return new int[]{ -1, -1 }; } }
package net.i2p.router; import java.io.FileInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Properties; import net.i2p.I2PAppContext; import net.i2p.util.Log; /** * Fire up multiple routers in the same VM, all with their own RouterContext * (and all that entails). In addition, this creates a root I2PAppContext for * any objects not booted through one of the RouterContexts. Each of these * contexts are configured through a simple properties file (where the name=value * contained in them are used for the context's getProperty(name)). <p /> * * <b>Usage:</b><pre> * MultiRouter globalContextFile routerContextFile[ routerContextFile]* * </pre> * * Each routerContext specified is used to boot up a single router. It is HIGHLY * recommended that those context files contain a few base env properties: <ul> * <li>loggerFilenameOverride=rN/logs/log-router-#.txt</li> * <li>router.configLocation=rN/router.config</li> * </ul> * (where "rN" is an instance number, such as r0 or r9). * Additionally, two other properties might be useful:<ul> * <li>i2p.vmCommSystem=true</li> * <li>i2p.encryption=off</li> * </ul> * The first line tells the router to use an in-VM comm system for sending * messages back and forth between routers (see net.i2p.transport.VMCommSystem), * and the second tells the router to stub out ElGamal, AES, and DSA code, reducing * the CPU load (but obviously making the router incapable of talking to things * that need the encryption enabled). To run a client app through a router that * has i2p.encryption=off, you should also add that line to the client's JVM * (for example, <code>java -Di2p.encryption=off -jar lib/i2ptunnel.jar</code>).<p /> * * The multirouter waits until all of the routers are shut down (which none will * do on their own, so as before, you'll want to kill the proc or ^C it). */ public class MultiRouter { private static Log _log; private static ArrayList _routers = new ArrayList(8); private static I2PAppContext _defaultContext; public static void main(String args[]) { if ( (args == null) || (args.length <= 1) ) { usage(); return; } _defaultContext = new I2PAppContext(getEnv(args[0])); _log = _defaultContext.logManager().getLog(MultiRouter.class); try { Thread.sleep(5*1000); } catch (InterruptedException ie) {} Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { Thread.currentThread().setName("Router* Shutdown"); try { Thread.sleep(120*1000); } catch (InterruptedException ie) {} Runtime.getRuntime().halt(-1); } }); for (int i = 1; i < args.length; i++) { Router router = new Router(getEnv(args[i])); router.setKillVMOnEnd(false); _routers.add(router); _log.info("Router " + i + " created from " + args[i]); try { Thread.sleep(5*1000 + new java.util.Random().nextInt(5)*1000); } catch (InterruptedException ie) {} } for (int i = 0; i < _routers.size(); i++) { ((Router)_routers.get(i)).runRouter(); _log.info("Router " + i + " started"); try { Thread.sleep(4*1000 + new java.util.Random().nextInt(4)*1000); } catch (InterruptedException ie) {} } _log.info("All " + _routers.size() + " routers started up"); waitForCompletion(); } private static Properties getEnv(String filename) { Properties props = new Properties(); try { props.load(new FileInputStream(filename)); return props; } catch (IOException ioe) { ioe.printStackTrace(); return null; } } private static void waitForCompletion() { while (true) { int alive = 0; for (int i = 0; i < _routers.size(); i++) { Router r = (Router)_routers.get(i); if (!r.isAlive()) { if (_log.shouldLog(Log.INFO)) _log.info("Router " + i + " is dead"); } else { alive++; } } if (alive > 0) { try { Thread.sleep(30*1000); } catch (InterruptedException ie) {} } else { break; } } _log.info("All routers shut down"); } private static void usage() { System.err.println("Usage: MultiRouter globalContextFile routerContextFile[ routerContextFile]*"); System.err.println(" The context files contain key=value entries specifying properties"); System.err.println(" to load into the given context. In addition, each routerContextFile"); System.err.println(" in turn is used to boot a router"); } }
// modification, are permitted provided that the following conditions are met: // documentation and/or other materials provided with the distribution. // * Neither the name of the <organization> nor the // names of its contributors may be used to endorse or promote products // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL DAVID J. PEARCE BE LIABLE FOR ANY // DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package wyjc.testing; import static org.junit.Assert.fail; import java.io.File; import org.junit.*; import wyc.WycMain; import wyc.testing.TestUtils; import wyc.util.WycBuildTask; import wyjc.WyjcMain; import wyjc.util.WyjcBuildTask; /** * Run through all valid test cases with verification disabled. Since every test * file is valid, a successful test occurs when the compiler succeeds and, when * executed, the compiled file produces the expected output. Note that an * internal failure does not count as a valid pass, and indicates the test * exposed some kind of compiler bug. * * @author David J. Pearce * */ public class RuntimeValidTests { /** * The directory containing the source files for each test case. Every test * corresponds to a file in this directory. */ public final static String WHILEY_SRC_DIR = "../../tests/valid"; /** * The directory where compiler libraries are stored. This is necessary * since it will contain the Whiley Runtime. */ public final static String WYC_LIB_DIR = "../../lib/"; /** * The path to the Whiley RunTime (WyRT) library. This contains the Whiley * standard library, which includes various helper functions, etc. */ private static String WYRT_PATH; /** * The path to the Whiley-2-Java class files. These are needed so we can * access the JVM compiled version of the Whiley standard library, along * with additional runtime support classes. */ private static final String WYJC_CLASS_DIR="../../modules/wyjc/src/"; private static final String WYBS_CLASS_DIR="../../modules/wybs/src/"; private static final String WYRL_CLASS_DIR="../../modules/wyrl/src/"; static { // The purpose of this is to figure out what the proper name for the // wyrt file is. Since there can be multiple versions of this file, // we're not sure which one to pick. File file = new File(WYC_LIB_DIR); for(String f : file.list()) { if(f.startsWith("wyrt-v")) { WYRT_PATH = WYC_LIB_DIR + f; } } } // Test Harness /** * Compile a syntactically invalid test case with verification enabled. The * expectation is that compilation should fail with an error and, hence, the * test fails if compilation does not. * * @param name * Name of the test to run. This must correspond to a whiley * source file in the <code>WHILEY_SRC_DIR</code> directory. */ protected void runTest(String name) { // this will need to turn on verification at some point. String filename = WHILEY_SRC_DIR + File.separatorChar + name + ".whiley"; int r = compile( "-wd", WHILEY_SRC_DIR, // location of source directory "-cd", WHILEY_SRC_DIR, // location where to place class files "-wp", WYRT_PATH, // add wyrt to whileypath filename); // name of test to compile if (r != WycMain.SUCCESS) { fail("Test failed to compile!"); } else if (r == WycMain.INTERNAL_FAILURE) { fail("Test caused internal failure!"); } String CLASSPATH = CLASSPATH(WHILEY_SRC_DIR, WYJC_CLASS_DIR, WYRL_CLASS_DIR, WYBS_CLASS_DIR); // Second, execute the generated JavaScript Program. String output = TestUtils.exec(CLASSPATH,WHILEY_SRC_DIR,name); // The name of the file which contains the output for this test String sampleOutputFile = WHILEY_SRC_DIR + File.separatorChar + name + ".sysout"; // Third, compare the output! TestUtils.compare(output,sampleOutputFile); } public static int compile(String... args) { return new WyjcMain(new WyjcBuildTask(), WyjcMain.DEFAULT_OPTIONS) .run(args); } public String CLASSPATH(String... components) { String r = ""; boolean firstTime = true; for (String c : components) { if (!firstTime) { r = r + ":"; } firstTime = false; r = r + c; } return r; } // Tests @Test public void Access_Valid_1() { runTest("Access_Valid_1"); } @Test public void Access_Valid_2() { runTest("Access_Valid_2"); } @Ignore("unclassified") @Test public void Assert_Valid_1() { runTest("Assert_Valid_1"); } @Test public void Assume_Valid_1() { runTest("Assume_Valid_1"); } @Test public void Assume_Valid_2() { runTest("Assume_Valid_2"); } @Test public void BoolAssign_Valid_1() { runTest("BoolAssign_Valid_1"); } @Test public void BoolAssign_Valid_2() { runTest("BoolAssign_Valid_2"); } @Test public void BoolAssign_Valid_3() { runTest("BoolAssign_Valid_3"); } @Test public void BoolAssign_Valid_4() { runTest("BoolAssign_Valid_4"); } @Test public void BoolAssign_Valid_5() { runTest("BoolAssign_Valid_5"); } @Test public void BoolAssign_Valid_6() { runTest("BoolAssign_Valid_6"); } @Test public void BoolFun_Valid_1() { runTest("BoolFun_Valid_1"); } @Test public void BoolIfElse_Valid_1() { runTest("BoolIfElse_Valid_1"); } @Test public void BoolIfElse_Valid_2() { runTest("BoolIfElse_Valid_2"); } @Test public void BoolList_Valid_1() { runTest("BoolList_Valid_1"); } @Test public void BoolList_Valid_2() { runTest("BoolList_Valid_2"); } @Test public void BoolList_Valid_3() { runTest("BoolList_Valid_3"); } @Test public void BoolRecord_Valid_1() { runTest("BoolRecord_Valid_1"); } @Test public void BoolRecord_Valid_2() { runTest("BoolRecord_Valid_2"); } @Test public void BoolRequires_Valid_1() { runTest("BoolRequires_Valid_1"); } @Test public void BoolReturn_Valid_1() { runTest("BoolReturn_Valid_1"); } @Test public void Byte_Valid_1() { runTest("Byte_Valid_1"); } @Test public void Byte_Valid_2() { runTest("Byte_Valid_2"); } @Test public void Byte_Valid_3() { runTest("Byte_Valid_3"); } @Test public void Byte_Valid_4() { runTest("Byte_Valid_4"); } @Test public void Byte_Valid_5() { runTest("Byte_Valid_5"); } @Test public void Byte_Valid_6() { runTest("Byte_Valid_6"); } @Test public void Byte_Valid_7() { runTest("Byte_Valid_7"); } @Test public void Byte_Valid_8() { runTest("Byte_Valid_8"); } @Test public void Byte_Valid_9() { runTest("Byte_Valid_9"); } @Test public void Cast_Valid_1() { runTest("Cast_Valid_1"); } @Test public void Cast_Valid_2() { runTest("Cast_Valid_2"); } @Test public void Cast_Valid_3() { runTest("Cast_Valid_3"); } @Test public void Cast_Valid_4() { runTest("Cast_Valid_4"); } @Test public void Cast_Valid_5() { runTest("Cast_Valid_5"); } @Test public void Char_Valid_1() { runTest("Char_Valid_1"); } @Test public void Char_Valid_2() { runTest("Char_Valid_2"); } @Test public void Char_Valid_3() { runTest("Char_Valid_3"); } @Test public void Char_Valid_4() { runTest("Char_Valid_4"); } @Test public void Char_Valid_5() { runTest("Char_Valid_5"); } @Test public void Char_Valid_6() { runTest("Char_Valid_6"); } @Test public void Char_Valid_7() { runTest("Char_Valid_7"); } @Test public void Coercion_Valid_1() { runTest("Coercion_Valid_1"); } @Test public void Coercion_Valid_2() { runTest("Coercion_Valid_2"); } @Test public void Coercion_Valid_3() { runTest("Coercion_Valid_3"); } @Test public void Coercion_Valid_4() { runTest("Coercion_Valid_4"); } @Ignore("unclassified") @Test public void Coercion_Valid_5() { runTest("Coercion_Valid_5"); } @Test public void Coercion_Valid_6() { runTest("Coercion_Valid_6"); } @Test public void Coercion_Valid_7() { runTest("Coercion_Valid_7"); } @Test public void Coercion_Valid_8() { runTest("Coercion_Valid_8"); } @Test public void Complex_Valid_1() { runTest("Complex_Valid_1"); } @Test public void Complex_Valid_2() { runTest("Complex_Valid_2"); } @Ignore("unclassified") @Test public void Complex_Valid_3() { runTest("Complex_Valid_3"); } @Test public void Complex_Valid_4() { runTest("Complex_Valid_4"); } @Ignore("unclassified") @Test public void Complex_Valid_5() { runTest("Complex_Valid_5"); } @Test public void Complex_Valid_6() { runTest("Complex_Valid_6"); } @Ignore("unclassified") @Test public void Constant_Valid_1() { runTest("Constant_Valid_1"); } @Ignore("unclassified") @Test public void Constant_Valid_2() { runTest("Constant_Valid_2"); } @Test public void Constant_Valid_3() { runTest("Constant_Valid_3"); } @Test public void ConstrainedDictionary_Valid_1() { runTest("ConstrainedDictionary_Valid_1"); } @Test public void ConstrainedInt_Valid_1() { runTest("ConstrainedInt_Valid_1"); } @Test public void ConstrainedInt_Valid_10() { runTest("ConstrainedInt_Valid_10"); } @Test public void ConstrainedInt_Valid_11() { runTest("ConstrainedInt_Valid_11"); } @Test public void ConstrainedInt_Valid_12() { runTest("ConstrainedInt_Valid_12"); } @Test public void ConstrainedInt_Valid_13() { runTest("ConstrainedInt_Valid_13"); } @Test public void ConstrainedInt_Valid_14() { runTest("ConstrainedInt_Valid_14"); } @Test public void ConstrainedInt_Valid_15() { runTest("ConstrainedInt_Valid_15"); } @Test public void ConstrainedInt_Valid_16() { runTest("ConstrainedInt_Valid_16"); } @Test public void ConstrainedInt_Valid_17() { runTest("ConstrainedInt_Valid_17"); } @Test public void ConstrainedInt_Valid_18() { runTest("ConstrainedInt_Valid_18"); } @Test public void ConstrainedInt_Valid_19() { runTest("ConstrainedInt_Valid_19"); } @Test public void ConstrainedInt_Valid_2() { runTest("ConstrainedInt_Valid_2"); } @Test public void ConstrainedInt_Valid_20() { runTest("ConstrainedInt_Valid_20"); } @Test public void ConstrainedInt_Valid_21() { runTest("ConstrainedInt_Valid_21"); } @Test public void ConstrainedInt_Valid_22() { runTest("ConstrainedInt_Valid_22"); } @Test public void ConstrainedInt_Valid_23() { runTest("ConstrainedInt_Valid_23"); } @Test public void ConstrainedInt_Valid_3() { runTest("ConstrainedInt_Valid_3"); } @Test public void ConstrainedInt_Valid_4() { runTest("ConstrainedInt_Valid_4"); } @Test public void ConstrainedInt_Valid_5() { runTest("ConstrainedInt_Valid_5"); } @Test public void ConstrainedInt_Valid_6() { runTest("ConstrainedInt_Valid_6"); } @Test public void ConstrainedInt_Valid_7() { runTest("ConstrainedInt_Valid_7"); } @Test public void ConstrainedInt_Valid_8() { runTest("ConstrainedInt_Valid_8"); } @Test public void ConstrainedInt_Valid_9() { runTest("ConstrainedInt_Valid_9"); } @Test public void ConstrainedList_Valid_1() { runTest("ConstrainedList_Valid_1"); } @Test public void ConstrainedList_Valid_10() { runTest("ConstrainedList_Valid_10"); } @Test public void ConstrainedList_Valid_11() { runTest("ConstrainedList_Valid_11"); } @Test public void ConstrainedList_Valid_12() { runTest("ConstrainedList_Valid_12"); } @Test public void ConstrainedList_Valid_13() { runTest("ConstrainedList_Valid_13"); } @Ignore("unclassified") @Test public void ConstrainedList_Valid_14() { runTest("ConstrainedList_Valid_14"); } @Test public void ConstrainedList_Valid_15() { runTest("ConstrainedList_Valid_15"); } @Test public void ConstrainedList_Valid_16() { runTest("ConstrainedList_Valid_16"); } @Test public void ConstrainedList_Valid_17() { runTest("ConstrainedList_Valid_17"); } @Ignore("unclassified") @Test public void ConstrainedList_Valid_18() { runTest("ConstrainedList_Valid_18"); } @Test public void ConstrainedList_Valid_19() { runTest("ConstrainedList_Valid_19"); } @Test public void ConstrainedList_Valid_2() { runTest("ConstrainedList_Valid_2"); } @Test public void ConstrainedList_Valid_20() { runTest("ConstrainedList_Valid_20"); } @Test public void ConstrainedList_Valid_21() { runTest("ConstrainedList_Valid_21"); } @Test public void ConstrainedList_Valid_22() { runTest("ConstrainedList_Valid_22"); } @Test public void ConstrainedList_Valid_23() { runTest("ConstrainedList_Valid_23"); } @Test public void ConstrainedList_Valid_24() { runTest("ConstrainedList_Valid_24"); } @Test public void ConstrainedList_Valid_25() { runTest("ConstrainedList_Valid_25"); } @Test public void ConstrainedList_Valid_26() { runTest("ConstrainedList_Valid_26"); } @Test public void ConstrainedList_Valid_3() { runTest("ConstrainedList_Valid_3"); } @Ignore("unclassified") @Test public void ConstrainedList_Valid_4() { runTest("ConstrainedList_Valid_4"); } @Test public void ConstrainedList_Valid_5() { runTest("ConstrainedList_Valid_5"); } @Ignore("unclassified") @Test public void ConstrainedList_Valid_6() { runTest("ConstrainedList_Valid_6"); } @Test public void ConstrainedList_Valid_7() { runTest("ConstrainedList_Valid_7"); } @Test public void ConstrainedList_Valid_8() { runTest("ConstrainedList_Valid_8"); } @Test public void ConstrainedList_Valid_9() { runTest("ConstrainedList_Valid_9"); } @Ignore("unclassified") @Test public void ConstrainedNegation_Valid_1() { runTest("ConstrainedNegation_Valid_1"); } @Test public void ConstrainedRecord_Valid_1() { runTest("ConstrainedRecord_Valid_1"); } @Test public void ConstrainedRecord_Valid_2() { runTest("ConstrainedRecord_Valid_2"); } @Test public void ConstrainedRecord_Valid_3() { runTest("ConstrainedRecord_Valid_3"); } @Test public void ConstrainedRecord_Valid_4() { runTest("ConstrainedRecord_Valid_4"); } @Test public void ConstrainedRecord_Valid_5() { runTest("ConstrainedRecord_Valid_5"); } @Test public void ConstrainedRecord_Valid_6() { runTest("ConstrainedRecord_Valid_6"); } @Test public void ConstrainedRecord_Valid_7() { runTest("ConstrainedRecord_Valid_7"); } @Test public void ConstrainedRecord_Valid_8() { runTest("ConstrainedRecord_Valid_8"); } @Test public void ConstrainedRecord_Valid_9() { runTest("ConstrainedRecord_Valid_9"); } @Test public void ConstrainedSet_Valid_1() { runTest("ConstrainedSet_Valid_1"); } @Test public void ConstrainedSet_Valid_2() { runTest("ConstrainedSet_Valid_2"); } @Test public void ConstrainedSet_Valid_3() { runTest("ConstrainedSet_Valid_3"); } @Test public void ConstrainedSet_Valid_4() { runTest("ConstrainedSet_Valid_4"); } @Test public void ConstrainedSet_Valid_5() { runTest("ConstrainedSet_Valid_5"); } @Test public void ConstrainedSet_Valid_6() { runTest("ConstrainedSet_Valid_6"); } @Test public void ConstrainedSet_Valid_7() { runTest("ConstrainedSet_Valid_7"); } @Test public void ConstrainedSet_Valid_8() { runTest("ConstrainedSet_Valid_8"); } @Test public void ConstrainedTuple_Valid_1() { runTest("ConstrainedTuple_Valid_1"); } @Ignore("unclassified") @Test public void Contractive_Valid_1() { runTest("Contractive_Valid_1"); } @Test public void Contractive_Valid_2() { runTest("Contractive_Valid_2"); } @Test public void DecimalAssignment_Valid_1() { runTest("DecimalAssignment_Valid_1"); } @Test public void Define_Valid_1() { runTest("Define_Valid_1"); } @Test public void Define_Valid_2() { runTest("Define_Valid_2"); } @Test public void Define_Valid_3() { runTest("Define_Valid_3"); } @Test public void Define_Valid_4() { runTest("Define_Valid_4"); } @Test public void Dictionary_Valid_1() { runTest("Dictionary_Valid_1"); } @Test public void Dictionary_Valid_10() { runTest("Dictionary_Valid_10"); } @Test public void Dictionary_Valid_11() { runTest("Dictionary_Valid_11"); } @Test public void Dictionary_Valid_12() { runTest("Dictionary_Valid_12"); } @Test public void Dictionary_Valid_13() { runTest("Dictionary_Valid_13"); } @Test public void Dictionary_Valid_14() { runTest("Dictionary_Valid_14"); } @Test public void Dictionary_Valid_15() { runTest("Dictionary_Valid_15"); } @Test public void Dictionary_Valid_16() { runTest("Dictionary_Valid_16"); } @Test public void Dictionary_Valid_2() { runTest("Dictionary_Valid_2"); } @Test public void Dictionary_Valid_3() { runTest("Dictionary_Valid_3"); } @Test public void Dictionary_Valid_4() { runTest("Dictionary_Valid_4"); } @Test public void Dictionary_Valid_5() { runTest("Dictionary_Valid_5"); } @Test public void Dictionary_Valid_6() { runTest("Dictionary_Valid_6"); } @Test public void Dictionary_Valid_7() { runTest("Dictionary_Valid_7"); } @Test public void Dictionary_Valid_8() { runTest("Dictionary_Valid_8"); } @Test public void Dictionary_Valid_9() { runTest("Dictionary_Valid_9"); } @Test public void DoWhile_Valid_1() { runTest("DoWhile_Valid_1"); } @Test public void DoWhile_Valid_2() { runTest("DoWhile_Valid_2"); } @Ignore("unclassified") @Test public void DoWhile_Valid_3() { runTest("DoWhile_Valid_3"); } @Test public void DoWhile_Valid_4() { runTest("DoWhile_Valid_4"); } @Test public void EffectiveList_Valid_1() { runTest("EffectiveList_Valid_1"); } @Test public void Ensures_Valid_1() { runTest("Ensures_Valid_1"); } @Test public void Ensures_Valid_2() { runTest("Ensures_Valid_2"); } @Test public void Ensures_Valid_3() { runTest("Ensures_Valid_3"); } @Test public void Ensures_Valid_4() { runTest("Ensures_Valid_4"); } @Test public void Ensures_Valid_5() { runTest("Ensures_Valid_5"); } @Test public void For_Valid_1() { runTest("For_Valid_1"); } @Test public void For_Valid_10() { runTest("For_Valid_10"); } @Test public void For_Valid_11() { runTest("For_Valid_11"); } @Test public void For_Valid_12() { runTest("For_Valid_12"); } @Test public void For_Valid_13() { runTest("For_Valid_13"); } @Test public void For_Valid_14() { runTest("For_Valid_14"); } @Test public void For_Valid_15() { runTest("For_Valid_15"); } @Test public void For_Valid_16() { runTest("For_Valid_16"); } @Test public void For_Valid_17() { runTest("For_Valid_17"); } @Test public void For_Valid_18() { runTest("For_Valid_18"); } @Test public void For_Valid_2() { runTest("For_Valid_2"); } @Test public void For_Valid_3() { runTest("For_Valid_3"); } @Ignore("unclassified") @Test public void For_Valid_4() { runTest("For_Valid_4"); } @Ignore("unclassified") @Test public void For_Valid_5() { runTest("For_Valid_5"); } @Ignore("unclassified") @Test public void For_Valid_6() { runTest("For_Valid_6"); } @Test public void For_Valid_7() { runTest("For_Valid_7"); } @Test public void For_Valid_8() { runTest("For_Valid_8"); } @Ignore("unclassified") @Test public void For_Valid_9() { runTest("For_Valid_9"); } @Test public void FunctionRef_Valid_1() { runTest("FunctionRef_Valid_1"); } @Ignore("unclassified") @Test public void FunctionRef_Valid_2() { runTest("FunctionRef_Valid_2"); } @Ignore("unclassified") @Test public void FunctionRef_Valid_3() { runTest("FunctionRef_Valid_3"); } @Test public void FunctionRef_Valid_4() { runTest("FunctionRef_Valid_4"); } @Test public void FunctionRef_Valid_5() { runTest("FunctionRef_Valid_5"); } @Ignore("unclassified") @Test public void FunctionRef_Valid_6() { runTest("FunctionRef_Valid_6"); } @Test public void FunctionRef_Valid_7() { runTest("FunctionRef_Valid_7"); } @Test public void FunctionRef_Valid_8() { runTest("FunctionRef_Valid_8"); } @Test public void FunctionRef_Valid_9() { runTest("FunctionRef_Valid_9"); } @Test public void Function_Valid_1() { runTest("Function_Valid_1"); } @Test public void Function_Valid_10() { runTest("Function_Valid_10"); } @Ignore("unclassified") @Test public void Function_Valid_11() { runTest("Function_Valid_11"); } @Test public void Function_Valid_12() { runTest("Function_Valid_12"); } @Test public void Function_Valid_13() { runTest("Function_Valid_13"); } @Test public void Function_Valid_14() { runTest("Function_Valid_14"); } @Ignore("unclassified") @Test public void Function_Valid_15() { runTest("Function_Valid_15"); } @Test public void Function_Valid_16() { runTest("Function_Valid_16"); } @Test public void Function_Valid_17() { runTest("Function_Valid_17"); } @Test public void Function_Valid_18() { runTest("Function_Valid_18"); } @Test public void Function_Valid_19() { runTest("Function_Valid_19"); } @Test public void Function_Valid_2() { runTest("Function_Valid_2"); } @Test public void Function_Valid_20() { runTest("Function_Valid_20"); } @Test public void Function_Valid_21() { runTest("Function_Valid_21"); } @Test public void Function_Valid_3() { runTest("Function_Valid_3"); } @Test public void Function_Valid_4() { runTest("Function_Valid_4"); } @Test public void Function_Valid_5() { runTest("Function_Valid_5"); } @Test public void Function_Valid_6() { runTest("Function_Valid_6"); } @Test public void Function_Valid_7() { runTest("Function_Valid_7"); } @Test public void Function_Valid_8() { runTest("Function_Valid_8"); } @Test public void Function_Valid_9() { runTest("Function_Valid_9"); } @Test public void HexAssign_Valid_1() { runTest("HexAssign_Valid_1"); } @Test public void IfElse_Valid_1() { runTest("IfElse_Valid_1"); } @Test public void IfElse_Valid_2() { runTest("IfElse_Valid_2"); } @Test public void IfElse_Valid_3() { runTest("IfElse_Valid_3"); } @Test public void IfElse_Valid_4() { runTest("IfElse_Valid_4"); } @Test public void Import_Valid_1() { runTest("Import_Valid_1"); } @Test public void Import_Valid_2() { runTest("Import_Valid_2"); } @Test public void Import_Valid_3() { runTest("Import_Valid_3"); } @Test public void Import_Valid_4() { runTest("Import_Valid_4"); } @Test public void Import_Valid_5() { runTest("Import_Valid_5"); } @Test public void Import_Valid_6() { runTest("Import_Valid_6"); } @Test public void Import_Valid_7() { runTest("Import_Valid_7"); } @Test public void IntConst_Valid_1() { runTest("IntConst_Valid_1"); } @Test public void IntDefine_Valid_1() { runTest("IntDefine_Valid_1"); } @Test public void IntDefine_Valid_2() { runTest("IntDefine_Valid_2"); } @Test public void IntDiv_Valid_1() { runTest("IntDiv_Valid_1"); } @Test public void IntDiv_Valid_2() { runTest("IntDiv_Valid_2"); } @Ignore("unclassified") @Test public void IntDiv_Valid_3() { runTest("IntDiv_Valid_3"); } @Test public void IntDiv_Valid_4() { runTest("IntDiv_Valid_4"); } @Test public void IntDiv_Valid_5() { runTest("IntDiv_Valid_5"); } @Test public void IntEquals_Valid_1() { runTest("IntEquals_Valid_1"); } @Test public void IntMul_Valid_1() { runTest("IntMul_Valid_1"); } @Test public void IntOp_Valid_1() { runTest("IntOp_Valid_1"); } @Ignore("unclassified") @Test public void Intersection_Valid_1() { runTest("Intersection_Valid_1"); } @Ignore("unclassified") @Test public void Intersection_Valid_2() { runTest("Intersection_Valid_2"); } @Test public void Lambda_Valid_1() { runTest("Lambda_Valid_1"); } @Test public void Lambda_Valid_2() { runTest("Lambda_Valid_2"); } @Test public void Lambda_Valid_3() { runTest("Lambda_Valid_3"); } @Test public void Lambda_Valid_4() { runTest("Lambda_Valid_4"); } @Test public void Lambda_Valid_5() { runTest("Lambda_Valid_5"); } @Test public void Lambda_Valid_6() { runTest("Lambda_Valid_6"); } @Ignore("unclassified") @Test public void Lambda_Valid_7() { runTest("Lambda_Valid_7"); } @Test public void Lambda_Valid_8() { runTest("Lambda_Valid_8"); } @Test public void LengthOf_Valid_1() { runTest("LengthOf_Valid_1"); } @Test public void LengthOf_Valid_2() { runTest("LengthOf_Valid_2"); } @Test public void LengthOf_Valid_3() { runTest("LengthOf_Valid_3"); } @Test public void LengthOf_Valid_4() { runTest("LengthOf_Valid_4"); } @Test public void LengthOf_Valid_5() { runTest("LengthOf_Valid_5"); } @Test public void ListAccess_Valid_1() { runTest("ListAccess_Valid_1"); } @Test public void ListAccess_Valid_2() { runTest("ListAccess_Valid_2"); } @Test public void ListAccess_Valid_3() { runTest("ListAccess_Valid_3"); } @Test public void ListAccess_Valid_4() { runTest("ListAccess_Valid_4"); } @Test public void ListAccess_Valid_5() { runTest("ListAccess_Valid_5"); } @Ignore("unclassified") @Test public void ListAccess_Valid_6() { runTest("ListAccess_Valid_6"); } @Ignore("unclassified") @Test public void ListAccess_Valid_7() { runTest("ListAccess_Valid_7"); } @Ignore("unclassified") @Test public void ListAccess_Valid_8() { runTest("ListAccess_Valid_8"); } @Test public void ListAppend_Valid_1() { runTest("ListAppend_Valid_1"); } @Test public void ListAppend_Valid_10() { runTest("ListAppend_Valid_10"); } @Test public void ListAppend_Valid_11() { runTest("ListAppend_Valid_11"); } @Test public void ListAppend_Valid_12() { runTest("ListAppend_Valid_12"); } @Test public void ListAppend_Valid_13() { runTest("ListAppend_Valid_13"); } @Test public void ListAppend_Valid_14() { runTest("ListAppend_Valid_14"); } @Test public void ListAppend_Valid_2() { runTest("ListAppend_Valid_2"); } @Test public void ListAppend_Valid_3() { runTest("ListAppend_Valid_3"); } @Test public void ListAppend_Valid_4() { runTest("ListAppend_Valid_4"); } @Test public void ListAppend_Valid_5() { runTest("ListAppend_Valid_5"); } @Test public void ListAppend_Valid_6() { runTest("ListAppend_Valid_6"); } @Test public void ListAppend_Valid_7() { runTest("ListAppend_Valid_7"); } @Test public void ListAppend_Valid_8() { runTest("ListAppend_Valid_8"); } @Test public void ListAppend_Valid_9() { runTest("ListAppend_Valid_9"); } @Test public void ListAssign_Valid_1() { runTest("ListAssign_Valid_1"); } @Test public void ListAssign_Valid_10() { runTest("ListAssign_Valid_10"); } @Test public void ListAssign_Valid_11() { runTest("ListAssign_Valid_11"); } @Test public void ListAssign_Valid_12() { runTest("ListAssign_Valid_12"); } @Test public void ListAssign_Valid_2() { runTest("ListAssign_Valid_2"); } @Test public void ListAssign_Valid_3() { runTest("ListAssign_Valid_3"); } @Test public void ListAssign_Valid_4() { runTest("ListAssign_Valid_4"); } @Test public void ListAssign_Valid_5() { runTest("ListAssign_Valid_5"); } @Test public void ListAssign_Valid_6() { runTest("ListAssign_Valid_6"); } @Test public void ListAssign_Valid_7() { runTest("ListAssign_Valid_7"); } @Test public void ListAssign_Valid_8() { runTest("ListAssign_Valid_8"); } @Test public void ListAssign_Valid_9() { runTest("ListAssign_Valid_9"); } @Test public void ListConversion_Valid_1() { runTest("ListConversion_Valid_1"); } @Test public void ListElemOf_Valid_1() { runTest("ListElemOf_Valid_1"); } @Test public void ListEmpty_Valid_1() { runTest("ListEmpty_Valid_1"); } @Test public void ListEquals_Valid_1() { runTest("ListEquals_Valid_1"); } @Test public void ListGenerator_Valid_1() { runTest("ListGenerator_Valid_1"); } @Test public void ListGenerator_Valid_2() { runTest("ListGenerator_Valid_2"); } @Test public void ListGenerator_Valid_3() { runTest("ListGenerator_Valid_3"); } @Test public void ListGenerator_Valid_4() { runTest("ListGenerator_Valid_4"); } @Test public void ListGenerator_Valid_5() { runTest("ListGenerator_Valid_5"); } @Test public void ListLength_Valid_1() { runTest("ListLength_Valid_1"); } @Test public void ListLength_Valid_2() { runTest("ListLength_Valid_2"); } @Test public void ListLength_Valid_3() { runTest("ListLength_Valid_3"); } @Test public void ListRange_Valid_1() { runTest("ListRange_Valid_1"); } @Test public void ListSublist_Valid_1() { runTest("ListSublist_Valid_1"); } @Test public void ListSublist_Valid_2() { runTest("ListSublist_Valid_2"); } @Test public void ListSublist_Valid_3() { runTest("ListSublist_Valid_3"); } @Test public void ListSublist_Valid_4() { runTest("ListSublist_Valid_4"); } @Test public void ListSublist_Valid_5() { runTest("ListSublist_Valid_5"); } @Ignore("unclassified") @Test public void MessageRef_Valid_1() { runTest("MessageRef_Valid_1"); } @Ignore("unclassified") @Test public void MessageRef_Valid_2() { runTest("MessageRef_Valid_2"); } @Test public void MessageSend_Valid_1() { runTest("MessageSend_Valid_1"); } @Test public void MessageSend_Valid_2() { runTest("MessageSend_Valid_2"); } @Test public void MessageSend_Valid_3() { runTest("MessageSend_Valid_3"); } @Test public void MessageSend_Valid_4() { runTest("MessageSend_Valid_4"); } @Test public void MessageSend_Valid_5() { runTest("MessageSend_Valid_5"); } @Test public void MethodCall_Valid_1() { runTest("MethodCall_Valid_1"); } @Test public void MethodCall_Valid_2() { runTest("MethodCall_Valid_2"); } @Test public void MethodCall_Valid_3() { runTest("MethodCall_Valid_3"); } @Ignore("unclassified") @Test public void MethodCall_Valid_4() { runTest("MethodCall_Valid_4"); } @Test public void MethodRef_Valid_1() { runTest("MethodRef_Valid_1"); } @Test public void MethodRef_Valid_2() { runTest("MethodRef_Valid_2"); } @Test public void Method_Valid_1() { runTest("Method_Valid_1"); } @Test public void MultiLineComment_Valid_1() { runTest("MultiLineComment_Valid_1"); } @Test public void MultiLineComment_Valid_2() { runTest("MultiLineComment_Valid_2"); } @Test public void NegationType_Valid_1() { runTest("NegationType_Valid_1"); } @Test public void NegationType_Valid_2() { runTest("NegationType_Valid_2"); } @Ignore("unclassified") @Test public void NegationType_Valid_3() { runTest("NegationType_Valid_3"); } @Test public void NegationType_Valid_4() { runTest("NegationType_Valid_4"); } @Test public void OpenRecord_Valid_1() { runTest("OpenRecord_Valid_1"); } @Test public void OpenRecord_Valid_10() { runTest("OpenRecord_Valid_10"); } @Test public void OpenRecord_Valid_2() { runTest("OpenRecord_Valid_2"); } @Ignore("unclassified") @Test public void OpenRecord_Valid_3() { runTest("OpenRecord_Valid_3"); } @Test public void OpenRecord_Valid_4() { runTest("OpenRecord_Valid_4"); } @Test public void OpenRecord_Valid_5() { runTest("OpenRecord_Valid_5"); } @Test public void OpenRecord_Valid_6() { runTest("OpenRecord_Valid_6"); } @Test public void OpenRecord_Valid_7() { runTest("OpenRecord_Valid_7"); } @Test public void OpenRecord_Valid_8() { runTest("OpenRecord_Valid_8"); } @Test public void OpenRecord_Valid_9() { runTest("OpenRecord_Valid_9"); } @Test public void Print_Valid_1() { runTest("Print_Valid_1"); } @Test public void ProcessAccess_Valid_1() { runTest("ProcessAccess_Valid_1"); } @Test public void ProcessAccess_Valid_2() { runTest("ProcessAccess_Valid_2"); } @Test public void Process_Valid_1() { runTest("Process_Valid_1"); } @Ignore("unclassified") @Test public void Process_Valid_10() { runTest("Process_Valid_10"); } @Test public void Process_Valid_11() { runTest("Process_Valid_11"); } @Test public void Process_Valid_12() { runTest("Process_Valid_12"); } @Test public void Process_Valid_13() { runTest("Process_Valid_13"); } @Test public void Process_Valid_14() { runTest("Process_Valid_14"); } @Test public void Process_Valid_2() { runTest("Process_Valid_2"); } @Test public void Process_Valid_3() { runTest("Process_Valid_3"); } @Test public void Process_Valid_4() { runTest("Process_Valid_4"); } @Test public void Process_Valid_5() { runTest("Process_Valid_5"); } @Test public void Process_Valid_6() { runTest("Process_Valid_6"); } @Test public void Process_Valid_7() { runTest("Process_Valid_7"); } @Test public void Process_Valid_8() { runTest("Process_Valid_8"); } @Test public void Process_Valid_9() { runTest("Process_Valid_9"); } @Test public void Quantifiers_Valid_1() { runTest("Quantifiers_Valid_1"); } @Test public void Range_Valid_1() { runTest("Range_Valid_1"); } @Test public void RealConst_Valid_1() { runTest("RealConst_Valid_1"); } @Test public void RealDiv_Valid_1() { runTest("RealDiv_Valid_1"); } @Test public void RealDiv_Valid_2() { runTest("RealDiv_Valid_2"); } @Test public void RealDiv_Valid_3() { runTest("RealDiv_Valid_3"); } @Test public void RealDiv_Valid_4() { runTest("RealDiv_Valid_4"); } @Test public void RealDiv_Valid_5() { runTest("RealDiv_Valid_5"); } @Test public void RealDiv_Valid_6() { runTest("RealDiv_Valid_6"); } @Test public void RealDiv_Valid_7() { runTest("RealDiv_Valid_7"); } @Test public void RealNeg_Valid_1() { runTest("RealNeg_Valid_1"); } @Test public void RealNeg_Valid_2() { runTest("RealNeg_Valid_2"); } @Test public void RealSplit_Valid_1() { runTest("RealSplit_Valid_1"); } @Test public void RealSub_Valid_1() { runTest("RealSub_Valid_1"); } @Test public void RealSub_Valid_2() { runTest("RealSub_Valid_2"); } @Test public void RealSub_Valid_3() { runTest("RealSub_Valid_3"); } @Test public void Real_Valid_1() { runTest("Real_Valid_1"); } @Test public void RecordAccess_Valid_1() { runTest("RecordAccess_Valid_1"); } @Test public void RecordAccess_Valid_2() { runTest("RecordAccess_Valid_2"); } @Test public void RecordAssign_Valid_1() { runTest("RecordAssign_Valid_1"); } @Test public void RecordAssign_Valid_10() { runTest("RecordAssign_Valid_10"); } @Test public void RecordAssign_Valid_2() { runTest("RecordAssign_Valid_2"); } @Test public void RecordAssign_Valid_3() { runTest("RecordAssign_Valid_3"); } @Test public void RecordAssign_Valid_4() { runTest("RecordAssign_Valid_4"); } @Test public void RecordAssign_Valid_5() { runTest("RecordAssign_Valid_5"); } @Test public void RecordAssign_Valid_6() { runTest("RecordAssign_Valid_6"); } @Test public void RecordAssign_Valid_7() { runTest("RecordAssign_Valid_7"); } @Test public void RecordAssign_Valid_8() { runTest("RecordAssign_Valid_8"); } @Test public void RecordAssign_Valid_9() { runTest("RecordAssign_Valid_9"); } @Test public void RecordCoercion_Valid_1() { runTest("RecordCoercion_Valid_1"); } @Test public void RecordConversion_Valid_1() { runTest("RecordConversion_Valid_1"); } @Test public void RecordDefine_Valid_1() { runTest("RecordDefine_Valid_1"); } @Test public void RecordDefine_Valid_2() { runTest("RecordDefine_Valid_2"); } @Ignore("unclassified") @Test public void RecordSubtype_Valid_1() { runTest("RecordSubtype_Valid_1"); } @Ignore("unclassified") @Test public void RecordSubtype_Valid_2() { runTest("RecordSubtype_Valid_2"); } @Test public void RecursiveType_Valid_1() { runTest("RecursiveType_Valid_1"); } @Test public void RecursiveType_Valid_10() { runTest("RecursiveType_Valid_10"); } @Test public void RecursiveType_Valid_11() { runTest("RecursiveType_Valid_11"); } @Test public void RecursiveType_Valid_12() { runTest("RecursiveType_Valid_12"); } @Test public void RecursiveType_Valid_13() { runTest("RecursiveType_Valid_13"); } @Test public void RecursiveType_Valid_14() { runTest("RecursiveType_Valid_14"); } @Test public void RecursiveType_Valid_15() { runTest("RecursiveType_Valid_15"); } @Test public void RecursiveType_Valid_16() { runTest("RecursiveType_Valid_16"); } @Test public void RecursiveType_Valid_17() { runTest("RecursiveType_Valid_17"); } @Test public void RecursiveType_Valid_18() { runTest("RecursiveType_Valid_18"); } @Test public void RecursiveType_Valid_19() { runTest("RecursiveType_Valid_19"); } @Test public void RecursiveType_Valid_2() { runTest("RecursiveType_Valid_2"); } @Test public void RecursiveType_Valid_20() { runTest("RecursiveType_Valid_20"); } @Test public void RecursiveType_Valid_21() { runTest("RecursiveType_Valid_21"); } @Test public void RecursiveType_Valid_22() { runTest("RecursiveType_Valid_22"); } @Test public void RecursiveType_Valid_23() { runTest("RecursiveType_Valid_23"); } @Test public void RecursiveType_Valid_24() { runTest("RecursiveType_Valid_24"); } @Test public void RecursiveType_Valid_25() { runTest("RecursiveType_Valid_25"); } @Test public void RecursiveType_Valid_26() { runTest("RecursiveType_Valid_26"); } @Test public void RecursiveType_Valid_27() { runTest("RecursiveType_Valid_27"); } @Test public void RecursiveType_Valid_3() { runTest("RecursiveType_Valid_3"); } @Test public void RecursiveType_Valid_4() { runTest("RecursiveType_Valid_4"); } @Ignore("unclassified") @Test public void RecursiveType_Valid_5() { runTest("RecursiveType_Valid_5"); } @Test public void RecursiveType_Valid_6() { runTest("RecursiveType_Valid_6"); } @Test public void RecursiveType_Valid_7() { runTest("RecursiveType_Valid_7"); } @Test public void RecursiveType_Valid_8() { runTest("RecursiveType_Valid_8"); } @Test public void RecursiveType_Valid_9() { runTest("RecursiveType_Valid_9"); } @Test public void Remainder_Valid_1() { runTest("Remainder_Valid_1"); } @Test public void Requires_Valid_1() { runTest("Requires_Valid_1"); } @Test public void Resolution_Valid_1() { runTest("Resolution_Valid_1"); } @Test public void SetAssign_Valid_1() { runTest("SetAssign_Valid_1"); } @Test public void SetAssign_Valid_2() { runTest("SetAssign_Valid_2"); } @Test public void SetAssign_Valid_3() { runTest("SetAssign_Valid_3"); } @Test public void SetComprehension_Valid_1() { runTest("SetComprehension_Valid_1"); } @Test public void SetComprehension_Valid_10() { runTest("SetComprehension_Valid_10"); } @Test public void SetComprehension_Valid_11() { runTest("SetComprehension_Valid_11"); } @Test public void SetComprehension_Valid_12() { runTest("SetComprehension_Valid_12"); } @Test public void SetComprehension_Valid_2() { runTest("SetComprehension_Valid_2"); } @Test public void SetComprehension_Valid_3() { runTest("SetComprehension_Valid_3"); } @Test public void SetComprehension_Valid_4() { runTest("SetComprehension_Valid_4"); } @Test public void SetComprehension_Valid_5() { runTest("SetComprehension_Valid_5"); } @Test public void SetComprehension_Valid_6() { runTest("SetComprehension_Valid_6"); } @Test public void SetComprehension_Valid_7() { runTest("SetComprehension_Valid_7"); } @Test public void SetComprehension_Valid_8() { runTest("SetComprehension_Valid_8"); } @Test public void SetComprehension_Valid_9() { runTest("SetComprehension_Valid_9"); } @Test public void SetConversion_Valid_1() { runTest("SetConversion_Valid_1"); } @Test public void SetDefine_Valid_1() { runTest("SetDefine_Valid_1"); } @Test public void SetDefine_Valid_2() { runTest("SetDefine_Valid_2"); } @Test public void SetDefine_Valid_3() { runTest("SetDefine_Valid_3"); } @Test public void SetDifference_Valid_1() { runTest("SetDifference_Valid_1"); } @Test public void SetElemOf_Valid_1() { runTest("SetElemOf_Valid_1"); } @Test public void SetEmpty_Valid_1() { runTest("SetEmpty_Valid_1"); } @Test public void SetEquals_Valid_1() { runTest("SetEquals_Valid_1"); } @Test public void SetGenerator_Valid_1() { runTest("SetGenerator_Valid_1"); } @Test public void SetIntersect_Valid_1() { runTest("SetIntersect_Valid_1"); } @Test public void SetIntersect_Valid_2() { runTest("SetIntersect_Valid_2"); } @Test public void SetIntersection_Valid_1() { runTest("SetIntersection_Valid_1"); } @Test public void SetIntersection_Valid_2() { runTest("SetIntersection_Valid_2"); } @Test public void SetIntersection_Valid_3() { runTest("SetIntersection_Valid_3"); } @Test public void SetIntersection_Valid_4() { runTest("SetIntersection_Valid_4"); } @Test public void SetIntersection_Valid_5() { runTest("SetIntersection_Valid_5"); } @Test public void SetIntersection_Valid_6() { runTest("SetIntersection_Valid_6"); } @Test public void SetIntersection_Valid_7() { runTest("SetIntersection_Valid_7"); } @Test public void SetLength_Valid_1() { runTest("SetLength_Valid_1"); } @Test public void SetNull_Valid_1() { runTest("SetNull_Valid_1"); } @Test public void SetSubset_Valid_1() { runTest("SetSubset_Valid_1"); } @Test public void SetSubset_Valid_10() { runTest("SetSubset_Valid_10"); } @Test public void SetSubset_Valid_11() { runTest("SetSubset_Valid_11"); } @Test public void SetSubset_Valid_12() { runTest("SetSubset_Valid_12"); } @Test public void SetSubset_Valid_2() { runTest("SetSubset_Valid_2"); } @Test public void SetSubset_Valid_3() { runTest("SetSubset_Valid_3"); } @Test public void SetSubset_Valid_4() { runTest("SetSubset_Valid_4"); } @Test public void SetSubset_Valid_5() { runTest("SetSubset_Valid_5"); } @Test public void SetSubset_Valid_6() { runTest("SetSubset_Valid_6"); } @Test public void SetSubset_Valid_7() { runTest("SetSubset_Valid_7"); } @Test public void SetSubset_Valid_8() { runTest("SetSubset_Valid_8"); } @Test public void SetSubset_Valid_9() { runTest("SetSubset_Valid_9"); } @Test public void SetUnion_Valid_1() { runTest("SetUnion_Valid_1"); } @Test public void SetUnion_Valid_10() { runTest("SetUnion_Valid_10"); } @Test public void SetUnion_Valid_11() { runTest("SetUnion_Valid_11"); } @Test public void SetUnion_Valid_2() { runTest("SetUnion_Valid_2"); } @Test public void SetUnion_Valid_3() { runTest("SetUnion_Valid_3"); } @Test public void SetUnion_Valid_4() { runTest("SetUnion_Valid_4"); } @Test public void SetUnion_Valid_5() { runTest("SetUnion_Valid_5"); } @Test public void SetUnion_Valid_6() { runTest("SetUnion_Valid_6"); } @Test public void SetUnion_Valid_7() { runTest("SetUnion_Valid_7"); } @Test public void SetUnion_Valid_8() { runTest("SetUnion_Valid_8"); } @Test public void SetUnion_Valid_9() { runTest("SetUnion_Valid_9"); } @Test public void SingleLineComment_Valid_1() { runTest("SingleLineComment_Valid_1"); } @Test public void Skip_Valid_1() { runTest("Skip_Valid_1"); } @Test public void String_Valid_1() { runTest("String_Valid_1"); } @Test public void String_Valid_2() { runTest("String_Valid_2"); } @Test public void String_Valid_3() { runTest("String_Valid_3"); } @Test public void String_Valid_4() { runTest("String_Valid_4"); } @Test public void String_Valid_5() { runTest("String_Valid_5"); } @Test public void String_Valid_6() { runTest("String_Valid_6"); } @Test public void String_Valid_7() { runTest("String_Valid_7"); } @Test public void String_Valid_8() { runTest("String_Valid_8"); } @Test public void Subtype_Valid_1() { runTest("Subtype_Valid_1"); } @Test public void Subtype_Valid_10() { runTest("Subtype_Valid_10"); } @Test public void Subtype_Valid_11() { runTest("Subtype_Valid_11"); } @Test public void Subtype_Valid_12() { runTest("Subtype_Valid_12"); } @Test public void Subtype_Valid_13() { runTest("Subtype_Valid_13"); } @Test public void Subtype_Valid_14() { runTest("Subtype_Valid_14"); } @Test public void Subtype_Valid_2() { runTest("Subtype_Valid_2"); } @Test public void Subtype_Valid_3() { runTest("Subtype_Valid_3"); } @Test public void Subtype_Valid_4() { runTest("Subtype_Valid_4"); } @Test public void Subtype_Valid_5() { runTest("Subtype_Valid_5"); } @Test public void Subtype_Valid_6() { runTest("Subtype_Valid_6"); } @Test public void Subtype_Valid_7() { runTest("Subtype_Valid_7"); } @Test public void Subtype_Valid_8() { runTest("Subtype_Valid_8"); } @Test public void Subtype_Valid_9() { runTest("Subtype_Valid_9"); } @Test public void Switch_Valid_1() { runTest("Switch_Valid_1"); } @Test public void Switch_Valid_10() { runTest("Switch_Valid_10"); } @Test public void Switch_Valid_11() { runTest("Switch_Valid_11"); } @Test public void Switch_Valid_12() { runTest("Switch_Valid_12"); } @Test public void Switch_Valid_13() { runTest("Switch_Valid_13"); } @Test public void Switch_Valid_2() { runTest("Switch_Valid_2"); } @Test public void Switch_Valid_3() { runTest("Switch_Valid_3"); } @Ignore("unclassified") @Test public void Switch_Valid_4() { runTest("Switch_Valid_4"); } @Test public void Switch_Valid_5() { runTest("Switch_Valid_5"); } @Test public void Switch_Valid_6() { runTest("Switch_Valid_6"); } @Test public void Switch_Valid_7() { runTest("Switch_Valid_7"); } @Test public void Switch_Valid_8() { runTest("Switch_Valid_8"); } @Test public void Switch_Valid_9() { runTest("Switch_Valid_9"); } @Test public void Syntax_Valid_1() { runTest("Syntax_Valid_1"); } @Test public void TryCatch_Valid_1() { runTest("TryCatch_Valid_1"); } @Test public void TryCatch_Valid_2() { runTest("TryCatch_Valid_2"); } @Test public void TryCatch_Valid_3() { runTest("TryCatch_Valid_3"); } @Test public void TryCatch_Valid_4() { runTest("TryCatch_Valid_4"); } @Test public void TupleType_Valid_1() { runTest("TupleType_Valid_1"); } @Test public void TupleType_Valid_2() { runTest("TupleType_Valid_2"); } @Test public void TupleType_Valid_3() { runTest("TupleType_Valid_3"); } @Test public void TupleType_Valid_4() { runTest("TupleType_Valid_4"); } @Test public void TupleType_Valid_5() { runTest("TupleType_Valid_5"); } @Test public void TupleType_Valid_6() { runTest("TupleType_Valid_6"); } @Test public void TupleType_Valid_7() { runTest("TupleType_Valid_7"); } @Test public void TupleType_Valid_8() { runTest("TupleType_Valid_8"); } @Test public void TypeEquals_Valid_1() { runTest("TypeEquals_Valid_1"); } @Test public void TypeEquals_Valid_10() { runTest("TypeEquals_Valid_10"); } @Test public void TypeEquals_Valid_11() { runTest("TypeEquals_Valid_11"); } @Test public void TypeEquals_Valid_12() { runTest("TypeEquals_Valid_12"); } @Test public void TypeEquals_Valid_13() { runTest("TypeEquals_Valid_13"); } @Test public void TypeEquals_Valid_14() { runTest("TypeEquals_Valid_14"); } @Test public void TypeEquals_Valid_15() { runTest("TypeEquals_Valid_15"); } @Test public void TypeEquals_Valid_16() { runTest("TypeEquals_Valid_16"); } @Test public void TypeEquals_Valid_17() { runTest("TypeEquals_Valid_17"); } @Test public void TypeEquals_Valid_18() { runTest("TypeEquals_Valid_18"); } @Test public void TypeEquals_Valid_19() { runTest("TypeEquals_Valid_19"); } @Test public void TypeEquals_Valid_2() { runTest("TypeEquals_Valid_2"); } @Test public void TypeEquals_Valid_20() { runTest("TypeEquals_Valid_20"); } @Test public void TypeEquals_Valid_21() { runTest("TypeEquals_Valid_21"); } @Test public void TypeEquals_Valid_22() { runTest("TypeEquals_Valid_22"); } @Ignore("unclassified") @Test public void TypeEquals_Valid_23() { runTest("TypeEquals_Valid_23"); } @Test public void TypeEquals_Valid_24() { runTest("TypeEquals_Valid_24"); } @Test public void TypeEquals_Valid_25() { runTest("TypeEquals_Valid_25"); } @Test public void TypeEquals_Valid_26() { runTest("TypeEquals_Valid_26"); } @Test public void TypeEquals_Valid_27() { runTest("TypeEquals_Valid_27"); } @Test public void TypeEquals_Valid_28() { runTest("TypeEquals_Valid_28"); } @Test public void TypeEquals_Valid_29() { runTest("TypeEquals_Valid_29"); } @Ignore("unclassified") @Test public void TypeEquals_Valid_3() { runTest("TypeEquals_Valid_3"); } @Test public void TypeEquals_Valid_30() { runTest("TypeEquals_Valid_30"); } @Test public void TypeEquals_Valid_31() { runTest("TypeEquals_Valid_31"); } @Test public void TypeEquals_Valid_32() { runTest("TypeEquals_Valid_32"); } @Test public void TypeEquals_Valid_33() { runTest("TypeEquals_Valid_33"); } @Test public void TypeEquals_Valid_34() { runTest("TypeEquals_Valid_34"); } @Test public void TypeEquals_Valid_35() { runTest("TypeEquals_Valid_35"); } @Ignore("unclassified") @Test public void TypeEquals_Valid_36() { runTest("TypeEquals_Valid_36"); } @Ignore("unclassified") @Test public void TypeEquals_Valid_37() { runTest("TypeEquals_Valid_37"); } @Ignore("unclassified") @Test public void TypeEquals_Valid_38() { runTest("TypeEquals_Valid_38"); } @Test public void TypeEquals_Valid_39() { runTest("TypeEquals_Valid_39"); } @Ignore("unclassified") @Test public void TypeEquals_Valid_4() { runTest("TypeEquals_Valid_4"); } @Test public void TypeEquals_Valid_40() { runTest("TypeEquals_Valid_40"); } @Ignore("unclassified") @Test public void TypeEquals_Valid_41() { runTest("TypeEquals_Valid_41"); } @Test public void TypeEquals_Valid_42() { runTest("TypeEquals_Valid_42"); } @Test public void TypeEquals_Valid_43() { runTest("TypeEquals_Valid_43"); } @Test public void TypeEquals_Valid_44() { runTest("TypeEquals_Valid_44"); } @Ignore("unclassified") @Test public void TypeEquals_Valid_45() { runTest("TypeEquals_Valid_45"); } @Test public void TypeEquals_Valid_46() { runTest("TypeEquals_Valid_46"); } @Test public void TypeEquals_Valid_47() { runTest("TypeEquals_Valid_47"); } @Test public void TypeEquals_Valid_5() { runTest("TypeEquals_Valid_5"); } @Test public void TypeEquals_Valid_6() { runTest("TypeEquals_Valid_6"); } @Test public void TypeEquals_Valid_7() { runTest("TypeEquals_Valid_7"); } @Test public void TypeEquals_Valid_8() { runTest("TypeEquals_Valid_8"); } @Test public void TypeEquals_Valid_9() { runTest("TypeEquals_Valid_9"); } @Test public void UnionType_Valid_1() { runTest("UnionType_Valid_1"); } @Test public void UnionType_Valid_10() { runTest("UnionType_Valid_10"); } @Test public void UnionType_Valid_11() { runTest("UnionType_Valid_11"); } @Test public void UnionType_Valid_12() { runTest("UnionType_Valid_12"); } @Test public void UnionType_Valid_13() { runTest("UnionType_Valid_13"); } @Test public void UnionType_Valid_14() { runTest("UnionType_Valid_14"); } @Test public void UnionType_Valid_15() { runTest("UnionType_Valid_15"); } @Test public void UnionType_Valid_16() { runTest("UnionType_Valid_16"); } @Test public void UnionType_Valid_17() { runTest("UnionType_Valid_17"); } @Test public void UnionType_Valid_18() { runTest("UnionType_Valid_18"); } @Test public void UnionType_Valid_19() { runTest("UnionType_Valid_19"); } @Test public void UnionType_Valid_2() { runTest("UnionType_Valid_2"); } @Test public void UnionType_Valid_20() { runTest("UnionType_Valid_20"); } @Test public void UnionType_Valid_21() { runTest("UnionType_Valid_21"); } @Test public void UnionType_Valid_22() { runTest("UnionType_Valid_22"); } @Test public void UnionType_Valid_23() { runTest("UnionType_Valid_23"); } @Test public void UnionType_Valid_3() { runTest("UnionType_Valid_3"); } @Test public void UnionType_Valid_4() { runTest("UnionType_Valid_4"); } @Test public void UnionType_Valid_5() { runTest("UnionType_Valid_5"); } @Test public void UnionType_Valid_6() { runTest("UnionType_Valid_6"); } @Test public void UnionType_Valid_7() { runTest("UnionType_Valid_7"); } @Test public void UnionType_Valid_8() { runTest("UnionType_Valid_8"); } @Test public void UnionType_Valid_9() { runTest("UnionType_Valid_9"); } @Ignore("unclassified") @Test public void Update_Valid_1() { runTest("Update_Valid_1"); } @Ignore("unclassified") @Test public void Update_Valid_2() { runTest("Update_Valid_2"); } @Test public void VarDecl_Valid_1() { runTest("VarDecl_Valid_1"); } @Test public void VarDecl_Valid_2() { runTest("VarDecl_Valid_2"); } @Test public void VarDecl_Valid_3() { runTest("VarDecl_Valid_3"); } @Test public void VarDecl_Valid_4() { runTest("VarDecl_Valid_4"); } @Test public void While_Valid_1() { runTest("While_Valid_1"); } @Test public void While_Valid_10() { runTest("While_Valid_10"); } @Test public void While_Valid_11() { runTest("While_Valid_11"); } @Test public void While_Valid_12() { runTest("While_Valid_12"); } @Test public void While_Valid_13() { runTest("While_Valid_13"); } @Test public void While_Valid_14() { runTest("While_Valid_14"); } @Test public void While_Valid_15() { runTest("While_Valid_15"); } @Test public void While_Valid_16() { runTest("While_Valid_16"); } @Test public void While_Valid_17() { runTest("While_Valid_17"); } @Test public void While_Valid_18() { runTest("While_Valid_18"); } @Test public void While_Valid_19() { runTest("While_Valid_19"); } @Test public void While_Valid_2() { runTest("While_Valid_2"); } @Test public void While_Valid_20() { runTest("While_Valid_20"); } @Test public void While_Valid_21() { runTest("While_Valid_21"); } @Test public void While_Valid_22() { runTest("While_Valid_22"); } @Ignore("unclassified") @Test public void While_Valid_23() { runTest("While_Valid_23"); } @Ignore("unclassified") @Test public void While_Valid_24() { runTest("While_Valid_24"); } @Ignore("unclassified") @Test public void While_Valid_25() { runTest("While_Valid_25"); } @Test public void While_Valid_26() { runTest("While_Valid_26"); } @Test public void While_Valid_3() { runTest("While_Valid_3"); } @Test public void While_Valid_4() { runTest("While_Valid_4"); } @Test public void While_Valid_5() { runTest("While_Valid_5"); } @Test public void While_Valid_6() { runTest("While_Valid_6"); } @Test public void While_Valid_7() { runTest("While_Valid_7"); } @Test public void While_Valid_8() { runTest("While_Valid_8"); } @Test public void While_Valid_9() { runTest("While_Valid_9"); } }
package com.intellij.ide.actions; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.wm.impl.IdeFrame; import java.awt.*; import java.awt.event.WindowEvent; /** * @author Vladimir Kondratyev */ public class CloseWindowAction extends AnAction{ public CloseWindowAction(){ setEnabledInModalContext(true); } private static Window getWindow(){ Window focusedWindow=KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusedWindow(); if(!(focusedWindow instanceof Dialog) && !(focusedWindow instanceof Frame)){ return null; } if(focusedWindow instanceof Dialog){ Dialog dialog=(Dialog)focusedWindow; if(!dialog.isUndecorated()){ return focusedWindow; }else{ return null; } }else if(!(focusedWindow instanceof IdeFrame)){ Frame frame=(Frame)focusedWindow; if(!frame.isUndecorated()){ return focusedWindow; }else{ return null; } }else{ return null; } } public void actionPerformed(AnActionEvent e){ Window window=getWindow(); WindowEvent event=new WindowEvent(window,WindowEvent.WINDOW_CLOSING); window.dispatchEvent(event); } public void update(AnActionEvent e){ super.update(e); e.getPresentation().setEnabled(getWindow()!=null); } }
package risk; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class RiskBoard { private List<Territory> territories; // A new board will be blank, with no territories and no connections public RiskBoard(){ territories = new ArrayList<Territory>(); } /** * Will attempt to setup the board based on an input file. Territories * will be added first and then routes will be set up. * <p> * A valid file should contain Regions in the format "Region: Name". * followed by the names of territories. After all the territories * in that region should be a blank line. (You can have as many regions as you like.) * Following all the regions and territories, the routes are set up by starting * a line with "Routes:". This should be followed by a list of each connection * (routes are all bi-directional) in the format "Place-Place2". * * @param fileName the name of a file containing valid board information **/ public void setup(String fileName) { try { BufferedReader br = new BufferedReader(new FileReader(fileName)); while(br.ready()){ String input = br.readLine(); if (input.contains("Region: ")){ // setup regions this.setupRegions(br); }else if(input.contains("Routes: ")){ // setup routes this.setupRoutes(br); } } } catch (FileNotFoundException e) { System.out.println("File not found: "); e.printStackTrace(); } catch (IOException e){ System.out.println("File read error: "); e.printStackTrace(); } } /** * Private method takes a BufferedReader and reads in each line, * adds connection to territory objects in the territories list until * it reaches a blank line or end of file. The accepted format is: * "Territory1-Terrotory2"; * * @param br a BufferedReader object of the file with setup information **/ private void setupRoutes(BufferedReader br) throws IOException { while(br.ready()){ String input = br.readLine(); if(input.equals("")) return; else { String[] route = input.split("-"); addConnection(route[1],route[2]); } } } /** * Method to add connections to territories. Note: all connections are 2 way. * * @paramfrom Territory to start in * @param to Territory to end in **/ public void addConnection(String from, String to){ for(Territory terra : territories){ if (terra.getName().equals(from)){ terra.addConnection(to); } else if(terra.getName().equals(to)){ terra.addConnection(from); } } } /** * Private method takes a BufferedReader and reads in each line, * creates a territory object, and adds it to the territories list until * it reaches a blank line or end of file. * * @param br a BufferedReader object of the file with setup information **/ private void setupRegions(BufferedReader br) throws IOException { while(br.ready()){ String input = br.readLine(); if(input.equals("")) return; else territories.add(new Territory(input)); } } /** * Get method for territories. * * @return the territories in List<Territory> form. **/ public List<Territory> getTerritories() {return territories;} /** * Method to get the number of troops in a particular territory. * Method will return 0 for calls without a valid name. * * @param territory the name of the territory to get info from * @return returns the number of troops in a territory **/ public int getTroops(String territory) { for(Territory terra : territories){ if (terra.getName().equals(territory)){ return terra.getTroops(); } } return 0; } /** * Method to add (positive number) or subtract (negative number) troops from a given territory. * Any calls without a valid name will be ignored. This method will check to ensure the number * of troops in a territory does not fall below 0. If it does, the number will be set to 0. * * @param territory the name of the territory to add to * @param num the number of troops to add(or subtract) **/ public void changeTroops(String territory, int num) { for(Territory terra : territories){ if (terra.getName().equals(territory)){ int troops = terra.getTroops() + num; if(troops > 0){ terra.setTroops(troops); } else { terra.setTroops(0); } } } } /** * Will return the name of the faction holding the territroy given. * * @param territory the name of the territory to look up * @return a string with the name of the faction in control **/ public String getFaction(String territory) { for(Territory terra : territories){ if (terra.getName().equals(territory)){ return terra.getFaction(); } } return "None"; } /** * Sets the name of the faction for a partuicular territory. * * @param territory the name of the territory * @param faction the name of the faction to change it to **/ public void setFaction(String territory, String faction) { for(Territory terra : territories){ if (terra.getName().equals(territory)){ terra.setFaction(faction); } } } }