Example usage for java.text SimpleDateFormat SimpleDateFormat

List of usage examples for java.text SimpleDateFormat SimpleDateFormat

Introduction

In this page you can find the example usage for java.text SimpleDateFormat SimpleDateFormat.

Prototype

public SimpleDateFormat(String pattern) 

Source Link

Document

Constructs a SimpleDateFormat using the given pattern and the default date format symbols for the default java.util.Locale.Category#FORMAT FORMAT locale.

Usage

From source file:com.movielabs.availstool.AvailsTool.java

public static void main(String[] args) throws Exception {
    String fileName, outFile, sheetName;
    int sheetNum = -1;

    Logger log = LogManager.getLogger(AvailsTool.class.getName());
    log.info("Initializing logger");

    Options options = new Options();
    options.addOption(Opts.v.name(), false, "verbose mode");
    options.addOption(Opts.s.name(), true, "specify sheet");
    options.addOption(Opts.f.name(), true, "specify file name");
    options.addOption(Opts.o.name(), true, "specify output file name");
    options.addOption(Opts.sstoxml.name(), false, "convert avails spreadsheet to XML");
    options.addOption(Opts.xmltoss.name(), false, "convert avails XML to a spreadsheet");
    options.addOption(Opts.dumpsheet.name(), false, "dump a single sheet from a spreadsheet");
    options.addOption(Opts.dumpss.name(), false, "dump a spreadsheet file");
    options.addOption(Opts.wx.name(), false, "treat warning as fatal error");
    options.addOption(Opts.clean.name(), false, "clean up data entries");

    CommandLineParser cli = new DefaultParser();

    try {//from ww w. j  a v  a2s .  co m
        CommandLine cmd = cli.parse(options, args);
        boolean optToXML = cmd.hasOption(Opts.sstoxml.name());
        boolean optToSS = cmd.hasOption(Opts.xmltoss.name());
        boolean optDumpSS = cmd.hasOption(Opts.dumpss.name());
        boolean optDumpSheet = cmd.hasOption(Opts.dumpsheet.name());
        fileName = cmd.getOptionValue(Opts.f.name());
        sheetName = cmd.getOptionValue(Opts.s.name());
        boolean clean = cmd.hasOption(Opts.clean.name());
        boolean wx = cmd.hasOption(Opts.wx.name());
        boolean verbose = cmd.hasOption(Opts.v.name());
        AvailSS ss;
        AvailsSheet as;
        String message;

        if (sheetName != null) {
            Pattern pat = Pattern.compile("^\\d+$");
            Matcher m = pat.matcher(sheetName);
            if (m.matches())
                sheetNum = Integer.parseInt(sheetName);
        }

        if (fileName == null)
            throw new ParseException("input file not specified");

        if (!(optToXML | optToSS | optDumpSS | optDumpSheet))
            throw new ParseException("missing operation");

        if (optToXML) {
            if (optToSS | optDumpSS | optDumpSheet)
                throw new ParseException("more than one operation specified");
            outFile = cmd.getOptionValue(Opts.o.name());
            if (outFile == null)
                throw new ParseException("output file not specified");

            ss = new AvailSS(fileName, log, wx, clean);
            if (sheetNum < 0)
                as = ss.addSheet(sheetName);
            else
                as = ss.addSheet(sheetNum);
            message = "toXML file: " + fileName + " sheet: " + sheetName;
            log.info(message);
            if (verbose)
                System.out.println(message);
            log.info("Options: -clean:" + clean + "; -wx:" + wx + "; output file: " + outFile);
            String timeStamp = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(new java.util.Date());
            String shortDesc = String.format("generated XML from %s:%s on %s", fileName, sheetName, timeStamp);
            as.makeXMLFile(outFile, shortDesc);
        } else if (optToSS) {
            if (optToXML | optDumpSS | optDumpSheet)
                throw new ParseException("more than one operation specified");
            // TODO implement this
            outFile = cmd.getOptionValue(Opts.o.name());
            if (outFile == null)
                throw new ParseException("output file not specified");
            AvailXML x = new AvailXML(fileName, log);
            x.makeSS(outFile);
        } else if (optDumpSS) {
            if (optToXML | optToSS | optDumpSheet)
                throw new ParseException("more than one operation specified");
            message = "dumping file: " + fileName;
            log.info(message);
            if (verbose)
                System.out.println(message);
            AvailSS.dumpFile(fileName);
        } else { // dumpSheet
            if (sheetName == null)
                throw new ParseException("sheet name not specified");
            message = "dumping file: " + fileName + " sheet: " + sheetName;
            log.info(message);
            if (verbose)
                System.out.println(message);
            ss = new AvailSS(fileName, log, wx, clean);
            if (sheetNum < 0)
                as = ss.addSheet(sheetName);
            else
                as = ss.addSheet(sheetNum);

            ss.dumpSheet(sheetName);
        }
    } catch (ParseException exp) {
        System.out.println("bad command line: " + exp.getMessage());
        usage();
        System.exit(-1);
    }
}

From source file:at.asitplus.regkassen.demo.RKSVCashboxSimulator.java

