Example usage for java.io IOException printStackTrace

List of usage examples for java.io IOException printStackTrace

Introduction

In this page you can find the example usage for java.io IOException printStackTrace.

Prototype

public void printStackTrace() 

Source Link

Document

Prints this throwable and its backtrace to the standard error stream.

Usage

From source file:net.massbank.validator.RecordValidator.java

public static void main(String[] args) {
    RequestDummy request;//from  www  .ja va2 s .  c o m

    PrintStream out = System.out;

    Options lvOptions = new Options();
    lvOptions.addOption("h", "help", false, "show this help.");
    lvOptions.addOption("r", "recdata", true,
            "points to the recdata directory containing massbank records. Reads all *.txt files in there.");

    CommandLineParser lvParser = new BasicParser();
    CommandLine lvCmd = null;
    try {
        lvCmd = lvParser.parse(lvOptions, args);
        if (lvCmd.hasOption('h')) {
            printHelp(lvOptions);
            return;
        }
    } catch (org.apache.commons.cli.ParseException pvException) {
        System.out.println(pvException.getMessage());
    }

    String recDataPath = lvCmd.getOptionValue("recdata");

    // ---------------------------------------------
    // ????
    // ---------------------------------------------

    final String baseUrl = MassBankEnv.get(MassBankEnv.KEY_BASE_URL);
    final String dbRootPath = "./";
    final String dbHostName = MassBankEnv.get(MassBankEnv.KEY_DB_HOST_NAME);
    final String tomcatTmpPath = ".";
    final String tmpPath = (new File(tomcatTmpPath + sdf.format(new Date()))).getPath() + File.separator;
    GetConfig conf = new GetConfig(baseUrl);
    int recVersion = 2;
    String selDbName = "";
    Object up = null; // Was: file Upload
    boolean isResult = true;
    String upFileName = "";
    boolean upResult = false;
    DatabaseAccess db = null;

    try {
        // ----------------------------------------------------
        // ???
        // ----------------------------------------------------
        // if (FileUpload.isMultipartContent(request)) {
        // (new File(tmpPath)).mkdir();
        // String os = System.getProperty("os.name");
        // if (os.indexOf("Windows") == -1) {
        // isResult = FileUtil.changeMode("777", tmpPath);
        // if (!isResult) {
        // out.println(msgErr("[" + tmpPath
        // + "]  chmod failed."));
        // return;
        // }
        // }
        // up = new FileUpload(request, tmpPath);
        // }

        // ----------------------------------------------------
        // ?DB????
        // ----------------------------------------------------
        List<String> dbNameList = Arrays.asList(conf.getDbName());
        ArrayList<String> dbNames = new ArrayList<String>();
        dbNames.add("");
        File[] dbDirs = (new File(dbRootPath)).listFiles();
        if (dbDirs != null) {
            for (File dbDir : dbDirs) {
                if (dbDir.isDirectory()) {
                    int pos = dbDir.getName().lastIndexOf("\\");
                    String dbDirName = dbDir.getName().substring(pos + 1);
                    pos = dbDirName.lastIndexOf("/");
                    dbDirName = dbDirName.substring(pos + 1);
                    if (dbNameList.contains(dbDirName)) {
                        // DB???massbank.conf???DB????
                        dbNames.add(dbDirName);
                    }
                }
            }
        }
        if (dbDirs == null || dbNames.size() == 0) {
            out.println(msgErr("[" + dbRootPath + "] directory not exist."));
            return;
        }
        Collections.sort(dbNames);

        // ----------------------------------------------------
        // ?
        // ----------------------------------------------------
        // if (FileUpload.isMultipartContent(request)) {
        // HashMap<String, String[]> reqParamMap = new HashMap<String,
        // String[]>();
        // reqParamMap = up.getRequestParam();
        // if (reqParamMap != null) {
        // for (Map.Entry<String, String[]> req : reqParamMap
        // .entrySet()) {
        // if (req.getKey().equals("ver")) {
        // try {
        // recVersion = Integer
        // .parseInt(req.getValue()[0]);
        // } catch (NumberFormatException nfe) {
        // }
        // } else if (req.getKey().equals("db")) {
        // selDbName = req.getValue()[0];
        // }
        // }
        // }
        // } else {
        // if (request.getParameter("ver") != null) {
        // try {
        // recVersion = Integer.parseInt(request
        // .getParameter("ver"));
        // } catch (NumberFormatException nfe) {
        // }
        // }
        // selDbName = request.getParameter("db");
        // }
        // if (selDbName == null || selDbName.equals("")
        // || !dbNames.contains(selDbName)) {
        // selDbName = dbNames.get(0);
        // }

        // ---------------------------------------------
        // 
        // ---------------------------------------------
        out.println("Database: ");
        for (int i = 0; i < dbNames.size(); i++) {
            String dbName = dbNames.get(i);
            out.print("dbName");
            if (dbName.equals(selDbName)) {
                out.print(" selected");
            }
            if (i == 0) {
                out.println("------------------");
            } else {
                out.println(dbName);
            }
        }
        out.println("Record Version : ");
        out.println(recVersion);

        out.println("Record Archive :");

        // ---------------------------------------------
        // 
        // ---------------------------------------------
        //         HashMap<String, Boolean> upFileMap = up.doUpload();
        //         if (upFileMap != null) {
        //            for (Map.Entry<String, Boolean> e : upFileMap.entrySet()) {
        //               upFileName = e.getKey();
        //               upResult = e.getValue();
        //               break;
        //            }
        //            if (upFileName.equals("")) {
        //               out.println(msgErr("please select file."));
        //               isResult = false;
        //            } else if (!upResult) {
        //               out.println(msgErr("[" + upFileName
        //                     + "] upload failed."));
        //               isResult = false;
        //            } else if (!upFileName.endsWith(ZIP_EXTENSION)
        //                  && !upFileName.endsWith(MSBK_EXTENSION)) {
        //               out.println(msgErr("please select ["
        //                     + UPLOAD_RECDATA_ZIP
        //                     + "] or ["
        //                     + UPLOAD_RECDATA_MSBK + "]."));
        //               up.deleteFile(upFileName);
        //               isResult = false;
        //            }
        //         } else {
        //            out.println(msgErr("server error."));
        //            isResult = false;
        //         }
        //         up.deleteFileItem();
        //         if (!isResult) {
        //            return;
        //         }

        // ---------------------------------------------
        // ???
        // ---------------------------------------------
        //         final String upFilePath = (new File(tmpPath + File.separator
        //               + upFileName)).getPath();
        //         isResult = FileUtil.unZip(upFilePath, tmpPath);
        //         if (!isResult) {
        //            out.println(msgErr("["
        //                  + upFileName
        //                  + "]  extraction failed. possibility of time-out."));
        //            return;
        //         }

        // ---------------------------------------------
        // ??
        // ---------------------------------------------
        final String recPath = (new File(dbRootPath + File.separator + selDbName)).getPath();
        File tmpRecDir = new File(recDataPath);
        if (!tmpRecDir.isDirectory()) {
            tmpRecDir.mkdirs();
        }

        // ---------------------------------------------
        // ???
        // ---------------------------------------------
        // data?
        //         final String recDataPath = (new File(tmpPath + File.separator
        //               + RECDATA_DIR_NAME)).getPath()
        //               + File.separator;
        //
        //         if (!(new File(recDataPath)).isDirectory()) {
        //            if (upFileName.endsWith(ZIP_EXTENSION)) {
        //               out.println(msgErr("["
        //                     + RECDATA_DIR_NAME
        //                     + "]  directory is not included in the up-loading file."));
        //            } else if (upFileName.endsWith(MSBK_EXTENSION)) {
        //               out.println(msgErr("The uploaded file is not record data."));
        //            }
        //            return;
        //         }

        // ---------------------------------------------
        // DB
        // ---------------------------------------------
        //         db = new DatabaseAccess(dbHostName, selDbName);
        //         isResult = db.open();
        //         if (!isResult) {
        //            db.close();
        //            out.println(msgErr("not connect to database."));
        //            return;
        //         }

        // ---------------------------------------------
        // ??
        // ---------------------------------------------
        TreeMap<String, String> resultMap = validationRecord(db, out, recDataPath, recPath, recVersion);
        if (resultMap.size() == 0) {
            return;
        }

        // ---------------------------------------------
        // ?
        // ---------------------------------------------
        isResult = dispResult(out, resultMap);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        if (db != null) {
            db.close();
        }
        File tmpDir = new File(tmpPath);
        if (tmpDir.exists()) {
            FileUtil.removeDir(tmpDir.getPath());
        }
    }

}

