Example usage for java.nio.file Paths get

List of usage examples for java.nio.file Paths get

Introduction

In this page you can find the example usage for java.nio.file Paths get.

Prototype

public static Path get(URI uri) 

Source Link

Document

Converts the given URI to a Path object.

Usage

From source file:edu.usc.goffish.gofs.tools.GoFSFormat.java

public static void main(String[] args) throws IOException {
    if (args.length < REQUIRED_ARGS) {
        PrintUsageAndQuit(null);/*from  ww  w .  ja va  2 s .c o  m*/
    }

    if (args.length == 1 && args[0].equals("-help")) {
        PrintUsageAndQuit(null);
    }

    Path executableDirectory;
    try {
        executableDirectory = Paths
                .get(GoFSFormat.class.getProtectionDomain().getCodeSource().getLocation().toURI()).getParent();
    } catch (URISyntaxException e) {
        throw new RuntimeException("Unexpected error retrieving executable location", e);
    }
    Path configPath = executableDirectory.resolve(DEFAULT_CONFIG).normalize();

    boolean copyBinaries = false;

    // parse optional arguments
    int i = 0;
    OptArgLoop: for (i = 0; i < args.length - REQUIRED_ARGS; i++) {
        switch (args[i]) {
        case "-config":
            i++;

            try {
                configPath = Paths.get(args[i]);
            } catch (InvalidPathException e) {
                PrintUsageAndQuit("Config file - " + e.getMessage());
            }

            break;
        case "-copyBinaries":
            copyBinaries = true;
            break;
        default:
            break OptArgLoop;
        }
    }

    if (args.length - i < REQUIRED_ARGS) {
        PrintUsageAndQuit(null);
    }

    // finished parsing args
    if (i < args.length) {
        PrintUsageAndQuit("Unrecognized argument \"" + args[i] + "\"");
    }

    // parse config

    System.out.println("Parsing config...");

    PropertiesConfiguration config = new PropertiesConfiguration();
    config.setDelimiterParsingDisabled(true);
    try {
        config.load(Files.newInputStream(configPath));
    } catch (ConfigurationException e) {
        throw new IOException(e);
    }

    // retrieve data nodes
    ArrayList<URI> dataNodes;
    {
        String[] dataNodesArray = config.getStringArray(GOFS_DATANODES_KEY);
        if (dataNodesArray.length == 0) {
            throw new ConversionException("Config must contain key " + GOFS_DATANODES_KEY);
        }

        dataNodes = new ArrayList<>(dataNodesArray.length);

        if (dataNodesArray.length == 0) {
            throw new ConversionException("Config key " + GOFS_DATANODES_KEY
                    + " has invalid format - must define at least one data node");
        }

        try {
            for (String node : dataNodesArray) {
                URI dataNodeURI = new URI(node);

                if (!"file".equalsIgnoreCase(dataNodeURI.getScheme())) {
                    throw new ConversionException("config key " + GOFS_DATANODES_KEY + " value \"" + dataNodeURI
                            + "\" has invalid format - data node urls must have 'file' scheme");
                } else if (dataNodeURI.getPath() == null || dataNodeURI.getPath().isEmpty()) {
                    throw new ConversionException("config key " + GOFS_DATANODES_KEY + " value \"" + dataNodeURI
                            + "\" has invalid format - data node urls must have an absolute path specified");
                }

                // ensure uri ends with a slash, so we know it is a directory
                if (!dataNodeURI.getPath().endsWith("/")) {
                    dataNodeURI = dataNodeURI.resolve(dataNodeURI.getPath() + "/");
                }

                dataNodes.add(dataNodeURI);
            }
        } catch (URISyntaxException e) {
            throw new ConversionException(
                    "Config key " + GOFS_DATANODES_KEY + " has invalid format - " + e.getMessage());
        }
    }

    // validate serializer type
    Class<? extends ISliceSerializer> serializerType;
    {
        String serializerTypeName = config.getString(GOFS_SERIALIZER_KEY);
        if (serializerTypeName == null) {
            throw new ConversionException("Config must contain key " + GOFS_SERIALIZER_KEY);
        }

        try {
            serializerType = SliceSerializerProvider.loadSliceSerializerType(serializerTypeName);
        } catch (ReflectiveOperationException e) {
            throw new ConversionException(
                    "Config key " + GOFS_SERIALIZER_KEY + " has invalid format - " + e.getMessage());
        }
    }

    // retrieve name node
    IInternalNameNode nameNode;
    try {
        nameNode = NameNodeProvider.loadNameNodeFromConfig(config, GOFS_NAMENODE_TYPE_KEY,
                GOFS_NAMENODE_LOCATION_KEY);
    } catch (ReflectiveOperationException e) {
        throw new RuntimeException("Unable to load name node", e);
    }

    System.out.println("Contacting name node...");

    // validate name node
    if (!nameNode.isAvailable()) {
        throw new IOException("Name node at " + nameNode.getURI() + " is not available");
    }

    System.out.println("Contacting data nodes...");

    // validate data nodes
    for (URI dataNode : dataNodes) {
        // only attempt ssh if host exists
        if (dataNode.getHost() != null) {
            try {
                SSHHelper.SSH(dataNode, "true");
            } catch (IOException e) {
                throw new IOException("Data node at " + dataNode + " is not available", e);
            }
        }
    }

    // create temporary directory
    Path workingDir = Files.createTempDirectory("gofs_format");
    try {
        // create deploy directory
        Path deployDirectory = Files.createDirectory(workingDir.resolve(DATANODE_DIR_NAME));

        // create empty slice directory
        Files.createDirectory(deployDirectory.resolve(DataNode.DATANODE_SLICE_DIR));

        // copy binaries
        if (copyBinaries) {
            System.out.println("Copying binaries...");
            FileUtils.copyDirectory(executableDirectory.toFile(),
                    deployDirectory.resolve(executableDirectory.getFileName()).toFile());
        }

        // write config file
        Path dataNodeConfigFile = deployDirectory.resolve(DataNode.DATANODE_CONFIG);
        try {
            // create config for every data node and scp deploy folder into place
            for (URI dataNodeParent : dataNodes) {
                URI dataNode = dataNodeParent.resolve(DATANODE_DIR_NAME);

                PropertiesConfiguration datanode_config = new PropertiesConfiguration();
                datanode_config.setDelimiterParsingDisabled(true);
                datanode_config.setProperty(DataNode.DATANODE_INSTALLED_KEY, true);
                datanode_config.setProperty(DataNode.DATANODE_NAMENODE_TYPE_KEY,
                        config.getString(GOFS_NAMENODE_TYPE_KEY));
                datanode_config.setProperty(DataNode.DATANODE_NAMENODE_LOCATION_KEY,
                        config.getString(GOFS_NAMENODE_LOCATION_KEY));
                datanode_config.setProperty(DataNode.DATANODE_LOCALHOSTURI_KEY, dataNode.toString());

                try {
                    datanode_config.save(Files.newOutputStream(dataNodeConfigFile));
                } catch (ConfigurationException e) {
                    throw new IOException(e);
                }

                System.out.println("Formatting data node " + dataNode.toString() + "...");

                // scp everything into place on the data node
                SCPHelper.SCP(deployDirectory, dataNodeParent);

                // update name node
                nameNode.addDataNode(dataNode);
            }

            // update name node
            nameNode.setSerializer(serializerType);
        } catch (Exception e) {
            System.out.println(
                    "ERROR: data node formatting interrupted - name node and data nodes are in an inconsistent state and require clean up");
            throw e;
        }

        System.out.println("GoFS format complete");

    } finally {
        FileUtils.deleteQuietly(workingDir.toFile());
    }
}

