Example usage for java.util.logging Level INFO

List of usage examples for java.util.logging Level INFO

Introduction

In this page you can find the example usage for java.util.logging Level INFO.

Prototype

Level INFO

To view the source code for java.util.logging Level INFO.

Click Source Link

Document

INFO is a message level for informational messages.

Usage

From source file:to.sparks.mtgox.example.HowToWithdrawBitcoins.java

/** *
 * Send the entire bitcoin balance of a MtGox account to a destination
 * bitcoin address./*ww w.ja v a 2  s  .  c o m*/
 * OTP is not supported! Please turn off Yubikey/OTP
 *
 * @param args The destination bitcoin address
 * @throws Exception OTP is not supported! Please turn off Yubikey/OTP
 */
public static void main(String[] args) throws Exception {

    // Obtain a $USD instance of the API
    ApplicationContext context = new ClassPathXmlApplicationContext("to/sparks/mtgox/example/Beans.xml");
    MtGoxHTTPClient mtGoxAPI = (MtGoxHTTPClient) context.getBean("mtgoxUSD");

    HashMap<String, Wallet> wallets = mtGoxAPI.getAccountInfo().getWallets();
    Wallet btcWallet = wallets.get("BTC");
    MtGoxBitcoin mtgoxBalance = (MtGoxBitcoin) btcWallet.getBalance();
    logger.log(Level.INFO, "MtGox account balance: BTC {0}", mtgoxBalance.toPlainString());
    if (mtgoxBalance.compareTo(BigDecimal.ZERO) > 0) {

        MtGoxBitcoin fee = new MtGoxBitcoin(0.0005D); // Transaction fee
        MtGoxBitcoin transferAmount = new MtGoxBitcoin(mtgoxBalance.subtract(fee));

        if (transferAmount.compareTo(BigDecimal.ZERO) > 0) {
            logger.log(Level.INFO, "Transferring BTC {0} to bitcoin address {1} and paying fee {2}",
                    new Object[] { transferAmount.toPlainString(), args[0], fee.toPlainString() });
            SendBitcoinsTransaction trx = mtGoxAPI.sendBitcoins(args[0], transferAmount, fee, true, false);
            logger.log(Level.INFO, "Transfer success.  trx: {0}", trx.getTrx());
        }
    }
}

From source file:bookChapter.theoretical.AnalyzeTheoreticalMSMSCalculation.java

/**
 *
 * @param args/*from  w  w  w  .  ja  v a 2 s . co m*/
 * @throws IOException
 * @throws FileNotFoundException
 * @throws ClassNotFoundException
 * @throws InterruptedException
 * @throws MzMLUnmarshallerException
 */
