Example usage for org.joda.time DateTime toString

List of usage examples for org.joda.time DateTime toString

Introduction

In this page you can find the example usage for org.joda.time DateTime toString.

Prototype

public String toString(String pattern) 

Source Link

Document

Output the instant using the specified format pattern.

Usage

From source file:com.example.managedvms.gettingstartedjava.util.CloudStorageHelper.java

License:Open Source License

/**
 * Uploads a file to Google Cloud Storage to the bucket specified in the BUCKET_NAME
 * environment variable, appending a timestamp to end of the uploaded filename.
 *///ww  w  . ja  va 2 s.com
public String uploadFile(Part filePart, final String bucketName) throws IOException {
    DateTimeFormatter dtf = DateTimeFormat.forPattern("-YYYY-MM-dd-HHmmssSSS");
    DateTime dt = DateTime.now(DateTimeZone.UTC);
    String dtString = dt.toString(dtf);
    final String fileName = filePart.getSubmittedFileName() + dtString;

    // the inputstream is closed by default, so we don't need to close it here
    BlobInfo blobInfo = storage.create(BlobInfo.builder(bucketName, fileName)
            // Modify access list to allow all users with link to read file
            .acl(new ArrayList<>(Arrays.asList(Acl.of(User.ofAllUsers(), Role.READER)))).build(),
            filePart.getInputStream());
    logger.log(Level.INFO, "Uploaded file {0} as {1}",
            new Object[] { filePart.getSubmittedFileName(), fileName });
    // return the public download link
    return blobInfo.mediaLink();
}

From source file:com.flowpowered.jsoncache.connector.DefaultURLConnector.java

License:MIT License

@Override
public InputStream openURL(URL url, final File temp, final File writeTo) throws IOException {
    URLConnection conn = url.openConnection();

    HttpURLConnection httpconn = null;
    if (url.getProtocol().equalsIgnoreCase("http")) {
        httpconn = (HttpURLConnection) conn;
    }//from w ww.  j av  a2  s.  c  o  m

    // Check modified date.
    DateTime modified = null;
    if (writeTo.exists()) {
        modified = new DateTime(writeTo.lastModified());
        conn.setRequestProperty("If-Modified-Since", modified.toString(HTTP_DATE_TIME));
    }

    setHeaders(conn);

    // Set the user agent for the request.
    System.setProperty("http.agent",
            "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.162 Safari/535.19");
    conn.setRequestProperty("User-Agent",
            "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.162 Safari/535.19");

    conn.connect();

    onConnected(conn);

    // Modified date handling. If server copy isn't newer than the cache, don't download again and use cached copy instead.

    // This checks if the server has replied with 304 NOT MODIFIED.
    if (httpconn != null && httpconn.getResponseCode() == 304) { // Not modified.
        try {
            conn.getInputStream().close();
        } catch (IOException ignore) {
        }
        try {
            conn.getOutputStream().close();
        } catch (IOException ignore) {
        }
        return new FileInputStream(writeTo);
    }

    if (modified != null) {
        // This checks for the last modified date.
        long i = conn.getHeaderFieldDate("Last-Modified", -1);
        DateTime serverModified = new DateTime(i, DateTimeZone.forOffsetHours(0));
        if (serverModified.isBefore(modified) || serverModified.isEqual(modified)) { // File hasn't changed.
            try {
                conn.getInputStream().close();
            } catch (IOException ignore) {
            }
            try {
                conn.getOutputStream().close();
            } catch (IOException ignore) {
            }
            return new FileInputStream(writeTo);
        }
    }

    return download(conn, temp, writeTo);
}

From source file:com.francelabs.datafari.servlets.admin.alertsAdmin.java

License:Apache License

