Example usage for org.apache.commons.io IOUtils copy

List of usage examples for org.apache.commons.io IOUtils copy

Introduction

In this page you can find the example usage for org.apache.commons.io IOUtils copy.

Prototype

public static void copy(Reader input, OutputStream output) throws IOException 

Source Link

Document

Copy chars from a Reader to bytes on an OutputStream using the default character encoding of the platform, and calling flush.

Usage

From source file:io.fluo.webindex.data.Copy.java

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

    if (args.length != 3) {
        log.error("Usage: Copy <pathsFile> <range> <dest>");
        System.exit(1);//from  w ww .  j  a v  a 2  s  .  c  o  m
    }
    final String hadoopConfDir = IndexEnv.getHadoopConfDir();
    final List<String> copyList = IndexEnv.getPathsRange(args[0], args[1]);
    if (copyList.isEmpty()) {
        log.error("No files to copy given {} {}", args[0], args[1]);
        System.exit(1);
    }

    DataConfig dataConfig = DataConfig.load();

    SparkConf sparkConf = new SparkConf().setAppName("webindex-copy");
    try (JavaSparkContext ctx = new JavaSparkContext(sparkConf)) {

        FileSystem hdfs = FileSystem.get(ctx.hadoopConfiguration());
        Path destPath = new Path(args[2]);
        if (!hdfs.exists(destPath)) {
            hdfs.mkdirs(destPath);
        }

        log.info("Copying {} files (Range {} of paths file {}) from AWS to HDFS {}", copyList.size(), args[1],
                args[0], destPath.toString());

        JavaRDD<String> copyRDD = ctx.parallelize(copyList, dataConfig.getNumExecutorInstances());

        final String prefix = DataConfig.CC_URL_PREFIX;
        final String destDir = destPath.toString();

        copyRDD.foreachPartition(iter -> {
            FileSystem fs = IndexEnv.getHDFS(hadoopConfDir);
            iter.forEachRemaining(ccPath -> {
                try {
                    Path dfsPath = new Path(destDir + "/" + getFilename(ccPath));
                    if (fs.exists(dfsPath)) {
                        log.error("File {} exists in HDFS and should have been previously filtered",
                                dfsPath.getName());
                    } else {
                        String urlToCopy = prefix + ccPath;
                        log.info("Starting copy of {} to {}", urlToCopy, destDir);
                        try (OutputStream out = fs.create(dfsPath);
                                BufferedInputStream in = new BufferedInputStream(
                                        new URL(urlToCopy).openStream())) {
                            IOUtils.copy(in, out);
                        }
                        log.info("Created {}", dfsPath.getName());
                    }
                } catch (IOException e) {
                    log.error("Exception while copying {}", ccPath, e);
                }
            });
        });
    }
}

From source file:alluxio.examples.MultiMount.java

/**
 * Entry point for the {@link MultiMount} program.
 *
 * @param args command-line arguments/*from www .j a v  a2 s  .  c  o  m*/
 */
public static void main(String[] args) {
    if (args.length != 1) {
        System.err.println("Usage: ./bin/alluxio runClass alluxio.examples.MultiMount <HDFS_URL>");
        System.exit(-1);
    }

    AlluxioURI mntPath = new AlluxioURI("/mnt");
    AlluxioURI s3Mount = new AlluxioURI("/mnt/s3");
    AlluxioURI inputPath = new AlluxioURI("/mnt/s3/hello.txt");
    AlluxioURI s3Path = new AlluxioURI("s3n://alluxio-demo/");
    AlluxioURI hdfsMount = new AlluxioURI("/mnt/hdfs");
    AlluxioURI outputPath = new AlluxioURI("/mnt/hdfs/hello.txt");
    AlluxioURI hdfsPath = new AlluxioURI(args[0]);
    FileSystem fileSystem = FileSystem.Factory.get();

    try {
        // Make sure mount directory exists.
        if (!fileSystem.exists(mntPath)) {
            System.out.print("creating " + mntPath + " ... ");
            fileSystem.createDirectory(mntPath);
            System.out.println("done");
        }

        // Make sure the S3 mount point does not exist.
        if (fileSystem.exists(s3Mount)) {
            System.out.print("unmounting " + s3Mount + " ... ");
            fileSystem.unmount(s3Mount);
            System.out.println("done");
        }

        // Make sure the HDFS mount point does not exist.
        if (fileSystem.exists(hdfsMount)) {
            System.out.print("unmounting " + hdfsMount + " ... ");
            fileSystem.unmount(hdfsMount);
            System.out.println("done");
        }

        // Mount S3.
        System.out.print("mounting " + s3Path + " to " + s3Mount + " ... ");
        fileSystem.mount(s3Mount, s3Path);
        System.out.println("done");

        // Mount HDFS.
        System.out.print("mounting " + hdfsPath + " to " + hdfsMount + " ... ");
        fileSystem.mount(hdfsMount, hdfsPath);
        System.out.println("done");

        // Make sure output file does not exist.
        if (fileSystem.exists(outputPath)) {
            System.out.print("deleting " + outputPath + " ... ");
            fileSystem.delete(outputPath);
            System.out.println("done");
        }

        // Open the input stream.
        System.out.print("opening " + inputPath + " ... ");
        FileInStream is = fileSystem.openFile(inputPath);
        System.out.println("done");

        // Open the output stream, setting the write type to make sure result is persisted.
        System.out.print("opening " + outputPath + " ... ");
        CreateFileOptions options = CreateFileOptions.defaults().setWriteType(WriteType.CACHE_THROUGH);
        FileOutStream os = fileSystem.createFile(outputPath, options);
        System.out.println("done");

        // Copy the data
        System.out.print("transferring data from " + inputPath + " to " + outputPath + " ... ");
        IOUtils.copy(is, os);
        System.out.println("done");

        // Close the input stream.
        System.out.print("closing " + inputPath + " ... ");
        is.close();
        System.out.println("done");

        // Close the output stream.
        System.out.print("closing " + outputPath + " ... ");
        os.close();
        System.out.println("done");
    } catch (Exception e) {
        System.out.println("fail");
        e.printStackTrace();
    } finally {
        // Make sure the S3 mount point is removed.
        try {
            if (fileSystem.exists(s3Mount)) {
                System.out.print("unmounting " + s3Mount + " ... ");
                fileSystem.unmount(s3Mount);
                System.out.println("done");
            }
        } catch (Exception e) {
            System.out.println("fail");
            e.printStackTrace();
        }

        // Make sure the HDFS mount point is removed.
        try {
            if (fileSystem.exists(hdfsMount)) {
                System.out.print("unmounting " + hdfsMount + " ... ");
                fileSystem.unmount(hdfsMount);
                System.out.println("done");
            }
        } catch (Exception e) {
            System.out.println("fail");
            e.printStackTrace();
        }
    }
}

