Example usage for java.text SimpleDateFormat applyPattern

List of usage examples for java.text SimpleDateFormat applyPattern

Introduction

In this page you can find the example usage for java.text SimpleDateFormat applyPattern.

Prototype

public void applyPattern(String pattern) 

Source Link

Document

Applies the given pattern string to this date format.

Usage

From source file:org.exoplatform.wiki.rendering.macro.update.RecentlyUpdatedMacro.java

private ListItemBlock transformToBlock(SearchResult res, MacroTransformationContext context) throws Exception {
    List<Block> blocks = new ArrayList<Block>();
    String pageName = res.getPageName();
    if (pageName.indexOf("/") >= 0) {
        pageName = pageName.substring(pageName.lastIndexOf("/") + 1);
    }/*from  w  w  w.  j  a v a 2  s.co  m*/
    WikiPageParams params = markupContextManager.getMarkupContext(pageName, ResourceType.DOCUMENT);
    DocumentResourceReference link = new DocumentResourceReference(getReferenceBuilder(context).build(params));
    //link to wiki page
    List<Block> content = new ArrayList<Block>();
    content.add(new WordBlock(res.getTitle()));
    LinkBlock linkBlock = new LinkBlock(content, link, true);
    blocks.add(linkBlock);
    //created by or updated by
    blocks.add(new SpaceBlock());
    WikiService wikiService = (WikiService) ExoContainerContext.getCurrentContainer()
            .getComponentInstanceOfType(WikiService.class);
    PageImpl page = (PageImpl) wikiService.getPageById(params.getType(), params.getOwner(), params.getPageId());
    String modifyText = page.getCreatedDate().equals(page.getUpdatedDate()) ? "created by " : " updated by";
    blocks.add(new WordBlock(modifyText));
    //user name
    blocks.add(new SpaceBlock());
    blocks.add(new WordBlock(page.getAuthor()));
    //time
    blocks.add(new SpaceBlock());
    SimpleDateFormat formatDateTime = new SimpleDateFormat();
    formatDateTime.applyPattern("yyyy.MMMM.dd GGG hh:mm aaa");
    blocks.add(new WordBlock(formatDateTime.format(
            page.getJCRPageNode().getProperty(WikiNodeType.Definition.UPDATED_DATE).getDate().getTime())));

    return new ListItemBlock(blocks);
}

From source file:com.zxy.commons.lang.utils.DatesUtils.java

/**
 * ?/*w  ww .j a  va2s .co m*/
 * 
 * @param date 
 * @return 
 */
public String toString(Date date) {
    if (date == null) {
        return "";
    }
    try {
        SimpleDateFormat df = new SimpleDateFormat(this.getDateType(), Locale.ENGLISH);
        df.applyPattern(this.getDateType());
        return df.format(date);
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        return "";
    }
}

From source file:org.exoplatform.wiki.rendering.macro.update.RecentlyUpdatedMacro.java

private String getTimeConstraint(String time) throws MacroExecutionException {
    StringBuffer timeConstraint = new StringBuffer();
    Calendar date = new GregorianCalendar();
    if (StringUtils.isNotBlank(time)) {
        timeConstraint.append(" AND ( ");
        String pattern = "((\\d)+d)?((\\d)+h)?((\\d)+m)?((\\d)+s)?";
        if (time.matches(pattern)) {
            //get time value
            int day = getValue(time, "(\\d)+d");
            int hour = getValue(time, "(\\d)+h");
            int minute = getValue(time, "(\\d)+m");
            int second = getValue(time, "(\\d)+s");
            date.add(Calendar.DATE, (-1) * day);
            date.add(Calendar.HOUR, (-1) * hour);
            date.add(Calendar.MINUTE, (-1) * minute);
            date.add(Calendar.SECOND, (-1) * second);
            //append constraint
            SimpleDateFormat formatDateTime = new SimpleDateFormat();
            formatDateTime.applyPattern("YYYY-MM-DDThh:mm:ss.sTZD");
            String calculatedTime = formatDateTime.format(date.getTime()) + "T00:00:00.000";
            timeConstraint.append(WikiNodeType.Definition.EXO_LAST_MODIFIED_DATE).append(" >= TIMESTAMP '")
                    .append(calculatedTime).append("'");
        } else {// w w w .  j ava2 s. c o m
            throw new MacroExecutionException(
                    String.format("Time is not correct: %s, please use pattern d h m s", time));
        }
        timeConstraint.append(" ) ");
    }
    return timeConstraint.toString();
}