private String getNextEvent(final String frequency, final String initialDate) {
    final DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/yyyy/HH:mm");
    final DateTime scheduledDate = new DateTime(formatter.parseDateTime(initialDate));
    final Calendar cal = Calendar.getInstance();
    cal.setTime(new Date());
    cal.set(Calendar.SECOND, 0);// www  .  j a  v a2 s. co m
    cal.set(Calendar.MILLISECOND, 0);
    final DateTime currentDateTime = new DateTime(cal.getTime());
    DateTime scheduledDateTimeUpdate = new DateTime(cal.getTime());

    switch (frequency.toLowerCase()) {
    case "hourly":
        // Create what would be the current scheduled date
        cal.setTime(new Date());
        cal.set(Calendar.MINUTE, scheduledDate.getMinuteOfHour());
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        scheduledDateTimeUpdate = new DateTime(cal.getTime());

        // Compare the current date with the current scheduled one, if the
        // current date is later than the scheduled one then create the next
        // scheduled date
        if (!currentDateTime.isBefore(scheduledDateTimeUpdate)) {
            cal.add(Calendar.HOUR_OF_DAY, 1);
            scheduledDateTimeUpdate = new DateTime(cal.getTime());
        }
        break;

    case "daily":
        // Create what would be the current scheduled date
        cal.setTime(new Date());
        cal.set(Calendar.HOUR_OF_DAY, scheduledDate.getHourOfDay());
        cal.set(Calendar.MINUTE, scheduledDate.getMinuteOfHour());
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        scheduledDateTimeUpdate = new DateTime(cal.getTime());

        // Compare the current date with the current scheduled one, if the
        // current date is later than the scheduled one then create the next
        // scheduled date
        if (!currentDateTime.isBefore(scheduledDateTimeUpdate)) {
            cal.add(Calendar.DAY_OF_YEAR, 1);
            scheduledDateTimeUpdate = new DateTime(cal.getTime());
        }
        break;

    case "weekly":
        // Create what would be the current scheduled date
        cal.setTime(new Date());
        cal.set(Calendar.DAY_OF_WEEK, scheduledDate.getDayOfWeek() + 1); // +1
        // =
        // diff
        // between
        // Joda
        // and
        // Calendar
        cal.set(Calendar.HOUR_OF_DAY, scheduledDate.getHourOfDay());
        cal.set(Calendar.MINUTE, scheduledDate.getMinuteOfHour());
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        scheduledDateTimeUpdate = new DateTime(cal.getTime());

        // Compare the current date with the current scheduled one, if the
        // current date is later than the scheduled one then create the next
        // scheduled date
        if (!currentDateTime.isBefore(scheduledDateTimeUpdate)) {
            cal.add(Calendar.WEEK_OF_YEAR, 1);
            scheduledDateTimeUpdate = new DateTime(cal.getTime());
        }
        break;

    default:
        break;
    }
    return scheduledDateTimeUpdate.toString(formatter);
}

From source file:com.github.jeanmerelis.jeanson.ext.typehandler.JodaDateTimeHandler.java

License:Apache License

@Override
public void write(Writer w, DateTime obj) throws IOException {
    if (obj == null) {
        w.write("null");
        return;//from   w  ww .  ja  va  2s. c  o  m
    }
    if (!usesMills) {
        DefaultStringHandler.escapeAndQuote(w, obj.toString(pattern));
    } else {
        w.write(String.valueOf(obj.getMillis()));
    }
}

From source file:com.github.matthesrieke.realty.CrawlerServlet.java

License:Apache License

private String createGroupedItemsMarkup() {
    Map<DateTime, List<Ad>> items;
    StringBuilder sb = new StringBuilder();
    try {/*from  w ww.  ja  v a 2 s .  c om*/
        items = this.storage.getItemsGroupedByDate();
    } catch (IOException e) {
        logger.warn("Retrieval of items failed.", e);
        sb.append("Retrieval of items failed.");
        sb.append(e);
        return sb.toString();
    }

    List<DateTime> sortedKeys = new ArrayList<DateTime>(items.keySet());
    Collections.sort(sortedKeys);
    Collections.reverse(sortedKeys);
    for (DateTime a : sortedKeys) {
        StringBuilder adsBuilder = new StringBuilder();
        List<Ad> ads = items.get(a);
        for (Ad ad : ads) {
            adsBuilder.append(ad.toHTML());
        }
        sb.append(this.groupTemplate.toString().replace("${GROUP_DATE}", a.toString(Util.GER_DATE_FORMAT))
                .replace("${entries}", adsBuilder.toString()));
    }

    return sb.toString();
}

From source file:com.google.android.apps.paco.RawDataActivity.java

License:Open Source License