From source file:com.nextdoor.bender.ValidateSchema.java

public static void main(String[] args) throws ParseException, InterruptedException, IOException {

    /*/*w w w.ja  v a  2 s .  co  m*/
     * Parse cli arguments
     */
    Options options = new Options();
    options.addOption(Option.builder().longOpt("schema").hasArg()
            .desc("Filename to output schema to. Default: schema.json").build());
    options.addOption(Option.builder().longOpt("configs").hasArgs()
            .desc("List of config files to validate against schema.").build());
    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = parser.parse(options, args);

    String schemaFilename = cmd.getOptionValue("schema", "schema.json");
    String[] configFilenames = cmd.getOptionValues("configs");

    /*
     * Validate config files against schema
     */
    boolean hasFailures = false;
    for (String configFilename : configFilenames) {
        StringBuilder sb = new StringBuilder();
        Files.lines(Paths.get(configFilename), StandardCharsets.UTF_8).forEach(p -> sb.append(p + "\n"));

        System.out.println("Attempting to validate " + configFilename);
        try {
            ObjectMapper mapper = BenderConfig.getObjectMapper(configFilename);
            mapper.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);
            BenderConfig.load(configFilename, sb.toString(), mapper, true);
            System.out.println("Valid");
            BenderConfig config = BenderConfig.load(configFilename, sb.toString());
        } catch (ConfigurationException e) {
            System.out.println("Invalid");
            e.printStackTrace();
            hasFailures = true;
        }
    }

    if (hasFailures) {
        System.exit(1);
    }
}