From source file:com.kolich.http.BlockingTest.java

public static void main(String[] args) {

    final HttpClient client = getNewInstanceWithProxySelector("foobar");

    final Either<Integer, String> result = new HttpClient4Closure<Integer, String>(client) {
        @Override//from www  .jav  a  2 s. c o  m
        public void before(final HttpRequestBase request) {
            request.addHeader("Authorization", "super-secret-password");
        }

        @Override
        public String success(final HttpSuccess success) throws Exception {
            return EntityUtils.toString(success.getResponse().getEntity(), UTF_8);
        }

        @Override
        public Integer failure(final HttpFailure failure) {
            return failure.getStatusCode();
        }
    }.get("http://google.com");
    if (result.success()) {
        System.out.println(result.right());
    } else {
        System.out.println(result.left());
    }

    final Either<Void, Header[]> hResult = new HttpClient4Closure<Void, Header[]>(client) {
        @Override
        public Header[] success(final HttpSuccess success) throws Exception {
            return success.getResponse().getAllHeaders();
        }
    }.head("http://example.com");
    if (hResult.success()) {
        System.out.println("Fetched " + hResult.right().length + " request headers.");
    }

    final Either<Void, String> sResult = new StringOrNullClosure(client).get("http://mark.koli.ch");
    if (sResult.success()) {
        System.out.println(sResult.right());
    } else {
        System.out.println(sResult.left());
    }

    final Either<Exception, String> eResult = new HttpClient4Closure<Exception, String>(client) {
        @Override
        public String success(final HttpSuccess success) throws Exception {
            return EntityUtils.toString(success.getResponse().getEntity(), UTF_8);
        }

        @Override
        public Exception failure(final HttpFailure failure) {
            return failure.getCause();
        }
    }.put("http://lskdjflksdfjslkf.jfjkfhddfgsdfsdf.com");
    if (!eResult.success()) {
        System.out.println(eResult.left());
    }

    // Custom check for "success".
    final Either<Exception, String> cResult = new HttpClient4Closure<Exception, String>(client) {
        @Override
        public boolean check(final HttpResponse response, final HttpContext context) {
            return (response.getStatusLine().getStatusCode() == 405);
        }

        @Override
        public String success(final HttpSuccess success) throws Exception {
            return EntityUtils.toString(success.getResponse().getEntity(), UTF_8);
        }
    }.put("http://google.com");
    if (cResult.success()) {
        System.out.println(cResult.right());
    }

    final Either<Exception, OutputStream> bResult = new HttpClient4Closure<Exception, OutputStream>(client) {
        @Override
        public OutputStream success(final HttpSuccess success) throws Exception {
            final OutputStream os = new ByteArrayOutputStream();
            IOUtils.copy(success.getResponse().getEntity().getContent(), os);
            return os;
        }

        @Override
        public Exception failure(final HttpFailure failure) {
            return failure.getCause();
        }
    }.get("http://google.com");
    if (bResult.success()) {
        System.out.println("Loaded bytes into output stream!");
    }

    final OutputStream os = new ByteArrayOutputStream();
    final Either<Exception, Integer> stResult = new HttpClient4Closure<Exception, Integer>(client) {
        @Override
        public Integer success(final HttpSuccess success) throws Exception {
            return IOUtils.copy(success.getResponse().getEntity().getContent(), os);
        }
        /*
        @Override
        public Exception failure(final HttpFailure failure) {
           return failure.getCause();
        }
        */
    }.get("http://mark.koli.ch");
    if (stResult.success()) {
        System.out.println("Loaded " + stResult.right() + " bytes.");
    }

    /*
    final HttpContext context = new BasicHttpContext();
    // Setup a basic cookie store so that the response can fetch
    // any cookies returned by the server in the response.
    context.setAttribute(COOKIE_STORE, new BasicCookieStore());
    final Either<Void,String> cookieResult =
       new HttpClientClosureExpectString(client)
    .get(new HttpGet("http://google.com"), context);
    if(cookieResult.success()) {
       // List out all cookies that came back from Google in the response.
       final CookieStore cookies = (CookieStore)context.getAttribute(COOKIE_STORE);
       for(final Cookie c : cookies.getCookies()) {
    System.out.println(c.getName() + " -> " + c.getValue());
       }
    }*/

    final Either<Integer, List<Cookie>> mmmmm = new HttpClient4Closure<Integer, List<Cookie>>(client) {
        @Override
        public void before(final HttpRequestBase request, final HttpContext context) {
            context.setAttribute(COOKIE_STORE, new BasicCookieStore());
        }

        @Override
        public List<Cookie> success(final HttpSuccess success) {
            // Extract a list of cookies from the request.
            // Might be empty.
            return ((CookieStore) success.getContext().getAttribute(COOKIE_STORE)).getCookies();
        }

        @Override
        public Integer failure(final HttpFailure failure) {
            return failure.getStatusCode();
        }
    }.get("http://google.com");
    final List<Cookie> cookies;
    if ((cookies = mmmmm.right()) != null) {
        for (final Cookie c : cookies) {
            System.out.println(c.getName() + " -> " + c.getValue());
        }
    } else {
        System.out.println("Failed miserably: " + mmmmm.left());
    }

    final Either<Void, Header[]> haResult = new HttpClient4Closure<Void, Header[]>(client) {
        @Override
        public Header[] success(final HttpSuccess success) {
            return success.getResponse().getAllHeaders();
        }
    }.head("http://java.com");
    final Header[] headers = haResult.right();
    if (headers != null) {
        for (final Header h : headers) {
            System.out.println(h.getName() + ": " + h.getValue());
        }
    }

}