public static void main(String[] args) {
    try {// w  w w .j a va  2 s  .c  o m
        //IMPORTANT HINT REGARDING STRING ENCODING
        //in Java all Strings have UTF-8 as default encoding
        //therefore: there are only a few references to UTF-8 encoding in this demo code
        //however, if values are retrieved from a database or another program language is used, then one needs to
        //make sure that the UTF-8 encoding is correctly implemented

        //this demo cashbox does not implement error handling
        //it should only demonstrate the core elements of the RKSV and any boilerplate code is avoided as much as possible
        //if an error occurs, only the stacktraces are logged
        //obviously this needs to be adapted in a productive cashbox

        //----------------------------------------------------------------------------------------------------
        //basic inits
        //add bouncycastle provider
        Security.addProvider(new BouncyCastleProvider());

        //----------------------------------------------------------------------------------------------------
        //check if unlimited strength policy files are installed, they are required for strong crypto algorithms ==> AES 256
        if (!CryptoUtil.isUnlimitedStrengthPolicyAvailable()) {
            System.out.println(
                    "Your JVM does not provide the unlimited strength policy. However, this policy is required to enable strong cryptography (e.g. AES with 256 bits). Please install the required policy files.");
            System.exit(0);
        }

        //----------------------------------------------------------------------------------------------------
        //parse cmd line options
        Options options = new Options();

        // add CMD line options
        options.addOption("o", "output-dir", true,
                "specify base output directory, if none is specified, a new directory will be created in the current working directory");
        //options.addOption("i", "simulation-file-or-directory", true, "cashbox simulation (file) or multiple cashbox simulation files (directory), if none is specified the internal test suites will be executed (can also be considered as demo mode)");
        options.addOption("v", "verbose", false, "dump demo receipts to cmd line");
        options.addOption("c", "closed system", false, "simulate closed system");

        ///parse CMD line options
        CommandLineParser parser = new DefaultParser();
        CommandLine cmd = parser.parse(options, args);

        //setup inputs from cmd line
        //verbose
        VERBOSE = cmd.hasOption("v");
        CLOSED_SYSTEM = cmd.hasOption("c");

        //output directory
        String outputParentDirectoryString = cmd.getOptionValue("o");
        if (outputParentDirectoryString == null) {
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH-mm-ss");
            outputParentDirectoryString = "./CashBoxDemoOutput" + df.format(new Date());
        }
        File OUTPUT_PARENT_DIRECTORY = new File(outputParentDirectoryString);
        OUTPUT_PARENT_DIRECTORY.mkdirs();

        //----------------------------------------------------------------------------------------------------
        //external simulation runs... not implemented yet, currently only the internal test suites can be executed
        //String simulationFileOrDirectoryPath = cmd.getOptionValue("i");
        //handling of arbitrary input simulation files will be possible in 0.7
        //if (simulationFileOrDirectoryPath == null) {
        //} else {
        //                File simulationFileOrDirectory = new File(simulationFileOrDirectoryPath);
        //                cashBoxSimulationList = readCashBoxSimulationFromFile(simulationFileOrDirectory);
        //}

        List<CashBoxSimulation> cashBoxSimulationList = TestSuiteGenerator.getSimulationRuns();

        //setup simulation and execute
        int index = 1;
        for (CashBoxSimulation cashboxSimulation : cashBoxSimulationList) {
            System.out.println("Executing simulation run " + index + "/" + cashBoxSimulationList.size());
            System.out.println("Simulation run: " + cashboxSimulation.getSimulationRunLabel());
            index++;

            File testSetDirectory = new File(OUTPUT_PARENT_DIRECTORY,
                    cashboxSimulation.getSimulationRunLabel());
            testSetDirectory.mkdirs();

            CashBoxParameters cashBoxParameters = new CashBoxParameters();
            cashBoxParameters.setCashBoxId(cashboxSimulation.getCashBoxId());
            cashBoxParameters.setTurnOverCounterAESKey(
                    CryptoUtil.convertBase64KeyToSecretKey(cashboxSimulation.getBase64AesKey()));
            cashBoxParameters.setDepModul(new SimpleMemoryDEPModule());
            cashBoxParameters.setPrinterModule(new SimplePDFPrinterModule());
            cashBoxParameters.setCompanyID(cashboxSimulation.getCompanyID());

            //create pre-defined number of signature devices
            for (int i = 0; i < cashboxSimulation.getNumberOfSignatureDevices(); i++) {
                JWSModule jwsModule = new ManualJWSModule();
                SignatureModule signatureModule;
                if (!CLOSED_SYSTEM) {
                    signatureModule = new NEVER_USE_IN_A_REAL_SYSTEM_SoftwareCertificateOpenSystemSignatureModule(
                            RKSuite.R1_AT100, null);
                } else {
                    signatureModule = new NEVER_USE_IN_A_REAL_SYSTEM_SoftwareKeySignatureModule(
                            cashboxSimulation.getCompanyID() + "-" + "K" + i);
                }
                jwsModule.setOpenSystemSignatureModule(signatureModule);
                cashBoxParameters.getJwsSignatureModules().add(jwsModule);
            }

            //init cashbox
            DemoCashBox demoCashBox = new DemoCashBox(cashBoxParameters);

            //exceute simulation run
            demoCashBox.executeSimulation(cashboxSimulation.getCashBoxInstructionList());

            //----------------------------------------------------------------------------------------------------
            //export DEP
            DEPExportFormat depExportFormat = demoCashBox.exportDEP();
            //get JSON rep and dump export format to file/std output
            File depExportFile = new File(testSetDirectory, "dep-export.json");
            dumpJSONRepOfObject(depExportFormat, depExportFile, true,
                    "------------DEP-EXPORT-FORMAT------------");

            //----------------------------------------------------------------------------------------------------
            //store signature certificates and AES key (so that they can be used for verification purposes)
            CryptographicMaterialContainer cryptographicMaterialContainer = new CryptographicMaterialContainer();
            HashMap<String, CertificateOrPublicKeyContainer> certificateContainerMap = new HashMap<>();
            cryptographicMaterialContainer.setCertificateOrPublicKeyMap(certificateContainerMap);

            //store AES key as BASE64 String
            //ATTENTION, this is only for demonstration purposes, the AES key must be stored in a secure location
            cryptographicMaterialContainer.setBase64AESKey(cashboxSimulation.getBase64AesKey());
            List<JWSModule> jwsSignatureModules = demoCashBox.getCashBoxParameters().getJwsSignatureModules();
            for (JWSModule jwsSignatureModule : jwsSignatureModules) {
                CertificateOrPublicKeyContainer certificateOrPublicKeyContainer = new CertificateOrPublicKeyContainer();
                certificateOrPublicKeyContainer.setId(jwsSignatureModule.getSerialNumberOfKeyID());
                certificateContainerMap.put(jwsSignatureModule.getSerialNumberOfKeyID(),
                        certificateOrPublicKeyContainer);
                X509Certificate certificate = (X509Certificate) jwsSignatureModule.getSignatureModule()
                        .getSigningCertificate();
                if (certificate == null) {
                    //must be public key based... (closed system)
                    PublicKey publicKey = jwsSignatureModule.getSignatureModule().getSigningPublicKey();
                    certificateOrPublicKeyContainer.setSignatureCertificateOrPublicKey(
                            CashBoxUtils.base64Encode(publicKey.getEncoded(), false));
                    certificateOrPublicKeyContainer.setSignatureDeviceType(SignatureDeviceType.PUBLIC_KEY);
                } else {
                    certificateOrPublicKeyContainer.setSignatureCertificateOrPublicKey(
                            CashBoxUtils.base64Encode(certificate.getEncoded(), false));
                    certificateOrPublicKeyContainer.setSignatureDeviceType(SignatureDeviceType.CERTIFICATE);
                }
            }

            File cryptographicMaterialContainerFile = new File(testSetDirectory,
                    "cryptographicMaterialContainer.json");
            dumpJSONRepOfObject(cryptographicMaterialContainer, cryptographicMaterialContainerFile, true,
                    "------------CRYPTOGRAPHIC MATERIAL------------");

            //----------------------------------------------------------------------------------------------------
            //export QR codes to file
            //dump machine readable code of receipts (this "code" is used for the QR-codes)
            //REF TO SPECIFICATION: Detailspezifikation/Abs 12
            //dump to File
            File qrCoreRepExportFile = new File(testSetDirectory, "qr-code-rep.json");
            List<ReceiptPackage> receiptPackages = demoCashBox.getStoredReceipts();
            List<String> qrCodeRepList = new ArrayList<>();
            for (ReceiptPackage receiptPackage : receiptPackages) {
                qrCodeRepList.add(CashBoxUtils.getQRCodeRepresentationFromJWSCompactRepresentation(
                        receiptPackage.getJwsCompactRepresentation()));
            }
            dumpJSONRepOfObject(qrCodeRepList, qrCoreRepExportFile, true,
                    "------------QR-CODE-REP------------");

            //----------------------------------------------------------------------------------------------------
            //export OCR codes to file
            //dump machine readable code of receipts (this "code" is used for the OCR-codes)
            //REF TO SPECIFICATION: Detailspezifikation/Abs 14
            //dump to File
            File ocrCoreRepExportFile = new File(testSetDirectory, "ocr-code-rep.json");
            List<String> ocrCodeRepList = new ArrayList<>();
            for (ReceiptPackage receiptPackage : receiptPackages) {
                ocrCodeRepList.add(CashBoxUtils.getOCRCodeRepresentationFromJWSCompactRepresentation(
                        receiptPackage.getJwsCompactRepresentation()));
            }
            dumpJSONRepOfObject(ocrCodeRepList, ocrCoreRepExportFile, true,
                    "------------OCR-CODE-REP------------");

            //----------------------------------------------------------------------------------------------------
            //create PDF receipts and print to directory
            //REF TO SPECIFICATION: Detailspezifikation/Abs 12
            File qrCodeDumpDirectory = new File(testSetDirectory, "qr-code-dir-pdf");
            qrCodeDumpDirectory.mkdirs();
            List<byte[]> printedQRCodeReceipts = demoCashBox.printReceipt(receiptPackages,
                    ReceiptPrintType.QR_CODE);
            CashBoxUtils.writeReceiptsToFiles(printedQRCodeReceipts, "QR-", qrCodeDumpDirectory);

            //----------------------------------------------------------------------------------------------------
            //export receipts as PDF (OCR)
            //REF TO SPECIFICATION: Detailspezifikation/Abs 14
            File ocrCodeDumpDirectory = new File(testSetDirectory, "ocr-code-dir-pdf");
            ocrCodeDumpDirectory.mkdirs();
            List<byte[]> printedOCRCodeReceipts = demoCashBox.printReceipt(receiptPackages,
                    ReceiptPrintType.OCR);
            CashBoxUtils.writeReceiptsToFiles(printedOCRCodeReceipts, "OCR-", ocrCodeDumpDirectory);

            //----------------------------------------------------------------------------------------------------
            //dump executed testsuite
            File testSuiteDumpFile = new File(testSetDirectory,
                    cashboxSimulation.getSimulationRunLabel() + ".json");
            dumpJSONRepOfObject(cashboxSimulation, testSuiteDumpFile, true,
                    "------------CASHBOX Simulation------------");
        }
    } catch (CertificateEncodingException e) {
        e.printStackTrace();
    } catch (ParseException e) {
        e.printStackTrace();
    }
}