From source file:edu.jhu.hlt.concrete.gigaword.expt.ConvertGigawordDocuments.java

/**
 * @param args/*from   www .j  a  v a  2 s. co m*/
 */
public static void main(String... args) {
    Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {

        @Override
        public void uncaughtException(Thread t, Throwable e) {
            logger.error("Thread {} caught unhandled exception.", t.getName());
            logger.error("Unhandled exception.", e);
        }
    });

    if (args.length != 2) {
        logger.info("Usage: {} {} {}", GigawordConcreteConverter.class.getName(), "path/to/expt/file",
                "path/to/out/folder");
        System.exit(1);
    }

    String exptPathStr = args[0];
    String outPathStr = args[1];

    // Verify path points to something.
    Path exptPath = Paths.get(exptPathStr);
    if (!Files.exists(exptPath)) {
        logger.error("File: {} does not exist. Re-run with the correct path to "
                + " the experiment 2 column file. See README.md.");
        System.exit(1);
    }

    logger.info("Experiment map located at: {}", exptPathStr);

    // Create output dir if not yet created.
    Path outPath = Paths.get(outPathStr);
    if (!Files.exists(outPath)) {
        logger.info("Creating directory: {}", outPath.toString());
        try {
            Files.createDirectories(outPath);
        } catch (IOException e) {
            logger.error("Caught an IOException when creating output dir.", e);
            System.exit(1);
        }
    }

    logger.info("Output directory located at: {}", outPathStr);

    // Read in expt map. See README.md.
    Map<String, Set<String>> exptMap = null;
    try (Reader r = ExperimentUtils.createReader(exptPath); BufferedReader br = new BufferedReader(r)) {
        exptMap = ExperimentUtils.createFilenameToIdMap(br);
    } catch (IOException e) {
        logger.error("Caught an IOException when creating expt map.", e);
        System.exit(1);
    }

    // Start a timer.
    logger.info("Gigaword -> Concrete beginning.");
    StopWatch sw = new StopWatch();
    sw.start();
    // Iterate over expt map.
    exptMap.entrySet()
            // .parallelStream()
            .forEach(p -> {
                final String pathStr = p.getKey();
                final Set<String> ids = p.getValue();
                final Path lp = Paths.get(pathStr);
                logger.info("Converting path: {}", pathStr);

                // Get the file name and immediate folder it is under.
                int nElements = lp.getNameCount();
                Path fileName = lp.getName(nElements - 1);
                Path subFolder = lp.getName(nElements - 2);
                String newFnStr = fileName.toString().split("\\.")[0] + ".tar";

                // Mirror folders in output dir.
                Path localOutFolder = outPath.resolve(subFolder);
                Path localOutPath = localOutFolder.resolve(newFnStr);

                // Create output subfolders.
                if (!Files.exists(localOutFolder) && !Files.isDirectory(localOutFolder)) {
                    logger.info("Creating out file: {}", localOutFolder.toString());
                    try {
                        Files.createDirectories(localOutFolder);
                    } catch (IOException e) {
                        throw new RuntimeException("Caught an IOException when creating output dir.", e);
                    }
                }

                // Iterate over communications.
                Iterator<Communication> citer;
                try (OutputStream os = Files.newOutputStream(localOutPath);
                        BufferedOutputStream bos = new BufferedOutputStream(os);
                        Archiver archiver = new TarArchiver(bos);) {
                    citer = new ConcreteGigawordDocumentFactory().iterator(lp);
                    while (citer.hasNext()) {
                        Communication c = citer.next();
                        String cId = c.getId();

                        // Document ID must be in the set. Remove.
                        boolean wasInSet = ids.remove(cId);
                        if (!wasInSet) {
                            // Some IDs are duplicated in Gigaword.
                            // See ERRATA.
                            logger.debug(
                                    "ID: {} was parsed from path: {}, but was not in the experiment map. Attempting to remove dupe.",
                                    cId, pathStr);

                            // Attempt to create a duplicate id (append .duplicate to the id).
                            // Then, try to remove again.
                            String newId = RepairDuplicateIDs.repairDuplicate(cId);
                            boolean dupeRemoved = ids.remove(newId);
                            // There are not nested duplicates, so this should never fire.
                            if (!dupeRemoved) {
                                logger.info("Failed to remove dupe.");
                                return;
                            } else
                                // Modify the communication ID to the unique version.
                                c.setId(newId);
                        }

                        archiver.addEntry(new ArchivableCommunication(c));
                    }

                    logger.info("Finished path: {}", pathStr);
                } catch (ConcreteException ex) {
                    logger.error("Caught ConcreteException during Concrete mapping.", ex);
                    logger.error("Path: {}", pathStr);
                } catch (IOException e) {
                    logger.error("Error archiving communications.", e);
                    logger.error("Path: {}", localOutPath.toString());
                }
            });

    sw.stop();
    logger.info("Finished.");
    Minutes m = new Duration(sw.getTime()).toStandardMinutes();
    logger.info("Runtime: Approximately {} minutes.", m.getMinutes());
}

