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

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

Introduction

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

Prototype

public String print(ReadablePeriod period) 

Source Link

Document

Prints a ReadablePeriod to a new String.

Usage

From source file:ca.phon.session.AgeFormatter.java

License:Open Source License

/**
 * Format a {@link Period} object as an age string.
 * //  w  ww  .  j a  va 2  s  . c  o m
 * @param age
 * @return age as a string
 */
public static String ageToString(Period age) {
    final PeriodFormatter formatter = createFormatter();
    return formatter.print(age);
}

From source file:ching.icecreaming.action.ViewAction.java

License:Open Source License

@Action(value = "view", results = { @Result(name = "login", location = "edit.jsp"),
        @Result(name = "input", location = "view.jsp"), @Result(name = "success", location = "view.jsp"),
        @Result(name = "error", location = "error.jsp") })
public String execute() throws Exception {
    Enumeration enumerator = null;
    String[] array1 = null, array2 = null;
    int int1 = -1, int2 = -1, int3 = -1;
    InputStream inputStream1 = null;
    OutputStream outputStream1 = null;
    java.io.File file1 = null, file2 = null, dir1 = null;
    List<File> files = null;
    HttpHost httpHost1 = null;/*from www  .  j av  a2 s. c om*/
    HttpGet httpGet1 = null, httpGet2 = null;
    HttpPut httpPut1 = null;
    URI uri1 = null;
    URL url1 = null;
    DefaultHttpClient httpClient1 = null;
    URIBuilder uriBuilder1 = null, uriBuilder2 = null;
    HttpResponse httpResponse1 = null, httpResponse2 = null;
    HttpEntity httpEntity1 = null, httpEntity2 = null;
    List<NameValuePair> nameValuePair1 = null;
    String string1 = null, string2 = null, string3 = null, string4 = null, return1 = LOGIN;
    XMLConfiguration xmlConfiguration = null;
    List<HierarchicalConfiguration> list1 = null, list2 = null;
    HierarchicalConfiguration hierarchicalConfiguration2 = null;
    DataModel1 dataModel1 = null;
    DataModel2 dataModel2 = null;
    List<DataModel1> listObject1 = null, listObject3 = null;
    org.joda.time.DateTime dateTime1 = null, dateTime2 = null;
    org.joda.time.Period period1 = null;
    PeriodFormatter periodFormatter1 = new PeriodFormatterBuilder().appendYears()
            .appendSuffix(String.format(" %s", getText("year")), String.format(" %s", getText("years")))
            .appendSeparator(" ").appendMonths()
            .appendSuffix(String.format(" %s", getText("month")), String.format(" %s", getText("months")))
            .appendSeparator(" ").appendWeeks()
            .appendSuffix(String.format(" %s", getText("week")), String.format(" %s", getText("weeks")))
            .appendSeparator(" ").appendDays()
            .appendSuffix(String.format(" %s", getText("day")), String.format(" %s", getText("days")))
            .appendSeparator(" ").appendHours()
            .appendSuffix(String.format(" %s", getText("hour")), String.format(" %s", getText("hours")))
            .appendSeparator(" ").appendMinutes()
            .appendSuffix(String.format(" %s", getText("minute")), String.format(" %s", getText("minutes")))
            .appendSeparator(" ").appendSeconds().minimumPrintedDigits(2)
            .appendSuffix(String.format(" %s", getText("second")), String.format(" %s", getText("seconds")))
            .printZeroNever().toFormatter();
    if (StringUtils.isBlank(urlString) || StringUtils.isBlank(wsType)) {
        urlString = portletPreferences.getValue("urlString", "/");
        wsType = portletPreferences.getValue("wsType", "folder");
    }
    Configuration propertiesConfiguration1 = new PropertiesConfiguration("system.properties");
    timeZone1 = portletPreferences.getValue("timeZone", TimeZone.getDefault().getID());
    enumerator = portletPreferences.getNames();
    if (enumerator.hasMoreElements()) {
        array1 = portletPreferences.getValues("server", null);
        if (array1 != null) {
            if (ArrayUtils.isNotEmpty(array1)) {
                for (int1 = 0; int1 < array1.length; int1++) {
                    switch (int1) {
                    case 0:
                        sid = array1[int1];
                        break;
                    case 1:
                        uid = array1[int1];
                        break;
                    case 2:
                        pid = array1[int1];
                        break;
                    case 3:
                        alias1 = array1[int1];
                        break;
                    default:
                        break;
                    }
                }
                sid = new String(Base64.decodeBase64(sid.getBytes()));
                uid = new String(Base64.decodeBase64(uid.getBytes()));
                pid = new String(Base64.decodeBase64(pid.getBytes()));
            }
            return1 = INPUT;
        } else {
            return1 = LOGIN;
        }
    } else {
        return1 = LOGIN;
    }

    if (StringUtils.equals(urlString, "/")) {

        if (listObject1 != null) {
            listObject1.clear();
        }
        if (session.containsKey("breadcrumbs")) {
            session.remove("breadcrumbs");
        }
    } else {
        array2 = StringUtils.split(urlString, "/");
        listObject1 = (session.containsKey("breadcrumbs")) ? (List<DataModel1>) session.get("breadcrumbs")
                : new ArrayList<DataModel1>();
        int2 = array2.length - listObject1.size();
        if (int2 > 0) {
            listObject1.add(new DataModel1(urlString, label1));
        } else {
            int2 += listObject1.size();
            for (int1 = listObject1.size() - 1; int1 >= int2; int1--) {
                listObject1.remove(int1);
            }
        }
        session.put("breadcrumbs", listObject1);
    }
    switch (wsType) {
    case "folder":
        break;
    case "reportUnit":
        try {
            dateTime1 = new org.joda.time.DateTime();
            return1 = INPUT;
            httpClient1 = new DefaultHttpClient();
            if (StringUtils.equals(button1, getText("Print"))) {
                nameValuePair1 = new ArrayList<NameValuePair>();
                if (listObject2 != null) {
                    if (listObject2.size() > 0) {
                        for (DataModel2 dataObject2 : listObject2) {
                            listObject3 = dataObject2.getOptions();
                            if (listObject3 == null) {
                                string2 = dataObject2.getValue1();
                                if (StringUtils.isNotBlank(string2))
                                    nameValuePair1.add(new BasicNameValuePair(dataObject2.getId(), string2));
                            } else {
                                for (int1 = listObject3.size() - 1; int1 >= 0; int1--) {
                                    dataModel1 = (DataModel1) listObject3.get(int1);
                                    string2 = dataModel1.getString2();
                                    if (StringUtils.isNotBlank(string2))
                                        nameValuePair1
                                                .add(new BasicNameValuePair(dataObject2.getId(), string2));
                                }
                            }
                        }
                    }
                }
                url1 = new URL(sid);
                uriBuilder1 = new URIBuilder(sid);
                uriBuilder1.setUserInfo(uid, pid);
                if (StringUtils.isBlank(format1))
                    format1 = "pdf";
                uriBuilder1.setPath(url1.getPath() + "/rest_v2/reports" + urlString + "." + format1);
                if (StringUtils.isNotBlank(locale2)) {
                    nameValuePair1.add(new BasicNameValuePair("userLocale", locale2));
                }
                if (StringUtils.isNotBlank(page1)) {
                    if (NumberUtils.isNumber(page1)) {
                        nameValuePair1.add(new BasicNameValuePair("page", page1));
                    }
                }
                if (nameValuePair1.size() > 0) {
                    uriBuilder1.setQuery(URLEncodedUtils.format(nameValuePair1, "UTF-8"));
                }
                uri1 = uriBuilder1.build();
                httpGet1 = new HttpGet(uri1);
                httpResponse1 = httpClient1.execute(httpGet1);
                int1 = httpResponse1.getStatusLine().getStatusCode();
                if (int1 == HttpStatus.SC_OK) {
                    string3 = System.getProperty("java.io.tmpdir") + File.separator
                            + httpServletRequest.getSession().getId();
                    dir1 = new File(string3);
                    if (!dir1.exists()) {
                        dir1.mkdir();
                    }
                    httpEntity1 = httpResponse1.getEntity();
                    file1 = new File(string3, StringUtils.substringAfterLast(urlString, "/") + "." + format1);
                    if (StringUtils.equalsIgnoreCase(format1, "html")) {
                        result1 = EntityUtils.toString(httpEntity1);
                        FileUtils.writeStringToFile(file1, result1);
                        array1 = StringUtils.substringsBetween(result1, "<img src=\"", "\"");
                        if (ArrayUtils.isNotEmpty(array1)) {
                            dir1 = new File(
                                    string3 + File.separator + FilenameUtils.getBaseName(file1.getName()));
                            if (dir1.exists()) {
                                FileUtils.deleteDirectory(dir1);
                            }
                            file2 = new File(FilenameUtils.getFullPath(file1.getAbsolutePath())
                                    + FilenameUtils.getBaseName(file1.getName()) + ".zip");
                            if (file2.exists()) {
                                if (FileUtils.deleteQuietly(file2)) {
                                }
                            }
                            for (int2 = 0; int2 < array1.length; int2++) {
                                try {
                                    string2 = url1.getPath() + "/rest_v2/reports" + urlString + "/"
                                            + StringUtils.substringAfter(array1[int2], "/");
                                    uriBuilder1.setPath(string2);
                                    uri1 = uriBuilder1.build();
                                    httpGet1 = new HttpGet(uri1);
                                    httpResponse1 = httpClient1.execute(httpGet1);
                                    int1 = httpResponse1.getStatusLine().getStatusCode();
                                } finally {
                                    if (int1 == HttpStatus.SC_OK) {
                                        try {
                                            string2 = StringUtils.substringBeforeLast(array1[int2], "/");
                                            dir1 = new File(string3 + File.separator + string2);
                                            if (!dir1.exists()) {
                                                dir1.mkdirs();
                                            }
                                            httpEntity1 = httpResponse1.getEntity();
                                            inputStream1 = httpEntity1.getContent();
                                        } finally {
                                            string1 = StringUtils.substringAfterLast(array1[int2], "/");
                                            file2 = new File(string3 + File.separator + string2, string1);
                                            outputStream1 = new FileOutputStream(file2);
                                            IOUtils.copy(inputStream1, outputStream1);
                                        }
                                    }
                                }
                            }
                            outputStream1 = new FileOutputStream(
                                    FilenameUtils.getFullPath(file1.getAbsolutePath())
                                            + FilenameUtils.getBaseName(file1.getName()) + ".zip");
                            ArchiveOutputStream archiveOutputStream1 = new ArchiveStreamFactory()
                                    .createArchiveOutputStream(ArchiveStreamFactory.ZIP, outputStream1);
                            archiveOutputStream1.putArchiveEntry(new ZipArchiveEntry(file1, file1.getName()));
                            IOUtils.copy(new FileInputStream(file1), archiveOutputStream1);
                            archiveOutputStream1.closeArchiveEntry();
                            dir1 = new File(FilenameUtils.getFullPath(file1.getAbsolutePath())
                                    + FilenameUtils.getBaseName(file1.getName()));
                            files = (List<File>) FileUtils.listFiles(dir1, TrueFileFilter.INSTANCE,
                                    TrueFileFilter.INSTANCE);
                            for (File file3 : files) {
                                archiveOutputStream1.putArchiveEntry(new ZipArchiveEntry(file3, StringUtils
                                        .substringAfter(file3.getCanonicalPath(), string3 + File.separator)));
                                IOUtils.copy(new FileInputStream(file3), archiveOutputStream1);
                                archiveOutputStream1.closeArchiveEntry();
                            }
                            archiveOutputStream1.close();
                        }
                        bugfixGateIn = propertiesConfiguration1.getBoolean("bugfixGateIn", false);
                        string4 = bugfixGateIn
                                ? String.format("<img src=\"%s/namespace1/file-link?sessionId=%s&fileName=",
                                        portletRequest.getContextPath(),
                                        httpServletRequest.getSession().getId())
                                : String.format("<img src=\"%s/namespace1/file-link?fileName=",
                                        portletRequest.getContextPath());
                        result1 = StringUtils.replace(result1, "<img src=\"", string4);
                    } else {
                        inputStream1 = httpEntity1.getContent();
                        outputStream1 = new FileOutputStream(file1);
                        IOUtils.copy(inputStream1, outputStream1);
                        result1 = file1.getAbsolutePath();
                    }
                    return1 = SUCCESS;
                } else {
                    addActionError(String.format("%s %d: %s", getText("Error"), int1,
                            getText(Integer.toString(int1))));
                }
                dateTime2 = new org.joda.time.DateTime();
                period1 = new Period(dateTime1, dateTime2.plusSeconds(1));
                message1 = getText("Execution.time") + ": " + periodFormatter1.print(period1);
            } else {
                url1 = new URL(sid);
                uriBuilder1 = new URIBuilder(sid);
                uriBuilder1.setUserInfo(uid, pid);
                uriBuilder1.setPath(url1.getPath() + "/rest_v2/reports" + urlString + "/inputControls");
                uri1 = uriBuilder1.build();
                httpGet1 = new HttpGet(uri1);
                httpResponse1 = httpClient1.execute(httpGet1);
                int1 = httpResponse1.getStatusLine().getStatusCode();
                switch (int1) {
                case HttpStatus.SC_NO_CONTENT:
                    break;
                case HttpStatus.SC_OK:
                    httpEntity1 = httpResponse1.getEntity();
                    if (httpEntity1 != null) {
                        inputStream1 = httpEntity1.getContent();
                        if (inputStream1 != null) {
                            xmlConfiguration = new XMLConfiguration();
                            xmlConfiguration.load(inputStream1);
                            list1 = xmlConfiguration.configurationsAt("inputControl");
                            if (list1.size() > 0) {
                                listObject2 = new ArrayList<DataModel2>();
                                for (HierarchicalConfiguration hierarchicalConfiguration1 : list1) {
                                    string2 = hierarchicalConfiguration1.getString("type");
                                    dataModel2 = new DataModel2();
                                    dataModel2.setId(hierarchicalConfiguration1.getString("id"));
                                    dataModel2.setLabel1(hierarchicalConfiguration1.getString("label"));
                                    dataModel2.setType1(string2);
                                    dataModel2.setMandatory(hierarchicalConfiguration1.getBoolean("mandatory"));
                                    dataModel2.setReadOnly(hierarchicalConfiguration1.getBoolean("readOnly"));
                                    dataModel2.setVisible(hierarchicalConfiguration1.getBoolean("visible"));
                                    switch (string2) {
                                    case "bool":
                                    case "singleValueText":
                                    case "singleValueNumber":
                                    case "singleValueDate":
                                    case "singleValueDatetime":
                                        hierarchicalConfiguration2 = hierarchicalConfiguration1
                                                .configurationAt("state");
                                        dataModel2.setValue1(hierarchicalConfiguration2.getString("value"));
                                        break;
                                    case "singleSelect":
                                    case "singleSelectRadio":
                                    case "multiSelect":
                                    case "multiSelectCheckbox":
                                        hierarchicalConfiguration2 = hierarchicalConfiguration1
                                                .configurationAt("state");
                                        list2 = hierarchicalConfiguration2.configurationsAt("options.option");
                                        if (list2.size() > 0) {
                                            listObject3 = new ArrayList<DataModel1>();
                                            for (HierarchicalConfiguration hierarchicalConfiguration3 : list2) {
                                                dataModel1 = new DataModel1(
                                                        hierarchicalConfiguration3.getString("label"),
                                                        hierarchicalConfiguration3.getString("value"));
                                                if (hierarchicalConfiguration3.getBoolean("selected")) {
                                                    dataModel2.setValue1(
                                                            hierarchicalConfiguration3.getString("value"));
                                                }
                                                listObject3.add(dataModel1);
                                            }
                                            dataModel2.setOptions(listObject3);
                                        }
                                        break;
                                    default:
                                        break;
                                    }
                                    listObject2.add(dataModel2);
                                }
                            }
                        }
                    }
                    break;
                default:
                    addActionError(String.format("%s %d: %s", getText("Error"), int1,
                            getText(Integer.toString(int1))));
                    break;
                }
                if (httpEntity1 != null) {
                    EntityUtils.consume(httpEntity1);
                }
                uriBuilder1.setPath(url1.getPath() + "/rest/resource" + urlString);
                uri1 = uriBuilder1.build();
                httpGet1 = new HttpGet(uri1);
                httpResponse1 = httpClient1.execute(httpGet1);
                int2 = httpResponse1.getStatusLine().getStatusCode();
                if (int2 == HttpStatus.SC_OK) {
                    httpEntity1 = httpResponse1.getEntity();
                    inputStream1 = httpEntity1.getContent();
                    xmlConfiguration = new XMLConfiguration();
                    xmlConfiguration.load(inputStream1);
                    list1 = xmlConfiguration.configurationsAt("resourceDescriptor");
                    for (HierarchicalConfiguration hierarchicalConfiguration4 : list1) {
                        if (StringUtils.equalsIgnoreCase(
                                StringUtils.trim(hierarchicalConfiguration4.getString("[@wsType]")), "prop")) {
                            if (map1 == null)
                                map1 = new HashMap<String, String>();
                            string2 = StringUtils.substringBetween(
                                    StringUtils.substringAfter(
                                            hierarchicalConfiguration4.getString("[@uriString]"), "_files/"),
                                    "_", ".properties");
                            map1.put(string2,
                                    StringUtils.isBlank(string2) ? getText("Default") : getText(string2));
                        }
                    }
                }
                if (httpEntity1 != null) {
                    EntityUtils.consume(httpEntity1);
                }
            }
        } catch (IOException | ConfigurationException | URISyntaxException exception1) {
            exception1.printStackTrace();
            addActionError(exception1.getLocalizedMessage());
            httpGet1.abort();
            return ERROR;
        } finally {
            httpClient1.getConnectionManager().shutdown();
            IOUtils.closeQuietly(inputStream1);
        }
        break;
    default:
        addActionError(getText("This.file.type.is.not.supported"));
        break;
    }
    if (return1 != LOGIN) {
        sid = new String(Base64.encodeBase64(sid.getBytes()));
        uid = new String(Base64.encodeBase64(uid.getBytes()));
        pid = new String(Base64.encodeBase64(pid.getBytes()));
    }
    return return1;
}