From source file:ta4jexamples.analysis.BuyAndSellSignalsToChart.java

public static void main(String[] args) {

    // Getting the time series
    TimeSeries series = CsvTradesLoader.loadBitstampSeries();
    // Building the trading strategy
    Strategy strategy = MovingMomentumStrategy.buildStrategy(series);

    /**//w  w  w .j av  a 2 s  .com
     * Building chart datasets
     */
    TimeSeriesCollection dataset = new TimeSeriesCollection();
    dataset.addSeries(buildChartTimeSeries(series, new ClosePriceIndicator(series), "Bitstamp Bitcoin (BTC)"));

    /**
     * Creating the chart
     */
    JFreeChart chart = ChartFactory.createTimeSeriesChart("Bitstamp BTC", // title
            "Date", // x-axis label
            "Price", // y-axis label
            dataset, // data
            true, // create legend?
            true, // generate tooltips?
            false // generate URLs?
    );
    XYPlot plot = (XYPlot) chart.getPlot();
    DateAxis axis = (DateAxis) plot.getDomainAxis();
    axis.setDateFormatOverride(new SimpleDateFormat("MM-dd HH:mm"));

    /**
     * Running the strategy and adding the buy and sell signals to plot
     */
    addBuySellSignals(series, strategy, plot);

    /**
     * Displaying the chart
     */
    displayChart(chart);
}