From source file:com.me.jvmi.Main.java

public static void main(String[] args) throws IOException {

    final Path localProductImagesPath = Paths.get("/Volumes/jvmpubfs/WEB/images/products/");
    final Path uploadCSVFile = Paths.get("/Users/jbabic/Documents/products/upload.csv");
    final Config config = new Config(Paths.get("../config.properties"));

    LuminateOnlineClient luminateClient2 = new LuminateOnlineClient("https://secure2.convio.net/jvmi/admin/",
            3);//from   ww  w .ja va  2s.c  o  m
    luminateClient2.login(config.luminateUser(), config.luminatePassword());

    Set<String> completed = new HashSet<>(
            IOUtils.readLines(Files.newBufferedReader(Paths.get("completed.txt"))));

    try (InputStream is = Files.newInputStream(Paths.get("donforms.csv"));
            PrintWriter pw = new PrintWriter(new FileOutputStream(new File("completed.txt"), true))) {

        for (String line : IOUtils.readLines(is)) {
            if (completed.contains(line)) {
                System.out.println("completed: " + line);
                continue;
            }
            try {
                luminateClient2.editDonationForm(line, "-1");
                pw.println(line);
                System.out.println("done: " + line);
                pw.flush();
            } catch (Exception e) {
                System.out.println("skipping: " + line);
                e.printStackTrace();
            }
        }
    }

    //        luminateClient2.editDonationForm("8840", "-1");
    //        Collection<String> ids = luminateClient2.donFormSearch("", true);
    //        
    //        CSVFormat csvFileFormat = CSVFormat.DEFAULT.withRecordSeparator("\n");
    //        try (FileWriter fileWriter = new FileWriter(new File("donforms.csv"));
    //                CSVPrinter csvFilePrinter = new CSVPrinter(fileWriter, csvFileFormat);) {
    //
    //            for (String id : ids) {
    //                csvFilePrinter.printRecord(id);
    //            }
    //        }
    //        

    if (true) {
        return;
    }

    Collection<InputRecord> records = parseInput(uploadCSVFile);

    LuminateFTPClient ftp = new LuminateFTPClient("customerftp.convio.net");
    ftp.login(config.ftpUser(), config.ftpPassword());

    ProductImages images = new ProductImages(localProductImagesPath, ftp);

    validateImages(records, images);

    Map<String, DPCSClient> dpcsClients = new HashMap<>();
    dpcsClients.put("us", new DPCSClient("https://donor.dpconsulting.com/NewDDI/Logon.asp?client=jvm"));
    dpcsClients.put("ca", new DPCSClient("https://donor.dpconsulting.com/NewDDI/Logon.asp?client=jvcn"));
    dpcsClients.put("uk", new DPCSClient("https://donor.dpconsulting.com/NewDDI/Logon.asp?client=jvuk"));

    for (DPCSClient client : dpcsClients.values()) {
        client.login(config.dpcsUser(), config.dpcsPassword());
    }

    Map<String, LuminateOnlineClient> luminateClients = new HashMap<>();
    luminateClients.put("us", new LuminateOnlineClient("https://secure2.convio.net/jvmi/admin/", 10));
    luminateClients.put("ca", new LuminateOnlineClient("https://secure3.convio.net/jvmica/admin/", 10));
    luminateClients.put("uk", new LuminateOnlineClient("https://secure3.convio.net/jvmiuk/admin/", 10));

    Map<String, EcommerceProductFactory> ecommFactories = new HashMap<>();
    ecommFactories.put("us", new EcommerceProductFactory(dpcsClients.get("us"), images, Categories.us));
    ecommFactories.put("ca", new EcommerceProductFactory(dpcsClients.get("ca"), images, Categories.ca));
    ecommFactories.put("uk", new EcommerceProductFactory(dpcsClients.get("uk"), images, Categories.uk));

    List<String> countries = Arrays.asList("us", "ca", "uk");

    boolean error = false;
    for (InputRecord record : records) {
        for (String country : countries) {
            if (record.ignore(country)) {
                System.out.println("IGNORE: " + country + " " + record);
                continue;
            }
            try {
                EcommerceProductFactory ecommFactory = ecommFactories.get(country);
                LuminateOnlineClient luminateClient = luminateClients.get(country);
                luminateClient.login(config.luminateUser(), config.luminatePassword());

                ECommerceProduct product = ecommFactory.createECommerceProduct(record);
                luminateClient.createOrUpdateProduct(product);
            } catch (Exception e) {
                System.out.println("ERROR: " + country + " " + record);
                //System.out.println(e.getMessage());
                error = true;
                e.printStackTrace();
            }
        }
    }

    if (!error) {
        for (String country : countries) {
            LuminateOnlineClient luminateClient = luminateClients.get(country);
            DPCSClient dpcsClient = dpcsClients.get(country);
            luminateClient.close();
            dpcsClient.close();
        }
    }
}