From source file:geocodingissues.Main.java

/**
 * @param args the command line arguments
 *//*w  w  w.  j  ava 2  s  .  c om*/
public static void main(String[] args) throws JSONException {
    Main x = new Main();
    ResultSet rs = null;

    x.establishConnection();
    //x.addColumns(); //already did this

    rs = x.getLatLong();

    int id;
    double latitude;
    double longitude;
    String req;

    String street_no;
    String street;
    String neighborhood;
    String locality;
    String PC;

    JSONObject jObject;
    JSONArray resultArray;
    JSONArray compArray;

    try {
        while (rs.next()) {
            id = rs.getInt("id");
            latitude = rs.getDouble("latitude");
            longitude = rs.getDouble("longitude");

            //System.out.println("id: " + id);

            req = "https://maps.googleapis.com/maps/api/geocode/json?latlng=" + Double.toString(latitude) + ","
                    + Double.toString(longitude)
                    + "&result_type=street_address|neighborhood|locality|postal_code&key=" + key;

            try {
                URL url = new URL(req + "&sensor=false");
                URLConnection conn = url.openConnection();
                ByteArrayOutputStream output = new ByteArrayOutputStream(1024);
                IOUtils.copy(conn.getInputStream(), output);
                output.close();
                req = output.toString();
            } catch (Exception e) {
                System.out.println("Geocoding Error");
            }
            if (req.contains("OVER_QUERY_LIMIT")) {
                System.out.println("Over Daily Query Limit");
                System.exit(0);
            }
            if (!req.contains("ZERO_RESULTS")) {
                //System.out.println("req: ");
                //System.out.println(req);
                jObject = new JSONObject(req);
                resultArray = jObject.getJSONArray("results");

                // Retrieve information on street address and insert into table
                compArray0 = resultArray.getJSONObject(0).getJSONArray("address_components");
                street_no = compArray0.getJSONObject(0).getString("long_name");
                street = compArray0.getJSONObject(1).getString("long_name");
                x.insertValues(id, street_no, street);

                // Retrieve information on neighborhood and insert into table
                compArray1 = resultArray.getJSONObject(1).getJSONArray("address_components");
                neighborhood = compArray1.getJSONObject(0).getString("long_name");
                x.insertNbhd(id, neighborhood);

                // Retrieve information on locality and insert into table
                compArray2 = resultArray.getJSONObject(2).getJSONArray("address_components");
                locality = compArray2.getJSONObject(0).getString("long_name");
                x.insertLocality(id, locality);

                // Retrieve information on postal code and insert into table
                compArray3 = resultArray.getJSONObject(3).getJSONArray("address_components");
                PC = compArray3.getJSONObject(0).getString("long_name");
                x.insertPC(id, PC);
            }
        }
    } catch (Exception e) {
        System.out.println("Problem when updating the database.");
    }
    x.closeConnection();
}