From source file:com.brighttag.agathon.dao.zerg.ZergDaoModule.java

License:Apache License

@Provides
@Singleton/*www.ja v a 2  s .co  m*/
AsyncHttpClientConfig provideAsyncHttpClientConfig(
        @Named(ZERG_CONNECTION_TIMEOUT_PROPERTY) Duration connectionTimeout,
        @Named(ZERG_REQUEST_TIMEOUT_PROPERTY) Duration requestTimeout) {
    PeriodFormatter formatter = PeriodFormat.getDefault();
    log.info("Using connection timeout {} and request timeout {}",
            formatter.print(connectionTimeout.toPeriod()), formatter.print(requestTimeout.toPeriod()));
    return new AsyncHttpClientConfig.Builder().setAllowPoolingConnection(true)
            .setConnectionTimeoutInMs(Ints.saturatedCast(connectionTimeout.getMillis()))
            .setRequestTimeoutInMs(Ints.saturatedCast(requestTimeout.getMillis())).setFollowRedirects(true)
            .setMaximumNumberOfRedirects(3).setMaxRequestRetry(1).build();
}

From source file:com.chiorichan.Loader.java

License:Mozilla Public License

public static String getUptime() {
    Duration duration = new Duration(System.currentTimeMillis() - startTime);
    PeriodFormatter formatter = new PeriodFormatterBuilder().appendDays().appendSuffix(" Day(s) ").appendHours()
            .appendSuffix(" Hour(s) ").appendMinutes().appendSuffix(" Minute(s) ").appendSeconds()
            .appendSuffix(" Second(s)").toFormatter();
    return formatter.print(duration.toPeriod());
}

