Example usage for java.util Optional get

List of usage examples for java.util Optional get

Introduction

In this page you can find the example usage for java.util Optional get.

Prototype

public T get() 

Source Link

Document

If a value is present, returns the value, otherwise throws NoSuchElementException .

Usage

From source file:example.IntroToRDF.java

public static void main(String[] args) {
    RDF rdf = new SimpleRDF();

    IRI alice = rdf.createIRI("Alice");
    System.out.println(alice.ntriplesString());

    IRI knows = rdf.createIRI("knows");
    IRI bob = rdf.createIRI("Bob");

    Triple aliceKnowsBob = rdf.createTriple(alice, knows, bob);
    System.out.println(aliceKnowsBob.getSubject().ntriplesString());

    System.out.println(aliceKnowsBob);

    Graph graph = rdf.createGraph();/* w w  w.  j  a va  2s  .c o  m*/
    graph.add(aliceKnowsBob);

    IRI charlie = rdf.createIRI("Charlie");

    IRI plays = rdf.createIRI("plays");

    IRI football = rdf.createIRI("Football");
    IRI tennis = rdf.createIRI("Tennis");

    graph.add(alice, knows, charlie);
    graph.add(alice, plays, tennis);
    graph.add(bob, knows, charlie);
    graph.add(bob, plays, football);
    graph.add(charlie, plays, tennis);

    System.out.println("Who plays Tennis?");
    for (Triple triple : graph.iterate(null, plays, tennis)) {
        System.out.println(triple.getSubject());
        System.out.println(plays.equals(triple.getPredicate()));
        System.out.println(tennis.equals(triple.getObject()));
    }

    System.out.println("Who does Alice know?");
    for (Triple triple : graph.iterate(alice, knows, null)) {
        System.out.println(triple.getObject());
    }

    System.out.println("Does Alice anyone that plays Football?");
    for (Triple triple : graph.iterate(alice, knows, null)) {
        RDFTerm aliceFriend = triple.getObject();
        if (!(aliceFriend instanceof BlankNodeOrIRI)) {
            continue;
        }
        if (graph.contains((BlankNodeOrIRI) aliceFriend, plays, football)) {
            System.out.println("Yes, it is " + aliceFriend);
        }
    }

    Literal aliceName = rdf.createLiteral("Alice W. Land");
    IRI name = rdf.createIRI("name");
    graph.add(alice, name, aliceName);

    Optional<? extends Triple> nameTriple = graph.stream(alice, name, null).findAny();
    if (nameTriple.isPresent()) {
        System.out.println(nameTriple.get());
    }

    graph.stream(alice, name, null).findAny().map(Triple::getObject).filter(obj -> obj instanceof Literal)
            .map(literalName -> ((Literal) literalName).getLexicalForm()).ifPresent(System.out::println);

    IRI playerRating = rdf.createIRI("playerRating");
    Literal aliceRating = rdf.createLiteral("13.37", Types.XSD_FLOAT);
    graph.add(alice, playerRating, aliceRating);

    Literal footballInEnglish = rdf.createLiteral("football", "en");
    Literal footballInNorwegian = rdf.createLiteral("fotball", "no");
    graph.add(football, name, footballInEnglish);
    graph.add(football, name, footballInNorwegian);

    Literal footballInAmericanEnglish = rdf.createLiteral("soccer", "en-US");
    graph.add(football, name, footballInAmericanEnglish);

    BlankNode someone = rdf.createBlankNode();
    graph.add(charlie, knows, someone);
    graph.add(someone, plays, football);

    BlankNode someoneElse = rdf.createBlankNode();
    graph.add(charlie, knows, someoneElse);

    for (Triple heKnows : graph.iterate(charlie, knows, null)) {
        if (!(heKnows.getObject() instanceof BlankNodeOrIRI)) {
            continue;
        }
        BlankNodeOrIRI who = (BlankNodeOrIRI) heKnows.getObject();
        System.out.println("Charlie knows " + who);
        for (Triple whoPlays : graph.iterate(who, plays, null)) {
            System.out.println("  who plays " + whoPlays.getObject());
        }
    }

    // Delete previous BlankNode statements
    graph.remove(null, null, someone);
    graph.remove(someone, null, null);

    // no Java variable for the new BlankNode instance
    graph.add(charlie, knows, rdf.createBlankNode("someone"));
    // at any point later (with the same RDF instance)
    graph.add(rdf.createBlankNode("someone"), plays, football);

    for (Triple heKnows : graph.iterate(charlie, knows, null)) {
        if (!(heKnows.getObject() instanceof BlankNodeOrIRI)) {
            continue;
        }
        BlankNodeOrIRI who = (BlankNodeOrIRI) heKnows.getObject();
        System.out.println("Charlie knows " + who);
        for (Triple whoPlays : graph.iterate(who, plays, null)) {
            System.out.println("  who plays " + whoPlays.getObject());
        }
    }

}

From source file:com.ikanow.aleph2.enrichment.utils.services.JsScriptEngineTestService.java

/** Entry point
 * @param args//from w w  w .j  av  a2s  .  co m
 * @throws IOException 
 */