public static void main(String[] args) throws IOException, FileNotFoundException, ClassNotFoundException,
        IOException, InterruptedException, MzMLUnmarshallerException {
    Logger l = Logger.getLogger("AnalyzeTheoreticalMSMSCalculation");
    Date date = Calendar.getInstance().getTime();
    DateFormat formatter = new SimpleDateFormat("EEEE, dd MMMM yyyy, hh:mm:ss.SSS a");
    String now = formatter.format(date);
    l.log(Level.INFO, "Calculation starts at {0}", now);
    double precursorTolerance = ConfigHolder.getInstance().getDouble("precursor.tolerance"),
            fragmentTolerance = ConfigHolder.getInstance().getDouble("fragment.tolerance");
    String databaseName = ConfigHolder.getInstance().getString("database.name"),
            spectraName = ConfigHolder.getInstance().getString("spectra.name"),
            output = ConfigHolder.getInstance().getString("output");
    int correctionFactor = ConfigHolder.getInstance().getInt("correctionFactor");
    boolean theoFromAllCharges = ConfigHolder.getInstance().getBoolean("hasAllPossCharge");
    BufferedWriter bw = new BufferedWriter(new FileWriter(output));
    bw.write("SpectrumTitle" + "\t" + "PrecursorMZ" + "\t" + "PrecursorCharge" + "\t" + "Observed Mass (M+H)"
            + "\t" + "AndromedaLikeScore" + "\t" + "SequestLikeScore" + "\t" + "PeptideByAndromedaLikeScore"
            + "\t" + "PeptideBySequestLikeScore" + "\t" + "LevenshteinDistance" + "\t" + "TotalScoredPeps"
            + "\t" + "isCorrectMatchByAndromedaLike" + "\t" + "isCorrectMatchBySequestLikeScore" + "\n");
    l.info("Getting database entries");
    // first load all sequences into the memory 
    HashSet<DBEntry> dbEntries = getDBEntries(databaseName);
    // for every spectrum-calculate both score...
    // now convert to binExperimental spectrum
    int num = 0;
    SpectrumFactory fct = SpectrumFactory.getInstance();
    num = 0;
    File f = new File(spectraName);
    if (spectraName.endsWith(".mgf")) {
        fct.addSpectra(f, new WaitingHandlerCLIImpl());
        l.log(Level.INFO, "Spectra scoring starts at {0}", now);
        for (String title : fct.getSpectrumTitles(f.getName())) {
            num++;
            MSnSpectrum ms = (MSnSpectrum) fct.getSpectrum(f.getName(), title);
            // here calculate all except this is an empty spectrum...
            if (ms.getPeakList().size() > 2) {
                // to check a spectrum with negative values..
                String text = result(ms, precursorTolerance, dbEntries, fragmentTolerance, correctionFactor,
                        theoFromAllCharges);
                if (!text.isEmpty()) {
                    bw.write(text);
                }
            }
            if (num % 500 == 0) {
                l.info("Running " + num + " spectra." + Calendar.getInstance().getTime());
            }
        }
    }
    l.info("Program finished at " + Calendar.getInstance().getTime());

    bw.close();
}

From source file:edu.unc.irss.arc.de.dvpublisher.DataverseClient.java

public static void main(String[] args) throws MalformedURLException {
    if (args.length != 5) {
        logger.log(Level.SEVERE,/*from w w w. ja va 2 s .  c  o m*/
                "Three arguments: dataverse_URL, Api_key, dataverse_Alias are expected dataset_Id file_location");
        throw new IllegalArgumentException("The number of arguments must be 5.");
    }

    for (String arg : args) {
        logger.log(Level.INFO, "arg={0}", arg);
    }

    if (StringUtils.isBlank(args[0])) {
        logger.log(Level.SEVERE, "dataverse URL should not be blank");
        throw new IllegalArgumentException("dataverse URL should not be blank");
    }

    if (StringUtils.isBlank(args[1])) {
        logger.log(Level.SEVERE, "API key should not be blank");
        throw new IllegalArgumentException("API Key should not be blank");
    }

    if (StringUtils.isBlank(args[2])) {
        logger.log(Level.SEVERE, "dataverse alias should not be blank");
        throw new IllegalArgumentException("dataverse alias should not be blank");
    }

    if (StringUtils.isBlank(args[3])) {
        logger.log(Level.SEVERE, "dataset Id should not be blank");
        throw new IllegalArgumentException("dataset Id should not be blank");
    }

    if (StringUtils.isBlank(args[4])) {
        logger.log(Level.SEVERE, "file location should not be blank");
        throw new IllegalArgumentException("file location should not be blank");
    }

    logger.log(Level.INFO, "running main method");
    logger.log(Level.INFO, "dataverseUrl:{0}", args[0]);
    logger.log(Level.INFO, "apiKey:{0}", args[1]);
    logger.log(Level.INFO, "dataverseAlias:{0}", args[2]);
    logger.log(Level.INFO, "datasetId:{0}", args[3]);
    logger.log(Level.INFO, "fileLocation:{0}", args[4]);

    DataverseClient dvClient = new DataverseClient(args[0], args[1], args[2]);

    logger.log(Level.INFO, "uploading a file to a target dataverse");
    dvClient.publishDatafile(args[3], args[4]);
    logger.log(Level.INFO, "uploading has been finished");
}

From source file:drpc.BptiEnsembleQuery.java