From source file:com.github.besherman.fingerprint.Main.java

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

    options.addOption(OptionBuilder.withDescription("creates a fingerprint file for the directory").hasArg()
            .withArgName("dir").create('c'));

    options.addOption(OptionBuilder.withDescription("shows a diff between two fingerprint files")
            .withArgName("left-file> <right-file").hasArgs(2).create('d'));

    options.addOption(OptionBuilder.withDescription("shows a diff between a fingerprint and a directory")
            .withArgName("fingerprint> <dir").hasArgs(2).create('t'));

    options.addOption(OptionBuilder.withDescription("shows duplicates in a directory").withArgName("dir")
            .hasArgs(1).create('u'));

    options.addOption(//from  w  ww  .j av a 2  s  .c  o m
            OptionBuilder.withDescription("output to file").withArgName("output-file").hasArg().create('o'));

    PosixParser parser = new PosixParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);
    } catch (ParseException ex) {
        System.out.println(ex.getMessage());
        System.out.println("");
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("fingerprint-dir", options, true);
        System.exit(7);
    }

    if (cmd.hasOption('c')) {
        Path root = Paths.get(cmd.getOptionValue('c'));

        if (!Files.isDirectory(root)) {
            System.err.println("root is not a directory");
            System.exit(7);
        }

        OutputStream out = System.out;

        if (cmd.hasOption('o')) {
            Path p = Paths.get(cmd.getOptionValue('o'));
            out = Files.newOutputStream(p);
        }

        Fingerprint fp = new Fingerprint(root, "");
        fp.write(out);

    } else if (cmd.hasOption('d')) {
        String[] ar = cmd.getOptionValues('d');
        Path leftFingerprintFile = Paths.get(ar[0]), rightFingerprintFile = Paths.get(ar[1]);
        if (!Files.isRegularFile(leftFingerprintFile)) {
            System.out.printf("%s is not a file%n", leftFingerprintFile);
            System.exit(7);
        }
        if (!Files.isRegularFile(rightFingerprintFile)) {
            System.out.printf("%s is not a file%n", rightFingerprintFile);
            System.exit(7);
        }

        Fingerprint left, right;
        try (InputStream input = Files.newInputStream(leftFingerprintFile)) {
            left = new Fingerprint(input);
        }

        try (InputStream input = Files.newInputStream(rightFingerprintFile)) {
            right = new Fingerprint(input);
        }

        Diff diff = new Diff(left, right);

        // TODO: if we have redirected output
        diff.print(System.out);
    } else if (cmd.hasOption('t')) {
        throw new RuntimeException("Not yet implemented");
    } else if (cmd.hasOption('u')) {
        Path root = Paths.get(cmd.getOptionValue('u'));
        Fingerprint fp = new Fingerprint(root, "");
        Map<String, FilePrint> map = new HashMap<>();
        fp.stream().forEach(f -> {
            if (map.containsKey(f.getHash())) {
                System.out.println("  " + map.get(f.getHash()).getPath());
                System.out.println("= " + f.getPath());
                System.out.println("");
            } else {
                map.put(f.getHash(), f);
            }
        });
    } else {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("fingd", options, true);
    }
}

