Example usage for org.apache.commons.lang.time DateFormatUtils format

List of usage examples for org.apache.commons.lang.time DateFormatUtils format

Introduction

In this page you can find the example usage for org.apache.commons.lang.time DateFormatUtils format.

Prototype

public static String format(Date date, String pattern) 

Source Link

Document

Formats a date/time into a specific pattern.

Usage

From source file:org.oxymores.chronix.core.timedata.RunLog.java

public String getLine() {
    String res = "";
    res = String.format(//ww  w. j  a  va  2s  .c  o  m
            "%36s | %-20s | %-20s | %-20s | %-20s | %-20s | %-10s | %-30s | %-3s | %-14s | %-14s | %-14s | %-14s | %-15s | %-15s | %-10s | %-5s | %36s",
            this.id, this.placeName.substring(0, Math.min(19, placeName.length())), this.executionNodeName,
            chainName.substring(0, Math.min(19, chainName.length())),
            applicationName.substring(0, Math.min(19, applicationName.length())),
            activeNodeName.substring(0, Math.min(19, activeNodeName.length())), osAccount,
            whatWasRun == null ? "" : whatWasRun.substring(0, Math.min(29, whatWasRun.length())), resultCode,
            enteredPipeAt == null ? null : DateFormatUtils.format(enteredPipeAt, DATE_FORMAT),
            beganRunningAt == null ? null : DateFormatUtils.format(beganRunningAt, DATE_FORMAT),
            stoppedRunningAt == null ? null : DateFormatUtils.format(stoppedRunningAt, DATE_FORMAT),
            markedForUnAt == null ? null : DateFormatUtils.format(markedForUnAt, DATE_FORMAT),
            calendarName == null ? null : calendarName.substring(0, Math.min(14, calendarName.length())),
            calendarOccurrence == null ? null
                    : calendarOccurrence.substring(0, Math.min(19, calendarOccurrence.length())),
            logPath == null ? null : logPath.substring(0, Math.min(9, logPath.length())), visible,
            chainLaunchId);
    return res;
}

From source file:org.patientview.radar.web.pages.patient.ExistingPatientsListingPage.java

public ExistingPatientsListingPage() {

    DemographicsDataProvider demographicsDataProvider = new DemographicsDataProvider(demographicsManager,
            RadarSecuredSession.get().getUser());

    // List existing patients
    add(new DataView<Patient>("patients", demographicsDataProvider) {
        @Override//from w  ww  .jav a  2s  . co  m
        protected void populateItem(Item<Patient> item) {
            // Populate fields
            Patient patient = item.getModelObject();

            // TODO: this is terrible as we need to check disease groups to know where to send it - well done abul
            // TODO: need to implement a patient base page with the constructors needed and then have an enum map
            // TODO: that maps disease ids to the page they need to go to so we dont need all these ifs
            if (patient.getDiseaseGroup() != null
                    && (patient.getDiseaseGroup().getId().equals(DiseaseGroup.SRNS_DISEASE_GROUP_ID)
                            || patient.getDiseaseGroup().getId().equals(DiseaseGroup.MPGN_DISEASEGROUP_ID))) {
                item.add(new BookmarkablePageLink<SrnsPatientPage>("edit", SrnsPatientPage.class,
                        SrnsPatientPage.getParameters(patient)));
            } else if (patient.getDiseaseGroup() != null
                    && patient.getDiseaseGroup().getId().equals(DiseaseGroup.ALPORT_DISEASEGROUP_ID)) {
                item.add(new BookmarkablePageLink<AlportPatientPage>("edit", AlportPatientPage.class,
                        AlportPatientPage.getPageParameters(patient)));
            } else if (patient.getDiseaseGroup() != null
                    && patient.getDiseaseGroup().getId().equals(DiseaseGroup.HNF1B_DISEASEGROUP_ID)) {
                item.add(new BookmarkablePageLink<AlportPatientPage>("edit", HNF1BPatientPage.class,
                        HNF1BPatientPage.getPageParameters(patient)));
            } else {
                item.add(new BookmarkablePageLink<GenericPatientPage>("edit", GenericPatientPage.class,
                        GenericPatientPage.getPageParameters(patient)));
            }

            item.add(new Label("surname"), new Label("forename"));
            item.add(DateLabel.forDatePattern("dob", RadarApplication.DATE_PATTERN2));
            item.add(new Label("id", Long.toString(patient.getRadarNo())));

            String diseaseGroup = "";
            if (patient.getDiseaseGroup() != null) {
                diseaseGroup = patient.getDiseaseGroup().getId();
            }

            item.add(new Label("diagnosis", diseaseGroup));

            item.add(new Label("nhsNumber", patient.getNhsno()).setEscapeModelStrings(false));
            item.add(new Label("hospitalnumber"));
            item.add(DateLabel.forDatePattern("dateReg", RadarApplication.DATE_PATTERN2));
            item.add(new Label("status.abbreviation",
                    patient.getStatusModel() != null ? patient.getStatusModel().getAbbreviation() : ""));
            item.add(new Label("renalUnit.name"));

            item.add(new Label("rrtModalityEunm"));
            DemographicsUserDetail demographicsUserDetail = demographicsManager
                    .getDemographicsUserDetail(patient.getNhsno(), patient.getUnitcode());

            item.add(new Label("lastverificationdate",
                    formatDate(demographicsUserDetail.getLastverificationdate())));
            item.add(new Label("email", patient.getEmailAddress()));

            item.add(new Label("lastlogon", formatDate(demographicsUserDetail.getLastlogon())));
            item.add(
                    new Label("accountlocked", "" + (demographicsUserDetail.isAccountlocked() ? "Yes" : "No")));
        }

        private String formatDate(Date date) {
            return date == null ? "" : DateFormatUtils.format(date, RadarApplication.DATE_PATTERN2);
        }
    });
}