public static void main(final String[] args) throws IOException, TException, DRPCExecutionException {
    if (args.length < 3) {
        System.err.println("Where are the arguments? args -- DrpcServer DrpcFunctionName folder");
        return;/*  w ww. j  a v a  2 s . co  m*/
    }

    final DRPCClient client = new DRPCClient(args[0], 3772, 1000000 /*timeout*/);
    final Queue<String> featureFiles = new ArrayDeque<String>();
    SpoutUtils.listFilesForFolder(new File(args[2]), featureFiles);

    Scanner scanner = new Scanner(featureFiles.peek());
    int i = 0;
    while (scanner.hasNextLine() && i++ < 1) {
        List<Map<String, List<Double>>> dict = SpoutUtils.pythonDictToJava(scanner.nextLine());
        for (Map<String, List<Double>> map : dict) {
            final Double[] features = map.get("chi1").toArray(new Double[0]);
            final Double[] moreFeatures = map.get("chi2").toArray(new Double[0]);
            final Double[] both = (Double[]) ArrayUtils.addAll(features, moreFeatures);
            final String parameters = serializeFeatureVector(ArrayUtils.toPrimitive(both));
            Logger.getAnonymousLogger().log(Level.INFO, runQuery(args[1], parameters, client));
        }
    }
    client.close();
}

From source file:Jimbo.Cheerlights.TweetListener.java

/**
 * @param args the command line arguments
 * @throws twitter4j.TwitterException// w  w  w  .jav a 2 s  .  c o m
 * @throws java.io.IOException
 * @throws org.apache.commons.cli.ParseException In case of command line error
 */
public static void main(String[] args) throws TwitterException, IOException, ParseException {
    // Set up simpler logging to stdout
    Jimbo.Logging.Logging.useStdout();

    LOG.log(Level.INFO, "Starting twitter listener");

    Options options = new Options();

    options.addOption("b", Listener.MQTT_BROKER_KEY, true, "URL of the broker")
            .addOption("c", Listener.MQTT_CLIENT_KEY, true, "The MQTT client name to use")
            .addOption("t", Listener.MQTT_TOPIC_KEY, true, "The MQTT topic to use");

    CommandLineParser parser = new DefaultParser();
    CommandLine command = parser.parse(options, args);

    MQTTClient mqtt = null;
    String mqtt_topic = Listener.DEFAULT_MQTT_TOPIC;

    if (command.hasOption(Listener.MQTT_BROKER_KEY)) {
        if (!command.hasOption(Listener.MQTT_CLIENT_KEY))
            throw new ParseException("MQTT without client name");

        if (command.hasOption(Listener.MQTT_TOPIC_KEY))
            mqtt_topic = command.getOptionValue(Listener.MQTT_TOPIC_KEY);

        try {
            mqtt = new MQTTClient(command.getOptionValue(Listener.MQTT_BROKER_KEY),
                    command.getOptionValue(Listener.MQTT_CLIENT_KEY));
            mqtt.run();
        }

        catch (MqttException e) {
            LOG.log(Level.WARNING, "Failed to create MQTT client: {0}", e.toString());
        }
    } else {
        if (command.hasOption(Listener.MQTT_TOPIC_KEY))
            LOG.warning("MQTT topic supplied but no broker");

        if (command.hasOption(Listener.MQTT_CLIENT_KEY))
            LOG.warning("MQTT client name but no broker");
    }

    Twitter twitter = new TwitterFactory().getInstance();
    StatusListener listener = new listener("224.1.1.1", (short) 5123, mqtt, mqtt_topic);
    FilterQuery fq = new FilterQuery();

    String keywords[] = { "#cheerlights" };

    fq.track(keywords);

    TwitterStream twitterStream = new TwitterStreamFactory().getInstance();
    twitterStream.addListener(listener);
    twitterStream.filter(fq);

    LOG.log(Level.INFO, "Up and running....");
}

From source file:bluevia.examples.MODemo.java

/**
 * @param args//from ww  w  .  j av a  2  s .co m
 */
