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.eclipse.gyrex.logback.config.internal.LogbackConfigGenerator.java

public File generateConfig() {
    // get state location
    if (!parentFolder.isDirectory() && !parentFolder.mkdirs()) {
        throw new IllegalStateException(
                String.format("Unable to create configs directory (%s).", parentFolder));
    }/*w  w w . java  2  s . c o m*/

    // save file
    final File configFile = new File(parentFolder,
            String.format("logback.%s.xml", DateFormatUtils.format(lastModified, "yyyyMMdd-HHmmssSSS")));
    OutputStream outputStream = null;
    XMLStreamWriter xmlStreamWriter = null;
    try {
        outputStream = new BufferedOutputStream(FileUtils.openOutputStream(configFile));
        final XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
        xmlStreamWriter = outputFactory.createXMLStreamWriter(outputStream, CharEncoding.UTF_8);
        // try to format the output
        try {
            final Class<?> clazz = getClass().getClassLoader()
                    .loadClass("com.sun.xml.internal.txw2.output.IndentingXMLStreamWriter");
            xmlStreamWriter = (XMLStreamWriter) clazz.getConstructor(XMLStreamWriter.class)
                    .newInstance(xmlStreamWriter);
        } catch (final Exception e) {
            // ignore
        }
        config.toXml(xmlStreamWriter);
        xmlStreamWriter.flush();
    } catch (final IOException e) {
        throw new IllegalStateException(
                String.format("Unable to create config file (%s).", ExceptionUtils.getRootCauseMessage(e)), e);
    } catch (final XMLStreamException e) {
        throw new IllegalStateException(
                String.format("Error writing config (%s).", ExceptionUtils.getRootCauseMessage(e)), e);
    } finally {
        if (null != xmlStreamWriter) {
            try {
                xmlStreamWriter.close();
            } catch (final Exception e) {
                // ignore
            }
        }
        IOUtils.closeQuietly(outputStream);
    }

    // cleanup directory
    removeOldFiles(parentFolder);

    return configFile;
}

From source file:org.eclipse.jubula.client.core.functions.FormateDateEvaluator.java

/**
 * /* w  w  w .j a  v a  2  s  .c  o  m*/
 * {@inheritDoc}
 */
public String evaluate(String[] arguments) throws InvalidDataException {
    validateParamCount(arguments, 2);
    try {
        Long dateTime = Long.valueOf(arguments[0]);
        if (dateTime < 0) {
            throw new InvalidDataException("value to small: " + dateTime, //$NON-NLS-1$
                    MessageIDs.E_TOO_SMALL_VALUE);
        }
        Date date = new Date(dateTime);

        return DateFormatUtils.format(date, arguments[1]);
    } catch (NumberFormatException e) {
        throw new InvalidDataException("not an integer: " + arguments[0], //$NON-NLS-1$
                MessageIDs.E_BAD_INT);

    }
}

From source file:org.eclipse.wb.internal.core.editor.errors.report2.ZipFileErrorReport.java

/**
 * Compress the contents of report into single zip file.
 *///from   ww  w .  j ava2s  .  c  om
private String createZipReport(IProgressMonitor monitor) throws Exception {
    monitor.beginTask(Messages.ZipFileErrorReport_taskTitle, m_entries.size());
    // store zip as temp file
    // prepare temp dir and file
    File tempDir = getReportTemporaryDirectory();
    String fileName = "report-" + DateFormatUtils.format(new Date(), "yyyyMMdd-HHmmss") + ".zip";
    File tempFile = new File(tempDir, fileName);
    tempFile.deleteOnExit();
    // create stream
    ZipOutputStream zipStream = null;
    try {
        zipStream = new ZipOutputStream(new FileOutputStream(tempFile));
        zipStream.setLevel(9);
        // compress the files
        for (IReportEntry reportInfo : m_entries) {
            try {
                reportInfo.write(zipStream);
            } catch (Throwable e) {
                DesignerPlugin.log(e);
            }
        }
    } finally {
        IOUtils.closeQuietly(zipStream);
    }
    return tempFile.getAbsolutePath();
}

From source file:org.fao.geonet.guiservices.versioning.Get.java