From source file:Text2ColumntStorageMR.java

@SuppressWarnings("deprecation")
public static void main(String[] args) throws Exception {

    if (args.length != 3) {
        System.out.println("Text2ColumnStorageMR <input> <output> <columnStorageMode>");
        System.exit(-1);/*from w  w  w  .ja v  a2 s  . co  m*/
    }

    JobConf conf = new JobConf(Text2ColumntStorageMR.class);

    conf.setJobName("Text2ColumnStorageMR");

    conf.setNumMapTasks(1);
    conf.setNumReduceTasks(4);

    conf.setOutputKeyClass(LongWritable.class);
    conf.setOutputValueClass(Unit.Record.class);

    conf.setMapperClass(TextFileMapper.class);
    conf.setReducerClass(ColumnStorageReducer.class);

    conf.setInputFormat(TextInputFormat.class);
    conf.setOutputFormat((Class<? extends OutputFormat>) ColumnStorageHiveOutputFormat.class);
    conf.set("mapred.output.compress", "flase");

    Head head = new Head();
    initHead(head);

    head.toJobConf(conf);

    int bt = Integer.valueOf(args[2]);

    FileInputFormat.setInputPaths(conf, args[0]);
    Path outputPath = new Path(args[1]);
    FileOutputFormat.setOutputPath(conf, outputPath);

    FileSystem fs = outputPath.getFileSystem(conf);
    fs.delete(outputPath, true);

    JobClient jc = new JobClient(conf);
    RunningJob rj = null;
    rj = jc.submitJob(conf);

    String lastReport = "";
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss,SSS");
    long reportTime = System.currentTimeMillis();
    long maxReportInterval = 3 * 1000;
    while (!rj.isComplete()) {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
        }

        int mapProgress = Math.round(rj.mapProgress() * 100);
        int reduceProgress = Math.round(rj.reduceProgress() * 100);

        String report = " map = " + mapProgress + "%,  reduce = " + reduceProgress + "%";

        if (!report.equals(lastReport) || System.currentTimeMillis() >= reportTime + maxReportInterval) {

            String output = dateFormat.format(Calendar.getInstance().getTime()) + report;
            System.out.println(output);
            lastReport = report;
            reportTime = System.currentTimeMillis();
        }
    }

    System.exit(0);

}