public static void main(String[] args) throws IOException {

    BufferedReader iReader = null;
    String apiDataFile = "API-AccessToken.ini";

    String consumer_key;
    String consumer_secret;
    String registrationId;

    OAuthConsumer apiConsumer = null;
    HttpURLConnection request = null;
    URL moAPIurl = null;

    Logger logger = Logger.getLogger("moSMSDemo.class");
    int i = 0;
    int rc = 0;

    Thread mThread = Thread.currentThread();

    try {
        System.setProperty("debug", "1");

        iReader = new BufferedReader(new FileReader(apiDataFile));

        // Private data: consumer info + access token info + phone info
        consumer_key = iReader.readLine();
        consumer_secret = iReader.readLine();
        registrationId = iReader.readLine();

        // Set up the oAuthConsumer
        while (true) {
            try {

                logger.log(Level.INFO, String.format("#%d: %s\n", ++i, "Requesting messages..."));

                apiConsumer = new DefaultOAuthConsumer(consumer_key, consumer_secret);

                apiConsumer.setMessageSigner(new HmacSha1MessageSigner());

                moAPIurl = new URL("https://api.bluevia.com/services/REST/SMS/inbound/" + registrationId
                        + "/messages?version=v1&alt=json");

                request = (HttpURLConnection) moAPIurl.openConnection();
                request.setRequestMethod("GET");

                apiConsumer.sign(request);

                StringBuffer doc = new StringBuffer();
                BufferedReader br = null;

                rc = request.getResponseCode();
                if (rc == HttpURLConnection.HTTP_OK) {
                    br = new BufferedReader(new InputStreamReader(request.getInputStream()));

                    String line = br.readLine();
                    while (line != null) {
                        doc.append(line);
                        line = br.readLine();
                    }

                    System.out.printf("Output message: %s\n", doc.toString());
                    try {
                        JSONObject apiResponse1 = new JSONObject(doc.toString());
                        String aux = apiResponse1.getString("receivedSMS");
                        if (aux != null) {
                            String szMessage;
                            String szOrigin;
                            String szDate;

                            JSONObject smsPool = apiResponse1.getJSONObject("receivedSMS");
                            JSONArray smsInfo = smsPool.optJSONArray("receivedSMS");
                            if (smsInfo != null) {
                                for (i = 0; i < smsInfo.length(); i++) {
                                    szMessage = smsInfo.getJSONObject(i).getString("message");
                                    szOrigin = smsInfo.getJSONObject(i).getJSONObject("originAddress")
                                            .getString("phoneNumber");
                                    szDate = smsInfo.getJSONObject(i).getString("dateTime");
                                    System.out.printf("#%d %s\n - from %s\n - message:%s\n", i, szDate,
                                            szOrigin, szMessage);
                                }
                            } else {
                                JSONObject sms = smsPool.getJSONObject("receivedSMS");
                                szMessage = sms.getString("message");
                                szOrigin = sms.getJSONObject("originAddress").getString("phoneNumber");
                                szDate = sms.getString("dateTime");
                                System.out.printf("#%d %s\n - from %s\n - message:%s\n", i, szDate, szOrigin,
                                        szMessage);
                            }
                        }
                    } catch (JSONException e) {
                        System.err.println("JSON error: " + e.getMessage());
                    }

                } else if (rc == HttpURLConnection.HTTP_NO_CONTENT)
                    System.out.printf("No content\n");
                else
                    System.err.printf("Error: %d:%s\n", rc, request.getResponseMessage());

                request.disconnect();

            } catch (Exception e) {
                System.err.println("Exception: " + e.getMessage());
            }
            mThread.sleep(15000);
        }
    } catch (Exception e) {
        System.err.println("Exception: " + e.getMessage());
    }
}