From source file:org.opencastproject.fsresources.ResourceServlet.java

/**
 * {@inheritDoc}/* w w w. ja v  a  2 s  . c  o  m*/
 * 
 * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse)
 */
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    logger.debug("Looking for static resource '{}'", req.getRequestURI());
    String path = req.getPathInfo();
    String normalized = path == null ? "/" : path.trim().replaceAll("/+", "/").replaceAll("\\.\\.", "");
    if (path == null) {
        path = "/";
    } else {
        // Replace duplicate slashes with a single slash, and remove .. from the listing
        path = path.trim().replaceAll("/+", "/").replaceAll("\\.\\.", "");
    }
    if (normalized != null && normalized.startsWith("/") && normalized.length() > 1) {
        normalized = normalized.substring(1);
    }

    File f = new File(root, normalized);
    boolean allowed = true;
    if (f.isFile() && f.canRead()) {
        allowed = checkDirectory(f.getParentFile());
        if (!allowed) {
            resp.sendError(HttpServletResponse.SC_FORBIDDEN);
            return;
        }

        logger.debug("Serving static resource '{}'", f.getAbsolutePath());
        FileInputStream in = new FileInputStream(f);
        try {
            IOUtils.copyLarge(in, resp.getOutputStream());
        } finally {
            IOUtils.closeQuietly(in);
        }
    } else if (f.isDirectory() && f.canRead()) {
        allowed = checkDirectory(f);
        if (!allowed) {
            resp.sendError(HttpServletResponse.SC_FORBIDDEN);
            return;
        }

        logger.debug("Serving index page for '{}'", f.getAbsolutePath());
        PrintWriter out = resp.getWriter();
        resp.setContentType("text/html;charset=UTF-8");
        out.write("<html>");
        out.write("<head><title>File Index for " + normalized + "</title></head>");
        out.write("<body>");
        out.write("<table>");
        SimpleDateFormat sdf = new SimpleDateFormat();
        sdf.applyPattern(dateFormat);
        for (File child : f.listFiles()) {

            if (child.isDirectory() && !checkDirectory(child)) {
                continue;
            }

            StringBuffer sb = new StringBuffer();
            sb.append("<tr><td>");
            sb.append("<a href=\"");
            if (req.getRequestURL().charAt(req.getRequestURL().length() - 1) != '/') {
                sb.append(req.getRequestURL().append("/").append(child.getName()));
            } else {
                sb.append(req.getRequestURL().append(child.getName()));
            }
            sb.append("\">");
            sb.append(child.getName());
            sb.append("</a>");
            sb.append("</td><td>");
            sb.append(formatLength(child.length()));
            sb.append("</td><td>");
            sb.append(sdf.format(child.lastModified()));
            sb.append("</td>");
            sb.append("</tr>");
            out.write(sb.toString());
        }
        out.write("</table>");
        out.write("</body>");
        out.write("</html>");
    } else {
        logger.debug("Error state for '{}', returning HTTP 404", f.getAbsolutePath());
        resp.sendError(HttpServletResponse.SC_NOT_FOUND);
    }
}

From source file:org.castor.cpa.test.test10.TestTypeHandling.java

public void testDateParameterized() throws PersistenceException, ParseException {
    LOG.debug("Testing date->int/numeric/char parameterized conversion");
    SimpleDateFormat df = new SimpleDateFormat();
    df.applyPattern("yyyy/MM/dd");
    Date date = df.parse("2000/05/27");
    df.applyPattern("yyyy/MM/dd HH:mm:ss.SSS");
    Date time = df.parse("2000/05/27 02:16:01.234");
    df.applyPattern("yyyy/MM/dd HH:mm:ss.SSS");
    Date timestamp = df.parse("2000/05/27 02:16:01.234");
    _db.begin();// ww  w. j  a  v a  2  s .co m
    _oql.bind(TypeHandling.DEFAULT_ID);
    Enumeration<?> enumeration = _oql.execute();
    if (enumeration.hasMoreElements()) {
        TypeHandling types = (TypeHandling) enumeration.nextElement();
        types.setDate2(date);
        types.setTime2(time);
        types.setTimestamp2(timestamp);
    }
    _db.commit();

    _db.begin();
    _oql.bind(TypeHandling.DEFAULT_ID);
    enumeration = _oql.execute();
    if (enumeration.hasMoreElements()) {
        TypeHandling types = (TypeHandling) enumeration.nextElement();
        if (!date.equals(types.getDate2())) {
            LOG.error("date/int value was not set");
            fail("date/int value was not set");
        }
        if (!time.equals(types.getTime2())) {
            LOG.error("time/string value was not set");
            fail("time/string vlaue was not set");
        }
        if (!timestamp.equals(types.getTimestamp2())) {
            LOG.error("timestamp/numeric value was not set");
            LOG.error("timestamp was set to: " + df.format(timestamp));
            LOG.error("with oid: " + timestamp.hashCode());
            LOG.error("timestamp is: " + df.format(types.getTimestamp2()));
            LOG.error("with oid: " + types.getTimestamp2().hashCode());
            fail("timestamp/numeric value was not set");
        }
    } else {
        LOG.error("failed to load object");
        fail("failed to load object");
    }
    _db.commit();
    LOG.debug("OK: date->int/numeric/char conversion passed");
}