From source file:com.chiorichan.tasks.Timings.java

License:Open Source License

/**
 * Converts the input value into a human readable string, e.g., 0 Day(s) 3 Hour(s) 13 Minutes(s) 42 Second(s).
 *
 * @param seconds The duration in seconds
 * @return Human readable duration string
 *///from w  ww.j a v a 2 s  . c  o  m
public static String readoutDuration(Number seconds) {
    Duration duration = new Duration(seconds);
    PeriodFormatter formatter = new PeriodFormatterBuilder().appendDays().appendSuffix(" Day(s) ").appendHours()
            .appendSuffix(" Hour(s) ").appendMinutes().appendSuffix(" Minute(s) ").appendSeconds()
            .appendSuffix(" Second(s)").toFormatter();
    return formatter.print(duration.toPeriod());
}

From source file:com.chiorichan.utils.UtilSystem.java

License:Open Source License

public static String uptime() {
    Duration duration = new Duration(System.currentTimeMillis() - AppLoader.startTime);
    PeriodFormatter formatter = new PeriodFormatterBuilder().appendDays().appendSuffix(" Day(s) ").appendHours()
            .appendSuffix(" Hour(s) ").appendMinutes().appendSuffix(" Minute(s) ").appendSeconds()
            .appendSuffix(" Second(s)").toFormatter();
    return formatter.print(duration.toPeriod());
}