private Element xml(final List<MetadataAction> list, final Element params) throws BadParameterEx {
    Element root = new Element("logentries");
    Document doc = new Document(root);
    doc.setRootElement(root);/* ww w  . j ava  2 s . c o m*/
    Element totalCount = new Element("totalcount").setText(String.valueOf(list.size()));
    doc.getRootElement().addContent(totalCount);
    for (MetadataAction metadataAction : getSmallerList(list, params)) {
        Element entry = new Element("entry");
        entry.addContent(new Element(DATE)
                .setText(DateFormatUtils.format(metadataAction.getDate(), "dd-MM-yyyy HH:mm:ss")));
        entry.addContent(new Element(USERNAME).setText(metadataAction.getUsername()));
        entry.addContent(new Element(IP).setText(metadataAction.getIp()));
        entry.addContent(new Element(ACTION).setText(metadataAction.translatedAction()));
        entry.addContent(new Element(SUBJECT).setText(metadataAction.translatedSubject()));
        entry.addContent(new Element(ID).setText(String.valueOf(metadataAction.getId())));
        entry.addContent(new Element(TITLE).setText(metadataAction.getTitle()));
        doc.getRootElement().addContent(entry);
    }
    return doc.detachRootElement();
}

From source file:org.fenixedu.academic.servlet.taglib.sop.examsMapNew.renderers.ExamsMapContentRenderer.java

@Override
public StringBuilder renderDayContents(ExamsMapSlot examsMapSlot, Integer year1, Integer year2, String typeUser,
        PageContext pageContext) {/*from   w  w  w . jav  a  2s  . co m*/
    StringBuilder strBuffer = new StringBuilder();

    for (int i = 0; i < examsMapSlot.getExams().size(); i++) {
        InfoExam infoExam = (InfoExam) examsMapSlot.getExams().get(i);
        Integer curicularYear = infoExam.getInfoExecutionCourse().getCurricularYear();

        if (curicularYear.equals(year1) || curicularYear.equals(year2)) {
            boolean isOnValidWeekDay = onValidWeekDay(infoExam);

            InfoExecutionCourse infoExecutionCourse = infoExam.getInfoExecutionCourse();
            String courseInitials = infoExam.getInfoExecutionCourse().getSigla();

            if (typeUser.equals("sop")) {
                strBuffer.append("<a href='showExamsManagement.do?method=edit&amp;"
                        + PresentationConstants.EXECUTION_COURSE_OID + "=" + infoExecutionCourse.getExternalId()
                        + "&amp;" + PresentationConstants.EXECUTION_PERIOD_OID + "="
                        + infoExecutionCourse.getInfoExecutionPeriod().getExternalId() + "&amp;"
                        + PresentationConstants.EXECUTION_DEGREE_OID + "="
                        + examsMap.getInfoExecutionDegree().getExternalId() + "&amp;"
                        + PresentationConstants.CURRICULAR_YEAR_OID + "=" + curicularYear.toString() + "&amp;"
                        + PresentationConstants.EXAM_OID + "=" + infoExam.getExternalId() + "'>");
                if (isOnValidWeekDay) {
                    strBuffer.append(courseInitials);
                } else {
                    strBuffer.append("<span class='redtxt'>" + courseInitials + "</span>");
                }

            } else if (typeUser.equals("public")) {

                String siteUrl = infoExecutionCourse.getExecutionCourse().getSiteUrl();
                siteUrl = siteUrl == null ? "#" : siteUrl;
                strBuffer.append(GenericChecksumRewriter.NO_CHECKSUM_PREFIX);
                strBuffer.append("<a href=\"");
                strBuffer.append(siteUrl);
                strBuffer.append("\">");
                strBuffer.append(courseInitials);
            }

            strBuffer.append("</a>");
            if (infoExam.getBeginning() != null) {
                boolean isAtValidHour = atValidHour(infoExam);
                String hoursText = infoExam.getBeginning().get(Calendar.HOUR_OF_DAY) + "h"
                        + DateFormatUtils.format(infoExam.getBeginning().getTime(), "mm");
                strBuffer.append(" ");
                strBuffer.append(getMessageResource(pageContext, "public.degree.information.label.as"));
                strBuffer.append(" ");

                if (isAtValidHour || !typeUser.equals("sop")) {
                    strBuffer.append(hoursText);
                } else {
                    strBuffer.append("<span class='redtxt'>" + hoursText + "</span>");
                }
            }

            strBuffer.append("<br />");
        }
    }

    strBuffer.append("<br />");

    return strBuffer;
}

From source file:org.fenixedu.academic.ui.struts.action.publico.RoomSiteViewerDispatchAction.java