From source file:mcnutty.music.get.MusicGet.java

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

    //print out music-get
    System.out.println("                     _                      _   ");
    System.out.println(" _ __ ___  _   _ ___(_) ___       __ _  ___| |_ ");
    System.out.println("| '_ ` _ \\| | | / __| |/ __|____ / _` |/ _ \\ __|");
    System.out.println("| | | | | | |_| \\__ \\ | (_|_____| (_| |  __/ |_ ");
    System.out.println("|_| |_| |_|\\__,_|___/_|\\___|     \\__, |\\___|\\__|");
    System.out.println("                                 |___/          \n");

    //these will always be initialised later (but the compiler doesn't know that)
    String directory = "";
    Properties prop = new Properties();

    try (InputStream input = new FileInputStream("config.properties")) {
        prop.load(input);/*  w  w w.j  a  v  a 2s . c  o m*/
        if (prop.getProperty("directory") != null) {
            directory = prop.getProperty("directory");
        } else {
            System.out.println(
                    "Error reading config property 'directory' - using default value of /tmp/musicserver/\n");
            directory = "/tmp/musicserver/";
        }
        if (prop.getProperty("password") == null) {
            System.out.println("Error reading config property 'password' - no default value, exiting\n");
            System.exit(1);
        }
    } catch (IOException e) {
        System.out.println("Error reading config file");
        System.exit(1);
    }

    //create a queue object
    ProcessQueue process_queue = new ProcessQueue();

    try {
        if (args.length > 0 && args[0].equals("clean")) {
            Files.delete(Paths.get("queue.json"));
        }
        //load an existing queue if possible
        String raw_queue = Files.readAllLines(Paths.get("queue.json")).toString();
        JSONArray queue_state = new JSONArray(raw_queue);
        ConcurrentLinkedQueue<QueueItem> loaded_queue = new ConcurrentLinkedQueue<>();
        JSONArray queue = queue_state.getJSONArray(0);
        for (int i = 0; i < queue.length(); i++) {
            JSONObject item = ((JSONObject) queue.get(i));
            QueueItem loaded_item = new QueueItem();
            loaded_item.ip = item.getString("ip");
            loaded_item.real_name = item.getString("name");
            loaded_item.disk_name = item.getString("guid");
            loaded_queue.add(loaded_item);
        }
        process_queue.bucket_queue = loaded_queue;
        System.out.println("Loaded queue from disk\n");
    } catch (Exception ex) {
        //otherwise clean out the music directory and start a new queue
        try {
            Files.walkFileTree(Paths.get(directory), new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    Files.delete(file);
                    return FileVisitResult.CONTINUE;
                }
            });
            Files.delete(Paths.get(directory));
        } catch (Exception e) {
            e.printStackTrace();
        }
        Files.createDirectory(Paths.get(directory));
        System.out.println("Created a new queue\n");
    }

    //start the web server
    StartServer start_server = new StartServer(process_queue, directory);
    new Thread(start_server).start();

    //wit for the web server to spool up
    Thread.sleep(1000);

    //read items from the queue and play them
    while (true) {
        QueueItem next_item = process_queue.next_item();
        if (!next_item.equals(new QueueItem())) {
            //Check the timeout
            int timeout = 547;
            try (FileInputStream input = new FileInputStream("config.properties")) {
                prop.load(input);
                timeout = Integer.parseInt(prop.getProperty("timeout", "547"));
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println("Playing " + next_item.real_name);
            process_queue.set_played(next_item);
            process_queue.save_queue();
            Process p = Runtime.getRuntime().exec("timeout " + timeout
                    + "s mplayer -fs -quiet -af volnorm=2:0.25 " + directory + next_item.disk_name);

            try {
                p.waitFor(timeout, TimeUnit.SECONDS);
                Files.delete(Paths.get(directory + next_item.disk_name));
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            process_queue.bucket_played.clear();
        }
        Thread.sleep(1000);
    }
}

From source file:com.zimbra.cs.lmtpserver.utils.LmtpInject.java

public static void main(String[] args) {
    CliUtil.toolSetup();// w  ww .j av a2 s  . c  om
    CommandLine cl = parseArgs(args);

    if (cl.hasOption("h")) {
        usage(null);
    }
    boolean quietMode = cl.hasOption("q");
    int threads = 1;
    if (cl.hasOption("t")) {
        threads = Integer.valueOf(cl.getOptionValue("t")).intValue();
    }

    String host = null;
    if (cl.hasOption("a")) {
        host = cl.getOptionValue("a");
    } else {
        host = "localhost";
    }

    int port;
    Protocol proto = null;
    if (cl.hasOption("smtp")) {
        proto = Protocol.SMTP;
        port = 25;
    } else
        port = 7025;
    if (cl.hasOption("p"))
        port = Integer.valueOf(cl.getOptionValue("p")).intValue();

    String[] recipients = cl.getOptionValues("r");
    String sender = cl.getOptionValue("s");
    boolean tracingEnabled = cl.hasOption("T");

    int everyN;
    if (cl.hasOption("N")) {
        everyN = Integer.valueOf(cl.getOptionValue("N")).intValue();
    } else {
        everyN = 100;
    }

    // Process files from the -d option.
    List<File> files = new ArrayList<File>();
    if (cl.hasOption("d")) {
        File dir = new File(cl.getOptionValue("d"));
        if (!dir.isDirectory()) {
            System.err.format("%s is not a directory.\n", dir.getPath());
            System.exit(1);
        }
        File[] fileArray = dir.listFiles();
        if (fileArray == null || fileArray.length == 0) {
            System.err.format("No files found in directory %s.\n", dir.getPath());
        }
        Collections.addAll(files, fileArray);
    }

    // Process files specified as arguments.
    for (String arg : cl.getArgs()) {
        files.add(new File(arg));
    }

    // Validate file content.
    if (!cl.hasOption("noValidation")) {
        Iterator<File> i = files.iterator();
        while (i.hasNext()) {
            InputStream in = null;
            File file = i.next();
            boolean valid = false;
            try {
                in = new FileInputStream(file);
                if (FileUtil.isGzipped(file)) {
                    in = new GZIPInputStream(in);
                }
                in = new BufferedInputStream(in); // Required for RFC 822 check
                if (!EmailUtil.isRfc822Message(in)) {
                    System.err.format("%s does not contain a valid RFC 822 message.\n", file.getPath());
                } else {
                    valid = true;
                }
            } catch (IOException e) {
                System.err.format("Unable to validate %s: %s.\n", file.getPath(), e.toString());
            } finally {
                ByteUtil.closeStream(in);
            }
            if (!valid) {
                i.remove();
            }
        }
    }

    if (files.size() == 0) {
        System.err.println("No files to inject.");
        System.exit(1);
    }

    if (!quietMode) {
        System.out.format(
                "Injecting %d message(s) to %d recipient(s).  Server %s, port %d, using %d thread(s).\n",
                files.size(), recipients.length, host, port, threads);
    }

    int totalFailed = 0;
    int totalSucceeded = 0;
    long startTime = System.currentTimeMillis();
    boolean verbose = cl.hasOption("v");
    boolean skipTLSCertValidation = cl.hasOption("skipTLSCertValidation");

    LmtpInject injector = null;
    try {
        injector = new LmtpInject(threads, sender, recipients, files, host, port, proto, quietMode,
                tracingEnabled, verbose, skipTLSCertValidation);
    } catch (Exception e) {
        mLog.error("Unable to initialize LmtpInject", e);
        System.exit(1);
    }

    injector.setReportEvery(everyN);
    injector.markStartTime();
    try {
        injector.run();
    } catch (IOException e) {
        e.printStackTrace();
        System.exit(1);
    }

    int succeeded = injector.getSuccessCount();
    int failedThisTime = injector.getFailureCount();
    long elapsedMS = System.currentTimeMillis() - startTime;
    double elapsed = elapsedMS / 1000.0;
    double msPerMsg = 0.0;
    double msgSizeKB = 0.0;
    if (succeeded > 0) {
        msPerMsg = elapsedMS;
        msPerMsg /= succeeded;
        msgSizeKB = injector.mFileSizeTotal / 1024.0;
        msgSizeKB /= succeeded;
    }
    double msgPerSec = ((double) succeeded / (double) elapsedMS) * 1000;
    if (!quietMode) {
        System.out.println();
        System.out.printf(
                "LmtpInject Finished\n" + "submitted=%d failed=%d\n" + "%.2fs, %.2fms/msg, %.2fmsg/s\n"
                        + "average message size = %.2fKB\n",
                succeeded, failedThisTime, elapsed, msPerMsg, msgPerSec, msgSizeKB);
    }

    totalFailed += failedThisTime;
    totalSucceeded += succeeded;

    if (totalFailed != 0)
        System.exit(1);
}

From source file:com.ricemap.spateDB.operations.RangeQuery.java

public static void main(String[] args) throws IOException {
    CommandLineArguments cla = new CommandLineArguments(args);
    final QueryInput query = cla.getQuery();
    final Path[] paths = cla.getPaths();
    if (paths.length == 0 || (cla.getPrism() == null && cla.getSelectionRatio() < 0.0f)) {
        printUsage();//from   www  .j a v a2  s.com
        throw new RuntimeException("Illegal parameters");
    }
    JobConf conf = new JobConf(FileMBR.class);
    final Path inputFile = paths[0];
    final FileSystem fs = inputFile.getFileSystem(conf);
    if (!fs.exists(inputFile)) {
        printUsage();
        throw new RuntimeException("Input file does not exist");
    }
    final Path outputPath = paths.length > 1 ? paths[1] : null;
    final Prism[] queryRanges = cla.getPrisms();
    int concurrency = cla.getConcurrency();
    final Shape stockShape = cla.getShape(true);
    final boolean overwrite = cla.isOverwrite();

    final long[] results = new long[queryRanges.length];
    final Vector<Thread> threads = new Vector<Thread>();

    final BooleanWritable exceptionHappened = new BooleanWritable();

    Thread.UncaughtExceptionHandler h = new Thread.UncaughtExceptionHandler() {
        public void uncaughtException(Thread th, Throwable ex) {
            ex.printStackTrace();
            exceptionHappened.set(true);
        }
    };

    for (int i = 0; i < queryRanges.length; i++) {
        Thread t = new Thread() {
            @Override
            public void run() {
                try {
                    int thread_i = threads.indexOf(this);

                    long result_count = rangeQueryMapReduce(fs, inputFile, outputPath, queryRanges[thread_i],
                            stockShape, overwrite, false, query);
                    results[thread_i] = result_count;
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        };
        t.setUncaughtExceptionHandler(h);
        threads.add(t);
    }

    long t1 = System.currentTimeMillis();
    do {
        // Ensure that there is at least MaxConcurrentThreads running
        int i = 0;
        while (i < concurrency && i < threads.size()) {
            Thread.State state = threads.elementAt(i).getState();
            if (state == Thread.State.TERMINATED) {
                // Thread already terminated, remove from the queue
                threads.remove(i);
            } else if (state == Thread.State.NEW) {
                // Start the thread and move to next one
                threads.elementAt(i++).start();
            } else {
                // Thread is still running, skip over it
                i++;
            }
        }
        if (!threads.isEmpty()) {
            try {
                // Sleep for 10 seconds or until the first thread terminates
                threads.firstElement().join(10000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    } while (!threads.isEmpty());
    long t2 = System.currentTimeMillis();

    if (exceptionHappened.get())
        throw new RuntimeException("Not all jobs finished correctly");
    System.out.println("Time for " + queryRanges.length + " jobs is " + (t2 - t1) + " millis");

    System.out.print("Result size: [");
    for (long result : results) {
        System.out.print(result + ", ");
    }
    System.out.println("]");
}

From source file:edu.usc.goffish.gopher.impl.Main.java

public static void main(String[] args) {

    Properties properties = new Properties();
    try {// w  ww  .  ja  v  a2  s.c o  m
        properties.load(new FileInputStream(CONFIG_FILE));
    } catch (IOException e) {
        String message = "Error while loading Container Configuration from " + CONFIG_FILE + " Cause -"
                + e.getCause();
        log.warning(message);
    }

    if (args.length == 4) {

        PropertiesConfiguration propertiesConfiguration;
        String url = null;

        URI uri = URI.create(args[3]);

        String dataDir = uri.getPath();

        String currentHost = uri.getHost();
        try {

            propertiesConfiguration = new PropertiesConfiguration(dataDir + "/gofs.config");
            propertiesConfiguration.load();
            url = (String) propertiesConfiguration.getString(DataNode.DATANODE_NAMENODE_LOCATION_KEY);

        } catch (ConfigurationException e) {

            String message = " Error while reading gofs-config cause -" + e.getCause();
            handleException(message);
        }

        URI nameNodeUri = URI.create(url);

        INameNode nameNode = new RemoteNameNode(nameNodeUri);
        int partition = -1;
        try {
            for (URI u : nameNode.getDataNodes()) {
                if (URIHelper.isLocalURI(u)) {
                    IDataNode dataNode = DataNode.create(u);
                    IntCollection partitions = dataNode.getLocalPartitions(args[2]);
                    partition = partitions.iterator().nextInt();
                    break;
                }
            }

            if (partition == -1) {
                String message = "Partition not loaded from uri : " + nameNodeUri;
                handleException(message);
            }

            properties.setProperty(GopherInfraHandler.PARTITION, String.valueOf(partition));

        } catch (Exception e) {
            String message = "Error while loading Partitions from " + nameNodeUri + " Cause -" + e.getMessage();
            e.printStackTrace();
            handleException(message);
        }

        properties.setProperty(Constants.STATIC_PELLET_COUNT, String.valueOf(1));
        FloeRuntimeEnvironment environment = FloeRuntimeEnvironment.getEnvironment();
        environment.setSystemConfig(properties);
        properties.setProperty(Constants.CURRET_HOST, currentHost);
        String managerHost = args[0];
        int managerPort = Integer.parseInt(args[1]);

        Container container = environment.getContainer();
        container.setManager(managerHost, managerPort);

        DefaultClientConfig config = new DefaultClientConfig();
        config.getProperties().put(ClientConfig.FEATURE_DISABLE_XML_SECURITY, true);
        config.getFeatures().put(ClientConfig.FEATURE_DISABLE_XML_SECURITY, true);

        Client c = Client.create(config);

        if (managerHost == null || managerPort == 0) {
            handleException("Manager Host / Port have to be configured in " + args[0]);
        }

        WebResource r = c.resource("http://" + managerHost + ":" + managerPort
                + "/Manager/addContainerInfo/Container=" + container.getContainerInfo().getContainerId()
                + "/Host=" + container.getContainerInfo().getContainerHost());
        c.getProperties().put(ClientConfig.PROPERTY_FOLLOW_REDIRECTS, true);
        r.post();
        log.log(Level.INFO, "Container started  ");

    } else {

        String message = "Invalid arguments , arg[0]=Manager host, "
                + "arg[1] = mamanger port,arg[2]=graph id,arg[3]=partition uri";

        message += "\n Current Arguments...." + args.length + "\n";
        for (int i = 0; i < args.length; i++) {
            message += "arg " + i + " : " + args[i] + "\n";
        }

        handleException(message);

    }

}

From source file:ch.bfh.evoting.verifier.Verifier.java

/**
 * This program is a verifier for MobiVote application with HKRS12 protocol
 * You have to indicate the XML file exported from the application as argument for this program.
 * You can also indicate the files of different participants. In this case, there will be checked if all files contain the same values.
 * @param args the file(s) containing the values of the protocol
 *///from  w  w  w  .j  a  v a 2 s  . co m
public static void main(String[] args) {

    /*
     * Reading files given as parameters
     */
    if (args.length < 1) {
        //Not enough arguments
        System.out.println(
                "You must indicate the location of the XML file containing the data to verify! You can also indicate the files of different participants.");
        return;
    } else if (args.length > 1) {
        //Make a digest of all files and compare them
        List<byte[]> digests = new ArrayList<byte[]>();
        for (String s : args) {
            try {
                MessageDigest md = MessageDigest.getInstance("SHA-256");

                InputStream is = Files.newInputStream(Paths.get(s));
                DigestInputStream dis = new DigestInputStream(is, md);
                @SuppressWarnings("unused")
                int numBytes = -1;
                while ((numBytes = dis.read()) != -1) {
                    dis.read();
                }

                byte[] digest = md.digest();
                digests.add(digest);

            } catch (IOException e) {
                System.out.println("One of the given files does not exists!");
                return;
            } catch (NoSuchAlgorithmException e1) {
                System.out.println("Unable to compute the digest of the file!");
                return;
            }
        }
        System.out.print("Checking the similarity of the files...");
        for (byte[] b : digests) {
            for (byte[] b2 : digests) {
                if (!Arrays.equals(b, b2)) {
                    System.out.print("\t\t\t\t\t\t\t\t\t\tWRONG\n");
                    System.out.println(
                            "The given files are not all identical! This means the content received by the participants was not the same.");
                    return;
                }
            }
        }
        System.out.print("\t\t\t\t\t\t\t\t\t\tOK\n\n");
    } else if (args.length == 1) {
        //Print a warning
        System.out.println(
                "BE CAREFUL: checking only one file ensure that the cryptographic values of the protocol are correct.\n"
                        + "But, it does NOT ensure that all users have the same result. This could happen when a participant missed some messages.\n"
                        + "This case is only covered by this verifier by giving multiple files as argument.\n");
    }

    Serializer serializer = new Persister();
    File source = new File(args[0]);

    poll = null;
    System.out.print("Reading file...");
    try {
        poll = serializer.read(XMLPoll.class, source);
        System.out.print("\t\t\t\t\t\t\t\t\t\t\t\t\tOK\n");
    } catch (Exception e) {
        System.out.print("\t\t\t\t\t\t\t\t\t\t\t\t\tFAILED\n");
        e.printStackTrace();
        return;
    }

    /*
     * Create the initializations needed by the protocol
     */
    G_q = GStarModSafePrime.getInstance(new BigInteger(poll.getP()));
    Z_q = G_q.getZModOrder();
    Zgroup = Z.getInstance();
    generator = poll.getGenerator().getValue(G_q);

    representations = new Element[poll.getOptions().size()];
    int i = 0;
    for (XMLOption op : poll.getOptions()) {
        representations[i] = op.getRepresentation().getValue(Z_q);
        i++;
    }

    System.out.println();
    System.out.println("Verifying vote: \"" + poll.getQuestion() + "\"");

    /*
     * Verify the dependence between cryptographic values and the vote properties
     */
    //Not used anymore, implicitly done with otherInputs of proofs
    //verifyDependencyTextCrypto();

    /*
     * Verify the proofs for the user
     */
    System.out.println();
    System.out.println("Verifying the proof for the participants...");
    a = new Element[poll.getParticipants().size()];
    b = new Element[poll.getParticipants().size()];
    h = new Element[poll.getParticipants().size()];
    hHat = new Element[poll.getParticipants().size()];
    hHatPowX = new Element[poll.getParticipants().size()];
    proofForX = new Element[poll.getParticipants().size()];
    validityProof = new Element[poll.getParticipants().size()];
    equalityProof = new Element[poll.getParticipants().size()];
    Tuple pollTuple = preparePollOtherInput(poll, representations, generator);

    int k = 0;
    for (XMLParticipant p : poll.getParticipants()) {
        System.out.println("\tParticipant " + p.getIdentification() + " (" + p.getUniqueId() + ")");

        if (p.getAi() != null) {
            a[k] = p.getAi().getValue(G_q);
            if (DEBUG)
                System.out.println("Value a: " + a[k]);
        }
        if (p.getHi() != null) {
            h[k] = p.getHi().getValue(G_q);
            if (DEBUG)
                System.out.println("Value h: " + h[k]);
        }
        if (p.getBi() != null) {
            b[k] = p.getBi().getValue(G_q);
            if (DEBUG)
                System.out.println("Value b: " + b[k]);
        }
        if (p.getHiHat() != null) {
            hHat[k] = p.getHiHat().getValue(G_q);
            if (DEBUG)
                System.out.println("Value h hat: " + hHat[k]);
        }
        if (p.getHiHatPowXi() != null) {
            hHatPowX[k] = p.getHiHatPowXi().getValue(G_q);
            if (DEBUG)
                System.out.println("Value h hat ^ x: " + hHatPowX[k]);
        }

        if (p.getProofForXi() != null) {
            ProductGroup group = ProductGroup.getInstance(G_q, Zgroup, Z_q);

            proofForX[k] = p.getProofForXi().getValue(group);
        }

        if (p.getProofValidVote() != null) {

            Group[] tripleElement1Groups = new Group[poll.getOptions().size()];
            Group[] tripleElement2Groups = new Group[poll.getOptions().size()];
            Group[] tripleElement3Groups = new Group[poll.getOptions().size()];
            for (i = 0; i < poll.getOptions().size(); i++) {
                tripleElement1Groups[i] = ProductGroup.getInstance(G_q, G_q);
                tripleElement2Groups[i] = Zgroup;
                tripleElement3Groups[i] = Z_q;
            }
            ProductGroup tripleElement1 = ProductGroup.getInstance(tripleElement1Groups);
            ProductGroup tripleElement2 = ProductGroup.getInstance(tripleElement2Groups);
            ProductGroup tripleElement3 = ProductGroup.getInstance(tripleElement3Groups);
            ProductGroup group = ProductGroup.getInstance(tripleElement1, tripleElement2, tripleElement3);

            validityProof[k] = p.getProofValidVote().getValue(group);

            if (DEBUG)
                System.out.println("Proof of validity: " + validityProof[k]);
        }

        if (p.getProofForHiHat() != null) {
            recoveryNeeded = true;
            ProductGroup group = ProductGroup.getInstance(ProductGroup.getInstance(G_q, G_q), Zgroup, Z_q);

            equalityProof[k] = p.getProofForHiHat().getValue(group);
        }

        Tuple participantTuple = prepareParticipantOtherInput(p);
        otherInput = Tuple.getInstance(participantTuple, pollTuple);

        /*
         * Verify proof of knowledge 
         */
        System.out.print("\t\tVerifying proof of knowledge of x value...");
        verifyProofOfKnowledgeOfX(k);

        /*
         * Verify proof of validity 
         */
        if (validityProof[k] != null) {
            System.out.print("\t\tVerifying proof of valid vote...");
            verifyValidityProof(k);
        }

        /*
         * Verify proof of equality 
         */
        if (equalityProof[k] != null) {
            System.out.print("\t\tVerifying proof of equality between discrete logarithm g^x and h_hat^x...");
            verifyEqualityProof(k);
        }
        k++;
    }

    /**
     * Computing the result
     */
    System.out.println();
    System.out.print("Computing the result...");
    computeResult();

}

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(/*from   w  ww  . j a v  a2  s  . 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.cloud.test.utils.SubmitCert.java

public static void main(String[] args) {
    // Parameters
    List<String> argsList = Arrays.asList(args);
    Iterator<String> iter = argsList.iterator();
    while (iter.hasNext()) {
        String arg = iter.next();

        if (arg.equals("-c")) {
            certFileName = iter.next();/*from  ww  w . j a  v a2 s.  c  o  m*/
        }

        if (arg.equals("-s")) {
            secretKey = iter.next();
        }

        if (arg.equals("-a")) {
            apiKey = iter.next();
        }

        if (arg.equals("-action")) {
            url = "Action=" + iter.next();
        }
    }

    Properties prop = new Properties();
    try {
        prop.load(new FileInputStream("conf/tool.properties"));
    } catch (IOException ex) {
        s_logger.error("Error reading from conf/tool.properties", ex);
        System.exit(2);
    }

    host = prop.getProperty("host");
    port = prop.getProperty("port");

    if (url.equals("Action=SetCertificate") && certFileName == null) {
        s_logger.error("Please set path to certificate (including file name) with -c option");
        System.exit(1);
    }

    if (secretKey == null) {
        s_logger.error("Please set secretkey  with -s option");
        System.exit(1);
    }

    if (apiKey == null) {
        s_logger.error("Please set apikey with -a option");
        System.exit(1);
    }

    if (host == null) {
        s_logger.error("Please set host in tool.properties file");
        System.exit(1);
    }

    if (port == null) {
        s_logger.error("Please set port in tool.properties file");
        System.exit(1);
    }

    TreeMap<String, String> param = new TreeMap<String, String>();

    String req = "GET\n" + host + ":" + prop.getProperty("port") + "\n/" + prop.getProperty("accesspoint")
            + "\n";
    String temp = "";

    if (certFileName != null) {
        cert = readCert(certFileName);
        param.put("cert", cert);
    }

    param.put("AWSAccessKeyId", apiKey);
    param.put("Expires", prop.getProperty("expires"));
    param.put("SignatureMethod", prop.getProperty("signaturemethod"));
    param.put("SignatureVersion", "2");
    param.put("Version", prop.getProperty("version"));

    StringTokenizer str1 = new StringTokenizer(url, "&");
    while (str1.hasMoreTokens()) {
        String newEl = str1.nextToken();
        StringTokenizer str2 = new StringTokenizer(newEl, "=");
        String name = str2.nextToken();
        String value = str2.nextToken();
        param.put(name, value);
    }

    //sort url hash map by key
    Set c = param.entrySet();
    Iterator it = c.iterator();
    while (it.hasNext()) {
        Map.Entry me = (Map.Entry) it.next();
        String key = (String) me.getKey();
        String value = (String) me.getValue();
        try {
            temp = temp + key + "=" + URLEncoder.encode(value, "UTF-8") + "&";
        } catch (Exception ex) {
            s_logger.error("Unable to set parameter " + value + " for the command " + param.get("command"), ex);
        }

    }
    temp = temp.substring(0, temp.length() - 1);
    String requestToSign = req + temp;
    String signature = UtilsForTest.signRequest(requestToSign, secretKey);
    String encodedSignature = "";
    try {
        encodedSignature = URLEncoder.encode(signature, "UTF-8");
    } catch (Exception ex) {
        ex.printStackTrace();
    }

    String url = "http://" + host + ":" + prop.getProperty("port") + "/" + prop.getProperty("accesspoint") + "?"
            + temp + "&Signature=" + encodedSignature;
    s_logger.info("Sending request with url:  " + url + "\n");
    sendRequest(url);
}

From source file:com.google.api.services.samples.youtube.cmdline.Topics.java

/**
 * Execute a search request that starts by calling the Freebase API to
 * retrieve a topic ID matching a user-provided term. Then initialize a
 * YouTube object to search for YouTube videos and call the YouTube Data
 * API's youtube.search.list method to retrieve a list of videos associated
 * with the selected Freebase topic and with another search query term,
 * which the user also enters. Finally, display the titles, video IDs, and
 * thumbnail images for the first five videos in the YouTube Data API
 * response./*  ww  w.j a v  a 2 s  .c  o  m*/
 *
 * @param args This application does not use command line arguments.
 */
public static void main(String[] args) {
    // Read the developer key from the properties file.
    Properties properties = new Properties();
    try {
        InputStream in = Topics.class.getResourceAsStream("/" + PROPERTIES_FILENAME);
        properties.load(in);

    } catch (IOException e) {
        System.err.println("There was an error reading " + PROPERTIES_FILENAME + ": " + e.getCause() + " : "
                + e.getMessage());
        System.exit(1);
    }

    try {
        // Retrieve a Freebase topic ID based on a user-entered query term.
        String topicsId = getTopicId();
        if (topicsId.length() < 1) {
            System.out.println("No topic id will be applied to your search.");
        }

        // Prompt the user to enter a search query term. This term will be
        // used to retrieve YouTube search results related to the topic
        // selected above.
        String queryTerm = getInputQuery("search");

        // This object is used to make YouTube Data API requests. The last
        // argument is required, but since we don't need anything
        // initialized when the HttpRequest is initialized, we override
        // the interface and provide a no-op function.
        youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, new HttpRequestInitializer() {
            public void initialize(HttpRequest request) throws IOException {
            }
        }).setApplicationName("youtube-cmdline-search-sample").build();

        YouTube.Search.List search = youtube.search().list("id,snippet");

        // Set your developer key from the Google Developers Console for
        // non-authenticated requests. See:
        // https://cloud.google.com/console
        String apiKey = properties.getProperty("youtube.apikey");
        search.setKey(apiKey);
        search.setQ(queryTerm);
        if (topicsId.length() > 0) {
            search.setTopicId(topicsId);
        }

        // Restrict the search results to only include videos. See:
        // https://developers.google.com/youtube/v3/docs/search/list#type
        search.setType("video");

        // To increase efficiency, only retrieve the fields that the
        // application uses.
        search.setFields("items(id/kind,id/videoId,snippet/title,snippet/thumbnails/default/url)");
        search.setMaxResults(NUMBER_OF_VIDEOS_RETURNED);
        SearchListResponse searchResponse = search.execute();

        List<SearchResult> searchResultList = searchResponse.getItems();

        if (searchResultList != null) {
            prettyPrint(searchResultList.iterator(), queryTerm, topicsId);
        } else {
            System.out.println("There were no results for your query.");
        }
    } catch (GoogleJsonResponseException e) {
        System.err.println(
                "There was a service error: " + e.getDetails().getCode() + " : " + e.getDetails().getMessage());
        e.printStackTrace();
    } catch (IOException e) {
        System.err.println("There was an IO error: " + e.getCause() + " : " + e.getMessage());
        e.printStackTrace();
    }
}