private void fillData() {
    List<String> nameAndTime = new ArrayList<String>();
    for (Event event : experiment.getEvents()) {
        StringBuilder buf = new StringBuilder();
        boolean first = true;
        for (Output output : event.getResponses()) {
            if (first) {
                first = false;//from w  ww .j  av  a2  s .c o m
            } else {
                buf.append(",");
            }
            buf.append(output.getName());
            buf.append("=");
            Input input = experiment.getInputById(output.getInputServerId());
            if (input != null && input.getResponseType() != null && (input.getResponseType().equals(Input.PHOTO)
                    || input.getResponseType().equals(Input.SOUND))) {
                buf.append("<multimedia:" + input.getResponseType() + ">");
            } else {
                buf.append(output.getAnswer());
            }
        }
        DateTime responseTime = event.getResponseTime();
        String signalTime = null;
        if (responseTime == null) {
            DateTime scheduledTime = event.getScheduledTime();
            if (scheduledTime != null) {
                signalTime = scheduledTime.toString(df) + ": " + getString(R.string.missed_signal_value);
            } else {
                signalTime = getString(R.string.missed_signal_value);
            }
        } else {
            signalTime = responseTime.toString(df);
        }
        nameAndTime.add(signalTime + ": " + buf.toString());
    }
    ArrayAdapter scheduleAdapter = new ArrayAdapter(this, R.layout.schedule_row, nameAndTime);
    setListAdapter(scheduleAdapter);

}

From source file:com.google.android.apps.paco.TimeUtil.java

License:Open Source License

public static String formatDateTime(DateTime dateTime) {
    return dateTime.toString(dateTimeFormatter);
}

From source file:com.google.android.apps.paco.TimeUtil.java

License:Open Source License

public static String formatDateWithZone(DateTime dateTime) {
    return dateTime.toString(dateZoneFormatter);
}

From source file:com.google.sites.liberation.export.HistoryExporterImpl.java

License:Apache License

@Override
public void exportHistory(List<BaseContentEntry<?>> revisions, Appendable out) throws IOException {
    XmlElement history = new XmlElement("table");
    history.setAttribute("width", "100%");
    XmlElement header = new XmlElement("tr");
    header.setAttribute("align", "left");
    header.addElement(new XmlElement("th").addText("Version"));
    header.addElement(new XmlElement("th").addText("Last Edited"));
    header.addElement(new XmlElement("th").addText("Edited By"));
    history.addElement(header);//from   ww w  .j  a  v  a2  s. co m
    int maxRevision = getMaxRevision(revisions);
    for (BaseContentEntry<?> revision : revisions) {
        int number = revision.getRevision().getValue();
        XmlElement row = new XmlElement("tr");
        String href = (number == maxRevision) ? "index.html" : "_revisions/" + number + ".html";
        XmlElement link = new XmlElement("a").addText("Version " + number).setAttribute("href", href);
        row.addElement(new XmlElement("td").addElement(link));
        DateTime jodaTime = new DateTime(revision.getUpdated().getValue());
        XmlElement updated = new XmlElement("td").addText(jodaTime.toString(formatter));
        row.addElement(updated);
        XmlElement author = new XmlElement("a");
        String name = revision.getAuthors().get(0).getName();
        String email = revision.getAuthors().get(0).getEmail();
        row.addElement(
                new XmlElement("td").addElement(author.addText(name).setAttribute("href", "mailto:" + email)));
        history.addElement(row);
    }
    XmlElement html = new XmlElement("html");
    XmlElement head = new XmlElement("head");
    XmlElement title = new XmlElement("title");
    title.addText("Version history for " + revisions.get(0).getTitle().getPlainText());
    html.addElement(head.addElement(title));
    html.addElement(new XmlElement("body").addElement(history));
    html.appendTo(out);
}

From source file:com.google.sites.liberation.renderers.RendererUtils.java

License:Apache License

/**
 * Creates a new hAtom "updated" element for the given entry.
 *//*from  w  w w  .j  a  v  a  2 s  .  co  m*/
static XmlElement getUpdatedElement(BaseContentEntry<?> entry) {
    checkNotNull(entry);
    XmlElement element = new XmlElement("abbr");
    element.setAttribute("class", "updated");
    element.setAttribute("title", entry.getUpdated().toString());
    DateTime jodaTime = new DateTime(entry.getUpdated().getValue(), DateTimeZone.UTC);
    element.addText(jodaTime.toString(formatter));
    return element;
}