public ActionForward roomViewer(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    String roomId = request.getParameter("roomId");
    String roomName = request.getParameter("roomName");
    if (roomId == null) {
        roomId = (String) request.getAttribute("roomId");
    }/*w w w  .  j  av a  2 s  .co m*/
    if (roomName == null) {
        roomName = (String) request.getAttribute("roomName");

    }
    request.setAttribute("roomName", roomName);
    request.setAttribute("roomId", roomId);
    RoomKey roomKey = null;
    Space room = null;
    if (roomName != null || roomId != null) {
        if (roomName != null) {
            roomKey = new RoomKey(roomName);
        }
        if (roomId != null) {
            room = FenixFramework.getDomainObject(roomId);
            if (!FenixFramework.isDomainObjectValid(room)) {
                room = null;
            }
        }
        InfoSiteRoomTimeTable bodyComponent = new InfoSiteRoomTimeTable();
        DynaActionForm indexForm = (DynaActionForm) form;
        Integer indexWeek = (Integer) indexForm.get("indexWeek");
        // Integer executionPeriodID = (Integer)
        // indexForm.get("selectedExecutionPeriodID");
        String executionPeriodIDString = request.getParameter("selectedExecutionPeriodID");
        if (executionPeriodIDString == null) {
            executionPeriodIDString = (String) request.getAttribute("selectedExecutionPeriodID");
        }
        String executionPeriodID = (executionPeriodIDString != null) ? executionPeriodIDString : null;
        if (executionPeriodID == null) {
            try {
                // executionPeriodID = (Integer)
                // indexForm.get("selectedExecutionPeriodID");
                executionPeriodID = indexForm.get("selectedExecutionPeriodID").equals("") ? null
                        : (String) indexForm.get("selectedExecutionPeriodID");
            } catch (IllegalArgumentException ex) {
            }
        }
        Calendar today = new DateMidnight().toCalendar(null);
        ArrayList weeks = new ArrayList();

        InfoExecutionPeriod executionPeriod;
        if (executionPeriodID == null) {
            executionPeriod = ReadCurrentExecutionPeriod.run();
            executionPeriodID = executionPeriod.getExternalId();
            try {
                indexForm.set("selectedExecutionPeriodID", executionPeriod.getExternalId().toString());
            } catch (IllegalArgumentException ex) {
            }
        } else {
            executionPeriod = ReadExecutionPeriodByOID.run(executionPeriodID);
        }

        // weeks
        Calendar begin = Calendar.getInstance();
        begin.setTime(executionPeriod.getBeginDate());
        Calendar end = Calendar.getInstance();
        end.setTime(executionPeriod.getEndDate());
        ArrayList weeksLabelValueList = new ArrayList();
        begin.add(Calendar.DATE, Calendar.MONDAY - begin.get(Calendar.DAY_OF_WEEK));
        int i = 0;
        boolean selectedWeek = false;
        while (begin.before(end) || begin.before(Calendar.getInstance())) {
            Calendar day = Calendar.getInstance();
            day.setTimeInMillis(begin.getTimeInMillis());
            weeks.add(day);
            String beginWeekString = DateFormatUtils.format(begin.getTime(), "dd/MM/yyyy");
            begin.add(Calendar.DATE, 5);
            String endWeekString = DateFormatUtils.format(begin.getTime(), "dd/MM/yyyy");
            weeksLabelValueList.add(
                    new LabelValueBean(beginWeekString + " - " + endWeekString, new Integer(i).toString()));
            begin.add(Calendar.DATE, 2);
            if (!selectedWeek && indexWeek == null && Calendar.getInstance().before(begin)) {
                indexForm.set("indexWeek", new Integer(i));
                selectedWeek = true;
            }
            i++;
        }

        final Collection<ExecutionSemester> executionSemesters = rootDomainObject.getExecutionPeriodsSet();
        final List<LabelValueBean> executionPeriodLabelValueBeans = new ArrayList<LabelValueBean>();
        for (final ExecutionSemester ep : executionSemesters) {
            if (ep.getState().equals(PeriodState.OPEN) || ep.getState().equals(PeriodState.CURRENT)) {
                executionPeriodLabelValueBeans.add(new LabelValueBean(
                        ep.getName() + " " + ep.getExecutionYear().getYear(), ep.getExternalId().toString()));
            }
        }
        request.setAttribute(PresentationConstants.LABELLIST_EXECUTIONPERIOD, executionPeriodLabelValueBeans);

        request.setAttribute(PresentationConstants.LABELLIST_WEEKS, weeksLabelValueList);
        if (indexWeek != null) {
            final int xpto = indexWeek.intValue();
            if (xpto < weeks.size()) {
                today = (Calendar) weeks.get(xpto);
            } else {
                today = (Calendar) weeks.iterator().next();
                indexForm.set("indexWeek", new Integer(0));
            }
        }

        try {
            InfoSiteRoomTimeTable component = null;
            if (room != null) {
                component = run(room, today, executionPeriodID);
            } else {
                if (roomKey != null) {
                    component = run(roomKey, today, executionPeriodID);
                }
            }
            request.setAttribute("component", component);
        } catch (NonExistingServiceException e) {
            throw new NonExistingActionException(e);
        } catch (FenixServiceException e) {
            throw new FenixActionException(e);
        }
        return mapping.findForward("roomViewer");
    }
    throw new FenixActionException();

}