From source file:com.adobe.aem.demomachine.Json2Csv.java

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

    String inputFile1 = null;/*from   ww  w. ja v  a 2s  .c  om*/
    String inputFile2 = null;
    String outputFile = null;

    HashMap<String, String> hmReportSuites = new HashMap<String, String>();

    // Command line options for this tool
    Options options = new Options();
    options.addOption("c", true, "Filename 1");
    options.addOption("r", true, "Filename 2");
    options.addOption("o", true, "Filename 3");
    CommandLineParser parser = new BasicParser();
    try {
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption("c")) {
            inputFile1 = cmd.getOptionValue("c");
        }

        if (cmd.hasOption("r")) {
            inputFile2 = cmd.getOptionValue("r");
        }

        if (cmd.hasOption("o")) {
            outputFile = cmd.getOptionValue("o");
        }

        if (inputFile1 == null || inputFile1 == null || outputFile == null) {
            System.exit(-1);
        }

    } catch (ParseException ex) {

        logger.error(ex.getMessage());

    }

    // List of customers and report suites for these customers
    String sInputFile1 = readFile(inputFile1, Charset.defaultCharset());
    sInputFile1 = sInputFile1.replaceAll("ObjectId\\(\"([0-9a-z]*)\"\\)", "\"$1\"");

    // Processing the list of report suites for each customer
    try {

        JSONArray jCustomers = new JSONArray(sInputFile1.trim());
        for (int i = 0, size = jCustomers.length(); i < size; i++) {
            JSONObject jCustomer = jCustomers.getJSONObject(i);
            Iterator<?> keys = jCustomer.keys();
            String companyName = null;
            while (keys.hasNext()) {
                String key = (String) keys.next();
                if (key.equals("company")) {
                    companyName = jCustomer.getString(key);
                }
            }
            keys = jCustomer.keys();
            while (keys.hasNext()) {
                String key = (String) keys.next();

                if (key.equals("report_suites")) {
                    JSONArray jReportSuites = jCustomer.getJSONArray(key);
                    for (int j = 0, rSize = jReportSuites.length(); j < rSize; j++) {
                        hmReportSuites.put(jReportSuites.getString(j), companyName);
                        System.out.println(jReportSuites.get(j) + " for company " + companyName);
                    }

                }
            }
        }

        // Creating the out put file
        PrintWriter writer = new PrintWriter(outputFile, "UTF-8");
        writer.println("\"" + "Customer" + "\",\"" + "ReportSuite ID" + "\",\"" + "Number of Documents"
                + "\",\"" + "Last Updated" + "\"");

        // Processing the list of SOLR collections
        String sInputFile2 = readFile(inputFile2, Charset.defaultCharset());
        sInputFile2 = sInputFile2.replaceAll("NumberLong\\(\"([0-9a-z]*)\"\\)", "\"$1\"");

        JSONObject jResults = new JSONObject(sInputFile2.trim());
        JSONArray jCollections = jResults.getJSONArray("result");
        for (int i = 0, size = jCollections.length(); i < size; i++) {
            JSONObject jCollection = jCollections.getJSONObject(i);
            String id = null;
            String number = null;
            String lastupdate = null;

            Iterator<?> keys = jCollection.keys();
            while (keys.hasNext()) {
                String key = (String) keys.next();
                if (key.equals("_id")) {
                    id = jCollection.getString(key);
                }
            }

            keys = jCollection.keys();
            while (keys.hasNext()) {
                String key = (String) keys.next();
                if (key.equals("noOfDocs")) {
                    number = jCollection.getString(key);
                }
            }

            keys = jCollection.keys();
            while (keys.hasNext()) {
                String key = (String) keys.next();
                if (key.equals("latestUpdateDate")) {
                    lastupdate = jCollection.getString(key);
                }
            }

            Date d = new Date(Long.parseLong(lastupdate));
            System.out.println(hmReportSuites.get(id) + "," + id + "," + number + "," + lastupdate + ","
                    + new SimpleDateFormat("MM-dd-yyyy").format(d));
            writer.println("\"" + hmReportSuites.get(id) + "\",\"" + id + "\",\"" + number + "\",\""
                    + new SimpleDateFormat("MM-dd-yyyy").format(d) + "\"");

        }

        writer.close();

    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:org.ala.hbase.RepoDataLoader.java

/**
 * This takes a list of infosource ids...
 * <p/>/*from w ww  .j  av a 2s . c o m*/
 * Usage: -stats or -reindex or -gList and list of infosourceId
 *
 * @param args
 */
public static void main(String[] args) throws Exception {
    //RepoDataLoader loader = new RepoDataLoader();
    ApplicationContext context = SpringUtils.getContext();
    RepoDataLoader loader = (RepoDataLoader) context.getBean(RepoDataLoader.class);
    long start = System.currentTimeMillis();
    loader.loadInfoSources();
    String filePath = repositoryDir;
    if (args.length > 0) {
        if (args[0].equalsIgnoreCase("-stats")) {
            loader.statsOnly = true;
            args = (String[]) ArrayUtils.subarray(args, 1, args.length);
        }
        if (args[0].equalsIgnoreCase("-reindex")) {
            loader.reindex = true;
            loader.indexer = context.getBean(PartialIndex.class);
            args = (String[]) ArrayUtils.subarray(args, 1, args.length);
            logger.info("**** -reindex: " + loader.reindex);
            logger.debug("reindex url: " + loader.reindexUrl);
        }
        if (args[0].equalsIgnoreCase("-gList")) {
            loader.gList = true;
            args = (String[]) ArrayUtils.subarray(args, 1, args.length);
            logger.info("**** -gList: " + loader.gList);
        }
        if (args[0].equalsIgnoreCase("-biocache")) {
            Hashtable<String, String> hashTable = new Hashtable<String, String>();
            hashTable.put("accept", "application/json");
            ObjectMapper mapper = new ObjectMapper();
            mapper.getDeserializationConfig().set(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES,
                    false);
            RestfulClient restfulClient = new RestfulClient(0);
            String fq = "&fq=";
            if (args.length > 1) {
                java.util.Date date = new java.util.Date();
                if (args[1].equals("-lastWeek")) {
                    date = DateUtils.addWeeks(date, -1);
                } else if (args[1].equals("-lastMonth")) {
                    date = DateUtils.addMonths(date, -1);
                } else if (args[1].equals("-lastYear")) {
                    date = DateUtils.addYears(date, -1);
                } else
                    date = null;
                if (date != null) {
                    SimpleDateFormat sfd = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");

                    fq += "last_load_date:%5B" + sfd.format(date) + "%20TO%20*%5D";
                }
            }

            Object[] resp = restfulClient
                    .restGet("http://biocache.ala.org.au/ws/occurrences/search?q=multimedia:Image" + fq
                            + "&facets=data_resource_uid&pageSize=0", hashTable);
            logger.info("The URL: " + "http://biocache.ala.org.au/ws/occurrences/search?q=multimedia:Image" + fq
                    + "&facets=data_resource_uid&pageSize=0");
            if ((Integer) resp[0] == HttpStatus.SC_OK) {
                String content = resp[1].toString();
                logger.debug(resp[1]);
                if (content != null && content.length() > "[]".length()) {
                    Map map = mapper.readValue(content, Map.class);
                    try {
                        List<java.util.LinkedHashMap<String, String>> list = ((List<java.util.LinkedHashMap<String, String>>) ((java.util.LinkedHashMap) ((java.util.ArrayList) map
                                .get("facetResults")).get(0)).get("fieldResult"));
                        Set<String> arg = new LinkedHashSet<String>();
                        for (int i = 0; i < list.size(); i++) {
                            java.util.LinkedHashMap<String, String> value = list.get(i);
                            String dataResource = getDataResource(value.get("fq"));
                            Object provider = (loader.getUidInfoSourceMap().get(dataResource));
                            if (provider != null) {
                                arg.add(provider.toString());
                            }
                        }
                        logger.info("Set of biocache infosource ids to load: " + arg);
                        args = new String[] {};
                        args = arg.toArray(args);
                        //handle the situation where biocache-service reports no data resources
                        if (args.length < 1) {
                            logger.error("No biocache data resources found. Unable to load.");
                            System.exit(0);
                        }
                    } catch (Exception e) {
                        logger.error("ERROR: exit process....." + e);
                        e.printStackTrace();
                        System.exit(0);
                    }
                }
            } else {
                logger.warn("Unable to process url: ");
            }
        }
    }
    int filesRead = loader.load(filePath, args); //FIX ME - move to config
    long finish = System.currentTimeMillis();
    logger.info(filesRead + " files scanned/loaded in: " + ((finish - start) / 60000) + " minutes "
            + ((finish - start) / 1000) + " seconds.");
    System.exit(1);
}

From source file:com.leonarduk.finance.analysis.CashFlowToChart.java

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

    // Getting the time series
    final StockFeed feed = new IntelligentStockFeed();
    final String ticker = "IUKD";
    final Stock stock = feed.get(Instrument.fromString(ticker), 2).get();
    final TimeSeries series = TimeseriesUtils.getTimeSeries(stock, 1);

    // Building the trading strategy
    final AbstractStrategy strategy = MovingMomentumStrategy.buildStrategy(series, 12, 26, 9);

    // Running the strategy
    final TradingRecord tradingRecord = series.run(strategy.getStrategy());
    // Getting the cash flow of the resulting trades
    final CashFlow cashFlow = new CashFlow(series, tradingRecord);

    /**// ww  w.j  a va  2  s  .  c om
     * Building chart datasets
     */
    final TimeSeriesCollection datasetAxis1 = new TimeSeriesCollection();
    datasetAxis1.addSeries(CashFlowToChart.buildChartTimeSeries(series, new ClosePriceIndicator(series),
            "Bitstamp Bitcoin (BTC)"));
    final TimeSeriesCollection datasetAxis2 = new TimeSeriesCollection();
    datasetAxis2.addSeries(CashFlowToChart.buildChartTimeSeries(series, cashFlow, "Cash Flow"));

    /**
     * Creating the chart
     */
    final JFreeChart chart = ChartFactory.createTimeSeriesChart("Bitstamp BTC", // title
            "Date", // x-axis label
            "Price", // y-axis label
            datasetAxis1, // data
            true, // create legend?
            true, // generate tooltips?
            false // generate URLs?
    );
    final XYPlot plot = (XYPlot) chart.getPlot();
    final DateAxis axis = (DateAxis) plot.getDomainAxis();
    axis.setDateFormatOverride(new SimpleDateFormat("MM-dd HH:mm"));

    /**
     * Adding the cash flow axis (on the right)
     */
    CashFlowToChart.addCashFlowAxis(plot, datasetAxis2);

    /**
     * Displaying the chart
     */
    CashFlowToChart.displayChart(chart);
}