From source file:com.cloudhopper.commons.util.demo.UptimeMain.java

License:Apache License

public static void main(String[] args) {

    //Period period = new Period(uptime, PeriodType.standard().withYearsRemoved().withWeeksRemoved().withMonthsRemoved().withMillisRemoved());
    //MutablePeriod period = new Duration(uptime).toPeriod().toMutablePeriod();

    long uptime = UPTIME_56_SECS;

    // ah, ha -- this is super important -- need to normalize the period!
    PeriodType periodType = PeriodType.standard().withYearsRemoved().withMonthsRemoved().withWeeksRemoved()
            .withMillisRemoved();/*from w ww .  j a  va2  s. c  o m*/
    Period period = new Period(uptime).normalizedStandard(periodType);

    System.out.println("Uptime: " + uptime + " ms");
    System.out.println("Weeks: " + period.getWeeks());
    System.out.println("Days: " + period.getDays());
    System.out.println("Millis: " + period.getMillis() + " ms");

    // print out the uptime
    String uptimeStyleString = PeriodFormatterUtil.getStandardUptimeStyle().print(period);
    String linuxStyleString = PeriodFormatterUtil.getLinuxUptimeStyle().print(period);

    System.out.println(uptimeStyleString);
    System.out.println(linuxStyleString);

    PeriodFormatter fmt = new PeriodFormatterBuilder().printZeroNever().appendDays()
            .appendSuffix(" day ", " days ").appendHours().appendSuffix(" hours ").appendMinutes()
            .appendSuffix(" mins ").printZeroAlways().appendSeconds().appendSuffix(" secs ").toFormatter();

    String str0 = fmt.print(period);
    System.out.println(str0);

    String str1 = PeriodFormat.getDefault().print(period);
    System.out.println(str1);
}

