Example usage for org.joda.time.format DateTimeFormatter print

List of usage examples for org.joda.time.format DateTimeFormatter print

Introduction

In this page you can find the example usage for org.joda.time.format DateTimeFormatter print.

Prototype

public String print(ReadablePartial partial) 

Source Link

Document

Prints a ReadablePartial to a new String.

Usage

From source file:damo.three.ie.util.HtmlUtilities.java

License:Open Source License

/**
 * Parses the My3 account usage page to nicer JSON format.
 *
 * @param pageContent Page content as HTML.
 * @return Usage information stripped out and formatted as JSON.
 * @throws JSONException//w  w w. j  a  va  2  s. c om
 */
public static JSONArray parseUsageAsJSONArray(String pageContent) throws JSONException {
    // The HTML on prepay is pig-ugly, so we will use JSoup to
    // clean and parse it.
    Document doc = Jsoup.parse(pageContent);
    HtmlUtilities.removeComments(doc);

    Elements elements = doc.getElementsByTag("table");

    JSONArray jsonArray = new JSONArray();

    // three don't have a sub label for the 3-to-3 calls, which is not consistent with other items.
    // .. feck them!
    boolean three2threeCallsBug = false;

    for (Element element : elements) {

        for (Element subelement : element.select("tbody > tr")) {

            if ((subelement.text().contains("3 to 3 Calls")) && (subelement.text().contains("Valid until"))) {
                three2threeCallsBug = true;
            }

            Elements subsubelements = subelement.select("td");

            if (subsubelements.size() == 3) {

                // skip the "total" entries
                if (subsubelements.select("td").get(0).text().contains("Total")) {
                    continue;
                }

                JSONObject currentItem = new JSONObject();

                if (three2threeCallsBug) {
                    currentItem.put("item", "3 to 3 Calls");
                } else {
                    // Get rid of that "non-breaking space" character if it exists
                    String titleToClean = subsubelements.select("td").get(0).text().replace("\u00a0", "")
                            .trim();
                    currentItem.put("item", titleToClean);
                }

                /**
                 * Check if date contains "Today", if so, change it to a date.
                 * Otherwise we will never know when usage ends, unless user refreshes, As 'today'
                 * is 'today', tomorrow.. see!
                 */
                String value1 = subsubelements.select("td").get(1).text();
                if (value1.equals("Today")) {
                    DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/yy").withLocale(Locale.UK);
                    DateTime dt = new DateTime(); // current datetime
                    value1 = "Expires " + formatter.print(dt);
                }
                currentItem.put("value1", value1);
                currentItem.put("value2", subsubelements.select("td").get(2).text());

                // Out of Bundle charges have an extra property
                if (currentItem.getString("item").startsWith("Internet")) {

                    Pattern p1 = Pattern.compile(Constants.OUT_OF_BUNDLE_REGEX, Pattern.DOTALL);
                    Matcher m1 = p1.matcher(pageContent);

                    StringBuilder cleanedDate = new StringBuilder();
                    if (m1.matches()) {
                        cleanedDate.append(m1.group(1));
                        cleanedDate.append(' ');
                        cleanedDate.append(m1.group(2));
                        cleanedDate.append(' ');
                        cleanedDate.append(m1.group(3));
                        currentItem.put("value3", cleanedDate.toString());
                    }

                }
                jsonArray.put(currentItem);
            }

        }

        // reset the 3-to-3 call bug flag for next Element
        if (three2threeCallsBug) {
            three2threeCallsBug = false;
        }
    }

    return jsonArray;
}

From source file:datetime.management.DateTimeManage.java

public void Increase30min() {
    DateTimeFormatter formatter = DateTimeFormat.forPattern("HH:mm");
    LocalTime time = formatter.parseLocalTime("14:00");
    time = time.plusMinutes(30);//from w w  w . ja  va 2s. c o  m
    System.out.println(formatter.print(time));
}

From source file:datetime.management.DateTimeManage.java

public String Increase30min(String inputTime) {
    DateTimeFormatter formatter = DateTimeFormat.forPattern("HH:mm");
    LocalTime time = formatter.parseLocalTime(inputTime);
    time = time.plusMinutes(30);/*from  w  ww .j  av a 2s.  c  om*/
    return formatter.print(time);
}

From source file:DateTimeManagement.TimeIncrease.java

public void Increase30min(String inputTime) {
    DateTimeFormatter formatter = DateTimeFormat.forPattern("HH:mm");
    LocalTime time = formatter.parseLocalTime(inputTime);
    time = time.plusMinutes(30);/* ww w  .  j  a va 2 s  . c o m*/
    System.out.println(formatter.print(time));
}

From source file:ddf.catalog.services.xsltlistener.XsltResponseQueueTransformer.java

License:Open Source License