From source file:com.xiaoxiaomo.flink.batch.distcp.DistCp.java

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

    // set up the execution environment
    final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();

    ParameterTool params = ParameterTool.fromArgs(args);
    if (!params.has("input") || !params.has("output")) {
        System.err.println("Usage: --input <path> --output <path> [--parallelism <n>]");
        return;/*from w w  w .ja v  a2s.c om*/
    }

    final Path sourcePath = new Path(params.get("input"));
    final Path targetPath = new Path(params.get("output"));
    if (!isLocal(env) && !(isOnDistributedFS(sourcePath) && isOnDistributedFS(targetPath))) {
        System.out.println("In a distributed mode only HDFS input/output paths are supported");
        return;
    }

    final int parallelism = params.getInt("parallelism", 10);
    if (parallelism <= 0) {
        System.err.println("Parallelism should be greater than 0");
        return;
    }

    // make parameters available in the web interface
    env.getConfig().setGlobalJobParameters(params);

    env.setParallelism(parallelism);

    long startTime = System.currentTimeMillis();
    LOGGER.info("Initializing copy tasks");
    List<FileCopyTask> tasks = getCopyTasks(sourcePath);
    LOGGER.info("Copy task initialization took " + (System.currentTimeMillis() - startTime) + "ms");

    DataSet<FileCopyTask> inputTasks = new DataSource<FileCopyTask>(env, new FileCopyTaskInputFormat(tasks),
            new GenericTypeInfo<FileCopyTask>(FileCopyTask.class), "fileCopyTasks");

    FlatMapOperator<FileCopyTask, Object> res = inputTasks
            .flatMap(new RichFlatMapFunction<FileCopyTask, Object>() {

                private static final long serialVersionUID = 1109254230243989929L;
                private LongCounter fileCounter;
                private LongCounter bytesCounter;

                @Override
                public void open(Configuration parameters) throws Exception {
                    bytesCounter = getRuntimeContext().getLongCounter(BYTES_COPIED_CNT_NAME);
                    fileCounter = getRuntimeContext().getLongCounter(FILES_COPIED_CNT_NAME);
                }

                @Override
                public void flatMap(FileCopyTask task, Collector<Object> out) throws Exception {
                    LOGGER.info("Processing task: " + task);
                    Path outPath = new Path(targetPath, task.getRelativePath());

                    FileSystem targetFs = targetPath.getFileSystem();
                    // creating parent folders in case of a local FS
                    if (!targetFs.isDistributedFS()) {
                        //dealing with cases like file:///tmp or just /tmp
                        File outFile = outPath.toUri().isAbsolute() ? new File(outPath.toUri())
                                : new File(outPath.toString());
                        File parentFile = outFile.getParentFile();
                        if (!parentFile.mkdirs() && !parentFile.exists()) {
                            throw new RuntimeException(
                                    "Cannot create local file system directories: " + parentFile);
                        }
                    }
                    FSDataOutputStream outputStream = null;
                    FSDataInputStream inputStream = null;
                    try {
                        outputStream = targetFs.create(outPath, true);
                        inputStream = task.getPath().getFileSystem().open(task.getPath());
                        int bytes = IOUtils.copy(inputStream, outputStream);
                        bytesCounter.add(bytes);
                    } finally {
                        IOUtils.closeQuietly(inputStream);
                        IOUtils.closeQuietly(outputStream);
                    }
                    fileCounter.add(1L);
                }
            });

    // no data sinks are needed, therefore just printing an empty result
    res.print();

    Map<String, Object> accumulators = env.getLastJobExecutionResult().getAllAccumulatorResults();
    LOGGER.info("== COUNTERS ==");
    for (Map.Entry<String, Object> e : accumulators.entrySet()) {
        LOGGER.info(e.getKey() + ": " + e.getValue());
    }
}