From source file:org.projectforge.plugins.poll.event.PollEventDO.java

/**
 * @see org.projectforge.core.AbstractBaseDO#toString()
 *///from  ww  w.j av  a 2s .c  o  m
@Override
public String toString() {
    final String pattern = DateFormats.getFormatString(DateFormatType.TIMESTAMP_MINUTES);
    return DateFormatUtils.format(startDate.getTime(), pattern) + " - "
            + DateFormatUtils.format(endDate.getTime(), pattern);
}

From source file:org.projectforge.plugins.poll.event.PollEventEntryPanel.java

/**
 * @param id/*from w  ww .  j ava2 s .  com*/
 * @param model
 */
public PollEventEntryPanel(final String id, final PollEventDO poll) {
    super(id);

    final DateTime start = new DateTime(poll.getStartDate());
    final DateTime end = new DateTime(poll.getEndDate());

    final String pattern = DateFormats.getFormatString(DateFormatType.TIMESTAMP_MINUTES);
    add(new Label("startDate", "Start: " + DateFormatUtils.format(start.getMillis(), pattern)));
    add(new Label("endDate", "Ende: " + DateFormatUtils.format(end.getMillis(), pattern)));

    final AjaxIconButtonPanel iconButton = new AjaxIconButtonPanel("delete", IconType.REMOVE) {
        private static final long serialVersionUID = -2464985733387718199L;

        /**
         * @see org.projectforge.web.wicket.flowlayout.AjaxIconButtonPanel#onSubmit(org.apache.wicket.ajax.AjaxRequestTarget)
         */
        @Override
        protected void onSubmit(final AjaxRequestTarget target) {
            onDeleteClick(target);
        }
    };
    add(iconButton);
}

From source file:org.soaplab.admin.ExploreStorage.java

/*************************************************************************
 * Print job info./*  w  w  w .jav  a2s  .co  m*/
 *************************************************************************/
static void jobInfo(PersistentStorage storage, String jobId, String title) throws SoaplabException {
    JobState state = storage.getJobState(jobId);
    msgln(title + ": " + jobId + " (" + state + ")");
    msgln("\tcreated: " + DateFormatUtils.format(state.getCreated(), SoaplabConstants.DT_FORMAT));
    msgln("\tstarted: " + DateFormatUtils.format(state.getStarted(), SoaplabConstants.DT_FORMAT));
    msgln("\tended:   " + DateFormatUtils.format(state.getEnded(), SoaplabConstants.DT_FORMAT));
    msgln("\telapsed: " + DurationFormatUtils.formatDurationHMS(state.getElapsed()));
    msgln("\tlast event: " + state.getLastEvent());
}

From source file:org.soaplab.clients.CmdLineClient.java

/*************************************************************************
 *
 * Entry point.../*from  w w  w.  j  a  v a2 s .  c  o  m*/
 *
 *************************************************************************/
