List of usage examples for org.joda.time.format DateTimeFormatter print
public String print(ReadablePartial partial)
From source file:com.sam.moca.applications.MloadAllMain.java
License:Open Source License
/** * This is the mainline for the mload_all application * @param args The command line arguments *//*from w w w . j av a2 s . co m*/ public static void main(String[] args) { Options opts = null; try { opts = Options.parse(COMMAND_LINE_OPTIONS, args); } catch (OptionsException e) { System.err.println("Invalid option: " + e.getMessage()); printUsage(); System.exit(1); } if (opts.isSet('h')) { printUsage(); System.exit(1); } System.out.print(AppUtils.getStartBanner("MLOAD All")); try { ServerUtils.setupDaemonContext("MloadAllMain", true, true); } catch (SystemConfigurationException e1) { e1.printStackTrace(); System.exit(1); } DateTimeFormatter dateFormat = DateTimeFormat.forPattern("yyMMdd_HHmmss"); String startTime = dateFormat.print(new Date().getTime()); String ctlFileExt = (opts.isSet('C') ? opts.getArgument('C') : "ctl"); String address = (opts.isSet('a') ? "-a " + opts.getArgument('a') : ""); String silent = (opts.isSet('s') ? " -s" : ""); String upgrade = (opts.isSet('U') ? " -U" : ""); Writer masterCtl = null; File masterFile = null; int errorCount = 0; try { if (opts.isSet('M')) { // In lieu of a getPID method from Java... (format is PID@Host) String pid = ManagementFactory.getRuntimeMXBean().getName(); // Set up a master control file that will be run instead String controlName = "mload_all_" + pid.substring(0, pid.indexOf('@')) + ".mld"; masterFile = new File(opts.getArgument('M') + File.separator + controlName); try { masterCtl = new OutputStreamWriter(new FileOutputStream(masterFile), "UTF-8"); masterCtl.write("#MLOAD\n"); } catch (IOException e) { System.err.println("Can not create control file -- " + masterFile.getName()); System.exit(1); } } // Standard output streams are the default out = System.out; err = System.err; if (opts.isSet('L')) { // Set up the LOG and ERROR filenames String dir = opts.getArgument('L'); File logDir = new File(dir); if (!logDir.isDirectory()) { System.err.println("Could not find log directory: " + dir); System.exit(1); } String baseFile = "mload_data_" + startTime; File logFile = new File(logDir, baseFile + ".log"); File errorFile = new File(logDir, baseFile + "_errors.log"); // Redirect out and err to the wanted files try { out = new PrintStream(new FileOutputStream(logFile), true, "UTF-8"); } catch (FileNotFoundException e) { System.err.println("Can't open '" + logFile.getName() + "' for logging!"); System.exit(1); } catch (UnsupportedEncodingException e) { System.err.println("Encoding exception: " + e.getMessage()); System.exit(1); } try { err = new PrintStream(new FileOutputStream(errorFile), true, "UTF-8"); } catch (FileNotFoundException e) { System.err.println("Can't open '" + errorFile.getName() + "' for errors!"); System.exit(1); } catch (UnsupportedEncodingException e) { System.err.println("Encoding exception: " + e.getMessage()); System.exit(1); } } // Either the user specified directories via command line options // or we'll process the current directory String[] remainArgs = opts.getRemainingArgs(); if (remainArgs.length == 0) remainArgs = new String[] { ".= " }; StringBuilder cmdStr; for (String arg : remainArgs) { // dir=opt pairs String[] vals = arg.split("="); // Iterate through all the control files in the specified directory File ctlDir = new File(vals[0]); if (!ctlDir.isDirectory()) { System.err.println("Could not change to directory: " + vals[0]); System.exit(1); } // Get the list of control files. File[] ctlFiles = ctlDir.listFiles(new WildcardFilenameFilter("*." + ctlFileExt)); // Sort the list of control files. Arrays.sort(ctlFiles, new Comparator<File>() { public int compare(File f1, File f2) { return f1.getName().compareTo(f2.getName()); } }); for (File ctlFile : ctlFiles) { // Check for a similarly named data directory String filename = ctlFile.getName(); File subdir = new File(ctlFile.getParent(), filename.substring(0, filename.indexOf('.'))); if (!subdir.isDirectory()) { System.err.println("Warning: Missing data directory " + ctlDir.getName() + "/" + subdir.getName() + "!"); continue; } // Build the command string and execute it or write it cmdStr = new StringBuilder(); cmdStr.append(address); cmdStr.append(" -H -c "); cmdStr.append(String.format("\"%s\"", ctlFile.getPath())); cmdStr.append(" -D "); cmdStr.append(String.format("\"%s\"", subdir.getPath())); cmdStr.append(silent); cmdStr.append(upgrade); cmdStr.append(" "); cmdStr.append(vals.length > 1 ? vals[1] : ""); if (opts.isSet('M')) { try { masterCtl.write(cmdStr.toString() + "\n"); } catch (IOException e) { System.err.println("Could not write to master control file!"); System.exit(1); } } else { try { errorCount += runMload(parse(cmdStr.toString())); } catch (OptionsException e) { System.err.println("Invalid options for Mload: " + cmdStr.toString()); errorCount++; } } } } } finally { if (masterCtl != null) { try { masterCtl.close(); } catch (IOException e) { System.err.println("Could not write to master control file!"); System.exit(1); } } } // If we're building a master control file, execute it if (opts.isSet('M')) { StringBuilder cmdStr = new StringBuilder(); cmdStr.append("-m -c "); cmdStr.append(String.format("\"%s\"", masterFile.getPath())); try { errorCount += runMload(parse(cmdStr.toString())); } catch (OptionsException e) { System.err.println("Invalid options for Mload: " + cmdStr.toString()); } System.out.println("NOTE: Please remove temporary file " + masterFile.getPath()); } String endTime = dateFormat.print(new Date().getTime()); System.out.println("Load Started at " + startTime); System.out.println("Load Ended at " + endTime); // Close the file logging output streams if necessary out.close(); err.close(); System.exit(errorCount); }
From source file:com.sam.moca.util.AppUtils.java
License:Open Source License
/** * Returns the same banner for Java applications as misGetStartBanner. * @param appName the name of the application. *///from w w w .j a v a2s .c o m public static String getStartBanner(String appName) { String banner; DateTimeFormatter outDate = DateTimeFormat.forPattern("EEE MMM d H:mm:ss yyyy"); // Build the banner to return to the caller banner = String.format("%n%s %s - %s%n%n%s%n%n", appName, INSTANCE._fullVersion, outDate.print(new Date().getTime()), MocaConstants.COPYRIGHT_STRING); return banner; }
From source file:com.sam.moca.util.AppUtils.java
License:Open Source License
private void setupVersionData() { InputStream in = AppUtils.class.getResourceAsStream("/com/redprairie/moca/resources/build.properties"); Properties buildProperties = new Properties(); if (in != null) { try {/*w ww.j a va 2s. c om*/ buildProperties.load(in); } catch (InterruptedIOException e) { throw new MocaInterruptedException(e); } catch (IOException e) { // Use default if unable to load properties } finally { try { in.close(); } catch (IOException ignore) { } } } String releaseVersion = buildProperties.getProperty("releaseVersion"); if (releaseVersion == null) { releaseVersion = "2013.2.2.15"; } try { DateTimeFormatter inDate = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss"); DateTimeFormatter outDate = DateTimeFormat.forPattern("MMM d yyyy"); _fullVersion = "Build date: " + outDate.print(inDate.parseDateTime(releaseVersion)); } catch (IllegalArgumentException e) { // We built with release=Y (probably), just return the version String[] splitVersion = releaseVersion.split("\\."); // Safety check if (splitVersion.length > 2) { _majorMinorRevision = splitVersion[0] + "." + splitVersion[1]; } _fullVersion = releaseVersion; } }
From source file:com.sam_chordas.android.stockhawk.app.utils.DateTimeUtils.java
License:Apache License
public static String getStringPatternFromDateTime(String pattern, DateTime date) { DateTimeFormatter presenter = DateTimeFormat.forPattern(pattern); return presenter.print(date); }
From source file:com.sapienter.jbilling.server.pluggableTask.BasicCompositionTask.java
License:Open Source License
/** * Composes the actual invoice line description based off of set entity preferences and the * order period being processed./*from w ww .j a v a 2 s. co m*/ * * @param order order being processed * @param period period of time being processed * @param desc original order line description * @return invoice line description */ public String composeDescription(OrderDTO order, PeriodOfTime period, String desc) { Locale locale = getLocale(order.getBaseUserByUserId().getId()); ResourceBundle bundle = ResourceBundle.getBundle("entityNotifications", locale); StringBuilder lineDescription = new StringBuilder(); lineDescription.append(desc); /* append the billing period to the order line for non one-time orders */ if (order.getOrderPeriod().getId() != Constants.ORDER_PERIOD_ONCE) { // period ends at midnight of the next day (E.g., Oct 1 00:00, effectivley end-of-day Sept 30th). // subtract 1 day from the end so the period print out looks human readable DateMidnight start = period.getDateMidnightStart(); DateMidnight end = period.getDateMidnightEnd().minusDays(1); DateTimeFormatter dateFormat = DateTimeFormat.forPattern(bundle.getString("format.date")); LOG.debug("Composing for period " + start + " to " + end); LOG.debug("Using date format: " + bundle.getString("format.date")); // now add this to the line lineDescription.append(" "); lineDescription.append(bundle.getString("invoice.line.period")); lineDescription.append(" "); lineDescription.append(dateFormat.print(start)); lineDescription.append(" "); lineDescription.append(bundle.getString("invoice.line.to")); lineDescription.append(" "); lineDescription.append(dateFormat.print(end)); } /* optionally append the order id if the entity has the preference set */ if (appendOrderId(order.getBaseUserByUserId().getCompany().getId())) { lineDescription.append(bundle.getString("invoice.line.orderNumber")); lineDescription.append(" "); lineDescription.append(order.getId().toString()); } return lineDescription.toString(); }
From source file:com.sapienter.jbilling.server.util.NanoStopWatch.java
License:Open Source License
/** * Gets the total elapsed time with format * 00:00:00.0000000 = 00:mm:ss.SSS + #### Ticks * @param elapsedTicks elapsed ticks between start and stop nano time *//*from w w w.j a va 2 s . c o m*/ private String formatTime(final long elapsedTicks) { String formattedTime = ""; // should be hh:mm:ss.SSS, but 00 starts with 01 DateTimeFormatter formatter = DateTimeFormat.forPattern("00:mm:ss.SSS"); Calendar calendar = Calendar.getInstance(); if (elapsedTicks <= 9999) { calendar.setTimeInMillis(0); formattedTime = formatter.print(calendar.getTime().getTime()) + String.valueOf(String.format("%04d", elapsedTicks)); } else { calendar.setTimeInMillis(elapsedTicks * nsPerTick / nsPerMs); String formattedTicks = String.format("%07d", elapsedTicks); formattedTicks = formattedTicks.substring(formattedTicks.length() - 4); formattedTime = formatter.print(calendar.getTime().getTime()) + formattedTicks; } return formattedTime; }
From source file:com.sappenin.utils.appengine.customernotifications.framework.scheduler.payload.AggregatableNotificationTaskPayload.java
License:Apache License
/** * @return The unique task name for aggregating notifications. This is essentially the ancestorGroupingKey, as a * String. In other words, for any NotificationTarget+NotificationType+AnticipatedSendDate, there should * only be a single task in the queue. *//*from www. j av a2 s.c o m*/ @JsonIgnore @Override public String getAggregatedTaskName() { // We do this as part of the framework so that framework users don't have to worry abou it. DateTimeFormatter fmt = ISODateTimeFormat.dateTimeNoMillis(); String timestamp = fmt.print(this.getEtaScheduledDateTime()); // No Need to append the DateTime because the framework will handle this for us. See javadoc above. return (this.ancestorGroupingKey.getString() + timestamp).replace(":", ""); }
From source file:com.semanticcms.core.sitemap.SiteMapIndexServlet.java
License:Open Source License
private static void writeSitemap(HttpServletRequest req, HttpServletResponse resp, PrintWriter out, Book book, ReadableInstant lastmod, DateTimeFormatter iso8601) throws IOException { out.println(" <sitemap>"); out.print(" <loc>"); ServletUtil.getAbsoluteURL(req, resp.encodeURL(book.getBookRef().getPrefix() + SiteMapServlet.SERVLET_PATH), textInXhtmlEncoder, out);// w w w . ja v a2s .c om out.println("</loc>"); if (lastmod != null) { out.print(" <lastmod>"); encodeTextInXhtml(iso8601.print(lastmod), out); out.println("</lastmod>"); } out.println(" </sitemap>"); }
From source file:com.semanticcms.core.sitemap.SiteMapServlet.java
License:Open Source License
@Override protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException { final ServletContext servletContext = getServletContext(); final Book book = getBook(SemanticCMS.getInstance(servletContext), req); if (book == null) { resp.sendError(HttpServletResponse.SC_NOT_FOUND); return;//w w w . j a v a 2 s . co m } final SortedSet<View> views = HtmlRenderer.getInstance(servletContext).getViews(); final DateTimeFormatter iso8601 = ISODateTimeFormat.dateTime(); resp.resetBuffer(); resp.setContentType(CONTENT_TYPE); resp.setCharacterEncoding(ENCODING); final PrintWriter out = resp.getWriter(); out.println("<?xml version=\"1.0\" encoding=\"" + ENCODING + "\"?>"); out.println("<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">"); CapturePage.traversePagesDepthFirst(servletContext, req, resp, book.getContentRoot(), CaptureLevel.META, new CapturePage.PageDepthHandler<Void>() { @Override public Void handlePage(Page page, int depth) throws ServletException, IOException { assert page.getPageRef().getBookRef().equals(book.getBookRef()); // TODO: Concurrency: Any benefit to processing each view concurrently? allowRobots and isApplicable can be expensive but should also benefit from capture caching for (View view : views) { if (view.getAllowRobots(servletContext, req, resp, page) && view.isApplicable(servletContext, req, resp, page)) { out.println(" <url>"); out.print(" <loc>"); encodeTextInXhtml(view.getCanonicalUrl(servletContext, req, resp, page), out); out.println("</loc>"); ReadableInstant lastmod = view.getLastModified(servletContext, req, resp, page); if (lastmod != null) { out.print(" <lastmod>"); encodeTextInXhtml(iso8601.print(lastmod), out); out.println("</lastmod>"); } out.println(" </url>"); } } return null; } }, new CapturePage.TraversalEdges() { @Override public Set<ChildRef> getEdges(Page page) { return page.getChildRefs(); } }, new CapturePage.EdgeFilter() { @Override public boolean applyEdge(PageRef childPage) { return book.getBookRef().equals(childPage.getBookRef()); } }, null); out.println("</urlset>"); }
From source file:com.sheepdog.mashmesh.DriveExporter.java
License:Apache License
public void snapshotUserTable() throws IOException { DateTimeFormatter formatter = ISODateTimeFormat.dateTime(); String timestamp = formatter.print(DateTime.now()); Table patientTable = new Table().setName("User Profile Data " + timestamp) .setDescription("Locations of patients and volunteers as of " + timestamp).setIsExportable(true) .setColumns(Arrays.asList(new Column().setName("User Type").setType("STRING"), new Column().setName("Location").setType("LOCATION"))); patientTable = fusiontables.table().insert(patientTable).execute(); FusionTableContentWriter fusionTableWriter = new FusionTableContentWriter(patientTable); for (UserProfile userProfile : UserProfile.listAll()) { fusionTableWriter.writeRecord(userProfile.getType().name(), userProfile.getLocation()); }// ww w . j a va2s .com AbstractInputStreamContent streamContent = fusionTableWriter.getInputStreamContent(); fusiontables.table().importRows(patientTable.getTableId(), streamContent).execute(); File patientFile = findFileByTitle(patientTable.getName()); addToFolder(patientFile); }