From source file:eu.sendregning.oxalis.Main.java

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

    OptionParser optionParser = getOptionParser();

    if (args.length == 0) {
        System.out.println("");
        optionParser.printHelpOn(System.out);
        System.out.println("");
        return;/* w w w. java2s  .  c  o  m*/
    }

    OptionSet optionSet;

    try {
        optionSet = optionParser.parse(args);
    } catch (Exception e) {
        printErrorMessage(e.getMessage());
        return;
    }

    File xmlInvoice = xmlDocument.value(optionSet);

    if (!xmlInvoice.exists()) {
        printErrorMessage("XML document " + xmlInvoice + " does not exist");
        return;
    }

    String recipientId = recipient.value(optionSet);
    String senderId = sender.value(optionSet);

    try {

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

        // bootstraps the Oxalis outbound module
        OxalisOutboundModule oxalisOutboundModule = new OxalisOutboundModule();

        // creates a transmission request builder and enable tracing
        TransmissionRequestBuilder requestBuilder = oxalisOutboundModule.getTransmissionRequestBuilder();
        requestBuilder.trace(trace.value(optionSet));
        System.out.println("Trace mode of RequestBuilder: " + requestBuilder.isTraceEnabled());

        // add receiver participant
        if (recipientId != null) {
            requestBuilder.receiver(new ParticipantId(recipientId));
        }

        // add sender participant
        if (senderId != null) {
            requestBuilder.sender((new ParticipantId(senderId)));
        }

        if (docType != null && docType.value(optionSet) != null) {
            requestBuilder.documentType(PeppolDocumentTypeId.valueOf(docType.value(optionSet)));
        }

        if (profileType != null && profileType.value(optionSet) != null) {
            requestBuilder.processType(PeppolProcessTypeId.valueOf(profileType.value(optionSet)));
        }

        // Supplies the payload
        requestBuilder.payLoad(new FileInputStream(xmlInvoice));

        // Overrides the destination URL if so requested
        if (optionSet.has(destinationUrl)) {
            String destinationString = destinationUrl.value(optionSet);
            URL destination;

            try {
                destination = new URL(destinationString);
            } catch (MalformedURLException e) {
                printErrorMessage("Invalid destination URL " + destinationString);
                return;
            }

            // Fetches the transmission method, which was overridden on the command line
            BusDoxProtocol busDoxProtocol = BusDoxProtocol.instanceFrom(transmissionMethod.value(optionSet));

            if (busDoxProtocol == BusDoxProtocol.AS2) {
                String accessPointSystemIdentifier = destinationSystemId.value(optionSet);
                if (accessPointSystemIdentifier == null) {
                    throw new IllegalStateException("Must specify AS2 system identifier if using AS2 protocol");
                }
                requestBuilder.overrideAs2Endpoint(destination, accessPointSystemIdentifier);
            } else {
                throw new IllegalStateException("Unknown busDoxProtocol : " + busDoxProtocol);
            }
        }

        // Specifying the details completed, creates the transmission request
        TransmissionRequest transmissionRequest = requestBuilder.build();

        // Fetches a transmitter ...
        Transmitter transmitter = oxalisOutboundModule.getTransmitter();

        // ... and performs the transmission
        TransmissionResponse transmissionResponse = transmitter.transmit(transmissionRequest);

        // Write the transmission id and where the message was delivered
        System.out.printf("Message using messageId %s sent to %s using %s was assigned transmissionId %s\n",
                transmissionResponse.getStandardBusinessHeader().getMessageId().stringValue(),
                transmissionResponse.getURL().toExternalForm(), transmissionResponse.getProtocol().toString(),
                transmissionResponse.getTransmissionId());

        String evidenceFileName = transmissionResponse.getTransmissionId().toString() + "-evidence.dat";
        IOUtils.copy(new ByteArrayInputStream(transmissionResponse.getEvidenceBytes()),
                new FileOutputStream(evidenceFileName));
        System.out.printf("Wrote transmission receipt to " + evidenceFileName);

    } catch (Exception e) {
        System.out.println("");
        System.out.println("Message failed : " + e.getMessage());
        //e.printStackTrace();
        System.out.println("");
    }
}

From source file:net.sf.jsignpdf.verify.Verifier.java

/**
 * @param args//from   w  w  w. j  ava2  s . co  m
 */