From source file:fr.inria.atlanmod.kyanos.benchmarks.XmiTraverser.java

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

    Option inputOpt = OptionBuilder.create(IN);
    inputOpt.setArgName("INPUT");
    inputOpt.setDescription("Input model");
    inputOpt.setArgs(1);/*from   w w w. jav a  2  s .c  o  m*/
    inputOpt.setRequired(true);

    Option inClassOpt = OptionBuilder.create(EPACKAGE_CLASS);
    inClassOpt.setArgName("CLASS");
    inClassOpt.setDescription("FQN of EPackage implementation class");
    inClassOpt.setArgs(1);
    inClassOpt.setRequired(true);

    options.addOption(inputOpt);
    options.addOption(inClassOpt);

    CommandLineParser parser = new PosixParser();

    try {
        CommandLine commandLine = parser.parse(options, args);

        URI uri = URI.createFileURI(commandLine.getOptionValue(IN));

        Class<?> inClazz = XmiTraverser.class.getClassLoader()
                .loadClass(commandLine.getOptionValue(EPACKAGE_CLASS));
        inClazz.getMethod("init").invoke(null);

        ResourceSet resourceSet = new ResourceSetImpl();
        resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("xmi",
                new XMIResourceFactoryImpl());
        resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("zxmi",
                new XMIResourceFactoryImpl());

        Resource resource = resourceSet.createResource(uri);

        Map<String, Object> loadOpts = new HashMap<String, Object>();
        resource.load(loadOpts);

        LOG.log(Level.INFO, "Start counting");
        int count = 0;
        long begin = System.currentTimeMillis();
        for (Iterator<EObject> iterator = resource.getAllContents(); iterator.hasNext(); iterator
                .next(), count++)
            ;
        long end = System.currentTimeMillis();
        LOG.log(Level.INFO, "End counting");
        LOG.log(Level.INFO, MessageFormat.format("Resource {0} contains {1} elements", uri, count));
        LOG.log(Level.INFO, MessageFormat.format("Time spent: {0}", MessageUtil.formatMillis(end - begin)));

        resource.unload();

    } catch (ParseException e) {
        MessageUtil.showError(e.toString());
        MessageUtil.showError("Current arguments: " + Arrays.toString(args));
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java -jar <this-file.jar>", options, true);
    } catch (Throwable e) {
        MessageUtil.showError(e.toString());
    }
}

From source file:fr.inria.atlanmod.emf.graphs.Connectedness.java

public static void main(String[] args) {

    Options options = createOptions();//from  w  w  w  .  j a  va  2 s . c o  m

    CommandLineParser parser = new PosixParser();

    try {
        CommandLine commandLine = parser.parse(options, args);
        String inputMetamodel = commandLine.getOptionValue(INPUT_METAMODEL);
        String inputModel = commandLine.getOptionValue(INPUT_MODEL);
        Boolean logUnreachable = commandLine.hasOption(LOG_UNREACHABLE);

        ResourceSet resourceSet = new ResourceSetImpl();
        Resource.Factory.Registry.INSTANCE.getExtensionToFactoryMap()
                .put(Resource.Factory.Registry.DEFAULT_EXTENSION, new XMIResourceFactoryImpl());

        {
            LOG.log(Level.INFO, "Loading input metamodel");
            URI uri = URI.createFileURI(inputMetamodel);
            Resource resource = resourceSet.getResource(uri, true);
            registerEPackages(resource);
        }

        URI uri = URI.createFileURI(inputModel);

        LOG.log(Level.INFO, "Loading input model");
        Resource resource = resourceSet.getResource(uri, true);

        LOG.log(Level.INFO, "Getting input model contents");
        Set<EObject> resourceContents = getResourceContents(resource);
        int totalCount = resourceContents.size();

        LOG.log(Level.INFO, MessageFormat.format("Input model contains {0} elements", totalCount));

        List<EClassifier> candidateEClassifiers = buildCandidateEClassifiers();

        for (Iterator<EObject> it = resource.getAllContents(); it.hasNext();) {
            EObject eObject = it.next();
            if (candidateEClassifiers.contains(eObject.eClass())) {
                Set<EObject> reachableEObjects = getReachableEObjects(eObject);
                int i = reachableEObjects.size();
                LOG.log(Level.INFO, MessageFormat.format("Found {0} reachable objects from {1} (EClass {2})", i,
                        EcoreUtil.getURI(eObject), eObject.eClass().getName()));
                if (logUnreachable) {
                    Set<EObject> unreachableEObjects = new HashSet<>(resourceContents);
                    unreachableEObjects.removeAll(reachableEObjects);
                    LOG.log(Level.INFO,
                            MessageFormat.format("{0} elements are unreachable from {1} (EClass {2})",
                                    unreachableEObjects.size(), EcoreUtil.getURI(eObject),
                                    eObject.eClass().getName()));
                    for (EObject unreachableEObject : unreachableEObjects) {
                        LOG.log(Level.INFO, MessageFormat.format("Unreachable EObject {0} is of type {1}",
                                EcoreUtil.getURI(unreachableEObject), unreachableEObject.eClass()));
                    }
                }
            }
        }

    } catch (ParseException e) {
        LOG.log(Level.SEVERE, e.getLocalizedMessage(), e);
        LOG.log(Level.INFO, "Current arguments: " + Arrays.toString(args));
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java -jar <this-file.jar>", options, true);
    } catch (Throwable e) {
        LOG.log(Level.SEVERE, e.getLocalizedMessage(), e);
        MessageUtil.showError(e.toString());
    }
}