From source file:org.nuxeo.connect.tools.report.viewer.Viewer.java

public static void main(String[] varargs) throws IOException, ParseException {

    class Arguments {
        Options options = new Options()
                .addOption(Option.builder("i").longOpt("input").hasArg().argName("file")
                        .desc("report input file").build())
                .addOption(Option.builder("o").longOpt("output").hasArg().argName("file")
                        .desc("thread dump output file").build());
        final CommandLine commandline = new DefaultParser().parse(options, varargs);

        Arguments() throws ParseException {

        }/* w  ww.jav  a 2 s  .  c  o  m*/

        InputStream input() throws IOException {
            if (!commandline.hasOption('i')) {
                return System.in;
            }
            return Files.newInputStream(Paths.get(commandline.getOptionValue('i')));
        }

        PrintStream output() throws IOException {
            if (!commandline.hasOption('o')) {
                return System.out;
            }
            return new PrintStream(commandline.getOptionValue('o'));
        }

    }

    Arguments arguments = new Arguments();
    final JsonFactory jsonFactory = new JsonFactory();
    PrintStream output = arguments.output();
    JsonParser parser = jsonFactory.createParser(arguments.input());
    ObjectMapper mapper = new ObjectMapper();
    while (!parser.isClosed() && parser.nextToken() != JsonToken.NOT_AVAILABLE) {
        String hostid = parser.nextFieldName();
        output.println(hostid);
        {
            parser.nextToken();
            while (parser.nextToken() == JsonToken.FIELD_NAME) {
                if ("mx-thread-dump".equals(parser.getCurrentName())) {
                    parser.nextToken(); // start mx-thread-dump report
                    while (parser.nextToken() == JsonToken.FIELD_NAME) {
                        if ("value".equals(parser.getCurrentName())) {
                            parser.nextToken();
                            printThreadDump(mapper.readTree(parser), output);
                        } else {
                            parser.nextToken();
                            parser.skipChildren();
                        }
                    }
                } else if ("mx-thread-deadlocked".equals(parser.getCurrentName())) {
                    parser.nextToken();
                    while (parser.nextToken() == JsonToken.FIELD_NAME) {
                        if ("value".equals(parser.getCurrentName())) {
                            if (parser.nextToken() == JsonToken.START_ARRAY) {
                                printThreadDeadlocked(mapper.readerFor(Long.class).readValue(parser), output);
                            }
                        } else {
                            parser.nextToken();
                            parser.skipChildren();
                        }
                    }
                } else if ("mx-thread-monitor-deadlocked".equals(parser.getCurrentName())) {
                    parser.nextToken();
                    while (parser.nextToken() == JsonToken.FIELD_NAME) {
                        if ("value".equals(parser.getCurrentName())) {
                            if (parser.nextToken() == JsonToken.START_ARRAY) {
                                printThreadMonitorDeadlocked(mapper.readerFor(Long.class).readValues(parser),
                                        output);
                            }
                        } else {
                            parser.nextToken();
                            parser.skipChildren();
                        }
                    }
                } else {
                    parser.nextToken();
                    parser.skipChildren();
                }
            }
        }
    }

}

