List of usage examples for java.text SimpleDateFormat SimpleDateFormat
public SimpleDateFormat(String pattern)
SimpleDateFormat
using the given pattern and the default date format symbols for the default java.util.Locale.Category#FORMAT FORMAT locale. From source file:isi.pasco2.Main.java
public static void main(String[] args) { CommandLineParser parser = new PosixParser(); Options options = new Options(); Option undelete = new Option("d", "Undelete activity records"); options.addOption(undelete);//from ww w . j a va 2 s .co m Option disableAllocation = new Option("M", "Disable allocation detection"); options.addOption(disableAllocation); Option fieldDelimeter = OptionBuilder.withArgName("field-delimeter").hasArg() .withDescription("Field Delimeter (TAB by default)").create("t"); options.addOption(fieldDelimeter); Option timeFormat = OptionBuilder.withArgName("time-format").hasArg() .withDescription("xsd or standard (pasco1 compatible)").create("f"); options.addOption(timeFormat); Option fileTypeOption = OptionBuilder.withArgName("file-type").hasArg() .withDescription("The type of file: cache or history").create("T"); options.addOption(fileTypeOption); try { CommandLine line = parser.parse(options, args); boolean undeleteMethod = false; String delimeter = null; String format = null; String fileType = null; boolean disableAllocationTest = false; if (line.hasOption("d")) { undeleteMethod = true; } if (line.hasOption('t')) { delimeter = line.getOptionValue('t'); } if (line.hasOption('M')) { disableAllocationTest = true; } if (line.hasOption('T')) { fileType = line.getOptionValue('T'); } if (line.hasOption('f')) { format = line.getOptionValue('f'); } if (line.getArgs().length != 1) { System.err.println("No file specified."); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("pasco2", options); System.exit(1); } String fileName = line.getArgs()[0]; try { IndexFile fr = new FastReadIndexFile(fileName, "r"); CountingCacheHandler handler = null; if (fileType == null) { handler = new CountingCacheHandler(); } if (fileType == null) { handler = new CountingCacheHandler(); } else if (fileType.equals("cache")) { handler = new CountingCacheHandler(); } else if (fileType.equals("history")) { handler = new Pasco2HistoryHandler(); } if (format != null) { if (format.equals("pasco")) { DateFormat regularDateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss.SSS"); handler.setDateFormat(regularDateFormat); TimeZone tz = TimeZone.getTimeZone("Australia/Brisbane"); regularDateFormat.setTimeZone(tz); } else if (format.equals("standard")) { DateFormat xsdDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); handler.setDateFormat(xsdDateFormat); xsdDateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); } else { System.err.println("Format not supported."); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("pasco2", options); System.exit(1); } } if (delimeter != null) { handler.setDelimeter(delimeter); } IEIndexFileParser logparser = null; if (fileType == null) { System.err.println("Using cache file parser."); logparser = new IECacheFileParser(fileName, fr, handler); } else if (fileType.equals("cache")) { logparser = new IECacheFileParser(fileName, fr, handler); } else if (fileType.equals("history")) { logparser = new IEHistoryFileParser(fileName, fr, handler); } else { System.err.println("Unsupported file type."); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("pasco2", options); System.exit(1); } if (disableAllocationTest) { logparser.setDisableAllocationTest(true); } logparser.parseFile(); } catch (Exception ex) { System.err.println(ex.getMessage()); ex.printStackTrace(); } } catch (ParseException exp) { System.out.println("Unexpected exception:" + exp.getMessage()); } }
From source file:com.qatickets.domain.Version.java
public static void main(String[] a) { // DD, dd MM yyyy // Wednesday, 14 May 2014 String d = new SimpleDateFormat("EEEE, dd MMM yyyy").format(new Date()); System.out.println(d);/*from www . java 2 s . co m*/ System.out.println(d.equals("Wednesday, 14 May 2014")); }
From source file:cz.alej.michalik.totp.util.TOTP.java
/** * Ukzka TOTP pro zprvu "12345678901234567890" *///from ww w. ja va2 s .com public static void main(String[] args) { // GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ v base32 String secret = "12345678901234567890"; System.out.printf("Heslo je: %s \nV Base32 to je: %s\n", secret, new Base32().encodeToString(secret.getBytes())); TOTP t = new TOTP(secret.getBytes()); System.out.printf("%s\n", t); while (true) { int time = Integer.valueOf(new SimpleDateFormat("ss").format(new Date())); if (time % 30 == 0) { System.out.printf("%s\n", t); } try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } }
From source file:com.google.api.services.samples.analytics.cmdline.CoreReportingApiReferenceSample.java
/** * Main demo. This first initializes an Analytics service object. It then queries for the top 25 * organic search keywords and traffic sources by visits. Finally each important part of the * response is printed to the screen.// ww w. j a va2 s .co m * * @param args command line args. */ public static void main(String[] args) { try { if (args.length == 2) { // Start and end date are supplied startDate = new SimpleDateFormat("yyyy-MM-dd").parse(args[0]); endDate = new SimpleDateFormat("yyyy-MM-dd").parse(args[1]); } System.out.println("Retrieving for dates " + startDate + " " + endDate); HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport(); DATA_STORE_FACTORY = new FileDataStoreFactory(DATA_STORE_DIR); Analytics analytics = initializeAnalytics(); MongoClient mongo = new MongoClient("localhost", 27017); DB regus_analytics_db = mongo.getDB("regus_analytics"); DBCollection regus_visited_companies = regus_analytics_db.getCollection("ga"); DBCollection regus_visit_attributes = regus_analytics_db.getCollection("visit_attrs"); DBCollection centerMapping = regus_analytics_db.getCollection("center_mapping"); GaData gaData; for (Date d = startDate; !DateUtils.isSameDay(d, DateUtils.addDays(endDate, 1)); d = DateUtils .addDays(d, 1)) { int startIndex = 0; do { System.out.println("Executing data query for visited companies for date: " + d); gaData = executeDataQueryForVisitedCompanies(analytics, TABLE_ID, startIndex, d); insertVisitedCompaniesData(gaData, regus_visited_companies, d); startIndex = gaData.getQuery().getStartIndex() + gaData.getQuery().getMaxResults(); } while (gaData.getNextLink() != null && !gaData.getNextLink().isEmpty()); startIndex = 0; do { System.out.println("Executing data query for visit attributes for date: " + d); gaData = executeDataQueryForVisitAttributes(analytics, TABLE_ID, startIndex, d); insertVisitAttributesData(gaData, regus_visit_attributes, d, centerMapping); startIndex = gaData.getQuery().getStartIndex() + gaData.getQuery().getMaxResults(); } while (gaData.getNextLink() != null && !gaData.getNextLink().isEmpty()); } } catch (GoogleJsonResponseException e) { System.err.println( "There was a service error: " + e.getDetails().getCode() + " : " + e.getDetails().getMessage()); } catch (Throwable t) { t.printStackTrace(); } }
From source file:FormatStorage2ColumnStorageMR.java
@SuppressWarnings("deprecation") public static void main(String[] args) throws Exception { if (args.length != 2) { System.out.println("FormatStorage2ColumnStorageMR <input> <output>"); System.exit(-1);// ww w . j a va2 s. c o m } JobConf conf = new JobConf(FormatStorageMR.class); conf.setJobName("FormatStorage2ColumnStorageMR"); conf.setNumMapTasks(1); conf.setNumReduceTasks(4); conf.setOutputKeyClass(LongWritable.class); conf.setOutputValueClass(Unit.Record.class); conf.setMapperClass(FormatStorageMapper.class); conf.setReducerClass(ColumnStorageReducer.class); conf.setInputFormat(FormatStorageInputFormat.class); conf.set("mapred.output.compress", "flase"); Head head = new Head(); initHead(head); head.toJobConf(conf); 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:ta4jexamples.indicators.IndicatorsToChart.java
public static void main(String[] args) { /**/*ww w.j a v a2 s.c om*/ * Getting time series */ TimeSeries series = CsvTicksLoader.loadAppleIncSeries(); /** * Creating indicators */ // Close price ClosePriceIndicator closePrice = new ClosePriceIndicator(series); EMAIndicator avg14 = new EMAIndicator(closePrice, 14); StandardDeviationIndicator sd14 = new StandardDeviationIndicator(closePrice, 14); // Bollinger bands BollingerBandsMiddleIndicator middleBBand = new BollingerBandsMiddleIndicator(avg14); BollingerBandsLowerIndicator lowBBand = new BollingerBandsLowerIndicator(middleBBand, sd14); BollingerBandsUpperIndicator upBBand = new BollingerBandsUpperIndicator(middleBBand, sd14); /** * Building chart dataset */ TimeSeriesCollection dataset = new TimeSeriesCollection(); dataset.addSeries(buildChartTimeSeries(series, closePrice, "Apple Inc. (AAPL) - NASDAQ GS")); dataset.addSeries(buildChartTimeSeries(series, lowBBand, "Low Bollinger Band")); dataset.addSeries(buildChartTimeSeries(series, upBBand, "High Bollinger Band")); /** * Creating the chart */ JFreeChart chart = ChartFactory.createTimeSeriesChart("Apple Inc. 2013 Close Prices", // title "Date", // x-axis label "Price Per Unit", // 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("yyyy-MM-dd")); /** * Displaying the chart */ displayChart(chart); }
From source file:ta4jexamples.analysis.CashFlowToChart.java
public static void main(String[] args) { // Getting the time series TimeSeries series = CsvTradesLoader.loadBitstampSeries(); // Building the trading strategy Strategy strategy = MovingMomentumStrategy.buildStrategy(series); // Running the strategy TimeSeriesManager seriesManager = new TimeSeriesManager(series); TradingRecord tradingRecord = seriesManager.run(strategy); // Getting the cash flow of the resulting trades CashFlow cashFlow = new CashFlow(series, tradingRecord); /**//w ww . java 2s . c om * Building chart datasets */ TimeSeriesCollection datasetAxis1 = new TimeSeriesCollection(); datasetAxis1 .addSeries(buildChartTimeSeries(series, new ClosePriceIndicator(series), "Bitstamp Bitcoin (BTC)")); TimeSeriesCollection datasetAxis2 = new TimeSeriesCollection(); datasetAxis2.addSeries(buildChartTimeSeries(series, cashFlow, "Cash Flow")); /** * Creating the chart */ 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? ); XYPlot plot = (XYPlot) chart.getPlot(); DateAxis axis = (DateAxis) plot.getDomainAxis(); axis.setDateFormatOverride(new SimpleDateFormat("MM-dd HH:mm")); /** * Adding the cash flow axis (on the right) */ addCashFlowAxis(plot, datasetAxis2); /** * Displaying the chart */ displayChart(chart); }
From source file:edu.uga.cs.fluxbuster.FluxbusterCLI.java
/** * The main method.// www . j av a2 s. c o m * * @param args the command line arguments */ public static void main(String[] args) { GnuParser parser = new GnuParser(); Options opts = FluxbusterCLI.initializeOptions(); CommandLine cli; try { cli = parser.parse(opts, args); if (cli.hasOption('?')) { throw new ParseException(null); } if (validateDate(cli.getOptionValue('d')) && validateDate(cli.getOptionValue('e'))) { if (log.isInfoEnabled()) { StringBuffer arginfo = new StringBuffer("\n"); arginfo.append("generate-clusters: " + cli.hasOption('g') + "\n"); arginfo.append("calc-features: " + cli.hasOption('f') + "\n"); arginfo.append("calc-similarity: " + cli.hasOption('s') + "\n"); arginfo.append("classify-clusters: " + cli.hasOption('c') + "\n"); arginfo.append("start-date: " + cli.getOptionValue('d') + "\n"); arginfo.append("end-date: " + cli.getOptionValue('e') + "\n"); log.info(arginfo.toString()); } try { boolean clus = true, feat = true, simil = true, clas = true; if (cli.hasOption('g') || cli.hasOption('f') || cli.hasOption('s') || cli.hasOption('c')) { if (!cli.hasOption('g')) { clus = false; } if (!cli.hasOption('f')) { feat = false; } if (!cli.hasOption('s')) { simil = false; } if (!cli.hasOption('c')) { clas = false; } } DBInterfaceFactory.init(); SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd"); Date logdate = df.parse(cli.getOptionValue('d')); long startTime = logdate.getTime() / 1000; long endTime = df.parse(cli.getOptionValue('e')).getTime() / 1000; if (clus) { ClusterGenerator cg = new ClusterGenerator(); List<DomainCluster> clusters = cg.generateClusters(startTime, endTime, true); cg.storeClusters(clusters, logdate); } if (feat) { FeatureCalculator calc = new FeatureCalculator(); calc.updateFeatures(logdate); } if (simil) { ClusterSimilarityCalculator calc2 = new ClusterSimilarityCalculator(); calc2.updateClusterSimilarities(logdate); } if (clas) { Classifier calc3 = new Classifier(); calc3.updateClusterClasses(logdate, 30); } } catch (Exception e) { if (log.isFatalEnabled()) { log.fatal("", e); } } finally { DBInterfaceFactory.shutdown(); } } else { throw new ParseException(null); } } catch (ParseException e1) { PrintWriter writer = new PrintWriter(System.out); HelpFormatter usageFormatter = new HelpFormatter(); usageFormatter.printHelp(writer, 80, "fluxbuster", "If none of the options g, f, s, c are specified " + "then the program will execute as if all of them " + "have been specified. Otherwise, the program will " + "only execute the options specified.", opts, 0, 2, ""); writer.close(); } }
From source file:org.jasig.schedassist.impl.AppointmentTool.java
/** * main method to interact with {@link AvailableApplicationTool}. * //from w w w. j av a2 s . c o m * @param args * @throws SchedulingException * @throws NotAVisitorException * @throws CalendarAccountNotFoundException */ public static void main(String[] args) throws CalendarAccountNotFoundException, NotAVisitorException, SchedulingException { // scan the arguments if (args.length == 0) { System.err.println( "Usage: AppointmentTool create [-owner username] [-visitor username] [-start YYYYmmdd-hhmm] [-duration minutes]"); System.exit(1); } if (CREATE.equals(args[0])) { String visitorUsername = null; String ownerUsername = null; Date startTime = null; int duration = 30; for (int i = 1; i < args.length; i++) { if (OWNER_ARG.equalsIgnoreCase(args[i])) { ownerUsername = args[++i]; } else if (VISITOR_ARG.equalsIgnoreCase(args[i])) { visitorUsername = args[++i]; } else if (START_ARG.equalsIgnoreCase(args[i])) { String start = args[++i]; SimpleDateFormat df = new SimpleDateFormat(DATE_FORMAT); try { startTime = df.parse(start); } catch (ParseException e) { System.err.println("Invalid format for start parameter, must match: " + DATE_FORMAT); System.exit(1); } } else if (DURATION_ARG.equalsIgnoreCase(args[i])) { String dur = args[++i]; duration = Integer.parseInt(dur); } } Validate.notEmpty(ownerUsername, "owner argument cannot be empty"); Validate.notEmpty(visitorUsername, "visitor argument cannot be empty"); Validate.notNull(startTime, "start argument cannot be empty"); ApplicationContext applicationContext = new ClassPathXmlApplicationContext(CONFIG); AppointmentTool tool = new AppointmentTool( (SchedulingAssistantService) applicationContext.getBean("schedulingAssistantService"), (ICalendarAccountDao) applicationContext.getBean("calendarAccountDao"), (OwnerDao) applicationContext.getBean("ownerDao"), (VisitorDao) applicationContext.getBean("visitorDao"), (AvailableScheduleDao) applicationContext.getBean("availableScheduleDao")); Date endDate = DateUtils.addMinutes(startTime, duration); VEvent event = tool.createAvailableAppointment(visitorUsername, ownerUsername, startTime, endDate); System.out.println("Event successfully created: "); System.out.println(event.toString()); } else { System.err.println("Unrecognized command: " + args[0]); System.exit(1); } }
From source file:it.isislab.dmason.util.SystemManagement.Worker.thrower.DMasonWorker.java
public static void main(String[] args) { RuntimeMXBean bean = ManagementFactory.getRuntimeMXBean(); ////www .j a va 2s.co 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) { // TODO Auto-generated catch block e.printStackTrace(); } logger = Logger.getLogger(DMasonWorker.class.getCanonicalName()); logger.debug("StartWorker " + version); autoStart = false; connect = false; ip = null; port = null; String topic = ""; updated = false; isBatch = false; topicPrefix = ""; if (args.length == 0) { // Force waiting for beacon (requires ActiveMQWrapper) autoStart = false; connect = true; } else if (args.length == 2) { // Launched with IP and Port ip = args[0]; port = args[1]; autoStart = true; connect = true; } else if (args.length == 4) { // Used by D-Mason in order to restart a // worker after update, batch execution, reset autoStart = true; ip = args[0]; port = args[1]; topic = args[2]; 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]; } } else { System.out.println("Usage: StartWorker IP PORT"); } DMasonWorker worker = new DMasonWorker(ip, port, topic); boolean connected = worker.startConnection(); if (connected) { logger.debug("CONNECTED:"); logger.debug(" IP : " + worker.ipAddress.getIPaddress()); logger.debug(" Port : " + worker.ipAddress.getPort()); logger.debug(" Prefix : " + DMasonWorker.topicPrefix); logger.debug(" Topic : " + worker.myTopic); } else { logger.info("CONNECTION FAILED:"); logger.debug(" IP : " + worker.ipAddress.getIPaddress()); logger.debug(" Port : " + worker.ipAddress.getPort()); logger.debug(" Prefix : " + DMasonWorker.topicPrefix); logger.debug(" Topic : " + worker.myTopic); } }