From source file:de.burlov.amazon.s3.dirsync.CLI.java

/**
 * @param args/*  ww  w  .ja  v a  2s  .  c  om*/
 */
@SuppressWarnings("static-access")
public static void main(String[] args) {
    Logger.getLogger("").setLevel(Level.OFF);
    Logger deLogger = Logger.getLogger("de");
    deLogger.setLevel(Level.INFO);
    Handler handler = new ConsoleHandler();
    handler.setFormatter(new VerySimpleFormatter());
    deLogger.addHandler(handler);
    deLogger.setUseParentHandlers(false);
    //      if (true)
    //      {
    //         LogFactory.getLog(CLI.class).error("test msg", new Exception("test extception"));
    //         return;
    //      }
    Options opts = new Options();
    OptionGroup gr = new OptionGroup();

    /*
     * Befehlsgruppe initialisieren
     */
    gr = new OptionGroup();
    gr.setRequired(true);
    gr.addOption(OptionBuilder.withArgName("up|down").hasArg()
            .withDescription("Upload/Download changed or new files").create(CMD_UPDATE));
    gr.addOption(OptionBuilder.withArgName("up|down").hasArg()
            .withDescription("Upload/Download directory snapshot").create(CMD_SNAPSHOT));
    gr.addOption(OptionBuilder.withDescription("Delete remote folder").create(CMD_DELETE_DIR));
    gr.addOption(OptionBuilder.withDescription("Delete a bucket").create(CMD_DELETE_BUCKET));
    gr.addOption(OptionBuilder.create(CMD_HELP));
    gr.addOption(OptionBuilder.create(CMD_VERSION));
    gr.addOption(OptionBuilder.withDescription("Prints summary for stored data").create(CMD_SUMMARY));
    gr.addOption(OptionBuilder.withDescription("Clean up orphaned objekts").create(CMD_CLEANUP));
    gr.addOption(OptionBuilder.withDescription("Changes encryption password").withArgName("new password")
            .hasArg().create(CMD_CHANGE_PASSWORD));
    gr.addOption(OptionBuilder.withDescription("Lists all buckets").create(CMD_LIST_BUCKETS));
    gr.addOption(OptionBuilder.withDescription("Lists raw objects in a bucket").create(CMD_LIST_BUCKET));
    gr.addOption(OptionBuilder.withDescription("Lists files in remote folder").create(CMD_LIST_DIR));
    opts.addOptionGroup(gr);
    /*
     * Parametergruppe initialisieren
     */
    opts.addOption(OptionBuilder.withArgName("key").isRequired(false).hasArg().withDescription("S3 access key")
            .create(OPT_S3S_KEY));
    opts.addOption(OptionBuilder.withArgName("secret").isRequired(false).hasArg()
            .withDescription("Secret key for S3 account").create(OPT_S3S_SECRET));
    opts.addOption(OptionBuilder.withArgName("bucket").isRequired(false).hasArg().withDescription(
            "Optional bucket name for storage. If not specified then an unique bucket name will be generated")
            .create(OPT_BUCKET));
    // opts.addOption(OptionBuilder.withArgName("US|EU").hasArg().
    // withDescription(
    // "Where the new bucket should be created. Default US").create(
    // OPT_LOCATION));
    opts.addOption(OptionBuilder.withArgName("path").isRequired(false).hasArg()
            .withDescription("Local directory path").create(OPT_LOCAL_DIR));
    opts.addOption(OptionBuilder.withArgName("name").isRequired(false).hasArg()
            .withDescription("Remote directory name").create(OPT_REMOTE_DIR));
    opts.addOption(OptionBuilder.withArgName("password").isRequired(false).hasArg()
            .withDescription("Encryption password").create(OPT_ENC_PASSWORD));
    opts.addOption(OptionBuilder.withArgName("patterns").hasArgs()
            .withDescription("Comma separated exclude file patterns like '*.tmp,*/dir/*.tmp'")
            .create(OPT_EXCLUDE_PATTERNS));
    opts.addOption(OptionBuilder.withArgName("patterns").hasArgs().withDescription(
            "Comma separated include patterns like '*.java'. If not specified, then all files in specified local directory will be included")
            .create(OPT_INCLUDE_PATTERNS));

    if (args.length == 0) {
        printUsage(opts);
        return;
    }

    CommandLine cmd = null;
    try {
        cmd = new GnuParser().parse(opts, args);
        if (cmd.hasOption(CMD_HELP)) {
            printUsage(opts);
            return;
        }
        if (cmd.hasOption(CMD_VERSION)) {
            System.out.println("s3dirsync version " + Version.CURRENT_VERSION);
            return;
        }
        String awsKey = cmd.getOptionValue(OPT_S3S_KEY);
        String awsSecret = cmd.getOptionValue(OPT_S3S_SECRET);
        String bucket = cmd.getOptionValue(OPT_BUCKET);
        String bucketLocation = cmd.getOptionValue(OPT_LOCATION);
        String localDir = cmd.getOptionValue(OPT_LOCAL_DIR);
        String remoteDir = cmd.getOptionValue(OPT_REMOTE_DIR);
        String password = cmd.getOptionValue(OPT_ENC_PASSWORD);
        String exclude = cmd.getOptionValue(OPT_EXCLUDE_PATTERNS);
        String include = cmd.getOptionValue(OPT_INCLUDE_PATTERNS);

        if (StringUtils.isBlank(awsKey) || StringUtils.isBlank(awsSecret)) {
            System.out.println("S3 account data required");
            return;
        }

        if (StringUtils.isBlank(bucket)) {
            bucket = awsKey + ".dirsync";
        }

        if (cmd.hasOption(CMD_DELETE_BUCKET)) {
            if (StringUtils.isBlank(bucket)) {
                System.out.println("Bucket name required");
                return;
            }
            int deleted = S3Utils.deleteBucket(awsKey, awsSecret, bucket);
            System.out.println("Deleted objects: " + deleted);
            return;
        }
        if (cmd.hasOption(CMD_LIST_BUCKETS)) {
            for (String str : S3Utils.listBuckets(awsKey, awsSecret)) {
                System.out.println(str);
            }
            return;
        }
        if (cmd.hasOption(CMD_LIST_BUCKET)) {
            if (StringUtils.isBlank(bucket)) {
                System.out.println("Bucket name required");
                return;
            }
            for (String str : S3Utils.listObjects(awsKey, awsSecret, bucket)) {
                System.out.println(str);
            }
            return;
        }
        if (StringUtils.isBlank(password)) {
            System.out.println("Encryption password required");
            return;
        }
        char[] psw = password.toCharArray();
        DirSync ds = new DirSync(awsKey, awsSecret, bucket, bucketLocation, psw);
        ds.setExcludePatterns(parseSubargumenths(exclude));
        ds.setIncludePatterns(parseSubargumenths(include));
        if (cmd.hasOption(CMD_SUMMARY)) {
            ds.printStorageSummary();
            return;
        }
        if (StringUtils.isBlank(remoteDir)) {
            System.out.println("Remote directory name required");
            return;
        }
        if (cmd.hasOption(CMD_DELETE_DIR)) {
            ds.deleteFolder(remoteDir);
            return;
        }
        if (cmd.hasOption(CMD_LIST_DIR)) {
            Folder folder = ds.getFolder(remoteDir);
            if (folder == null) {
                System.out.println("No such folder found: " + remoteDir);
                return;
            }
            for (Map.Entry<String, FileInfo> entry : folder.getIndexData().entrySet()) {
                System.out.println(entry.getKey() + " ("
                        + FileUtils.byteCountToDisplaySize(entry.getValue().getLength()) + ")");
            }
            return;
        }
        if (cmd.hasOption(CMD_CLEANUP)) {
            ds.cleanUp();
            return;
        }
        if (cmd.hasOption(CMD_CHANGE_PASSWORD)) {
            String newPassword = cmd.getOptionValue(CMD_CHANGE_PASSWORD);
            if (StringUtils.isBlank(newPassword)) {
                System.out.println("new password required");
                return;
            }
            char[] chars = newPassword.toCharArray();
            ds.changePassword(chars);
            newPassword = null;
            Arrays.fill(chars, ' ');
            return;
        }
        if (StringUtils.isBlank(localDir)) {
            System.out.println(OPT_LOCAL_DIR + " argument required");
            return;
        }
        String direction = "";
        boolean up = false;
        boolean snapshot = false;
        if (StringUtils.isNotBlank(cmd.getOptionValue(CMD_UPDATE))) {
            direction = cmd.getOptionValue(CMD_UPDATE);
        } else if (StringUtils.isNotBlank(cmd.getOptionValue(CMD_SNAPSHOT))) {
            direction = cmd.getOptionValue(CMD_SNAPSHOT);
            snapshot = true;
        }
        if (StringUtils.isBlank(direction)) {
            System.out.println("Operation direction required");
            return;
        }
        up = StringUtils.equalsIgnoreCase(OPT_UP, direction);
        File baseDir = new File(localDir);
        if (!baseDir.exists() && !baseDir.mkdirs()) {
            System.out.println("Invalid local directory: " + baseDir.getAbsolutePath());
            return;
        }
        ds.syncFolder(baseDir, remoteDir, up, snapshot);

    } catch (DirSyncException e) {
        System.out.println(e.getMessage());
        e.printStackTrace();
    } catch (ParseException e) {
        System.out.println(e.getMessage());
        printUsage(opts);

    } catch (Exception e) {
        e.printStackTrace(System.err);
    }
}