From source file:it.isislab.dmason.util.SystemManagement.Worker.thrower.DMasonWorkerWithGui.java

public static void main(String[] args) {
    RuntimeMXBean bean = ManagementFactory.getRuntimeMXBean();

    ////from w  ww.ja  v a  2 s. c o  m
    // Get name representing the running Java virtual machine.
    // It returns something like 6460@AURORA. Where the value
    // before the @ symbol is the PID.
    //
    String jvmName = bean.getName();

    //Used for log4j properties
    System.setProperty("logfile.name", "worker" + jvmName);

    //Used for log4j properties
    System.setProperty("steplog.name", "workerStep" + jvmName);

    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd_HH_mm_ss_SS");
    Date date = new Date();
    dateFormat.format(date);

    System.setProperty("timestamp", date.toLocaleString());

    System.setProperty("paramsfile.name", "params");
    try {
        File logPath = new File("Logs/workers");
        if (logPath.exists())
            FileUtils.cleanDirectory(logPath);
    } catch (IOException e) {
        //not a problem
    }

    logger = Logger.getLogger(DMasonWorker.class.getCanonicalName());
    logger.debug("StartWorker " + VERSION);

    autoStart = false;

    String ip = null;
    String port = null;
    String topic = "";
    updated = false;
    isBatch = false;
    topicPrefix = "";

    // ip, post, autoconnect
    if (args.length == 3) {
        ip = args[0];
        port = args[1];
        if (args[2].equals("autoconnect")) {
            autoStart = true;
        }
    }
    // ip, post, topic, event 
    if (args.length == 4) {
        autoStart = true;
        if (args[3].equals("update")) {
            updated = true;
        }
        if (args[3].equals("reset")) {
            updated = false;
            isBatch = false;
        }
        if (args[3].contains("Batch")) {
            updated = false;
            isBatch = true;
            topicPrefix = args[3];
        }
        ip = args[0];
        port = args[1];
        topic = args[2];
    }

    /*if(args.length == 2 && args[0].equals("auto"))
    {   autoStart = true;
       updated = true;
       topic = args[1];
    }
    if(args.length == 1 && args[0].equals("auto"))
    {   autoStart = true;
    }*/
    new DMasonWorkerWithGui(autoStart, updated, isBatch, topic, ip, port);
}