public static void main(String[] args) throws IOException {
    if (args.length < 3) {
        System.out
                .println("ARGS: <script-file> <input-file> <output-prefix> [{[len: <LEN>], [group: <GROUP>]}]");
    }

    // STEP 1: load script file

    final String user_script = Files.toString(new File(args[0]), Charsets.UTF_8);

    // STEP 2: get a stream for the JSON file

    final InputStream io_stream = new FileInputStream(new File(args[1]));

    // STEP 3: set up control if applicable

    Optional<JsonNode> json = Optional.of("").filter(__ -> args.length > 3).map(__ -> args[3])
            .map(Lambdas.wrap_u(j -> _mapper.readTree(j)));

    // STEP 4: set up the various objects

    final DataBucketBean bucket = Mockito.mock(DataBucketBean.class);

    final JsScriptEngineService service_under_test = new JsScriptEngineService();

    final LinkedList<ObjectNode> emitted = new LinkedList<>();
    final LinkedList<JsonNode> grouped = new LinkedList<>();
    final LinkedList<JsonNode> externally_emitted = new LinkedList<>();

    final IEnrichmentModuleContext context = Mockito.mock(IEnrichmentModuleContext.class, new Answer<Void>() {
        @SuppressWarnings("unchecked")
        public Void answer(InvocationOnMock invocation) {
            try {
                Object[] args = invocation.getArguments();
                if (invocation.getMethod().getName().equals("emitMutableObject")) {
                    final Optional<JsonNode> grouping = (Optional<JsonNode>) args[3];
                    if (grouping.isPresent()) {
                        grouped.add(grouping.get());
                    }
                    emitted.add((ObjectNode) args[1]);
                } else if (invocation.getMethod().getName().equals("externalEmit")) {
                    final DataBucketBean to = (DataBucketBean) args[0];
                    final Either<JsonNode, Map<String, Object>> out = (Either<JsonNode, Map<String, Object>>) args[1];
                    externally_emitted
                            .add(((ObjectNode) out.left().value()).put("__a2_bucket", to.full_name()));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }
    });

    final EnrichmentControlMetadataBean control = BeanTemplateUtils.build(EnrichmentControlMetadataBean.class)
            .with(EnrichmentControlMetadataBean::config,
                    new LinkedHashMap<String, Object>(
                            ImmutableMap.<String, Object>builder().put("script", user_script).build()))
            .done().get();

    service_under_test.onStageInitialize(context, bucket, control,
            Tuples._2T(ProcessingStage.batch, ProcessingStage.grouping), Optional.empty());

    final BeJsonParser json_parser = new BeJsonParser();

    // Run the file through

    final Stream<Tuple2<Long, IBatchRecord>> json_stream = StreamUtils
            .takeUntil(Stream.generate(() -> json_parser.getNextRecord(io_stream)), i -> null == i)
            .map(j -> Tuples._2T(0L, new BatchRecord(j)));

    service_under_test.onObjectBatch(json_stream, json.map(j -> j.get("len")).map(j -> (int) j.asLong(0L)),
            json.map(j -> j.get("group")));

    System.out.println("RESULTS: ");
    System.out.println("emitted: " + emitted.size());
    System.out.println("grouped: " + grouped.size());
    System.out.println("externally emitted: " + externally_emitted.size());
    Files.write(emitted.stream().map(j -> j.toString()).collect(Collectors.joining(";")),
            new File(args[2] + "emit.json"), Charsets.UTF_8);
    Files.write(grouped.stream().map(j -> j.toString()).collect(Collectors.joining(";")),
            new File(args[2] + "group.json"), Charsets.UTF_8);
    Files.write(externally_emitted.stream().map(j -> j.toString()).collect(Collectors.joining(";")),
            new File(args[2] + "external_emit.json"), Charsets.UTF_8);
}

From source file:edu.jhu.hlt.concrete.ingesters.simple.CompleteFileIngester.java

/**
 * See usage string.//from ww w . j a  v a2 s.c  o  m
 *
 * @param args
 */
public static void main(String[] args) {
    if (args.length != 3) {
        System.err.println("This program converts a character-based file to a .concrete file.");
        System.err.println("The text file must contain UTF-8 encoded characters.");
        System.err.println(
                "The .concrete file will share the same name as the input file, including the extension.");
        System.err.println("This program takes 3 arguments.");
        System.err.println("Argument 1: path/to/a/character/based/file");
        System.err.println("Argument 2: type of Communication to generate [e.g., tweet]");
        System.err.println("Argument 3: path/to/output/folder");
        System.err.println("Example usage: " + CompleteFileIngester.class.getName()
                + " /my/text/file story /my/output/folder");
        System.exit(1);
    }

    String inPathStr = args[0];
    Path inPath = Paths.get(inPathStr);
    try {
        ExistingNonDirectoryFile ef = new ExistingNonDirectoryFile(inPath);
        Optional<String> commType = Optional.ofNullable(args[1]);
        Optional<String> outPathStr = Optional.ofNullable(args[2]);

        Path ep = ef.getPath();
        String fn = ef.getName();
        Path outPath = Paths.get(outPathStr.get());
        Path outFile = outPath.resolve(fn + ".concrete");

        // Output directory exists, or it doesn't.
        // Try to create if it does not.
        if (!Files.exists(outPath)) {
            try {
                Files.createDirectories(outPath);
            } catch (IOException e) {
                logger.error("Caught exception when making output directories.", e);
            }

            // if it does, check to make sure it's a directory.
        } else {
            if (!Files.isDirectory(outPath)) {
                logger.error("Output path exists but is not a directory.");
                System.exit(1);
            } else {
                // check to make sure the output file won't be overwritten.
                if (Files.exists(outFile)) {
                    logger.warn("Output file {} exists; not overwriting.", outFile.toString());
                    System.exit(1);
                }
            }
        }

        try {
            UTF8FileIngester ing = new CompleteFileIngester(commType.get());
            Communication comm = ing.fromCharacterBasedFile(ep);
            new WritableCommunication(comm).writeToFile(outFile, false);
        } catch (IngestException e) {
            logger.error("Caught exception during ingest.", e);
            System.exit(1);
        } catch (ConcreteException e) {
            logger.error("Caught exception writing output.", e);
        }

    } catch (NoSuchFileException e) {
        logger.error("Path {} does not exist.", inPathStr);
        System.exit(1);
    } catch (NotFileException e) {
        logger.error("Path {} is a directory.", inPathStr);
        System.exit(1);
    }
}

From source file:edu.jhu.hlt.concrete.ingesters.simple.DoubleLineBreakFileIngester.java

/**
 * See usage string.//from   www. j a v a  2  s.  c o  m
 *
 * @param args
 */
public static void main(String[] args) {
    if (args.length != 4) {
        System.err.println("This program converts a character-based file to a .concrete file.");
        System.err.println("The text file must contain UTF-8 encoded characters.");
        System.err.println(
                "If the file contains any double-newlines, the file will be split into sections where those double-newlines occur.");
        System.err.println(
                "The .concrete file will share the same name as the input file, including the extension.");
        System.err.println("This program takes 4 arguments.");
        System.err.println("Argument 1: path/to/a/character/based/file");
        System.err.println("Argument 2: type of Communication to generate [e.g., tweet]");
        System.err.println("Argument 3: type of Sections to generate [e.g., passage]");
        System.err.println("Argument 4: path/to/out/concrete/file");
        System.err.println("Example usage: " + CompleteFileIngester.class.getName()
                + " /my/text/file story passage /my/output/folder");
        System.exit(1);
    }

    String inPathStr = args[0];
    Path inPath = Paths.get(inPathStr);
    try {
        ExistingNonDirectoryFile ef = new ExistingNonDirectoryFile(inPath);
        Optional<String> commType = Optional.ofNullable(args[1]);
        Optional<String> sectionType = Optional.ofNullable(args[2]);
        Optional<String> outPathStr = Optional.ofNullable(args[3]);

        Path ep = ef.getPath();
        String fn = ef.getName();
        Path outPath = Paths.get(outPathStr.get());
        Path outFile = outPath.resolve(fn + ".concrete");

        // Output directory exists, or it doesn't.
        // Try to create if it does not.
        if (!Files.exists(outPath)) {
            try {
                Files.createDirectories(outPath);
            } catch (IOException e) {
                logger.error("Caught exception when making output directories.", e);
            }

            // if it does, check to make sure it's a directory.
        } else {
            if (!Files.isDirectory(outPath)) {
                logger.error("Output path exists but is not a directory.");
                System.exit(1);
            } else {
                // check to make sure the output file won't be overwritten.
                if (Files.exists(outFile)) {
                    logger.warn("Output file {} exists; not overwriting.", outFile.toString());
                    System.exit(1);
                }
            }
        }

        try {
            UTF8FileIngester ing = new DoubleLineBreakFileIngester(commType.get(), sectionType.get());
            Communication comm = ing.fromCharacterBasedFile(ep);
            new WritableCommunication(comm).writeToFile(outFile, false);
        } catch (IngestException e) {
            logger.error("Caught exception during ingest.", e);
            System.exit(1);
        } catch (ConcreteException e) {
            logger.error("Caught exception writing output.", e);
        }

    } catch (NoSuchFileException e) {
        logger.error("Path {} does not exist.", inPathStr);
        System.exit(1);
    } catch (NotFileException e) {
        logger.error("Path {} is a directory.", inPathStr);
        System.exit(1);
    }
}

From source file:com.hortonworks.registries.storage.tool.sql.DatabaseUserInitializer.java

public static void main(String[] args) throws Exception {
    Options options = new Options();

    options.addOption(Option.builder("c").numberOfArgs(1).longOpt(OPTION_CONFIG_FILE_PATH)
            .desc("Config file path").build());

    options.addOption(Option.builder("m").numberOfArgs(1).longOpt(OPTION_MYSQL_JAR_URL_PATH)
            .desc("Mysql client jar url to download").build());

    options.addOption(Option.builder().hasArg().longOpt(OPTION_ADMIN_JDBC_URL)
            .desc("JDBC url to connect DBMS via admin.").build());

    options.addOption(Option.builder().hasArg().longOpt(OPTION_ADMIN_DB_USER)
            .desc("Admin user name: should be able to create and grant privileges.").build());

    options.addOption(Option.builder().hasArg().longOpt(OPTION_ADMIN_PASSWORD)
            .desc("Admin user's password: should be able to create and grant privileges.").build());

    options.addOption(/*from  w ww. j a  v a2  s . c o m*/
            Option.builder().hasArg().longOpt(OPTION_TARGET_USER).desc("Name of target user.").build());

    options.addOption(
            Option.builder().hasArg().longOpt(OPTION_TARGET_PASSWORD).desc("Password of target user.").build());

    options.addOption(
            Option.builder().hasArg().longOpt(OPTION_TARGET_DATABASE).desc("Target database.").build());

    CommandLineParser parser = new BasicParser();
    CommandLine commandLine = parser.parse(options, args);

    String[] neededOptions = { OPTION_CONFIG_FILE_PATH, OPTION_MYSQL_JAR_URL_PATH, OPTION_ADMIN_JDBC_URL,
            OPTION_ADMIN_DB_USER, OPTION_ADMIN_PASSWORD, OPTION_TARGET_USER, OPTION_TARGET_PASSWORD,
            OPTION_TARGET_DATABASE };

    boolean optNotFound = Arrays.stream(neededOptions).anyMatch(opt -> !commandLine.hasOption(opt));
    if (optNotFound) {
        usage(options);
        System.exit(1);
    }

    String confFilePath = commandLine.getOptionValue(OPTION_CONFIG_FILE_PATH);
    String mysqlJarUrl = commandLine.getOptionValue(OPTION_MYSQL_JAR_URL_PATH);

    Optional<AdminOptions> adminOptionsOptional = AdminOptions.from(commandLine);
    if (!adminOptionsOptional.isPresent()) {
        usage(options);
        System.exit(1);
    }

    AdminOptions adminOptions = adminOptionsOptional.get();

    Optional<TargetOptions> targetOptionsOptional = TargetOptions.from(commandLine);
    if (!targetOptionsOptional.isPresent()) {
        usage(options);
        System.exit(1);
    }

    TargetOptions targetOptions = targetOptionsOptional.get();

    DatabaseType databaseType = findDatabaseType(adminOptions.getJdbcUrl());

    Map<String, Object> conf;
    try {
        conf = Utils.readConfig(confFilePath);
    } catch (IOException e) {
        System.err.println("Error occurred while reading config file: " + confFilePath);
        System.exit(1);
        throw new IllegalStateException("Shouldn't reach here");
    }

    String bootstrapDirPath = null;
    try {
        bootstrapDirPath = System.getProperty("bootstrap.dir");
        Proxy proxy = Proxy.NO_PROXY;
        String httpProxyUrl = (String) conf.get(HTTP_PROXY_URL);
        String httpProxyUsername = (String) conf.get(HTTP_PROXY_USERNAME);
        String httpProxyPassword = (String) conf.get(HTTP_PROXY_PASSWORD);
        if ((httpProxyUrl != null) && !httpProxyUrl.isEmpty()) {
            URL url = new URL(httpProxyUrl);
            proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(url.getHost(), url.getPort()));
            if ((httpProxyUsername != null) && !httpProxyUsername.isEmpty()) {
                Authenticator.setDefault(getBasicAuthenticator(url.getHost(), url.getPort(), httpProxyUsername,
                        httpProxyPassword));
            }
        }

        StorageProviderConfiguration storageProperties = StorageProviderConfiguration.get(
                adminOptions.getJdbcUrl(), adminOptions.getUsername(), adminOptions.getPassword(),
                adminOptions.getDatabaseType());

        MySqlDriverHelper.downloadMySQLJarIfNeeded(storageProperties, bootstrapDirPath, mysqlJarUrl, proxy);
    } catch (Exception e) {
        System.err.println("Error occurred while downloading MySQL jar. bootstrap dir: " + bootstrapDirPath);
        System.exit(1);
        throw new IllegalStateException("Shouldn't reach here");
    }

    try (Connection conn = getConnectionViaAdmin(adminOptions)) {
        DatabaseCreator databaseCreator = DatabaseCreatorFactory.newInstance(adminOptions.getDatabaseType(),
                conn);
        UserCreator userCreator = UserCreatorFactory.newInstance(adminOptions.getDatabaseType(), conn);

        String database = targetOptions.getDatabase();
        String username = targetOptions.getUsername();

        createDatabase(databaseCreator, database);
        createUser(targetOptions, userCreator, username);
        grantPrivileges(databaseCreator, database, username);
    }
}

From source file:acmi.l2.clientmod.l2_version_switcher.Main.java

public static void main(String[] args) {
    if (args.length != 3 && args.length != 4) {
        System.out.println("USAGE: l2_version_switcher.jar host game version <--splash> <filter>");
        System.out.println("EXAMPLE: l2_version_switcher.jar " + L2.NCWEST_HOST + " " + L2.NCWEST_GAME
                + " 1 \"system\\*\"");
        System.out.println(/* w w w  .  j  a va 2s . c  o  m*/
                "         l2_version_switcher.jar " + L2.PLAYNC_TEST_HOST + " " + L2.PLAYNC_TEST_GAME + " 48");
        System.exit(0);
    }

    List<String> argsList = new ArrayList<>(Arrays.asList(args));
    String host = argsList.get(0);
    String game = argsList.get(1);
    int version = Integer.parseInt(argsList.get(2));
    Helper helper = new Helper(host, game, version);
    boolean available = false;

    try {
        available = helper.isAvailable();
    } catch (IOException e) {
        System.err.print(e.getClass().getSimpleName());
        if (e.getMessage() != null) {
            System.err.print(": " + e.getMessage());
        }

        System.err.println();
    }

    System.out.println(String.format("Version %d available: %b", version, available));
    if (!available) {
        System.exit(0);
    }

    List<FileInfo> fileInfoList = null;
    try {
        fileInfoList = helper.getFileInfoList();
    } catch (IOException e) {
        System.err.println("Couldn\'t get file info map");
        System.exit(1);
    }

    boolean splash = argsList.remove("--splash");
    if (splash) {
        Optional<FileInfo> splashObj = fileInfoList.stream()
                .filter(fi -> fi.getPath().contains("sp_32b_01.bmp")).findAny();
        if (splashObj.isPresent()) {
            try (InputStream is = new FilterInputStream(
                    Util.getUnzipStream(helper.getDownloadStream(splashObj.get().getPath()))) {
                @Override
                public int read() throws IOException {
                    int b = super.read();
                    if (b >= 0)
                        b ^= 0x36;
                    return b;
                }

                @Override
                public int read(byte[] b, int off, int len) throws IOException {
                    int r = super.read(b, off, len);
                    if (r >= 0) {
                        for (int i = 0; i < r; i++)
                            b[off + i] ^= 0x36;
                    }
                    return r;
                }
            }) {
                new DataInputStream(is).readFully(new byte[28]);
                BufferedImage bi = ImageIO.read(is);

                JFrame frame = new JFrame("Lineage 2 [" + version + "] " + splashObj.get().getPath());
                frame.setContentPane(new JComponent() {
                    {
                        setPreferredSize(new Dimension(bi.getWidth(), bi.getHeight()));
                    }

                    @Override
                    protected void paintComponent(Graphics g) {
                        g.drawImage(bi, 0, 0, null);
                    }
                });
                frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            System.out.println("Splash not found");
        }
        return;
    }

    String filter = argsList.size() > 3 ? separatorsToSystem(argsList.get(3)) : null;

    File l2Folder = new File(System.getProperty("user.dir"));
    List<FileInfo> toUpdate = fileInfoList.parallelStream().filter(fi -> {
        String filePath = separatorsToSystem(fi.getPath());

        if (filter != null && !wildcardMatch(filePath, filter, IOCase.INSENSITIVE))
            return false;
        File file = new File(l2Folder, filePath);

        try {
            if (file.exists() && file.length() == fi.getSize() && Util.hashEquals(file, fi.getHash())) {
                System.out.println(filePath + ": OK");
                return false;
            }
        } catch (IOException e) {
            System.out.println(filePath + ": couldn't check hash: " + e);
            return true;
        }

        System.out.println(filePath + ": need update");
        return true;
    }).collect(Collectors.toList());

    List<String> errors = Collections.synchronizedList(new ArrayList<>());
    ExecutorService executor = Executors.newFixedThreadPool(16);
    CompletableFuture[] tasks = toUpdate.stream().map(fi -> CompletableFuture.runAsync(() -> {
        String filePath = separatorsToSystem(fi.getPath());
        File file = new File(l2Folder, filePath);

        File folder = file.getParentFile();
        if (!folder.exists()) {
            if (!folder.mkdirs()) {
                errors.add(filePath + ": couldn't create parent dir");
                return;
            }
        }

        try (InputStream input = Util
                .getUnzipStream(new BufferedInputStream(helper.getDownloadStream(fi.getPath())));
                OutputStream output = new BufferedOutputStream(new FileOutputStream(file))) {
            byte[] buffer = new byte[Math.min(fi.getSize(), 1 << 24)];
            int pos = 0;
            int r;
            while ((r = input.read(buffer, pos, buffer.length - pos)) >= 0) {
                pos += r;
                if (pos == buffer.length) {
                    output.write(buffer, 0, pos);
                    pos = 0;
                }
            }
            if (pos != 0) {
                output.write(buffer, 0, pos);
            }
            System.out.println(filePath + ": OK");
        } catch (IOException e) {
            String msg = filePath + ": FAIL: " + e.getClass().getSimpleName();
            if (e.getMessage() != null) {
                msg += ": " + e.getMessage();
            }
            errors.add(msg);
        }
    }, executor)).toArray(CompletableFuture[]::new);
    CompletableFuture.allOf(tasks).thenRun(() -> {
        for (String err : errors)
            System.err.println(err);
        executor.shutdown();
    });
}

From source file:com.hurence.logisland.runner.SparkJobLauncher.java

/**
 * main entry point//from  w w  w.  j  a  va  2 s .c  o  m
 *
 * @param args
 */
public static void main(String[] args) {

    logger.info("starting StreamProcessingRunner");

    //////////////////////////////////////////
    // Commande lien management
    Parser parser = new GnuParser();
    Options options = new Options();

    String helpMsg = "Print this message.";
    Option help = new Option("help", helpMsg);
    options.addOption(help);

    OptionBuilder.withArgName(AGENT);
    OptionBuilder.withLongOpt("agent-quorum");
    OptionBuilder.isRequired();
    OptionBuilder.hasArg();
    OptionBuilder.withDescription("logisland agent quorum like host1:8081,host2:8081");
    Option agent = OptionBuilder.create(AGENT);
    options.addOption(agent);

    OptionBuilder.withArgName(JOB);
    OptionBuilder.withLongOpt("job-name");
    OptionBuilder.isRequired();
    OptionBuilder.hasArg();
    OptionBuilder.withDescription("logisland agent quorum like host1:8081,host2:8081");
    Option job = OptionBuilder.create(JOB);
    options.addOption(job);

    String logisland = "                      \n"
            + "     ????????   ?????     ??  ??\n"
            + "                    \n"
            + "             ????     ??  \n"
            + "??     ?\n"
            + "??????? ??????  ??????   ??????????????????  ????  ??????????   v0.10.0-SNAPSHOT\n\n\n";

    System.out.println(logisland);
    Optional<EngineContext> engineInstance = Optional.empty();
    try {
        // parse the command line arguments
        CommandLine line = parser.parse(options, args);
        String agentQuorum = line.getOptionValue(AGENT);
        String jobName = line.getOptionValue(JOB);

        // instanciate engine and all the processor from the config
        engineInstance = new RestComponentFactory(agentQuorum).getEngineContext(jobName);
        assert engineInstance.isPresent();
        assert engineInstance.get().isValid();

        logger.info("starting Logisland session version {}", engineInstance.get());
    } catch (Exception e) {
        logger.error("unable to launch runner : {}", e.toString());
    }

    try {
        // start the engine
        EngineContext engineContext = engineInstance.get();
        engineInstance.get().getEngine().start(engineContext);
    } catch (Exception e) {
        logger.error("something went bad while running the job : {}", e);
        System.exit(-1);
    }

}

From source file:com.hurence.logisland.runner.StreamProcessingRunner.java

/**
 * main entry point//from   ww  w .j ava 2  s . c  o m
 *
 * @param args
 */
public static void main(String[] args) {

    logger.info("starting StreamProcessingRunner");

    //////////////////////////////////////////
    // Commande lien management
    Parser parser = new GnuParser();
    Options options = new Options();

    String helpMsg = "Print this message.";
    Option help = new Option("help", helpMsg);
    options.addOption(help);

    OptionBuilder.withArgName("conf");
    OptionBuilder.withLongOpt("config-file");
    OptionBuilder.isRequired();
    OptionBuilder.hasArg();
    OptionBuilder.withDescription("config file path");
    Option conf = OptionBuilder.create("conf");
    options.addOption(conf);

    Optional<EngineContext> engineInstance = Optional.empty();
    try {
        System.out.println(BannerLoader.loadBanner());

        // parse the command line arguments
        CommandLine line = parser.parse(options, args);
        String configFile = line.getOptionValue("conf");

        // load the YAML config
        LogislandConfiguration sessionConf = ConfigReader.loadConfig(configFile);

        // instantiate engine and all the processor from the config
        engineInstance = ComponentFactory.getEngineContext(sessionConf.getEngine());
        if (!engineInstance.isPresent()) {
            throw new IllegalArgumentException("engineInstance could not be instantiated");
        }
        if (!engineInstance.get().isValid()) {
            throw new IllegalArgumentException("engineInstance is not valid with input configuration !");
        }
        logger.info("starting Logisland session version {}", sessionConf.getVersion());
        logger.info(sessionConf.getDocumentation());
    } catch (Exception e) {
        logger.error("unable to launch runner", e);
        System.exit(-1);
    }
    String engineName = engineInstance.get().getEngine().getIdentifier();
    try {
        // start the engine
        EngineContext engineContext = engineInstance.get();
        logger.info("start engine {}", engineName);
        engineInstance.get().getEngine().start(engineContext);
        logger.info("awaitTermination for engine {}", engineName);
        engineContext.getEngine().awaitTermination(engineContext);
        System.exit(0);
    } catch (Exception e) {
        logger.error("something went bad while running the job {} : {}", engineName, e);
        System.exit(-1);
    }

}

From source file:edu.nyupoly.cs6903.ag3671.FTPClientExample.java

public static void main(String[] args) throws UnknownHostException, Exception {
    // MY CODE//from w  w w  .j  a va2  s.  c  om
    if (crypto(Collections.unmodifiableList(Arrays.asList(args)))) {
        return;
    }
    ;
    // MY CODE -- END

    boolean storeFile = false, binaryTransfer = true, error = false, listFiles = false, listNames = false,
            hidden = false;
    boolean localActive = false, useEpsvWithIPv4 = false, feat = false, printHash = false;
    boolean mlst = false, mlsd = false;
    boolean lenient = false;
    long keepAliveTimeout = -1;
    int controlKeepAliveReplyTimeout = -1;
    int minParams = 5; // listings require 3 params
    String protocol = null; // SSL protocol
    String doCommand = null;
    String trustmgr = null;
    String proxyHost = null;
    int proxyPort = 80;
    String proxyUser = null;
    String proxyPassword = null;
    String username = null;
    String password = null;

    int base = 0;
    for (base = 0; base < args.length; base++) {
        if (args[base].equals("-s")) {
            storeFile = true;
        } else if (args[base].equals("-a")) {
            localActive = true;
        } else if (args[base].equals("-A")) {
            username = "anonymous";
            password = System.getProperty("user.name") + "@" + InetAddress.getLocalHost().getHostName();
        }
        // Always use binary transfer 
        //            else if (args[base].equals("-b")) {
        //                binaryTransfer = true;
        //            }
        else if (args[base].equals("-c")) {
            doCommand = args[++base];
            minParams = 3;
        } else if (args[base].equals("-d")) {
            mlsd = true;
            minParams = 3;
        } else if (args[base].equals("-e")) {
            useEpsvWithIPv4 = true;
        } else if (args[base].equals("-f")) {
            feat = true;
            minParams = 3;
        } else if (args[base].equals("-h")) {
            hidden = true;
        } else if (args[base].equals("-k")) {
            keepAliveTimeout = Long.parseLong(args[++base]);
        } else if (args[base].equals("-l")) {
            listFiles = true;
            minParams = 3;
        } else if (args[base].equals("-L")) {
            lenient = true;
        } else if (args[base].equals("-n")) {
            listNames = true;
            minParams = 3;
        } else if (args[base].equals("-p")) {
            protocol = args[++base];
        } else if (args[base].equals("-t")) {
            mlst = true;
            minParams = 3;
        } else if (args[base].equals("-w")) {
            controlKeepAliveReplyTimeout = Integer.parseInt(args[++base]);
        } else if (args[base].equals("-T")) {
            trustmgr = args[++base];
        } else if (args[base].equals("-PrH")) {
            proxyHost = args[++base];
            String parts[] = proxyHost.split(":");
            if (parts.length == 2) {
                proxyHost = parts[0];
                proxyPort = Integer.parseInt(parts[1]);
            }
        } else if (args[base].equals("-PrU")) {
            proxyUser = args[++base];
        } else if (args[base].equals("-PrP")) {
            proxyPassword = args[++base];
        } else if (args[base].equals("-#")) {
            printHash = true;
        } else {
            break;
        }
    }

    int remain = args.length - base;
    if (username != null) {
        minParams -= 2;
    }
    if (remain < minParams) // server, user, pass, remote, local [protocol]
    {
        System.err.println(USAGE);
        System.exit(1);
    }

    String server = args[base++];
    int port = 0;
    String parts[] = server.split(":");
    if (parts.length == 2) {
        server = parts[0];
        port = Integer.parseInt(parts[1]);
    }
    if (username == null) {
        username = args[base++];
        password = args[base++];
    }

    String remote = null;
    if (args.length - base > 0) {
        remote = args[base++];
    }

    String local = null;
    if (args.length - base > 0) {
        local = args[base++];
    }

    final FTPClient ftp;
    if (protocol == null) {
        if (proxyHost != null) {
            System.out.println("Using HTTP proxy server: " + proxyHost);
            ftp = new FTPHTTPClient(proxyHost, proxyPort, proxyUser, proxyPassword);
        } else {
            ftp = new FTPClient();
        }
    } else {
        FTPSClient ftps;
        if (protocol.equals("true")) {
            ftps = new FTPSClient(true);
        } else if (protocol.equals("false")) {
            ftps = new FTPSClient(false);
        } else {
            String prot[] = protocol.split(",");
            if (prot.length == 1) { // Just protocol
                ftps = new FTPSClient(protocol);
            } else { // protocol,true|false
                ftps = new FTPSClient(prot[0], Boolean.parseBoolean(prot[1]));
            }
        }
        ftp = ftps;
        if ("all".equals(trustmgr)) {
            ftps.setTrustManager(TrustManagerUtils.getAcceptAllTrustManager());
        } else if ("valid".equals(trustmgr)) {
            ftps.setTrustManager(TrustManagerUtils.getValidateServerCertificateTrustManager());
        } else if ("none".equals(trustmgr)) {
            ftps.setTrustManager(null);
        }
    }

    if (printHash) {
        ftp.setCopyStreamListener(createListener());
    }
    if (keepAliveTimeout >= 0) {
        ftp.setControlKeepAliveTimeout(keepAliveTimeout);
    }
    if (controlKeepAliveReplyTimeout >= 0) {
        ftp.setControlKeepAliveReplyTimeout(controlKeepAliveReplyTimeout);
    }
    ftp.setListHiddenFiles(hidden);

    // suppress login details
    ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out), true));

    try {
        int reply;
        if (port > 0) {
            ftp.connect(server, port);
        } else {
            ftp.connect(server);
        }
        System.out.println("Connected to " + server + " on " + (port > 0 ? port : ftp.getDefaultPort()));

        // After connection attempt, you should check the reply code to verify
        // success.
        reply = ftp.getReplyCode();

        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            System.err.println("FTP server refused connection.");
            System.exit(1);
        }
    } catch (IOException e) {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException f) {
                // do nothing
            }
        }
        System.err.println("Could not connect to server.");
        e.printStackTrace();
        System.exit(1);
    }

    __main: try {
        if (!ftp.login(username, password)) {
            ftp.logout();
            error = true;
            break __main;
        }

        System.out.println("Remote system is " + ftp.getSystemType());

        if (binaryTransfer) {
            ftp.setFileType(FTP.BINARY_FILE_TYPE);
        } else {
            // in theory this should not be necessary as servers should default to ASCII
            // but they don't all do so - see NET-500
            ftp.setFileType(FTP.ASCII_FILE_TYPE);
        }

        // Use passive mode as default because most of us are
        // behind firewalls these days.
        if (localActive) {
            ftp.enterLocalActiveMode();
        } else {
            ftp.enterLocalPassiveMode();
        }

        ftp.setUseEPSVwithIPv4(useEpsvWithIPv4);

        if (storeFile) {
            InputStream input;

            input = new FileInputStream(local);
            // MY CODE
            byte[] bytes = IOUtils.toByteArray(input);
            InputStream encrypted = new ByteArrayInputStream(cryptor.encrypt(bytes));
            // MY CODE -- END
            ftp.storeFile(remote, encrypted);

            input.close();
        } else if (listFiles) {
            if (lenient) {
                FTPClientConfig config = new FTPClientConfig();
                config.setLenientFutureDates(true);
                ftp.configure(config);
            }

            for (FTPFile f : ftp.listFiles(remote)) {
                System.out.println(f.getRawListing());
                System.out.println(f.toFormattedString());
            }
        } else if (mlsd) {
            for (FTPFile f : ftp.mlistDir(remote)) {
                System.out.println(f.getRawListing());
                System.out.println(f.toFormattedString());
            }
        } else if (mlst) {
            FTPFile f = ftp.mlistFile(remote);
            if (f != null) {
                System.out.println(f.toFormattedString());
            }
        } else if (listNames) {
            for (String s : ftp.listNames(remote)) {
                System.out.println(s);
            }
        } else if (feat) {
            // boolean feature check
            if (remote != null) { // See if the command is present
                if (ftp.hasFeature(remote)) {
                    System.out.println("Has feature: " + remote);
                } else {
                    if (FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
                        System.out.println("FEAT " + remote + " was not detected");
                    } else {
                        System.out.println("Command failed: " + ftp.getReplyString());
                    }
                }

                // Strings feature check
                String[] features = ftp.featureValues(remote);
                if (features != null) {
                    for (String f : features) {
                        System.out.println("FEAT " + remote + "=" + f + ".");
                    }
                } else {
                    if (FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
                        System.out.println("FEAT " + remote + " is not present");
                    } else {
                        System.out.println("Command failed: " + ftp.getReplyString());
                    }
                }
            } else {
                if (ftp.features()) {
                    //                        Command listener has already printed the output
                } else {
                    System.out.println("Failed: " + ftp.getReplyString());
                }
            }
        } else if (doCommand != null) {
            if (ftp.doCommand(doCommand, remote)) {
                //                  Command listener has already printed the output
                //                    for(String s : ftp.getReplyStrings()) {
                //                        System.out.println(s);
                //                    }
            } else {
                System.out.println("Failed: " + ftp.getReplyString());
            }
        } else {
            OutputStream output;

            output = new FileOutputStream(local);

            // MY CODE
            ByteArrayOutputStream remoteFile = new ByteArrayOutputStream();
            //InputStream byteIn = new ByteArrayInputStream(buf);
            ftp.retrieveFile(remote, remoteFile);
            remoteFile.flush();
            Optional<byte[]> opt = cryptor.decrypt(remoteFile.toByteArray());
            if (opt.isPresent()) {
                output.write(opt.get());
            }
            remoteFile.close();
            // MY CODE -- END
            output.close();
        }

        ftp.noop(); // check that control connection is working OK

        ftp.logout();
    } catch (FTPConnectionClosedException e) {
        error = true;
        System.err.println("Server closed connection.");
        e.printStackTrace();
    } catch (IOException e) {
        error = true;
        e.printStackTrace();
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException f) {
                // do nothing
            }
        }
    }

    System.exit(error ? 1 : 0);
}