@Override
public ddf.catalog.data.BinaryContent transform(SourceResponse upstreamResponse,
        Map<String, Serializable> arguments) throws CatalogTransformerException {

    LOGGER.debug("Transforming ResponseQueue with XSLT tranformer");

    long grandTotal = -1;

    try {/*  w w w  .  j a va2  s  .c o  m*/
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

        factory.setNamespaceAware(true);
        DocumentBuilder builder = factory.newDocumentBuilder();

        Document doc = builder.newDocument();

        Node resultsElement = doc.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "results", null));

        // TODO use streaming XSLT, not DOM
        List<Result> results = upstreamResponse.getResults();
        grandTotal = upstreamResponse.getHits();

        for (Result result : results) {
            Metacard metacard = result.getMetacard();
            String thisMetacard = metacard.getMetadata();
            if (metacard != null && thisMetacard != null) {
                Element metacardElement = createElement(doc, XML_RESULTS_NAMESPACE, "metacard", null);
                if (metacard.getId() != null) {
                    metacardElement
                            .appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "id", metacard.getId()));
                }
                if (metacard.getMetacardType().toString() != null) {
                    metacardElement.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "type",
                            metacard.getMetacardType().getName()));
                }
                if (metacard.getTitle() != null) {
                    metacardElement.appendChild(
                            createElement(doc, XML_RESULTS_NAMESPACE, "title", metacard.getTitle()));
                }
                if (result.getRelevanceScore() != null) {
                    metacardElement.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "score",
                            result.getRelevanceScore().toString()));
                }
                if (result.getDistanceInMeters() != null) {
                    metacardElement.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "distance",
                            result.getDistanceInMeters().toString()));
                }
                if (metacard.getSourceId() != null) {
                    metacardElement.appendChild(
                            createElement(doc, XML_RESULTS_NAMESPACE, "site", metacard.getSourceId()));
                }
                if (metacard.getContentTypeName() != null) {
                    String contentType = metacard.getContentTypeName();
                    Element typeElement = createElement(doc, XML_RESULTS_NAMESPACE, "content-type",
                            contentType);
                    // TODO revisit what to put in the qualifier
                    typeElement.setAttribute("qualifier", "content-type");
                    metacardElement.appendChild(typeElement);
                }
                if (metacard.getResourceURI() != null) {
                    try {
                        metacardElement.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "product",
                                metacard.getResourceURI().toString()));
                    } catch (DOMException e) {
                        LOGGER.warn(" Unable to create resource uri element", e);
                    }
                }
                if (metacard.getThumbnail() != null) {
                    metacardElement.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "thumbnail",
                            Base64.encodeBase64String(metacard.getThumbnail())));
                    try {
                        String mimeType = URLConnection
                                .guessContentTypeFromStream(new ByteArrayInputStream(metacard.getThumbnail()));
                        metacardElement
                                .appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "t_mimetype", mimeType));
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        metacardElement.appendChild(
                                createElement(doc, XML_RESULTS_NAMESPACE, "t_mimetype", "image/png"));
                    }
                }
                DateTimeFormatter fmt = ISODateTimeFormat.dateTime();
                if (metacard.getCreatedDate() != null) {
                    metacardElement.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "created",
                            fmt.print(metacard.getCreatedDate().getTime())));
                }
                // looking at the date last modified
                if (metacard.getModifiedDate() != null) {
                    metacardElement.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "updated",
                            fmt.print(metacard.getModifiedDate().getTime())));
                }
                if (metacard.getEffectiveDate() != null) {
                    metacardElement.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "effective",
                            fmt.print(metacard.getEffectiveDate().getTime())));
                }
                if (metacard.getLocation() != null) {
                    metacardElement.appendChild(
                            createElement(doc, XML_RESULTS_NAMESPACE, "location", metacard.getLocation()));
                }
                Element documentElement = doc.createElementNS(XML_RESULTS_NAMESPACE, "document");
                metacardElement.appendChild(documentElement);
                resultsElement.appendChild(metacardElement);

                Node importedNode = doc.importNode(new XPathHelper(thisMetacard).getDocument().getFirstChild(),
                        true);
                documentElement.appendChild(importedNode);
            } else {
                LOGGER.debug("Null content/document returned to XSLT ResponseQueueTransformer");
                continue;
            }
        }

        if (LOGGER.isDebugEnabled()) {
            DOMImplementationLS domImplementation = (DOMImplementationLS) doc.getImplementation();
            LSSerializer lsSerializer = domImplementation.createLSSerializer();
            LOGGER.debug("Generated XML input for transform: " + lsSerializer.writeToString(doc));
        }

        LOGGER.debug("Starting responsequeue xslt transform.");

        Transformer transformer;

        Map<String, Object> mergedMap = new HashMap<String, Object>();
        mergedMap.put(GRAND_TOTAL, grandTotal);
        if (arguments != null) {
            mergedMap.putAll(arguments);
        }

        BinaryContent resultContent;
        StreamResult resultOutput = null;
        Source source = new DOMSource(doc);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        resultOutput = new StreamResult(baos);

        try {
            transformer = templates.newTransformer();
        } catch (TransformerConfigurationException tce) {
            throw new CatalogTransformerException("Could not perform Xslt transform: " + tce.getException(),
                    tce.getCause());
        }

        if (mergedMap != null && !mergedMap.isEmpty()) {
            for (Map.Entry<String, Object> entry : mergedMap.entrySet()) {
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug(
                            "Adding parameter to transform {" + entry.getKey() + ":" + entry.getValue() + "}");
                }
                transformer.setParameter(entry.getKey(), entry.getValue());
            }
        }

        try {
            transformer.transform(source, resultOutput);
            byte[] bytes = baos.toByteArray();
            LOGGER.debug("Transform complete.");
            resultContent = new XsltTransformedContent(bytes, mimeType);
        } catch (TransformerException te) {
            LOGGER.error("Could not perform Xslt transform: " + te.getException(), te.getCause());
            throw new CatalogTransformerException("Could not perform Xslt transform: " + te.getException(),
                    te.getCause());
        } finally {
            // transformer.reset();
            // don't need to do that unless we are putting it back into a
            // pool -- which we should do, but that can wait until later.
        }

        return resultContent;
    } catch (ParserConfigurationException e) {
        LOGGER.warn("Error creating new document: " + e.getMessage(), e.getCause());
        throw new CatalogTransformerException("Error merging entries to xml feed.", e);
    }
}