public static void main(String[] args) {
    try {
        BaseCmdLine cmd = getCmdLine(args, CmdLineClient.class);

        // service location and protocol parameters
        ServiceLocator locator = InputUtils.getServiceLocator(cmd);

        // if we have a -job we may not need the -name (this is
        // just a hack, but not an important one, so who cares...)
        String jobId = cmd.getParam("-job");
        if (StringUtils.isNotEmpty(jobId) && StringUtils.isEmpty(locator.getServiceName())) {
            int posBegToken = jobId.indexOf("[");
            int posEndToken = jobId.indexOf("]");
            if (posBegToken > -1 && posEndToken > posBegToken) {
                locator.setServiceName(jobId.substring(posBegToken + 1, posEndToken));
            }
        }

        // list requests
        boolean listAll = cmd.hasOption("-l");
        boolean listServices = cmd.hasOption("-la");
        boolean listServicesWithDesc = cmd.hasOption("-lad");
        boolean listCategories = cmd.hasOption("-lc");
        String category = cmd.getParam("-category");
        String listSaveFile = cmd.getParam("-sl");

        if (cmd.params.length > 0) {
            // there are also non-list requests so a service name
            // is mandatory

            // where is the service
            if (StringUtils.isEmpty(locator.getServiceName())) {
                System.err.println("Service name must be given. Use '-name' or '-e'.");
                System.exit(1);
            }
        }

        SoaplabBaseClient client = new SoaplabBaseClient(locator);

        //
        // deal with list requests
        //

        PrintWriter pw = null;
        if (listSaveFile != null) {
            pw = new PrintWriter(listSaveFile);
        }

        if (listServices) {
            title("Available analyses:", pw);
            for (String analysis : client.getAvailableAnalyses())
                msgln(analysis, pw);
        }

        if (listServicesWithDesc) {
            title("Available analyses (with descriptions):", pw);
            SoaplabMap mapWithDesc = client.getAvailableAnalysesWithDescription();
            for (MapEntry entry : mapWithDesc.getEntries()) {
                msgln(entry.getKey(), pw);
                msgln("\t" + entry.getObjectValue(), pw);
            }
        }

        if (listCategories) {
            title("Available categories:", pw);
            for (String categ : client.getAvailableCategories())
                msgln(categ, pw);
        }

        if (listAll) {
            title("Available categories and analyses:", pw);
            for (String categ : client.getAvailableCategories()) {
                msgln(categ, pw);
                for (String analysis : client.getAvailableAnalysesInCategory(categ))
                    msgln("\t" + analysis, pw);
            }
        }

        if (category != null) {
            title("Category: " + category, pw);
            for (String analysis : client.getAvailableAnalysesInCategory(category))
                msgln(analysis, pw);
        }

        IOUtils.closeQuietly(pw);

        //
        // give me service's metadata
        //

        if (cmd.hasOption("-d")) {
            msgln(client.describe());
        }

        if (cmd.hasOption("-i") || cmd.hasOption("-ii")) {
            SoaplabMap[] attrs = client.getInputSpec();
            InputUtils.formatInputMetadata(SoaplabMap.toMaps(attrs), System.out, cmd.hasOption("-ii"), verbose);
        }

        if (cmd.hasOption("-o") || cmd.hasOption("-oo")) {
            SoaplabMap[] attrs = client.getResultSpec();
            InputUtils.formatOutputMetadata(SoaplabMap.toMaps(attrs), System.out, cmd.hasOption("-oo"),
                    verbose);
        }

        if (cmd.hasOption("-t")) {
            Map<String, Object> aType = SoaplabMap.toMap(client.getAnalysisType());
            title("Analysis properties:");
            if (aType != null) {
                for (Iterator<String> it = aType.keySet().iterator(); it.hasNext();) {
                    String key = it.next();
                    msgln(key + " => " + aType.get(key));
                }
                msgln("");
            }
        }

        //
        // deal with a job (creation, invocation, waiting for, killing...)
        //
        String jobIdFile = cmd.getParam("-jp");
        boolean createJob = cmd.hasOption("-j");
        boolean runJob = cmd.hasOption("-x");
        boolean waitForJob = cmd.hasOption("-w");
        boolean killJob = cmd.hasOption("-k");

        // collect inputs from the command line
        // (unless the job had been already created)
        SoaplabMap inputs = null;
        if (jobId == null && (createJob || runJob || waitForJob)) {
            inputs = SoaplabMap
                    .fromMap(InputUtils.collectInputs(cmd, SoaplabMap.toMaps(client.getInputSpec())));
        }

        //
        // read the rest of the command-line, including the result
        // names - so we can check that there are no unrecognized
        // parameters before we start any job
        //
        boolean getStatus = cmd.hasOption("-s");
        boolean getTimes = cmd.hasOption("-c");
        boolean getLastEvent = cmd.hasOption("-le");
        boolean doClean = cmd.hasOption("-clean");
        boolean getResultInfo = cmd.hasOption("-ri");
        boolean getResults = cmd.hasOption("-r");
        boolean printBinary = cmd.hasOption("-bp");
        boolean saveResults = cmd.hasOption("-sr");

        String[] resultNames = null;
        if (getResults) {
            // collect names of the results (from the command-line)
            resultNames = ResultUtils.collectResultNames(cmd, SoaplabMap.toMaps(client.getResultSpec()));
        }

        // any unrecognized parameter/option on the command-line?
        if (cmd.params.length > 0) {
            msg("Unrecognized or unused arguments (perhaps an \"action\" option missing?): ");
            for (String arg : cmd.params)
                msg(arg + " ");
            msgln("");
            System.exit(1);
        }

        // when we do not have a job ID from a previous invocation
        if (jobId == null) {
            if (waitForJob) {
                jobId = client.createAndRun(inputs);
                saveJobId(jobId, jobIdFile);
                client.waitFor(jobId);
            } else if (runJob) {
                jobId = client.createAndRun(inputs);
                saveJobId(jobId, jobIdFile);
            } else if (createJob) {
                jobId = client.createJob(inputs);
                saveJobId(jobId, jobIdFile);
            }

            // when we use a previously stored job ID
        } else {
            if (waitForJob) {
                client.waitFor(jobId);
            } else if (runJob) {
                client.run(jobId);
            } else if (killJob) {
                client.terminate(jobId);
            }
        }

        //
        // deal with the job status, characteristics and events
        // (makes sense only if we have a jobID)
        //
        if (jobId != null) {
            if (getStatus) {
                String status = client.getStatus(jobId);
                title("Status of job: " + jobId);
                msgln(status);
            }
            if (getTimes) {
                SoaplabMap times = client.getCharacteristics(jobId);
                title("Characteristics of job: " + jobId);
                Long millis = getLong(times.get(SoaplabConstants.TIME_CREATED));
                if (millis != null)
                    msgln("\tCreated: "
                            + DateFormatUtils.format(millis.longValue(), SoaplabConstants.DT_FORMAT));
                millis = getLong(times.get(SoaplabConstants.TIME_STARTED));
                if (millis != null)
                    msgln("\tStarted: "
                            + DateFormatUtils.format(millis.longValue(), SoaplabConstants.DT_FORMAT));
                millis = getLong(times.get(SoaplabConstants.TIME_ENDED));
                if (millis != null)
                    msgln("\tEnded:   "
                            + DateFormatUtils.format(millis.longValue(), SoaplabConstants.DT_FORMAT));
                Long ms = getLong(times.get(SoaplabConstants.TIME_ELAPSED));
                if (ms != null)
                    msgln("\tElapsed: " + DurationFormatUtils.formatDurationHMS(ms));
            }
            if (getLastEvent) {
                String lastEvent = client.getLastEvent(jobId);
                title("Last event reported for job: " + jobId);
                msgln(lastEvent);
            }
        }

        //
        // cleaning it all...
        // (does not make sense together with other options, except -job)
        //
        if (jobId != null && doClean)
            client.destroy(jobId);

        //
        // deal with results (makes sense only if we have a job ID)
        //
        if (jobId != null) {
            if (getResultInfo) {
                title("Results info for job: " + jobId);
                ResultUtils.formatResultInfo(SoaplabMap.toStringMaps(client.getResultsInfo(jobId)), System.out);
            }

            if (getResults || saveResults) {

                // getting results from the service (all or just some)
                Map<String, Object> results;
                if (resultNames.length == 0)
                    results = SoaplabMap.toMap(client.getResults(jobId));
                else
                    results = SoaplabMap.toMap(client.getSomeResults(jobId, resultNames));
                for (Iterator<String> it = results.keySet().iterator(); it.hasNext();) {
                    String resultName = it.next();
                    title(resultName);
                    String[] files = ResultUtils.handleResult(results.get(resultName), resultName,
                            (printBinary && !saveResults ? null : jobId), saveResults, System.out);
                    if (files != null) {
                        for (int i = 0; i < files.length; i++)
                            msgln("(written into: " + files[i] + ")");
                    }
                }
            }
        }

        exit(0);

    } catch (Throwable e) {
        processErrorAndExit(e);
    }
}