From source file:com.ethercis.servicemanager.common.IsoDateJoda.java

License:Apache License

/**
 * Calculate the difference of given millis.
 * @param diffMillis The elapsed time//from  www  .ja v  a 2  s.c om
 * @param trimDateIfPossible true:
 * <pre> 
 * 3000->00:00:03
 * 380000->00:06:20
 * 5692439078->1581:13:59.078
 * </pre>
 * false: 
 * <pre> 
*   3000->P0000-00-00T00:00:03
*   5692439078->P0000-00-00T1581:13:59.078
 * </pre>
 * 
 * @return The ISO 8601 Period like "P3Y6M4DT12H30M17S"
 */
public static String getDifference(long diffMillis, boolean trimDateIfPossible) {
    if (diffMillis == 0)
        return "";
    Period period = new Period(diffMillis);
    /*
    PeriodFormatter myFormatter = new PeriodFormatterBuilder()
      .printZeroAlways()
      .appendYears()
      .appendSuffix(" year", " years")
      .appendSeparator(" and ")
      .appendMonths()
      .appendSuffix(" month", " months")
      .toFormatter();
    */

    /*if (true) */ {
        //      3000->P0000-00-00T00:00:03
        //      5692439078->P0000-00-00T1581:13:59.078
        PeriodFormatter formatter = ISOPeriodFormat.alternateExtended();
        String periodStr = formatter.print(period);
        if (trimDateIfPossible) {
            if (periodStr.startsWith("P0000-00-00T"))
                periodStr = periodStr.substring("P0000-00-00T".length());
        }
        return periodStr;
    }
    /*
    else {
    // 3000->PT3S
    // 5692439078->PT1581H13M59.078S
    return period.toString();
    }
    */
}