From source file:ddf.catalog.source.opensearch.impl.OpenSearchParserImpl.java

License:Open Source License

@Override
public void populateTemporal(WebClient client, TemporalFilter temporal, List<String> parameters) {
    DateTimeFormatter fmt = ISODateTimeFormat.dateTime();
    String start = "";
    String end = "";
    String name = "";
    if (temporal != null) {
        long startLng = (temporal.getStartDate() != null) ? temporal.getStartDate().getTime() : 0;
        start = fmt.print(startLng);
        long endLng = (temporal.getEndDate() != null) ? temporal.getEndDate().getTime()
                : System.currentTimeMillis();
        end = fmt.print(endLng);//from   w w w .j a va  2s. com
    }
    checkAndReplace(client, start, TIME_START, parameters);
    checkAndReplace(client, end, TIME_END, parameters);
    checkAndReplace(client, name, TIME_NAME, parameters);
}

From source file:ddf.catalog.source.opensearch.OpenSearchSiteUtil.java

License:Open Source License

/**
 * Fills in the opensearch query URL with temporal information (Start, End, and Name). Currently
 * name is empty due to incompatibility with endpoints.
 *
 * @param client/*from  w w  w.  j  a  va 2  s  . c  o  m*/
 *            OpenSearch URL to populate
 * @param temporal
 *            TemporalCriteria that contains temporal data
 */
public static void populateTemporal(WebClient client, TemporalFilter temporal, List<String> parameters) {
    DateTimeFormatter fmt = ISODateTimeFormat.dateTime();
    String start = "";
    String end = "";
    String name = "";
    if (temporal != null) {
        long startLng = (temporal.getStartDate() != null) ? temporal.getStartDate().getTime() : 0;
        start = fmt.print(startLng);
        long endLng = (temporal.getEndDate() != null) ? temporal.getEndDate().getTime()
                : System.currentTimeMillis();
        end = fmt.print(endLng);
    }
    checkAndReplace(client, start, TIME_START, parameters);
    checkAndReplace(client, end, TIME_END, parameters);
    checkAndReplace(client, name, TIME_NAME, parameters);
}

From source file:ddf.metrics.plugin.webconsole.MetricsWebConsolePlugin.java

License:Open Source License

private void addCellLabelForRange(PrintWriter pw, DateMidnight startDate, DateTime endDate) {
    DateTimeFormatter dateFormatter = DateTimeFormat.forStyle(DATE_DISPLAY_FORMAT);
    String urlText = dateFormatter.print(startDate) + " - " + dateFormatter.print(endDate);
    LOGGER.debug("URL text = [{}]", urlText);
    addCellLabel(pw, urlText);/*from   ww  w .jav  a2s .  c  o m*/
}

From source file:de.codesourcery.threadwatcher.HiResInterval.java

License:Apache License

public String toUIString() {
    DateTimeFormatter DF = new DateTimeFormatterBuilder().appendYear(4, 4).appendLiteral('-')
            .appendMonthOfYear(1).appendLiteral('-').appendDayOfMonth(1).appendLiteral(" ").appendHourOfDay(2)
            .appendLiteral(':').appendMinuteOfHour(2).appendLiteral(':').appendSecondOfMinute(2)
            .appendLiteral('.').appendMillisOfSecond(1).toFormatter();

    final String start = DF.print(this.start.toDateTime());
    final String end = DF.print(this.end.toDateTime());
    return start + " - " + end + " [ " + getDurationInMilliseconds() + " ms ]";
}

From source file:de.codesourcery.threadwatcher.HiResTimestamp.java

License:Apache License

public String toUIString() {
    DateTimeFormatter DF = new DateTimeFormatterBuilder().appendYear(4, 4).appendLiteral('-')
            .appendMonthOfYear(1).appendLiteral('-').appendDayOfMonth(1).appendLiteral(" ").appendHourOfDay(2)
            .appendLiteral(':').appendMinuteOfHour(2).appendLiteral(':').appendSecondOfMinute(2)
            .appendLiteral('.').appendMillisOfSecond(1).toFormatter();

    return DF.print(toDateTime());
}