From source file:org.frat.common.security.authc.SessionTimeoutAuthenticationFilter.java

@Override
protected void saveRequestAndRedirectToLogin(ServletRequest request, ServletResponse response)
        throws IOException {
    saveRequest(request);/*w ww  .  ja  v a 2  s. com*/
    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse res = (HttpServletResponse) response;
    if (WebUtil.isAjaxRequest(req)) {
        ObjectMapper objectMapper = new ObjectMapper();
        res.setContentType("application/json;charset=UTF-8");
        res.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
        ResultDto error = new ResultDto();
        error.setCode(ResultCode.SESSION_TIME_OUT);
        error.setMessage(MessageUtil.getMessage(SESSION_TIMEOUT_MSG));
        objectMapper.writeValue(response.getWriter(), error);
        LOGGER.debug("session time out for ajax request:{}", req.getRequestURI());
    } else {
        LOGGER.debug("session time out for request:{}", req.getRequestURI());
        req.getSession().setAttribute(SESSION_TIMEOUT, true);
        redirectToLogin(request, response);
    }
    HttpSession session = req.getSession(false);
    if (session != null) {
        LOGGER.debug(
                "session time out with id:"
                        + " {}, is sesion new:{}, started: {}, last accessed: {}, request headers: {}",
                session.getId(), session.isNew(),
                DateFormatUtils.format(session.getCreationTime(), DATE_FORMAT),
                DateFormatUtils.format(session.getLastAccessedTime(), DATE_FORMAT), getHeaderString(request));
    } else {
        LOGGER.debug("session time out, no session available for current request");
    }
}

From source file:org.hibernate.search.test.performance.scenario.TestReporter.java

private static void printSummary(TestContext ctx, PrintWriter out) {
    long freeMemory2 = -1;
    long totalMemory2 = -1;
    if (MEASURE_MEMORY) {
        runGarbageCollectorAndWait();/*from w w w .j a va2 s  . com*/
        freeMemory2 = Runtime.getRuntime().freeMemory();
        totalMemory2 = Runtime.getRuntime().totalMemory();
    }

    long totalNanos = ctx.stopTime - ctx.startTime;
    long totalMilis = TimeUnit.MILLISECONDS.convert(totalNanos, TimeUnit.NANOSECONDS);

    out.println("");
    out.println("SUMMARY");
    out.println("    Name   : " + ctx.scenario.getClass().getSimpleName());
    out.println("    Date   : " + DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm"));
    out.println("");
    out.println("    Measured time (HH:mm:ss.SSS)");
    out.println("        MEASURED TASKS : " + DurationFormatUtils.formatDuration(totalMilis, "HH:mm:ss.SSS"));
    out.println("        init database  : "
            + DurationFormatUtils.formatDuration(ctx.scenario.initDatabaseStopWatch.getTime(), "HH:mm:ss.SSS"));
    out.println("        init index     : "
            + DurationFormatUtils.formatDuration(ctx.scenario.initIndexStopWatch.getTime(), "HH:mm:ss.SSS"));
    out.println("        warmup phase   : "
            + DurationFormatUtils.formatDuration(ctx.scenario.warmupStopWatch.getTime(), "HH:mm:ss.SSS"));

    if (MEASURE_MEMORY) {
        out.println("");
        out.println("    Memory usage (total-free):");
        out.println("        before : " + toMB(ctx.totalMemory - ctx.freeMemory));
        out.println("        after  : " + toMB(totalMemory2 - freeMemory2));
    }
}

From source file:org.hibernate.search.test.performance.scenario.TestReporter.java

private static PrintStream createOutputStream(String testScenarioName) {
    try {//from w w w . ja  v  a 2 s .  com
        Path targetDir = getTargetDir();
        String reportFileName = "report-" + testScenarioName + "-"
                + DateFormatUtils.format(new Date(), "yyyy-MM-dd-HH'h'mm'm'") + ".txt";
        Path reportFile = targetDir.resolve(reportFileName);

        final OutputStream std = System.out;
        final OutputStream file = new PrintStream(new FileOutputStream(reportFile.toFile()), true, "UTF-8");
        final OutputStream stream = new OutputStream() {

            @Override
            public void write(int b) throws IOException {
                std.write(b);
                file.write(b);
            }

            @Override
            public void flush() throws IOException {
                std.flush();
                file.flush();
            }

            @Override
            public void close() throws IOException {
                file.close();
            }
        };
        return new PrintStream(stream, false, "UTF-8");
    } catch (FileNotFoundException | UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.hibernate.search.test.performance.util.Util.java

public static void log(String msg) {
    System.out.println(DateFormatUtils.format(new Date(), "[yyyy-MM-dd HH:mm:ss.SSS]") + " " + msg);
}