public static void main(String[] args) {

    // create the Options
    Option optHelp = new Option("h", "help", false, "print this message");
    // Option optVersion = new Option("v", "version", false,
    // "print version info");
    Option optCerts = new Option("c", "cert", true, "use external semicolon separated X.509 certificate files");
    optCerts.setArgName("certificates");
    Option optPasswd = new Option("p", "password", true, "set password for opening PDF");
    optPasswd.setArgName("password");
    Option optExtract = new Option("e", "extract", true, "extract signed PDF revisions to given folder");
    optExtract.setArgName("folder");
    Option optListKs = new Option("lk", "list-keystore-types", false, "list keystore types provided by java");
    Option optListCert = new Option("lc", "list-certificates", false, "list certificate aliases in a KeyStore");
    Option optKsType = new Option("kt", "keystore-type", true, "use keystore type with given name");
    optKsType.setArgName("keystore_type");
    Option optKsFile = new Option("kf", "keystore-file", true, "use given keystore file");
    optKsFile.setArgName("file");
    Option optKsPass = new Option("kp", "keystore-password", true,
            "password for keystore file (look on -kf option)");
    optKsPass.setArgName("password");
    Option optFailFast = new Option("ff", "fail-fast", false,
            "flag which sets the Verifier to exit with error code on the first validation failure");

    final Options options = new Options();
    options.addOption(optHelp);
    // options.addOption(optVersion);
    options.addOption(optCerts);
    options.addOption(optPasswd);
    options.addOption(optExtract);
    options.addOption(optListKs);
    options.addOption(optListCert);
    options.addOption(optKsType);
    options.addOption(optKsFile);
    options.addOption(optKsPass);
    options.addOption(optFailFast);

    CommandLine line = null;
    try {
        // create the command line parser
        CommandLineParser parser = new PosixParser();
        // parse the command line arguments
        line = parser.parse(options, args);
    } catch (ParseException exp) {
        System.err.println("Illegal command used: " + exp.getMessage());
        System.exit(SignatureVerification.SIG_STAT_CODE_ERROR_UNEXPECTED_PROBLEM);
    }

    final boolean failFast = line.hasOption("ff");
    final String[] tmpArgs = line.getArgs();
    if (line.hasOption("h") || args == null || args.length == 0) {
        // automatically generate the help statement
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(70, "java -jar Verifier.jar [file1.pdf [file2.pdf ...]]",
                "JSignPdf Verifier is a command line tool for verifying signed PDF documents.", options, null,
                true);
    } else if (line.hasOption("lk")) {
        // list keystores
        for (String tmpKsType : KeyStoreUtils.getKeyStores()) {
            System.out.println(tmpKsType);
        }
    } else if (line.hasOption("lc")) {
        // list certificate aliases in the keystore
        for (String tmpCert : KeyStoreUtils.getCertAliases(line.getOptionValue("kt"), line.getOptionValue("kf"),
                line.getOptionValue("kp"))) {
            System.out.println(tmpCert);
        }
    } else {
        final VerifierLogic tmpLogic = new VerifierLogic(line.getOptionValue("kt"), line.getOptionValue("kf"),
                line.getOptionValue("kp"));
        tmpLogic.setFailFast(failFast);

        if (line.hasOption("c")) {
            String tmpCertFiles = line.getOptionValue("c");
            for (String tmpCFile : tmpCertFiles.split(";")) {
                tmpLogic.addX509CertFile(tmpCFile);
            }
        }
        byte[] tmpPasswd = null;
        if (line.hasOption("p")) {
            tmpPasswd = line.getOptionValue("p").getBytes();
        }
        String tmpExtractDir = null;
        if (line.hasOption("e")) {
            tmpExtractDir = new File(line.getOptionValue("e")).getPath();
        }

        int exitCode = 0;

        for (String tmpFilePath : tmpArgs) {
            int exitCodeForFile = 0;
            System.out.println("Verifying " + tmpFilePath);
            final File tmpFile = new File(tmpFilePath);
            if (!tmpFile.canRead()) {
                exitCodeForFile = SignatureVerification.SIG_STAT_CODE_ERROR_FILE_NOT_READABLE;
                System.err.println("Couln't read the file. Check the path and permissions.");
                if (failFast) {
                    System.exit(exitCodeForFile);
                }
                exitCode = Math.max(exitCode, exitCodeForFile);
                continue;
            }
            final VerificationResult tmpResult = tmpLogic.verify(tmpFilePath, tmpPasswd);
            if (tmpResult.getException() != null) {
                tmpResult.getException().printStackTrace();
                exitCodeForFile = SignatureVerification.SIG_STAT_CODE_ERROR_UNEXPECTED_PROBLEM;
                if (failFast) {
                    System.exit(exitCodeForFile);
                }
                exitCode = Math.max(exitCode, exitCodeForFile);
                continue;
            } else {
                System.out.println("Total revisions: " + tmpResult.getTotalRevisions());
                for (SignatureVerification tmpSigVer : tmpResult.getVerifications()) {
                    System.out.println(tmpSigVer.toString());
                    if (tmpExtractDir != null) {
                        try {
                            File tmpExFile = new File(tmpExtractDir + "/" + tmpFile.getName() + "_"
                                    + tmpSigVer.getRevision() + ".pdf");
                            System.out.println("Extracting to " + tmpExFile.getCanonicalPath());
                            FileOutputStream tmpFOS = new FileOutputStream(tmpExFile.getCanonicalPath());

                            InputStream tmpIS = tmpLogic.extractRevision(tmpFilePath, tmpPasswd,
                                    tmpSigVer.getName());
                            IOUtils.copy(tmpIS, tmpFOS);
                            tmpIS.close();
                            tmpFOS.close();
                        } catch (IOException ioe) {
                            ioe.printStackTrace();
                        }
                    }
                }
                exitCodeForFile = tmpResult.getVerificationResultCode();
                if (failFast && SignatureVerification.isError(exitCodeForFile)) {
                    System.exit(exitCodeForFile);
                }
            }
            exitCode = Math.max(exitCode, exitCodeForFile);
        }
        if (exitCode != 0 && tmpArgs.length > 1) {
            System.exit(SignatureVerification.isError(exitCode)
                    ? SignatureVerification.SIG_STAT_CODE_ERROR_ANY_ERROR
                    : SignatureVerification.SIG_STAT_CODE_WARNING_ANY_WARNING);
        } else {
            System.exit(exitCode);
        }
    }
}

From source file:net.sf.jsignpdf.InstallCert.java

/**
 * The main - whole logic of Install Cert Tool.
 * /*from w w w .jav a  2  s  . c o  m*/
 * @param args
 * @throws Exception
 */