From source file:com.rtl.http.Upload.java

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

    if (args.length != 4) {
        // Jxj001 20150603 d:\rpt_rtl_0001.txt d:\confDir
        logger.error("??4,dataTypedataVersionfilePathconfDir");
        // System.out.println("??3,dataTypedataVersionfilePath");
        return;//from   w  w w  .j ava 2 s . c o  m
    } else {
        Upload upload = new Upload();
        upload.readInfo(args[3]);

        Date date = new Date();
        DateFormat format1 = new SimpleDateFormat("yyyyMMdd");
        String todayDir = format1.format(date);

        File dir = new File(logDir + File.separator + todayDir);
        if (dir != null && !dir.exists()) {
            dir.mkdirs();
        }

        //         SimpleLayout layout = new SimpleLayout();
        PatternLayout layout = new PatternLayout("%d %-5p %c - %m%n");

        FileAppender appender = null;

        try {

            appender = new FileAppender(layout, dir.getPath() + File.separator + todayDir + "client.log", true);

        } catch (Exception e) {
            logger.error("");
        }

        logger.addAppender(appender);
        logger.setLevel(Level.INFO);

        InputStream fileIn;
        dataType = args[0];
        dataVersion = args[1];
        filePath = args[2];

        logger.info("dataType=" + dataType);
        logger.info("dataVersion=" + dataVersion);
        logger.info("filePath=" + filePath);

        try {
            File file = new File(filePath);
            if (!file.exists()) {
                // System.out.println("?:"+filePath);
                logger.error("?:" + filePath);
                return;
            }
            fileIn = new FileInputStream(filePath);
            String responseStr = send(upload.getJson(), fileIn, url);
            if (responseStr != null) {
                String[] values = responseStr.split(",");
                if ("ok".equals(values[0])) {
                    System.out.println("0");
                    logger.info("ok");
                } else {
                    System.out.println("1");
                    logger.info(" A" + values[1]);
                }
            } else {
                System.out.println("1");
                logger.info(" B????");
            }

        } catch (Exception e) {
            System.out.println("1");
            logger.error(" C" + e.getMessage());
        }
    }

    logger.info("??");
    // System.out.println("??");

}

From source file:io.druid.examples.rabbitmq.RabbitMQProducerMain.java