From source file:com.fatboyindustrial.gsonjodatime.PeriodConverter.java

License:Open Source License

/**
 * Gson invokes this call-back method during serialization when it encounters a field of the
 * specified type. <p>//from  w w  w  . j a v  a2  s  . c om
 *
 * In the implementation of this call-back method, you should consider invoking
 * {@link JsonSerializationContext#serialize(Object, Type)} method to create JsonElements for any
 * non-trivial field of the {@code src} object. However, you should never invoke it on the
 * {@code src} object itself since that will cause an infinite loop (Gson will call your
 * call-back method again).
 * @param src the object that needs to be converted to Json.
 * @param typeOfSrc the actual type (fully genericized version) of the source object.
 * @return a JsonElement corresponding to the specified object.
 */
@Override
public JsonElement serialize(Period src, Type typeOfSrc, JsonSerializationContext context) {
    final PeriodFormatter fmt = ISOPeriodFormat.standard();
    return new JsonPrimitive(fmt.print(src));
}

From source file:com.funambol.common.pim.utility.TimeUtils.java

License:Open Source License

/**
 * Returns the given minutes in iso 8601 duration format
 * @param minutes String//from w ww. j  ava2  s  . c  om
 * @return String
 */
public static String getIso8601Duration(String minutes) {

    if (minutes == null || minutes.equals("")) {
        return minutes;
    }

    int min = Integer.parseInt(minutes);

    if (min == -1) {
        return null;
    }

    long mills = min * 60L * 1000L;
    Duration d = new Duration(mills);

    PeriodFormatter formatter = ISOPeriodFormat.standard();
    return formatter.print(d.toPeriod());
}