From source file:com.github.jasmo.Bootstrap.java

public static void main(String[] args) {
    Options options = new Options().addOption("h", "help", false, "Print help message")
            .addOption("v", "verbose", false, "Increase verbosity")
            .addOption("c", "cfn", true,
                    "Enable 'crazy fucking names and set name length (large names == large output size)'")
            .addOption("p", "package", true, "Move obfuscated classes to this package")
            .addOption("k", "keep", true, "Don't rename this class");
    try {/*w  ww .ja  v a  2  s .c o  m*/
        CommandLineParser clp = new DefaultParser();
        CommandLine cl = clp.parse(options, args);
        if (cl.hasOption("help")) {
            help(options);
            return;
        }
        if (cl.hasOption("verbose")) {
            LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
            Configuration config = ctx.getConfiguration();
            LoggerConfig loggerConfig = config.getLoggerConfig(LogManager.ROOT_LOGGER_NAME);
            loggerConfig.setLevel(Level.DEBUG);
            ctx.updateLoggers();
        }
        String[] keep = cl.getOptionValues("keep");
        if (cl.getArgList().size() < 2) {
            throw new ParseException("Expected at-least two arguments");
        }
        log.debug("Input: {}, Output: {}", cl.getArgList().get(0), cl.getArgList().get(1));
        Obfuscator o = new Obfuscator();
        try {
            o.supply(Paths.get(cl.getArgList().get(0)));
        } catch (Exception e) {
            log.error("An error occurred while reading the source target", e);
            return;
        }
        try {
            UniqueStringGenerator usg;
            if (cl.hasOption("cfn")) {
                int size = Integer.parseInt(cl.getOptionValue("cfn"));
                usg = new UniqueStringGenerator.Crazy(size);
            } else {
                usg = new UniqueStringGenerator.Default();
            }
            o.apply(new FullAccessFlags());
            o.apply(new ScrambleStrings());
            o.apply(new ScrambleClasses(usg, cl.getOptionValue("package", ""),
                    keep == null ? new String[0] : keep));
            o.apply(new ScrambleFields(usg));
            o.apply(new ScrambleMethods(usg));
            o.apply(new InlineAccessors());
            o.apply(new RemoveDebugInfo());
            o.apply(new ShuffleMembers());
        } catch (Exception e) {
            log.error("An error occurred while applying transform", e);
            return;
        }
        try {
            o.write(Paths.get(cl.getArgList().get(1)));
        } catch (Exception e) {
            log.error("An error occurred while writing to the destination target", e);
            return;
        }
    } catch (ParseException e) {
        log.error("Failed to parse command line arguments", e);
        help(options);
    }
}

From source file:jparser.JParser.java