public static void main(String[] args) throws Exception {
    // We use a List to keep track of option insertion order. See below.
    final List<Option> optionList = new ArrayList<Option>();

    optionList.add(OptionBuilder.withLongOpt("help").withDescription("display this help message").create("h"));
    optionList.add(OptionBuilder.withLongOpt("hostname").hasArg()
            .withDescription("the hostname of the AMQP broker [defaults to AMQP library default]").create("b"));
    optionList.add(OptionBuilder.withLongOpt("port").hasArg()
            .withDescription("the port of the AMQP broker [defaults to AMQP library default]").create("n"));
    optionList.add(OptionBuilder.withLongOpt("username").hasArg()
            .withDescription("username to connect to the AMQP broker [defaults to AMQP library default]")
            .create("u"));
    optionList.add(OptionBuilder.withLongOpt("password").hasArg()
            .withDescription("password to connect to the AMQP broker [defaults to AMQP library default]")
            .create("p"));
    optionList.add(OptionBuilder.withLongOpt("vhost").hasArg()
            .withDescription("name of virtual host on the AMQP broker [defaults to AMQP library default]")
            .create("v"));
    optionList.add(OptionBuilder.withLongOpt("exchange").isRequired().hasArg()
            .withDescription("name of the AMQP exchange [required - no default]").create("e"));
    optionList.add(OptionBuilder.withLongOpt("key").hasArg()
            .withDescription("the routing key to use when sending messages [default: 'default.routing.key']")
            .create("k"));
    optionList.add(OptionBuilder.withLongOpt("type").hasArg()
            .withDescription("the type of exchange to create [default: 'topic']").create("t"));
    optionList.add(OptionBuilder.withLongOpt("durable")
            .withDescription("if set, a durable exchange will be declared [default: not set]").create("d"));
    optionList.add(OptionBuilder.withLongOpt("autodelete")
            .withDescription("if set, an auto-delete exchange will be declared [default: not set]")
            .create("a"));
    optionList.add(OptionBuilder.withLongOpt("single")
            .withDescription("if set, only a single message will be sent [default: not set]").create("s"));
    optionList.add(OptionBuilder.withLongOpt("start").hasArg()
            .withDescription("time to use to start sending messages from [default: 2010-01-01T00:00:00]")
            .create());//from w ww . jav  a2s . co m
    optionList.add(OptionBuilder.withLongOpt("stop").hasArg().withDescription(
            "time to use to send messages until (format: '2013-07-18T23:45:59') [default: current time]")
            .create());
    optionList.add(OptionBuilder.withLongOpt("interval").hasArg()
            .withDescription("the interval to add to the timestamp between messages in seconds [default: 10]")
            .create());
    optionList.add(OptionBuilder.withLongOpt("delay").hasArg()
            .withDescription("the delay between sending messages in milliseconds [default: 100]").create());

    // An extremely silly hack to maintain the above order in the help formatting.
    HelpFormatter formatter = new HelpFormatter();
    // Add a comparator to the HelpFormatter using the ArrayList above to sort by insertion order.
    formatter.setOptionComparator(new Comparator() {
        @Override
        public int compare(Object o1, Object o2) {
            // I know this isn't fast, but who cares! The list is short.
            return optionList.indexOf(o1) - optionList.indexOf(o2);
        }
    });

    // Now we can add all the options to an Options instance. This is dumb!
    Options options = new Options();
    for (Option option : optionList) {
        options.addOption(option);
    }

    CommandLine cmd = null;

    try {
        cmd = new BasicParser().parse(options, args);

    } catch (ParseException e) {
        formatter.printHelp("RabbitMQProducerMain", e.getMessage(), options, null);
        System.exit(1);
    }

    if (cmd.hasOption("h")) {
        formatter.printHelp("RabbitMQProducerMain", options);
        System.exit(2);
    }

    ConnectionFactory factory = new ConnectionFactory();

    if (cmd.hasOption("b")) {
        factory.setHost(cmd.getOptionValue("b"));
    }
    if (cmd.hasOption("u")) {
        factory.setUsername(cmd.getOptionValue("u"));
    }
    if (cmd.hasOption("p")) {
        factory.setPassword(cmd.getOptionValue("p"));
    }
    if (cmd.hasOption("v")) {
        factory.setVirtualHost(cmd.getOptionValue("v"));
    }
    if (cmd.hasOption("n")) {
        factory.setPort(Integer.parseInt(cmd.getOptionValue("n")));
    }

    String exchange = cmd.getOptionValue("e");
    String routingKey = "default.routing.key";
    if (cmd.hasOption("k")) {
        routingKey = cmd.getOptionValue("k");
    }

    boolean durable = cmd.hasOption("d");
    boolean autoDelete = cmd.hasOption("a");
    String type = cmd.getOptionValue("t", "topic");
    boolean single = cmd.hasOption("single");
    int interval = Integer.parseInt(cmd.getOptionValue("interval", "10"));
    int delay = Integer.parseInt(cmd.getOptionValue("delay", "100"));

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
    Date stop = sdf.parse(cmd.getOptionValue("stop", sdf.format(new Date())));

    Random r = new Random();
    Calendar timer = Calendar.getInstance();
    timer.setTime(sdf.parse(cmd.getOptionValue("start", "2010-01-01T00:00:00")));

    String msg_template = "{\"utcdt\": \"%s\", \"wp\": %d, \"gender\": \"%s\", \"age\": %d}";

    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    channel.exchangeDeclare(exchange, type, durable, autoDelete, null);

    do {
        int wp = (10 + r.nextInt(90)) * 100;
        String gender = r.nextBoolean() ? "male" : "female";
        int age = 20 + r.nextInt(70);

        String line = String.format(msg_template, sdf.format(timer.getTime()), wp, gender, age);

        channel.basicPublish(exchange, routingKey, null, line.getBytes());

        System.out.println("Sent message: " + line);

        timer.add(Calendar.SECOND, interval);

        Thread.sleep(delay);
    } while ((!single && stop.after(timer.getTime())));

    connection.close();
}