From source file:malware_classification.Malware_Classification.java

/**
 * @param args the command line arguments. Order is malicious_filename,
 * benign filename, (optional) bin_size/*from   w w  w .j  av a 2 s.c o  m*/
 */
public static void main(String[] args) {
    String malicious_file_path = args[0];
    String benign_file_path = args[1];
    int curr_bin_size;
    if (args.length > 2) {
        curr_bin_size = Integer.parseInt(args[2]);
    } else {
        curr_bin_size = -1;
    }
    String pid_str = ManagementFactory.getRuntimeMXBean().getName();
    logger.setLevel(Level.CONFIG);
    logger.log(Level.INFO, pid_str);
    boolean found_file = false;
    String output_base = "std_output";
    File output_file = null;
    for (int i = 0; !found_file; i++) {
        output_file = new File(output_base + i + ".txt");
        found_file = !output_file.exists();
    }

    FileHandler fh = null;
    try {
        fh = new FileHandler(output_file.getAbsolutePath());
    } catch (IOException ex) {
        Logger.getLogger(Malware_Classification.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SecurityException ex) {
        Logger.getLogger(Malware_Classification.class.getName()).log(Level.SEVERE, null, ex);
    }
    logger.addHandler(fh);
    logger.info("Writing output in " + output_file.getAbsolutePath());

    Malware_Classification classifier = new Malware_Classification(malicious_file_path, benign_file_path,
            curr_bin_size);
    //        classifier.run_tests();
}