/**
 * @param args the command line arguments
 *//*from w ww  .  j av a 2 s.c om*/
public static void main(String[] args) {

    Options options = new Options();
    CommandLineParser parser = new DefaultParser();

    options.addOption(
            Option.builder().longOpt("to").desc("Indica el tipo de archivo al que debera convertir: JSON / XML")
                    .hasArg().argName("tipo").build());

    options.addOption(Option.builder().longOpt("path")
            .desc("Indica la ruta donde se encuentra el archivo origen").hasArg().argName("origen").build());

    options.addOption(
            Option.builder().longOpt("target").desc("Indica la ruta donde se guardara el archivo resultante")
                    .hasArg().argName("destino").build());

    options.addOption("h", "help", false, "Muestra la guia de como usar la aplicacion");

    try {
        CommandLine command = parser.parse(options, args);
        Path source = null;
        Path target = null;
        FactoryFileParse.TypeParce type = FactoryFileParse.TypeParce.NULL;
        Optional<Customer> customer = Optional.empty();

        if (command.hasOption("h")) {
            HelpFormatter helper = new HelpFormatter();
            helper.printHelp("JParser", options);

            System.exit(0);
        }

        if (command.hasOption("to"))
            type = FactoryFileParse.TypeParce.fromValue(command.getOptionValue("to", ""));

        if (command.hasOption("path"))
            source = Paths.get(command.getOptionValue("path", ""));

        if (command.hasOption("target"))
            target = Paths.get(command.getOptionValue("target", ""));

        switch (type) {
        case JSON:
            customer = FactoryFileParse.createNewInstance(FactoryFileParse.TypeParce.XML).read(source);

            break;

        case XML:
            customer = FactoryFileParse.createNewInstance(FactoryFileParse.TypeParce.JSON).read(source);

            break;
        }

        if (customer.isPresent()) {
            Customer c = customer.get();

            boolean success = FactoryFileParse.createNewInstance(type).write(c, target);

            System.out.println(String.format("Operatation was: %s", success ? "success" : "fails"));
        }

    } catch (ParseException ex) {
        Logger.getLogger(JParser.class.getSimpleName()).log(Level.SEVERE, ex.getMessage(), ex);

        System.exit(-1);
    }
}

From source file:FindInt.java

public static void main(String[] args) throws IOException {
    Path file = Paths.get("datafile");
    int num = new FindInt(file).seek();
    System.out.println("The value is " + num);
}

From source file:com.example.bigtable.simplecli.Loader.java

public static void main(String argv[]) throws IOException {
    String inputFile = "/tmp/pagecounts-20160101-000000";

    // Connect//from  w  w  w.  j a v a 2s. c o  m
    Connection bigTableConnection = ConnectionFactory.createConnection();

    // Load the file, and do stuff each row
    Stream<String> stream = Files.lines(Paths.get(inputFile));
    stream.forEach(row -> {

        String[] splitRow = row.split(" ");
        assert splitRow.length == 4 : "unexpected row " + row;

        String hour = "20160101-000000"; //from file name
        String language = splitRow[0];
        String title = splitRow[1];
        String requests = splitRow[2];
        String size = splitRow[3];

        assert language.length() == 2 : "unexpected language size" + language;

        // create a row key
        // [languageCode]-[title md5]-[hour]
        String rowKey = language + "-" + DigestUtils.md5Hex(title) + "-" + hour;
        System.out.println(rowKey);

        // Put it into Bigtable - [table name]
        try {
            Table table = bigTableConnection.getTable(TableName.valueOf("wikipedia-stats"));

            // Create a new Put request.
            Put put = new Put(Bytes.toBytes(rowKey));

            // Add columns: [column family], [column], [data]
            put.addColumn(Bytes.toBytes("traffic"), Bytes.toBytes("requests"), Bytes.toBytes(requests));
            put.addColumn(Bytes.toBytes("traffic"), Bytes.toBytes("size"), Bytes.toBytes(size));

            // Execute the put on the table.
            table.put(put);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    });

    // Clean up
    bigTableConnection.close();
}