From source file:org.soaplab.services.Reporter.java

/******************************************************************************
 * Create a 'report' result from data reported so far, and from
 * the current job status. <p>/*from  www  . jav a2s  . co  m*/
 *
 * Note that a report can be created more than once, potentially
 * with richer property set each time. <p>
 *
 * TBD: how to deal with BIG reports - with memory problem...
 ******************************************************************************/
protected String createReportResult() {

    // 1) create "termination status"
    StringBuilder buf = new StringBuilder();
    buf.append("Summary:\n\tCompleted: ");
    if (state.isSuccessful())
        if (errBuf.length() > 0)
            buf.append("Maybe\n");
        else
            buf.append("Successfully\n");
    else if (state.isErroneous())
        buf.append("Erroneously\n");
    else if (state.isInProgress())
        buf.append("...in progress\n");
    else
        buf.append("Unknown\n");
    String ts = state.formatDetailedState();
    if (ts != null)
        buf.append("\tTermination status: " + ts + "\n");
    long started = state.getStarted();
    if (started > 0) {
        buf.append("\tStarted:   ");
        buf.append(DateFormatUtils.format(started, SoaplabConstants.DT_FORMAT));
        buf.append("\n");
    }
    long ended = state.getEnded();
    if (ended > 0) {
        buf.append("\tEnded:     ");
        buf.append(DateFormatUtils.format(ended, SoaplabConstants.DT_FORMAT));
        buf.append("\n");
    }
    long elapsed = state.getElapsed();
    if (elapsed > 0) {
        buf.append("\tDuration:  ");
        buf.append(DurationFormatUtils.formatDurationHMS(elapsed));
        buf.append("\n");
    }

    // 2) create report from report properties
    if (reportProps.size() > 0 || errBuf.length() > 0 || msgBuf.length() > 0)
        buf.append("Report:\n");
    buf.append(new String(reportProperties()));

    // 3) add the main and error messages
    if (errBuf.length() > 0) {
        buf.append(errBuf);
        buf.append("\n");
    }
    if (msgBuf.length() > 0) {
        buf.append(msgBuf);
        buf.append("\n");
    }

    // 4) add contents of registered files
    for (Enumeration<String> en = fileProps.keys(); en.hasMoreElements();) {
        String key = en.nextElement();
        File file = fileProps.get(key);
        buf.append(key);
        buf.append(":\n");
        buf.append(tryFile(file));
        buf.append("\n");
    }

    return buf.toString();
}