From source file:org.openmrs.module.patientportaltoolkit.fragment.controller.AddRelationshipFragmentController.java

private Date updateAge(String birthdate, String dateformat, String age) throws java.text.ParseException {
    SimpleDateFormat df = new SimpleDateFormat();
    if (!"".equals(dateformat)) {
        dateformat = dateformat.toLowerCase().replaceAll("m", "M");
    } else {//from  w  ww.  j av a  2 s .c  o  m
        dateformat = new String("MM/dd/yyyy");
    }
    df.applyPattern(dateformat);
    Calendar cal = Calendar.getInstance();
    cal.clear(Calendar.HOUR);
    cal.clear(Calendar.MINUTE);
    cal.clear(Calendar.SECOND);
    cal.clear(Calendar.MILLISECOND);
    if ("".equals(birthdate)) {
        if ("".equals(age)) {
            return cal.getTime();
        }
        try {
            cal.add(Calendar.YEAR, -(Integer.parseInt(age)));
        } catch (NumberFormatException nfe) {
            log.error("Error during adding date into calendar", nfe);
        }
        return cal.getTime();
    } else {
        cal.setTime(df.parse(birthdate));
    }
    return cal.getTime();
}

From source file:com.concursive.connect.web.modules.communications.jobs.EmailUpdatesJob.java

/**
 * Process email updates queue//  ww  w  .ja  va  2s.  c o  m
 *
 * @param context
 * @throws JobExecutionException
 */
