Example usage for java.util Collections singletonList

List of usage examples for java.util Collections singletonList

Introduction

In this page you can find the example usage for java.util Collections singletonList.

Prototype

public static <T> List<T> singletonList(T o) 

Source Link

Document

Returns an immutable list containing only the specified object.

Usage

From source file:averroes.Main.java

/**
 * The main Averroes method.//from w  w w  .  jav a  2  s .  c o  m
 * 
 * @param args
 */
public static void main(String[] args) {
    try {
        // Find the total execution time, instead of depending on the Unix
        // time command
        TimeUtils.splitStart();

        // Process the arguments
        AverroesOptions.processArguments(args);

        // Reset Soot
        G.reset();

        // Create the output directory and clean up any class files in there
        FileUtils.forceMkdir(Paths.libraryClassesOutputDirectory());
        FileUtils.cleanDirectory(Paths.classesOutputDirectory());

        // Organize the input JAR files
        System.out.println("");
        System.out.println("Organizing the JAR files ...");
        JarOrganizer jarOrganizer = new JarOrganizer();
        jarOrganizer.organizeInputJarFiles();

        // Print some statistics
        System.out.println("# application classes: " + jarOrganizer.applicationClassNames().size());
        System.out.println("# library classes: " + jarOrganizer.libraryClassNames().size());

        // Add the organized archives for the application and its
        // dependencies.
        TimeUtils.reset();
        JarFactoryClassProvider provider = new JarFactoryClassProvider();
        provider.prepareJarFactoryClasspath();

        // Set some soot parameters
        SourceLocator.v().setClassProviders(Collections.singletonList((ClassProvider) provider));
        SootSceneUtil.addCommonDynamicClasses(provider);
        Options.v().classes().addAll(provider.getApplicationClassNames());
        Options.v().set_main_class(AverroesOptions.getMainClass());
        Options.v().set_validate(true);

        // Load the necessary classes
        System.out.println("");
        System.out.println("Loading classes ...");
        Scene.v().loadNecessaryClasses();
        Scene.v().setMainClassFromOptions();
        double soot = TimeUtils.elapsedTime();
        System.out.println("Soot loaded the input classes in " + soot + " seconds.");

        // Now let Averroes do its thing
        // First, create the class hierarchy
        TimeUtils.reset();
        System.out.println("");
        System.out.println("Creating the class hierarchy for the placeholder library ...");
        Hierarchy.v();

        // Output some initial statistics
        System.out.println("# initial application classes: " + Hierarchy.v().getApplicationClasses().size());
        System.out.println("# initial library classes: " + Hierarchy.v().getLibraryClasses().size());
        System.out.println("# initial library methods: " + Hierarchy.v().getLibraryMethodCount());
        System.out.println("# initial library fields: " + Hierarchy.v().getLibraryFieldCount());
        System.out.println("# referenced library methods: " + Hierarchy.v().getReferencedLibraryMethodCount());
        System.out.println("# referenced library fields: " + Hierarchy.v().getReferencedLibraryFieldCount());

        // Cleanup the hierarchy
        System.out.println("");
        System.out.println("Cleaning up the class hierarchy ...");
        Hierarchy.v().cleanupLibraryClasses();

        // Output some cleanup statistics
        System.out.println("# removed library methods: " + Hierarchy.v().getRemovedLibraryMethodCount());
        System.out.println("# removed library fields: " + Hierarchy.v().getRemovedLibraryFieldCount());
        // The +1 is for Finalizer.register that will be added later
        System.out.println("# final library methods: " + (Hierarchy.v().getLibraryMethodCount() + 1));
        System.out.println("# final library fields: " + Hierarchy.v().getLibraryFieldCount());

        // Output some code generation statistics
        System.out.println("");
        System.out.println("Generating extra library classes ...");
        System.out.println("# generated library classes: " + CodeGenerator.v().getGeneratedClassCount());
        System.out.println("# generated library methods: " + CodeGenerator.v().getGeneratedMethodCount());

        // Create the Averroes library class
        System.out.println("");
        System.out.println("Creating the skeleton for Averroes's main library class ...");
        CodeGenerator.v().createAverroesLibraryClass();

        // Create method bodies to the library classes
        System.out.println("Generating the method bodies for the placeholder library classes ...");
        CodeGenerator.v().createLibraryMethodBodies();

        // Create empty classes for the basic classes required internally by
        // Soot
        System.out.println("Generating empty basic library classes required by Soot ...");
        for (SootClass basicClass : Hierarchy.v().getBasicClassesDatabase().getMissingBasicClasses()) {
            CodeGenerator.writeLibraryClassFile(basicClass);
        }
        double averroes = TimeUtils.elapsedTime();
        System.out.println("Placeholder library classes created and validated in " + averroes + " seconds.");

        // Create the jar file and add all the generated class files to it.
        TimeUtils.reset();
        JarFile librJarFile = new JarFile(Paths.placeholderLibraryJarFile());
        librJarFile.addGeneratedLibraryClassFiles();
        JarFile aveJarFile = new JarFile(Paths.averroesLibraryClassJarFile());
        aveJarFile.addAverroesLibraryClassFile();
        double bcel = TimeUtils.elapsedTime();
        System.out.println("Placeholder library JAR file verified in " + bcel + " seconds.");
        System.out.println(
                "Total time (without verification) is " + MathUtils.round(soot + averroes) + " seconds.");
        System.out.println(
                "Total time (with verification) is " + MathUtils.round(soot + averroes + bcel) + " seconds.");

        double total = TimeUtils.elapsedSplitTime();
        System.out.println("Elapsed time: " + total + " seconds.");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.example.user.UserEndpoint.java

public static void main(String[] args) {
    final ObjectMapper objectMapper = new ObjectMapper().registerModule(new Jackson2HalModule())
            .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
            .setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
    final MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(objectMapper);
    converter.setSupportedMediaTypes(Collections.singletonList(MediaTypes.HAL_JSON));
    final RestTemplate restTemplate = new RestTemplate(Collections.singletonList(converter));
    final ResponseEntity<PagedResources<Resource<UserEntity>>> entity = restTemplate.exchange(
            "http://localhost:5000/db-app/users", HttpMethod.GET, null,
            new ParameterizedTypeReference<PagedResources<Resource<UserEntity>>>() {
            });/*from ww w.j a va2 s  . com*/
    System.out.println(entity.getStatusCode());
    final PagedResources<Resource<UserEntity>> body = entity.getBody();
    System.out.println(body);
    final Collection<Resource<UserEntity>> contents = body.getContent();
    final List<UserEntity> userEntities = contents.stream().map(Resource::getContent).collect(toList());
}

From source file:com.example.bigtable.sample.WordCountHBase.java

public static void main(String[] args) throws Exception {
    Configuration conf = HBaseConfiguration.create();
    String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs();
    if (otherArgs.length < 2) {
        System.err.println("Usage: wordcount-hbase <in> [<in>...] <table-name>");
        System.exit(2);/*from   w  w w.  j av  a 2s.c o  m*/
    }

    Job job = Job.getInstance(conf, "word count");

    for (int i = 0; i < otherArgs.length - 1; ++i) {
        FileInputFormat.addInputPath(job, new Path(otherArgs[i]));
    }

    TableName tableName = TableName.valueOf(otherArgs[otherArgs.length - 1]);
    try {
        CreateTable.createTable(tableName, conf, Collections.singletonList(Bytes.toString(COLUMN_FAMILY)));
    } catch (Exception e) {
        LOG.error("Could not create the table.", e);
    }

    job.setJarByClass(WordCountHBase.class);
    job.setMapperClass(TokenizerMapper.class);
    job.setMapOutputValueClass(IntWritable.class);

    TableMapReduceUtil.initTableReducerJob(tableName.getNameAsString(), MyTableReducer.class, job);

    System.exit(job.waitForCompletion(true) ? 0 : 1);
}

From source file:com.flurry.proguard.UploadMapping.java

public static void main(String[] args) throws IOException {
    ArgumentParser parser = ArgumentParsers.newArgumentParser("com.flurry.proguard.UploadMapping", true)
            .description("Uploads Proguard/Native Mapping Files for Android");
    parser.addArgument("-k", "--api-key").required(true).help("API Key for your project");
    parser.addArgument("-u", "--uuid").required(true).help("The build UUID");
    parser.addArgument("-p", "--path").required(true)
            .help("Path to ProGuard/Native mapping file for the build");
    parser.addArgument("-t", "--token").required(true).help("A Flurry auth token to use for the upload");
    parser.addArgument("-to", "--timeout").type(Integer.class).setDefault(TEN_MINUTES_IN_MS)
            .help("How long to wait (in ms) for the upload to be processed");
    parser.addArgument("-n", "--ndk").type(Boolean.class).setDefault(false).help("Is it a Native mapping file");

    Namespace res = null;//from w  w w .  j ava2s  . c  o m
    try {
        res = parser.parseArgs(args);
    } catch (ArgumentParserException e) {
        parser.handleError(e);
        System.exit(1);
    }

    EXIT_PROCESS_ON_ERROR = true;
    if (res.getBoolean("ndk")) {
        uploadFiles(res.getString("api_key"), res.getString("uuid"),
                new ArrayList<>(Collections.singletonList(res.getString("path"))), res.getString("token"),
                res.getInt("timeout"), AndroidUploadType.ANDROID_NATIVE);
    } else {
        uploadFiles(res.getString("api_key"), res.getString("uuid"),
                new ArrayList<>(Collections.singletonList(res.getString("path"))), res.getString("token"),
                res.getInt("timeout"), AndroidUploadType.ANDROID_JAVA);
    }
}

From source file:Signing.java

public static void main(String[] args) throws Exception {
        SOAPMessage soapMessage = MessageFactory.newInstance().createMessage();
        SOAPPart soapPart = soapMessage.getSOAPPart();
        SOAPEnvelope soapEnvelope = soapPart.getEnvelope();

        SOAPHeader soapHeader = soapEnvelope.getHeader();
        SOAPHeaderElement headerElement = soapHeader.addHeaderElement(soapEnvelope.createName("Signature",
                "SOAP-SEC", "http://schemas.xmlsoap.org/soap/security/2000-12"));

        SOAPBody soapBody = soapEnvelope.getBody();
        soapBody.addAttribute(/*  ww  w  . ja  v a2 s.com*/
                soapEnvelope.createName("id", "SOAP-SEC", "http://schemas.xmlsoap.org/soap/security/2000-12"),
                "Body");
        Name bodyName = soapEnvelope.createName("FooBar", "z", "http://example.com");
        SOAPBodyElement gltp = soapBody.addBodyElement(bodyName);

        Source source = soapPart.getContent();
        Node root = null;
        if (source instanceof DOMSource) {
            root = ((DOMSource) source).getNode();
        } else if (source instanceof SAXSource) {
            InputSource inSource = ((SAXSource) source).getInputSource();
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            dbf.setNamespaceAware(true);
            DocumentBuilder db = null;

            db = dbf.newDocumentBuilder();

            Document doc = db.parse(inSource);
            root = (Node) doc.getDocumentElement();
        }

        dumpDocument(root);

        KeyPairGenerator kpg = KeyPairGenerator.getInstance("DSA");
        kpg.initialize(1024, new SecureRandom());
        KeyPair keypair = kpg.generateKeyPair();

        XMLSignatureFactory sigFactory = XMLSignatureFactory.getInstance();
        Reference ref = sigFactory.newReference("#Body", sigFactory.newDigestMethod(DigestMethod.SHA1, null));
        SignedInfo signedInfo = sigFactory.newSignedInfo(
                sigFactory.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS,
                        (C14NMethodParameterSpec) null),
                sigFactory.newSignatureMethod(SignatureMethod.DSA_SHA1, null), Collections.singletonList(ref));
        KeyInfoFactory kif = sigFactory.getKeyInfoFactory();
        KeyValue kv = kif.newKeyValue(keypair.getPublic());
        KeyInfo keyInfo = kif.newKeyInfo(Collections.singletonList(kv));

        XMLSignature sig = sigFactory.newXMLSignature(signedInfo, keyInfo);

        System.out.println("Signing the message...");
        PrivateKey privateKey = keypair.getPrivate();
        Element envelope = getFirstChildElement(root);
        Element header = getFirstChildElement(envelope);
        DOMSignContext sigContext = new DOMSignContext(privateKey, header);
        sigContext.putNamespacePrefix(XMLSignature.XMLNS, "ds");
        sigContext.setIdAttributeNS(getNextSiblingElement(header),
                "http://schemas.xmlsoap.org/soap/security/2000-12", "id");
        sig.sign(sigContext);

        dumpDocument(root);

        System.out.println("Validate the signature...");
        Element sigElement = getFirstChildElement(header);
        DOMValidateContext valContext = new DOMValidateContext(keypair.getPublic(), sigElement);
        valContext.setIdAttributeNS(getNextSiblingElement(header),
                "http://schemas.xmlsoap.org/soap/security/2000-12", "id");
        boolean valid = sig.validate(valContext);

        System.out.println("Signature valid? " + valid);
    }

From source file:ee.ria.xroad.common.signature.BatchSignerIntegrationTest.java

/**
 * Main program entry point.//from w w  w.  j a  va  2s  . c o  m
 * @param args command-line arguments
 * @throws Exception in case of any errors
 */
public static void main(String[] args) throws Exception {
    if (args.length == 0) {
        printUsage();

        return;
    }

    ActorSystem actorSystem = ActorSystem.create("Proxy", ConfigFactory.load().getConfig("proxy"));
    SignerClient.init(actorSystem);

    Thread.sleep(SIGNER_INIT_DELAY); // wait for signer client to connect

    BatchSigner.init(actorSystem);

    X509Certificate subjectCert = TestCertUtil.getConsumer().cert;
    X509Certificate issuerCert = TestCertUtil.getCaCert();
    X509Certificate signerCert = TestCertUtil.getOcspSigner().cert;
    PrivateKey signerKey = TestCertUtil.getOcspSigner().key;

    List<String> messages = new ArrayList<>();

    for (String arg : args) {
        messages.add(FileUtils.readFileToString(new File(arg)));
    }

    latch = new CountDownLatch(messages.size());

    Date thisUpdate = new DateTime().plusDays(1).toDate();
    final OCSPResp ocsp = OcspTestUtils.createOCSPResponse(subjectCert, issuerCert, signerCert, signerKey,
            CertificateStatus.GOOD, thisUpdate, null);

    for (final String message : messages) {
        new Thread(() -> {
            try {
                byte[] hash = hash(message);
                log.info("File: {}, hash: {}", message, hash);

                MessagePart hashPart = new MessagePart(MessageFileNames.MESSAGE, SHA512_ID,
                        calculateDigest(SHA512_ID, message.getBytes()), message.getBytes());

                List<MessagePart> hashes = Collections.singletonList(hashPart);

                SignatureBuilder builder = new SignatureBuilder();
                builder.addPart(hashPart);

                builder.setSigningCert(subjectCert);
                builder.addOcspResponses(Collections.singletonList(ocsp));

                log.info("### Calculating signature...");

                SignatureData signatureData = builder.build(
                        new SignerSigningKey(KEY_ID, CryptoUtils.CKM_RSA_PKCS_NAME), CryptoUtils.SHA512_ID);

                synchronized (sigIdx) {
                    log.info("### Created signature: {}", signatureData.getSignatureXml());

                    log.info("HashChainResult: {}", signatureData.getHashChainResult());
                    log.info("HashChain: {}", signatureData.getHashChain());

                    toFile("message-" + sigIdx + ".xml", message);

                    String sigFileName = signatureData.getHashChainResult() != null ? "batch-sig-" : "sig-";

                    toFile(sigFileName + sigIdx + ".xml", signatureData.getSignatureXml());

                    if (signatureData.getHashChainResult() != null) {
                        toFile("hash-chain-" + sigIdx + ".xml", signatureData.getHashChain());
                        toFile("hash-chain-result.xml", signatureData.getHashChainResult());
                    }

                    sigIdx++;
                }

                try {
                    verify(signatureData, hashes, message);

                    log.info("Verification successful (message hash: {})", hash);
                } catch (Exception e) {
                    log.error("Verification failed (message hash: {})", hash, e);
                }
            } catch (Exception e) {
                log.error("Error", e);
            } finally {
                latch.countDown();
            }
        }).start();
    }

    latch.await();
    actorSystem.shutdown();
}

From source file:act.installer.pubchem.PubchemSynonymFinder.java

public static void main(String[] args) throws Exception {
    org.apache.commons.cli.Options opts = new org.apache.commons.cli.Options();
    for (Option.Builder b : OPTION_BUILDERS) {
        opts.addOption(b.build());// w  w w . j  av a  2 s.  com
    }

    CommandLine cl = null;
    try {
        CommandLineParser parser = new DefaultParser();
        cl = parser.parse(opts, args);
    } catch (ParseException e) {
        System.err.format("Argument parsing failed: %s\n", e.getMessage());
        HELP_FORMATTER.printHelp(PubchemSynonymFinder.class.getCanonicalName(), HELP_MESSAGE, opts, null, true);
        System.exit(1);
    }

    if (cl.hasOption("help")) {
        HELP_FORMATTER.printHelp(PubchemSynonymFinder.class.getCanonicalName(), HELP_MESSAGE, opts, null, true);
        return;
    }

    File rocksDBFile = new File(cl.getOptionValue(OPTION_INDEX_PATH));
    if (!rocksDBFile.isDirectory()) {
        System.err.format("Index directory does not exist or is not a directory at '%s'",
                rocksDBFile.getAbsolutePath());
        HELP_FORMATTER.printHelp(PubchemSynonymFinder.class.getCanonicalName(), HELP_MESSAGE, opts, null, true);
        System.exit(1);
    }

    List<String> compoundIds = null;
    if (cl.hasOption(OPTION_PUBCHEM_COMPOUND_ID)) {
        compoundIds = Collections.singletonList(cl.getOptionValue(OPTION_PUBCHEM_COMPOUND_ID));
    } else if (cl.hasOption(OPTION_IDS_FILE)) {
        File idsFile = new File(cl.getOptionValue(OPTION_IDS_FILE));
        if (!idsFile.exists()) {
            System.err.format("Cannot find Pubchem CIDs file at %s", idsFile.getAbsolutePath());
            HELP_FORMATTER.printHelp(PubchemSynonymFinder.class.getCanonicalName(), HELP_MESSAGE, opts, null,
                    true);
            System.exit(1);
        }

        compoundIds = getCIDsFromFile(idsFile);

        if (compoundIds.size() == 0) {
            System.err.format("Found zero Pubchem CIDs to process in file at '%s', exiting",
                    idsFile.getAbsolutePath());
            HELP_FORMATTER.printHelp(PubchemSynonymFinder.class.getCanonicalName(), HELP_MESSAGE, opts, null,
                    true);
            System.exit(1);
        }
    } else {
        System.err.format("Must specify one of '%s' or '%s'; index is too big to print all synonyms.",
                OPTION_PUBCHEM_COMPOUND_ID, OPTION_IDS_FILE);
        HELP_FORMATTER.printHelp(PubchemSynonymFinder.class.getCanonicalName(), HELP_MESSAGE, opts, null, true);
        System.exit(1);
    }

    // Run a quick check to warn users of malformed ids.
    compoundIds.forEach(x -> {
        if (!PC_CID_PATTERN.matcher(x).matches()) { // Use matches() for complete matching.
            LOGGER.warn("Specified compound id does not match expected format: %s", x);
        }
    });

    LOGGER.info("Opening DB and searching for %d Pubchem CIDs", compoundIds.size());
    Pair<RocksDB, Map<PubchemTTLMerger.COLUMN_FAMILIES, ColumnFamilyHandle>> dbAndHandles = null;
    Map<String, PubchemSynonyms> results = new LinkedHashMap<>(compoundIds.size());
    try {
        dbAndHandles = PubchemTTLMerger.openExistingRocksDB(rocksDBFile);
        RocksDB db = dbAndHandles.getLeft();
        ColumnFamilyHandle cidToSynonymsCfh = dbAndHandles.getRight()
                .get(PubchemTTLMerger.COLUMN_FAMILIES.CID_TO_SYNONYMS);

        for (String cid : compoundIds) {
            PubchemSynonyms synonyms = null;
            byte[] val = db.get(cidToSynonymsCfh, cid.getBytes(UTF8));
            if (val != null) {
                ObjectInputStream oi = new ObjectInputStream(new ByteArrayInputStream(val));
                // We're relying on our use of a one-value-type per index model here so we can skip the instanceof check.
                synonyms = (PubchemSynonyms) oi.readObject();
            } else {
                LOGGER.warn("No synonyms available for compound id '%s'", cid);
            }
            results.put(cid, synonyms);
        }
    } finally {
        if (dbAndHandles != null) {
            dbAndHandles.getLeft().close();
        }
    }

    try (OutputStream outputStream = cl.hasOption(OPTION_OUTPUT)
            ? new FileOutputStream(cl.getOptionValue(OPTION_OUTPUT))
            : System.out) {
        OBJECT_MAPPER.writerWithDefaultPrettyPrinter().writeValue(outputStream, results);
        new OutputStreamWriter(outputStream).append('\n');
    }
    LOGGER.info("Done searching for Pubchem synonyms");
}

From source file:io.werval.cli.DamnSmallDevShell.java

public static void main(String[] args) {
    Options options = declareOptions();// w  w  w .j  av a2 s.c  om

    CommandLineParser parser = new PosixParser();
    try {
        CommandLine cmd = parser.parse(options, args);

        // Handle --help
        if (cmd.hasOption("help")) {
            PrintWriter out = new PrintWriter(System.out);
            printHelp(options, out);
            out.flush();
            System.exit(0);
        }

        // Handle --version
        if (cmd.hasOption("version")) {
            System.out.print(String.format(
                    "Werval CLI v%s\n" + "Git commit: %s%s, built on: %s\n" + "Java version: %s, vendor: %s\n"
                            + "Java home: %s\n" + "Default locale: %s, platform encoding: %s\n"
                            + "OS name: %s, version: %s, arch: %s\n",
                    VERSION, COMMIT, (DIRTY ? " (DIRTY)" : ""), DATE, System.getProperty("java.version"),
                    System.getProperty("java.vendor"), System.getProperty("java.home"),
                    Locale.getDefault().toString(), System.getProperty("file.encoding"),
                    System.getProperty("os.name"), System.getProperty("os.version"),
                    System.getProperty("os.arch")));
            System.out.flush();
            System.exit(0);
        }

        // Debug
        final boolean debug = cmd.hasOption('d');

        // Temporary directory
        final File tmpDir = new File(cmd.getOptionValue('t', "build" + separator + "devshell.tmp"));
        if (debug) {
            System.out.println("Temporary directory set to '" + tmpDir.getAbsolutePath() + "'.");
        }

        // Handle commands
        @SuppressWarnings("unchecked")
        List<String> commands = cmd.getArgList();
        if (commands.isEmpty()) {
            commands = Collections.singletonList("start");
        }
        if (debug) {
            System.out.println("Commands to be executed: " + commands);
        }
        Iterator<String> commandsIterator = commands.iterator();
        while (commandsIterator.hasNext()) {
            String command = commandsIterator.next();
            switch (command) {
            case "new":
                System.out.println(LOGO);
                newCommand(commandsIterator.hasNext() ? commandsIterator.next() : "werval-application", cmd);
                break;
            case "clean":
                cleanCommand(debug, tmpDir);
                break;
            case "devshell":
                System.out.println(LOGO);
                devshellCommand(debug, tmpDir, cmd);
                break;
            case "start":
                System.out.println(LOGO);
                startCommand(debug, tmpDir, cmd);
                break;
            case "secret":
                secretCommand();
                break;
            default:
                PrintWriter out = new PrintWriter(System.err);
                System.err.println("Unknown command: '" + command + "'");
                printHelp(options, out);
                out.flush();
                System.exit(1);
                break;
            }
        }
    } catch (IllegalArgumentException | ParseException | IOException ex) {
        PrintWriter out = new PrintWriter(System.err);
        printHelp(options, out);
        out.flush();
        System.exit(1);
    } catch (WervalException ex) {
        ex.printStackTrace(System.err);
        System.err.flush();
        System.exit(1);
    }
}

From source file:com.ltasks.LtasksNameFinderClient.java

public static void main(String[] args)
        throws HttpException, IOException, ParserConfigurationException, SAXException, InterruptedException {

    System.out.println("Initializing client...");

    // Create a client using the apikey from documentation.
    LtasksNameFinderClient client = new LtasksNameFinderClient("b2c4cf5c-52d3-4fef-ac9b-67dbe6b5e52d", true,
            true);//ww  w  . j a v  a  2 s .  co m

    System.out.println("Client started. Will do some annotation.");

    String data = "Ele se encontrar com Jos em Braslia.";

    System.out.println("Will annotate the text: " + data);
    LtasksObject result = client.processText(data);
    System.out.println("Text annotated. The result is: \n[" + result + "]");

    data = "http://pt.wikipedia.org/wiki/Cazuza";
    System.out.println("Will annotate a URL: " + data);
    result = client.processUrl(new URL(data));
    System.out.println("URL annotated. The result is: \n[" + result + "]");

    data = "<html>" + "<body>" + "<p id='a'>Ele se encontrar com Jos em Braslia.</p> "
            + "<div class='anId'>" + "<p id='a'>Ela se encontrar com Maria em So Paulo.</p>"
            + "<p id='b'>Maria se encontrar com Jos na Bahia.</p>" + "</div>" + "</body>" + "</html>";
    System.out.println("Will annotate a HTML: " + data);
    HtmlFilterOptions options = new HtmlFilterOptions();
    options.setFilter(HtmlFilter.none);
    // lets select only the div
    options.setInclude(Collections.singletonList(new SimpleXPath("div", "class", "anId")));
    // but exclude the paragraph with id a. We could create the list and the
    // object here, but lets try using the SimpleXPath parser
    options.setExclude(SimpleXPath.parse("//p[@id='a']"));

    result = client.processHtml(data, options);

    System.out.println("Vamos tentar acessar os resultados");

    if (result.isProcessedOk()) {
        System.out.println("Foi possivel anotar o texto.");
        if (result.getMessage() != null) {
            System.out.println("Mensagem do servidor: " + result.getMessage());
        }
        if (result.getSourceText() != null) {
            System.out.println("Texto fonte normalizado: \n[" + result.getSourceText() + "]");
        }
        if (result.getNamedEntities() != null) {
            for (NamedEntity entity : result.getNamedEntities()) {
                System.out.println("  tipo: " + entity.getType().value() + " inicio: " + entity.getBegin()
                        + " fim: " + entity.getEnd() + " texto: " + entity.getText());
            }
        }
    } else {
        System.out.println("Houve um erro! Vamos tentar obter a mensagem de erro.");
        System.out.println("Mensagem do servidor: " + result.getMessage());
    }

}

From source file:com.mgreau.jboss.as7.cli.CliLauncher.java

public static void main(String[] args) throws Exception {
    int exitCode = 0;
    CommandContext cmdCtx = null;/*from  w  ww  . jav a  2s  .c om*/
    boolean gui = false;
    String appName = "";
    try {
        String argError = null;
        List<String> commands = null;
        File file = null;
        boolean connect = false;
        String defaultControllerProtocol = "http-remoting";
        String defaultControllerHost = null;
        int defaultControllerPort = -1;
        boolean version = false;
        String username = null;
        char[] password = null;
        int connectionTimeout = -1;

        //App deployment
        boolean isAppDeployment = false;
        final Properties props = new Properties();

        for (String arg : args) {
            if (arg.startsWith("--controller=") || arg.startsWith("controller=")) {
                final String fullValue;
                final String value;
                if (arg.startsWith("--")) {
                    fullValue = arg.substring(13);
                } else {
                    fullValue = arg.substring(11);
                }
                final int protocolEnd = fullValue.lastIndexOf("://");
                if (protocolEnd == -1) {
                    value = fullValue;
                } else {
                    value = fullValue.substring(protocolEnd + 3);
                    defaultControllerProtocol = fullValue.substring(0, protocolEnd);
                }

                String portStr = null;
                int colonIndex = value.lastIndexOf(':');
                if (colonIndex < 0) {
                    // default port
                    defaultControllerHost = value;
                } else if (colonIndex == 0) {
                    // default host
                    portStr = value.substring(1);
                } else {
                    final boolean hasPort;
                    int closeBracket = value.lastIndexOf(']');
                    if (closeBracket != -1) {
                        //possible ip v6
                        if (closeBracket > colonIndex) {
                            hasPort = false;
                        } else {
                            hasPort = true;
                        }
                    } else {
                        //probably ip v4
                        hasPort = true;
                    }
                    if (hasPort) {
                        defaultControllerHost = value.substring(0, colonIndex).trim();
                        portStr = value.substring(colonIndex + 1).trim();
                    } else {
                        defaultControllerHost = value;
                    }
                }

                if (portStr != null) {
                    int port = -1;
                    try {
                        port = Integer.parseInt(portStr);
                        if (port < 0) {
                            argError = "The port must be a valid non-negative integer: '" + args + "'";
                        } else {
                            defaultControllerPort = port;
                        }
                    } catch (NumberFormatException e) {
                        argError = "The port must be a valid non-negative integer: '" + arg + "'";
                    }
                }
            } else if ("--connect".equals(arg) || "-c".equals(arg)) {
                connect = true;
            } else if ("--version".equals(arg)) {
                version = true;
            } else if ("--gui".equals(arg)) {
                gui = true;
            } else if (arg.startsWith("--appDeployment=") || arg.startsWith("appDeployment=")) {
                isAppDeployment = true;
                appName = arg.startsWith("--") ? arg.substring(16) : arg.substring(14);
            } else if (arg.startsWith("--file=") || arg.startsWith("file=")) {
                if (file != null) {
                    argError = "Duplicate argument '--file'.";
                    break;
                }
                if (commands != null) {
                    argError = "Only one of '--file', '--commands' or '--command' can appear as the argument at a time.";
                    break;
                }

                final String fileName = arg.startsWith("--") ? arg.substring(7) : arg.substring(5);
                if (!fileName.isEmpty()) {
                    file = new File(fileName);
                    if (!file.exists()) {
                        argError = "File " + file.getAbsolutePath() + " doesn't exist.";
                        break;
                    }
                } else {
                    argError = "Argument '--file' is missing value.";
                    break;
                }
            } else if (arg.startsWith("--commands=") || arg.startsWith("commands=")) {
                if (file != null) {
                    argError = "Only one of '--file', '--commands' or '--command' can appear as the argument at a time.";
                    break;
                }
                if (commands != null) {
                    argError = "Duplicate argument '--command'/'--commands'.";
                    break;
                }
                final String value = arg.startsWith("--") ? arg.substring(11) : arg.substring(9);
                commands = Util.splitCommands(value);
            } else if (arg.startsWith("--command=") || arg.startsWith("command=")) {
                if (file != null) {
                    argError = "Only one of '--file', '--commands' or '--command' can appear as the argument at a time.";
                    break;
                }
                if (commands != null) {
                    argError = "Duplicate argument '--command'/'--commands'.";
                    break;
                }
                final String value = arg.startsWith("--") ? arg.substring(10) : arg.substring(8);
                commands = Collections.singletonList(value);
            } else if (arg.startsWith("--user=")) {
                username = arg.startsWith("--") ? arg.substring(7) : arg.substring(5);
            } else if (arg.startsWith("--password=")) {
                password = (arg.startsWith("--") ? arg.substring(11) : arg.substring(9)).toCharArray();
            } else if (arg.startsWith("--timeout=")) {
                if (connectionTimeout > 0) {
                    argError = "Duplicate argument '--timeout'";
                    break;
                }
                final String value = arg.substring(10);
                try {
                    connectionTimeout = Integer.parseInt(value);
                } catch (final NumberFormatException e) {
                    //
                }
                if (connectionTimeout <= 0) {
                    argError = "The timeout must be a valid positive integer: '" + value + "'";
                }
            } else if (arg.equals("--help") || arg.equals("-h")) {
                commands = Collections.singletonList("help");
            } else if (arg.startsWith("--properties=")) {
                final String value = arg.substring(13);
                final File propertiesFile = new File(value);
                if (!propertiesFile.exists()) {
                    argError = "File doesn't exist: " + propertiesFile.getAbsolutePath();
                    break;
                }

                FileInputStream fis = null;
                try {
                    fis = new FileInputStream(propertiesFile);
                    props.load(fis);
                } catch (FileNotFoundException e) {
                    argError = e.getLocalizedMessage();
                    break;
                } catch (java.io.IOException e) {
                    argError = "Failed to load properties from " + propertiesFile.getAbsolutePath() + ": "
                            + e.getLocalizedMessage();
                    break;
                } finally {
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (java.io.IOException e) {
                        }
                    }
                }
                for (final Object prop : props.keySet()) {
                    AccessController.doPrivileged(new PrivilegedAction<Object>() {
                        public Object run() {
                            System.setProperty((String) prop, (String) props.get(prop));
                            return null;
                        }
                    });
                }
            } else if (!(arg.startsWith("-D") || arg.equals("-XX:"))) {// skip system properties and jvm options
                // assume it's commands
                if (file != null) {
                    argError = "Only one of '--file', '--commands' or '--command' can appear as the argument at a time: "
                            + arg;
                    break;
                }
                if (commands != null) {
                    argError = "Duplicate argument '--command'/'--commands'.";
                    break;
                }
                commands = Util.splitCommands(arg);
            }
        }

        if (argError != null) {
            System.err.println(argError);
            exitCode = 1;
            return;
        }

        if (version) {
            cmdCtx = initCommandContext(defaultControllerProtocol, defaultControllerHost, defaultControllerPort,
                    username, password, false, connect, connectionTimeout);
            VersionHandler.INSTANCE.handle(cmdCtx);
            return;
        }

        if (file != null) {
            cmdCtx = initCommandContext(defaultControllerProtocol, defaultControllerHost, defaultControllerPort,
                    username, password, false, connect, connectionTimeout);
            processFile(file, cmdCtx, isAppDeployment, appName, props);
            return;
        }

        if (commands != null) {
            cmdCtx = initCommandContext(defaultControllerProtocol, defaultControllerHost, defaultControllerPort,
                    username, password, false, connect, connectionTimeout);
            processCommands(commands, cmdCtx);
            return;
        }

        // Interactive mode
        cmdCtx = initCommandContext(defaultControllerProtocol, defaultControllerHost, defaultControllerPort,
                username, password, true, connect, connectionTimeout);
        cmdCtx.interact();
    } catch (Throwable t) {
        t.printStackTrace();
        exitCode = 1;
    } finally {
        if (cmdCtx != null && cmdCtx.getExitCode() != 0) {
            exitCode = cmdCtx.getExitCode();
        }
        if (!gui) {
            System.exit(exitCode);
        }
    }
    System.exit(exitCode);
}