From source file:org.soaplab.services.testing.TestingJob.java

/**************************************************************************
 * Really nothing here...//from  w  w  w . j av a 2s.co  m
 **************************************************************************/
protected void realRun() throws SoaplabException {

    log.info("Testing job run in progress.");
    reporter.setResult("result",
            "Current time is " + DateFormatUtils.format(new Date(), SoaplabConstants.DT_FORMAT));
}

From source file:org.sonar.core.permission.PermissionDao.java

private String generateTemplateKee(String name, Date timeStamp) {
    if (PermissionTemplateDto.DEFAULT.getName().equals(name)) {
        return PermissionTemplateDto.DEFAULT.getKee();
    }/*  www.j a v a  2s .  c  o  m*/
    String normalizedName = Normalizer.normalize(name, Normalizer.Form.NFD).replaceAll("[^\\p{ASCII}]", "")
            .replace(" ", "_");
    return normalizedName.toLowerCase() + "_" + DateFormatUtils.format(timeStamp, "yyyyMMdd_HHmmss");
}

From source file:org.talend.cwm.db.connection.MdmWebserviceConnection.java

private String getTechXSDFolderName() {
    String techXSDFolderName = DqRepositoryViewService
            .createTechnicalName(XSD_SUFIX + DateFormatUtils.format(new Date(), "yyyyMMddHHmmss"));//$NON-NLS-1$
    IFolder xsdFolder = ResourceManager.getMDMConnectionFolder().getFolder(XSD_SUFIX);
    if (xsdFolder.getFolder(techXSDFolderName).exists()) {
        try {/*w w  w  .  j  a  va 2  s .c o  m*/
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return getTechXSDFolderName();
    }
    return techXSDFolderName;
}