public static void main(String[] args) {
    String host;
    int port;
    char[] passphrase;

    System.out.println("InstallCert - Install CA certificate to Java Keystore");
    System.out.println("=====================================================");

    final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

    try {
        if ((args.length == 1) || (args.length == 2)) {
            String[] c = args[0].split(":");
            host = c[0];
            port = (c.length == 1) ? 443 : Integer.parseInt(c[1]);
            String p = (args.length == 1) ? "changeit" : args[1];
            passphrase = p.toCharArray();
        } else {
            String tmpStr;
            do {
                System.out.print("Enter hostname or IP address: ");
                tmpStr = StringUtils.defaultIfEmpty(reader.readLine(), null);
            } while (tmpStr == null);
            host = tmpStr;
            System.out.print("Enter port number [443]: ");
            tmpStr = StringUtils.defaultIfEmpty(reader.readLine(), null);
            port = tmpStr == null ? 443 : Integer.parseInt(tmpStr);
            System.out.print("Enter keystore password [changeit]: ");
            tmpStr = reader.readLine();
            String p = "".equals(tmpStr) ? "changeit" : tmpStr;
            passphrase = p.toCharArray();
        }

        char SEP = File.separatorChar;
        final File dir = new File(System.getProperty("java.home") + SEP + "lib" + SEP + "security");
        final File file = new File(dir, "cacerts");

        System.out.println("Loading KeyStore " + file + "...");
        InputStream in = new FileInputStream(file);
        KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
        ks.load(in, passphrase);
        in.close();

        SSLContext context = SSLContext.getInstance("TLS");
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(ks);
        X509TrustManager defaultTrustManager = (X509TrustManager) tmf.getTrustManagers()[0];
        SavingTrustManager tm = new SavingTrustManager(defaultTrustManager);
        context.init(null, new TrustManager[] { tm }, null);
        SSLSocketFactory factory = context.getSocketFactory();

        System.out.println("Opening connection to " + host + ":" + port + "...");
        SSLSocket socket = (SSLSocket) factory.createSocket(host, port);
        socket.setSoTimeout(10000);
        try {
            System.out.println("Starting SSL handshake...");
            socket.startHandshake();
            socket.close();
            System.out.println();
            System.out.println("No errors, certificate is already trusted");
        } catch (SSLException e) {
            System.out.println();
            System.out.println("Certificate is not yet trusted.");
            //        e.printStackTrace(System.out);
        }

        X509Certificate[] chain = tm.chain;
        if (chain == null) {
            System.out.println("Could not obtain server certificate chain");
            return;
        }

        System.out.println();
        System.out.println("Server sent " + chain.length + " certificate(s):");
        System.out.println();
        MessageDigest sha1 = MessageDigest.getInstance("SHA1");
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        for (int i = 0; i < chain.length; i++) {
            X509Certificate cert = chain[i];
            System.out.println(" " + (i + 1) + " Subject " + cert.getSubjectDN());
            System.out.println("   Issuer  " + cert.getIssuerDN());
            sha1.update(cert.getEncoded());
            System.out.println("   sha1    " + toHexString(sha1.digest()));
            md5.update(cert.getEncoded());
            System.out.println("   md5     " + toHexString(md5.digest()));
            System.out.println();
        }

        System.out.print("Enter certificate to add to trusted keystore or 'q' to quit [1]: ");
        String line = reader.readLine().trim();
        int k = -1;
        try {
            k = (line.length() == 0) ? 0 : Integer.parseInt(line) - 1;
        } catch (NumberFormatException e) {
        }

        if (k < 0 || k >= chain.length) {
            System.out.println("KeyStore not changed");
        } else {
            try {
                System.out.println("Creating keystore backup");
                final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
                final File backupFile = new File(dir,
                        CACERTS_KEYSTORE + "." + dateFormat.format(new java.util.Date()));
                final FileInputStream fis = new FileInputStream(file);
                final FileOutputStream fos = new FileOutputStream(backupFile);
                IOUtils.copy(fis, fos);
                fis.close();
                fos.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println("Installing certificate...");

            X509Certificate cert = chain[k];
            String alias = host + "-" + (k + 1);
            ks.setCertificateEntry(alias, cert);

            OutputStream out = new FileOutputStream(file);
            ks.store(out, passphrase);
            out.close();

            System.out.println();
            System.out.println(cert);
            System.out.println();
            System.out.println("Added certificate to keystore '" + file + "' using alias '" + alias + "'");
        }
    } catch (Exception e) {
        System.out.println();
        System.out.println("----------------------------------------------");
        System.out.println("Problem occured during installing certificate:");
        e.printStackTrace();
        System.out.println("----------------------------------------------");
    }
    System.out.println("Press Enter to finish...");
    try {
        reader.readLine();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.joseflavio.unhadegato.Concentrador.java

/**
 * @param args [0] = Diretrio de configuraes.
 *///from  ww  w  .  jav a2s  .co  m
public static void main(String[] args) {

    log.info(Util.getMensagem("unhadegato.iniciando"));

    try {

        /***********************/

        if (args.length > 0) {
            if (!args[0].isEmpty()) {
                configuracao = new File(args[0]);
                if (!configuracao.isDirectory()) {
                    String msg = Util.getMensagem("unhadegato.diretorio.incorreto");
                    System.out.println(msg);
                    log.error(msg);
                    System.exit(1);
                }
            }
        }

        if (configuracao == null) {
            configuracao = new File(System.getProperty("user.home") + File.separator + "unhadegato");
            configuracao.mkdirs();
        }

        log.info(Util.getMensagem("unhadegato.diretorio.endereco", configuracao.getAbsolutePath()));

        /***********************/

        File confGeralArq = new File(configuracao, "unhadegato.conf");

        if (!confGeralArq.exists()) {
            try (InputStream is = Concentrador.class.getResourceAsStream("/unhadegato.conf");
                    OutputStream os = new FileOutputStream(confGeralArq);) {
                IOUtils.copy(is, os);
            }
        }

        Properties confGeral = new Properties();

        try (FileInputStream fis = new FileInputStream(confGeralArq)) {
            confGeral.load(fis);
        }

        String prop_porta = confGeral.getProperty("porta");
        String prop_porta_segura = confGeral.getProperty("porta.segura");
        String prop_seg_pri = confGeral.getProperty("seguranca.privada");
        String prop_seg_pri_senha = confGeral.getProperty("seguranca.privada.senha");
        String prop_seg_pri_tipo = confGeral.getProperty("seguranca.privada.tipo");
        String prop_seg_pub = confGeral.getProperty("seguranca.publica");
        String prop_seg_pub_senha = confGeral.getProperty("seguranca.publica.senha");
        String prop_seg_pub_tipo = confGeral.getProperty("seguranca.publica.tipo");

        if (StringUtil.tamanho(prop_porta) == 0)
            prop_porta = "8885";
        if (StringUtil.tamanho(prop_porta_segura) == 0)
            prop_porta_segura = "8886";
        if (StringUtil.tamanho(prop_seg_pri) == 0)
            prop_seg_pri = "servidor.jks";
        if (StringUtil.tamanho(prop_seg_pri_senha) == 0)
            prop_seg_pri_senha = "123456";
        if (StringUtil.tamanho(prop_seg_pri_tipo) == 0)
            prop_seg_pri_tipo = "JKS";
        if (StringUtil.tamanho(prop_seg_pub) == 0)
            prop_seg_pub = "cliente.jks";
        if (StringUtil.tamanho(prop_seg_pub_senha) == 0)
            prop_seg_pub_senha = "123456";
        if (StringUtil.tamanho(prop_seg_pub_tipo) == 0)
            prop_seg_pub_tipo = "JKS";

        /***********************/

        File seg_pri = new File(prop_seg_pri);
        if (!seg_pri.isAbsolute())
            seg_pri = new File(configuracao.getAbsolutePath() + File.separator + prop_seg_pri);

        if (seg_pri.exists()) {
            System.setProperty("javax.net.ssl.keyStore", seg_pri.getAbsolutePath());
            System.setProperty("javax.net.ssl.keyStorePassword", prop_seg_pri_senha);
            System.setProperty("javax.net.ssl.keyStoreType", prop_seg_pri_tipo);
        }

        File seg_pub = new File(prop_seg_pub);
        if (!seg_pub.isAbsolute())
            seg_pub = new File(configuracao.getAbsolutePath() + File.separator + prop_seg_pub);

        if (seg_pub.exists()) {
            System.setProperty("javax.net.ssl.trustStore", seg_pub.getAbsolutePath());
            System.setProperty("javax.net.ssl.trustStorePassword", prop_seg_pub_senha);
            System.setProperty("javax.net.ssl.trustStoreType", prop_seg_pub_tipo);
        }

        /***********************/

        new Thread() {

            File arquivo = new File(configuracao, "copaibas.conf");

            long ultimaData = -1;

            @Override
            public void run() {

                while (true) {

                    long data = arquivo.lastModified();

                    if (data > ultimaData) {
                        executarCopaibas(arquivo);
                        ultimaData = data;
                    }

                    try {
                        Thread.sleep(5 * 1000);
                    } catch (InterruptedException e) {
                        return;
                    }

                }

            }

        }.start();

        /***********************/

        log.info(Util.getMensagem("unhadegato.conexao.esperando"));

        log.info(Util.getMensagem("copaiba.porta.normal.abrindo", prop_porta));
        Portal portal1 = new Portal(new SocketServidor(Integer.parseInt(prop_porta), false, true));

        log.info(Util.getMensagem("copaiba.porta.segura.abrindo", prop_porta_segura));
        Portal portal2 = new Portal(new SocketServidor(Integer.parseInt(prop_porta_segura), true, true));

        portal1.start();
        portal2.start();

        portal1.join();

        /***********************/

    } catch (Exception e) {

        log.error(e.getMessage(), e);

    } finally {

        for (CopaibaGerenciador gerenciador : gerenciadores.values())
            gerenciador.encerrar();
        gerenciadores.clear();
        gerenciadores = null;

    }

}

From source file:de.uni.bremen.monty.moco.Main.java

public static void main(String[] args) throws IOException, InterruptedException {
    Namespace ns = parseArgs(args);

    if (ns == null) {
        return;/*from   w  w  w. j a v  a  2s .c  om*/
    }

    String inputFileName = ns.get("file");
    String outputFileName = ns.get("outputFile");
    boolean emitAssembly = ns.get("emitAssembly");
    boolean compileOnly = ns.get("compileOnly");
    boolean stopOnFirstError = ns.get("stopOnFirstError");
    boolean printAST = ns.get("printAST");
    boolean debugParseTree = ns.get("debugParseTree");

    if (debugParseTree) {
        debugParseTree(inputFileName);
        return;
    }

    StringWriter writer = new StringWriter();
    IOUtils.copy(Main.class.getResourceAsStream("/std_llvm_include.ll"), writer);

    Package ast = buildPackage(inputFileName);

    if (!visitVisitors(ast, stopOnFirstError, writer.getBuffer())) {
        return;
    }

    if (printAST) {
        (new PrintVisitor()).visitDoubleDispatched(ast);
    }

    if (emitAssembly) {
        writeAssembly(outputFileName, inputFileName, writer.toString());
        return;
    }

    File executable = buildExecutable(outputFileName, inputFileName, compileOnly, writer.toString());
    if (!compileOnly) {
        runExecutable(executable);
    }
}