From source file:com.arpnetworking.metrics.mad.Main.java

/**
 * Entry point for Metrics Aggregator Daemon (MAD).
 *
 * @param args the command line arguments
 *///from   ww  w.j  a v a2 s.c  o  m
public static void main(final String[] args) {
    // Global initialization
    Thread.setDefaultUncaughtExceptionHandler((thread, throwable) -> {
        System.err.println("Unhandled exception! exception: " + throwable.toString());
        throwable.printStackTrace(System.err);
    });

    Thread.currentThread().setUncaughtExceptionHandler((thread, throwable) -> LOGGER.error()
            .setMessage("Unhandled exception!").setThrowable(throwable).log());

    LOGGER.info().setMessage("Launching mad").log();

    Runtime.getRuntime().addShutdownHook(SHUTDOWN_THREAD);

    System.setProperty("org.vertx.logger-delegate-factory-class-name",
            "org.vertx.java.core.logging.impl.SLF4JLogDelegateFactory");

    // Run the tsd aggregator
    if (args.length != 1) {
        throw new RuntimeException("No configuration file specified");
    }
    LOGGER.debug().setMessage("Loading configuration").addData("file", args[0]).log();

    Optional<DynamicConfiguration> configuration = Optional.empty();
    Optional<Configurator<Main, AggregatorConfiguration>> configurator = Optional.empty();
    try {
        final File configurationFile = new File(args[0]);
        configurator = Optional.of(new Configurator<>(Main::new, AggregatorConfiguration.class));
        configuration = Optional.of(new DynamicConfiguration.Builder().setObjectMapper(OBJECT_MAPPER)
                .addSourceBuilder(getFileSourceBuilder(configurationFile))
                .addTrigger(new FileTrigger.Builder().setFile(configurationFile).build())
                .addListener(configurator.get()).build());

        configuration.get().launch();
        // Wait for application shutdown
        SHUTDOWN_SEMAPHORE.acquire();
    } catch (final InterruptedException e) {
        throw Throwables.propagate(e);
    } finally {
        if (configurator.isPresent()) {
            configurator.get().shutdown();
        }
        if (configuration.isPresent()) {
            configuration.get().shutdown();
        }
        // Notify the shutdown that we're done
        SHUTDOWN_SEMAPHORE.release();
    }
}