public void execute(JobExecutionContext context) throws JobExecutionException {
    SchedulerContext schedulerContext = null;
    Connection db = null;
    try {
        schedulerContext = context.getScheduler().getContext();
        db = SchedulerUtils.getConnection(schedulerContext);
        ApplicationPrefs prefs = (ApplicationPrefs) schedulerContext.get("ApplicationPrefs");
        ServletContext servletContext = (ServletContext) schedulerContext.get("ServletContext");
        LOG.debug("EmailUpdatesJob triggered...");
        while (true) {
            //Retrieve retrieve the next item from the email_updates_queue that is scheduled for now.
            EmailUpdatesQueueList queueList = new EmailUpdatesQueueList();
            queueList.setScheduledOnly(true);
            queueList.setMax(1);
            queueList.buildList(db);
            if (queueList.size() == 0) {
                LOG.debug("No more scheduled emails to be processed...");
                break;
            } else {
                EmailUpdatesQueue queue = (EmailUpdatesQueue) queueList.get(0);
                //Lock that record by issuing a successful update which updates the status = 1 to status = 2.
                if (EmailUpdatesQueue.lockQueue(queue, db)) {
                    LOG.debug("Processing scheduled email queue...");

                    // User who needs to be sent an email
                    User user = UserUtils.loadUser(queue.getEnteredBy());

                    //Determine the date range to query the activity stream data
                    Timestamp min = queue.getProcessed();
                    Timestamp max = new Timestamp(System.currentTimeMillis());

                    if (min == null) {
                        //set the min value to be queue's entered date to restrict picking up all the records in the system
                        min = queue.getEntered();
                    }

                    Configuration configuration = ApplicationPrefs.getFreemarkerConfiguration(servletContext);
                    // Determine the message to be sent
                    String message = EmailUpdatesUtils.getEmailHTMLMessage(db, prefs, configuration, queue, min,
                            max);

                    if (message != null) {
                        // Use the user's locale to format the date
                        SimpleDateFormat formatter = (SimpleDateFormat) SimpleDateFormat
                                .getDateInstance(DateFormat.SHORT, user.getLocale());
                        formatter.applyPattern(
                                DateUtils.get4DigitYearDateFormat(formatter.toLocalizedPattern()));
                        String date = formatter.format(max);

                        String subject = "";
                        if (queue.getScheduleOften()) {
                            subject = "Activity Updates for " + date + " - Recent updates";
                        } else if (queue.getScheduleDaily()) {
                            subject = "Activity Updates for " + date + " - Daily update";
                        } else if (queue.getScheduleWeekly()) {
                            subject = "Activity Updates for " + date + " - Weekly update";
                        } else if (queue.getScheduleMonthly()) {
                            subject = "Activity Updates for " + date + " - Monthly update";
                        }
                        //Try to send the email
                        LOG.debug("Sending email...");
                        SMTPMessage email = SMTPMessageFactory.createSMTPMessageInstance(prefs.getPrefs());
                        email.setFrom(prefs.get(ApplicationPrefs.EMAILADDRESS));
                        email.addReplyTo(prefs.get(ApplicationPrefs.EMAILADDRESS));
                        email.addTo(user.getEmail());
                        email.setSubject(subject);
                        email.setType("text/html");
                        email.setBody(message);
                        email.send();
                    } else {
                        LOG.debug("No activities to report. Skipping email.");
                    }

                    //Determine the next schedule date and save the schedule date and status=1
                    LOG.debug("Calculating next run date...");
                    queue.calculateNextRunDate(db);

                    //Set the max date to be the queue's processed date
                    LOG.debug("Updating process date...");
                    queue.updateProcessedDate(db, max);
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace(System.out);
        throw new JobExecutionException(e.getMessage());
    } finally {
        SchedulerUtils.freeConnection(schedulerContext, db);
    }
}

From source file:com.alibaba.otter.node.etl.common.db.utils.SqlTimestampConverter.java

private Date parseDate(String str, String[] parsePatterns, Locale locale) throws ParseException {
    if ((str == null) || (parsePatterns == null)) {
        throw new IllegalArgumentException("Date and Patterns must not be null");
    }/*from   w  w w  .  j a  v  a  2 s. c o  m*/

    SimpleDateFormat parser = null;
    ParsePosition pos = new ParsePosition(0);

    for (int i = 0; i < parsePatterns.length; i++) {
        if (i == 0) {
            parser = new SimpleDateFormat(parsePatterns[0], locale);
        } else {
            parser.applyPattern(parsePatterns[i]);
        }
        pos.setIndex(0);
        Date date = parser.parse(str, pos);
        if ((date != null) && (pos.getIndex() == str.length())) {
            return date;
        }
    }

    throw new ParseException("Unable to parse the date: " + str, -1);
}

From source file:org.enerj.apache.commons.beanutils.locale.converters.DateLocaleConverter.java

/**
 * Convert the specified locale-sensitive input object into an output object of the
 * specified type.//from   w ww.j ava  2s.  co  m
 *
 * @param value The input object to be converted
 * @param pattern The pattern is used for the convertion
 *
 * @exception org.enerj.apache.commons.beanutils.ConversionException if conversion cannot be performed
 *  successfully
 */
protected Object parse(Object value, String pattern) throws ParseException {
    SimpleDateFormat formatter = getFormatter(pattern, locale);
    if (locPattern) {
        formatter.applyLocalizedPattern(pattern);
    } else {
        formatter.applyPattern(pattern);
    }
    return formatter.parse((String) value);
}

From source file:org.syncope.console.wicket.markup.html.form.DateTimeFieldPanel.java

@Override
public FieldPanel setNewModel(final List<Serializable> list) {
    final SimpleDateFormat formatter = DATE_FORMAT.get();

    if (datePattern != null) {
        formatter.applyPattern(datePattern);
    }/* www.ja va 2s.c o  m*/

    setNewModel(new Model() {

        private static final long serialVersionUID = 527651414610325237L;

        @Override
        public Serializable getObject() {
            Date date = null;

            if (list != null && !list.isEmpty() && StringUtils.hasText(list.get(0).toString())) {
                try {
                    // Parse string using datePattern
                    date = formatter.parse(list.get(0).toString());
                } catch (ParseException e) {
                    LOG.error("invalid parse exception", e);
                }
            }

            return date;
        }

        @Override
        public void setObject(final Serializable object) {
            if (object != null) {
                list.clear();
                list.add((String) formatter.format((Date) object));
            }
        }
    });

    return this;
}