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:de.hybris.platform.servicelayer.cronjob.impl.DefaultJobLogConverterTest.java

@Test
public void testValidFormatLogsWithEntriesTruncated() {
    final String pattern = "dd HH";
    converter.setDateFormatPattern(pattern);

    final StringBuilder messageFromLogs = new StringBuilder(1000);
    for (int i = 0; i < 15; i++) {
        messageFromLogs.append("message" + i + CharUtils.LF);
    }//w w w.j a  va  2 s.  co m

    final StringBuilder messageExpected = new StringBuilder(1000);
    for (int i = 0; i < 10; i++) {
        messageExpected.append("message" + i + (i == 9 ? "" : String.valueOf(CharUtils.LF)));
    }
    messageExpected.append(" ..." + CharUtils.LF);

    final Date date = new Date();

    final JobLogModel logEntry = new JobLogModel();
    logEntry.setCreationtime(date);
    logEntry.setLevel(JobLogLevel.FATAL);

    logEntry.setMessage(messageFromLogs.toString());

    final List<JobLogModel> entries = Arrays.asList(logEntry);

    final String result = converter.convert(entries);

    Mockito.verify(formatFactory, Mockito.times(1)).createDateTimeFormat(DateFormat.DEFAULT, -1);

    final SimpleDateFormat sdf = (SimpleDateFormat) formatFactory.createDateTimeFormat(DateFormat.DEFAULT, -1);
    sdf.applyPattern(pattern);

    Assert.assertEquals(result, String.format("%s: FATAL: " + messageExpected.toString(), sdf.format(date)));
}

From source file:nl.b3p.viewer.stripes.WriteWKTActionBean.java

@DefaultHandler
public Resolution write() {
    JSONObject obj = new JSONObject();
    obj.put("success", false);

    EntityManager em = Stripersist.getEntityManager();

    Set components = application.getComponents();
    for (Iterator it = components.iterator(); it.hasNext();) {
        ConfiguredComponent comp = (ConfiguredComponent) it.next();
        if (comp.getClassName().equals(COMPONENT_NAME)) {
            JSONObject config = new JSONObject(comp.getConfig());
            String basepath = config.optString(BASE_PATH);
            if (basepath != null && !basepath.isEmpty()) {
                File base = new File(basepath, type + File.separator);
                if (!base.exists()) {
                    if (!base.mkdir()) {
                        log.error("Can not create folder " + base.getAbsolutePath() + ".");
                    }//  w w  w .ja  va 2  s  .c o m
                }
                if (base.exists() && base.canWrite()) {
                    Date nowDate = new Date(System.currentTimeMillis());
                    SimpleDateFormat sdf = (SimpleDateFormat) SimpleDateFormat.getDateInstance();
                    sdf.applyPattern("HH-mm_dd-MM-yyyy");
                    String now = sdf.format(nowDate);
                    File f = new File(base, filename + now + ".txt");
                    try {
                        JSONObject file = new JSONObject();
                        file.put("title", filename);
                        file.put("description", mailaddress);
                        file.put("features", wkt);

                        FileUtils.writeStringToFile(f, file.toString(), "UTF-8");

                        obj.put("success", true);
                    } catch (IOException ex) {
                        obj.put("message", getBundle().getString("viewer.writewktactionbean.1"));
                        log.error("Error writing wkt file: ", ex);
                    }
                } else {
                    obj.put("message", getBundle().getString("viewer.writewktactionbean.2"));
                }
            } else {
                obj.put("message", getBundle().getString("viewer.writewktactionbean.3"));
                log.error("Error writing wkt file: Base path not configured. Contact your administrator.");
            }
            break;
        }
    }

    return new StreamingResolution("application/json", obj.toString());
}

From source file:de.tudarmstadt.dvs.myhealthassistant.myhealthhub.sensormodules.AbstractSensorModule.java

private String getDayFromDate(String timeOfMeasurement, String dateFormat, String applyPattern) {
    SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);

    try {/*from   w w  w .j  a  v  a  2s.c  om*/
        Date today = sdf.parse(timeOfMeasurement);
        sdf.applyPattern(applyPattern);

        return sdf.format(today);

    } catch (ParseException e) {
        e.printStackTrace();
    }
    return "";
}

From source file:org.xlcloud.openstack.model.climate.json.OpenStackDateDeserializer.java

private Date parseDate(String input, String[] datePatterns) throws ParseException {
    SimpleDateFormat parser = new SimpleDateFormat();
    parser.setLenient(true);/*from   w w  w.j a v a2  s.c o m*/
    parser.setTimeZone(DateUtils.UTC_TIME_ZONE);
    ParsePosition position = new ParsePosition(0);
    for (String datePattern : datePatterns) {
        parser.applyPattern(datePattern);
        Date date = parser.parse(input, position);
        if (date != null && position.getIndex() == input.length()) {
            return date;
        }
    }
    throw new ParseException("Unable to parse the date: " + input, -1);
}

From source file:nl.b3p.commons.taglib.WriteDateTag.java

/**
 * Process the start tag.//w w w  .j a v a2 s . co  m
 *
 * @exception JspException if a JSP exception has occurred
 */
public int doStartTag() throws JspException {

    // Look up the requested bean
    Object value = null;
    if (name != null) {
        // er zou een datum te vinden moeten zijn
        if (TagUtils.getInstance().lookup(pageContext, name, scope) == null) {
            return (SKIP_BODY); // Nothing to output
            // Look up the requested property value
        }
        value = TagUtils.getInstance().lookup(pageContext, name, property, scope);
    }
    if (value == null) {
        // een voorbeeld datum met locale wordt afgedrukt
        Date exValue = new Date();
        value = exValue;
    }

    // Get locale of this request for date printing
    HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
    Locale locale = request.getLocale();

    // Print this property value to our output writer
    String output = null;
    if (value != null) {
        if (value instanceof Date) {
            output = FormUtils.DateToString((Date) value, locale);
            if (log.isDebugEnabled()) {
                log.debug("Date: " + output);
            }
        } else if (value instanceof Timestamp) {
            Timestamp temptime = (Timestamp) value;
            Date tempdate = new Date();
            tempdate.setTime(temptime.getTime());
            output = FormUtils.DateToString(tempdate, locale);
            if (log.isDebugEnabled()) {
                log.debug("Timestamp: " + output);
            }
        } else if (value instanceof String) {
            SimpleDateFormat sdf = (SimpleDateFormat) SimpleDateFormat.getDateInstance();
            sdf.applyPattern("yyyy-MM-dd HH:mm");
            Date tempdate = null;
            try {
                tempdate = sdf.parse((String) value);
                output = FormUtils.DateToString(tempdate, locale);
                if (log.isDebugEnabled()) {
                    log.debug("String (yyyy-MM-dd HH:mm): " + output);
                }
            } catch (java.text.ParseException pe) {
                output = ((String) value).trim();
                int spacedex = output.indexOf(' ');
                if (spacedex > 1) {
                    output = output.substring(0, spacedex);
                }
                if (log.isDebugEnabled()) {
                    log.debug("No conversion: " + output);
                }
            }
        }
    }
    TagUtils.getInstance().write(pageContext, output);

    // Continue processing this page
    return (SKIP_BODY);

}

From source file:nl.b3p.viewer.stripes.DrawingActionBean.java

public Resolution save() {

    Date nowDate = new Date(System.currentTimeMillis());
    SimpleDateFormat sdf = (SimpleDateFormat) SimpleDateFormat.getDateInstance();
    sdf.applyPattern("HH-mm_dd-MM-yyyy");
    String now = sdf.format(nowDate);
    final String fileName = title + now;
    return new StreamingResolution("text/plain") {

        @Override//  ww w  .  jav a2 s .c  o  m
        public void stream(HttpServletResponse response) throws Exception {
            OutputStream out = response.getOutputStream();

            try {
                File features = File.createTempFile("Features", ".txt");
                JSONObject file = new JSONObject();
                file.put("title", title);
                file.put("description", description);
                file.put("features", saveObject);

                FileUtils.writeStringToFile(features, file.toString());
                InputStream in = null;
                try {
                    in = new FileInputStream(features);
                    IOUtils.copy(in, out);
                } catch (IOException ex) {
                    log.error("Could not write zip to output: ", ex);
                } finally {
                    out.close();
                    in.close();
                    features.delete();
                }
            } catch (Exception e) {
                log.error("Fout bij maken sld: ", e);
                response.setContentType("text/html;charset=UTF-8");
                PrintWriter pw = new PrintWriter(out);
                pw.write(e.getMessage());
            } finally {
                out.close();
            }
        }
    }.setAttachment(true).setFilename(fileName + ".txt");
}

From source file:org.photovault.imginfo.Volume.java

private File getNewFname(java.util.Date date, String strExtension) {
    log.debug("getNewFname " + date + " " + strExtension);
    SimpleDateFormat fmt = new SimpleDateFormat("yyyy");
    String strYear = fmt.format(date);
    fmt.applyPattern("yyyyMM");
    String strMonth = fmt.format(date);
    fmt.applyPattern("yyyyMMdd");
    String strDate = fmt.format(date);

    File yearDir = new File(getBaseDir(), strYear);
    log.debug("YearDir: " + yearDir);
    if (!yearDir.exists()) {
        log.debug("making yeardir");
        if (!yearDir.mkdir()) {
            log.error("Failed to create directory " + yearDir.getAbsoluteFile());
        }/*from  ww  w  . j  av  a  2s .com*/
    }

    // Create the month directeory if it does not exist yet
    File monthDir = new File(yearDir, strMonth);
    log.debug("MontDir: " + monthDir);
    if (!monthDir.exists()) {
        log.debug("making yeardir");
        if (!monthDir.mkdir()) {
            log.error("Failed to create " + monthDir.getAbsolutePath());
        }
    }

    // Find a free order num for this file
    String monthFiles[] = monthDir.list();
    int orderNum = 1;
    for (int n = 0; n < monthFiles.length; n++) {
        if (monthFiles[n].startsWith(strDate)) {
            int delimiterLoc = monthFiles[n].indexOf(".");
            String strFileNum = monthFiles[n].substring(strDate.length() + 1, delimiterLoc);
            int i = 0;
            try {
                i = Integer.parseInt(strFileNum);
            } catch (NumberFormatException e) {
            }
            if (i >= orderNum) {
                orderNum = i + 1;
            }
        }
    }

    String strOrderNum = String.valueOf(orderNum);

    // Find the file extension
    String fname = strDate + "_" + "00000".substring(0, 5 - strOrderNum.length()) + strOrderNum + "."
            + strExtension;
    File archiveFile = new File(monthDir, fname);
    return archiveFile;

}

From source file:entropy.plan.visualization.GanttVisualizer.java

/**
 * Build the plan agenda//  ww  w.  ja v  a2s. c o m
 *
 * @param plan the plan to visualize
 * @return {@code true} if the generation succeeds
 */
@Override
public boolean buildVisualization(TimedReconfigurationPlan plan) {
    File parent = new File(out).getParentFile();
    if (parent != null && !parent.exists() && !parent.mkdirs()) {
        Plan.logger.error("Unable to create '" + out + "'");
        return false;
    }
    final TaskSeriesCollection collection = new TaskSeriesCollection();
    TaskSeries ts = new TaskSeries("actions");
    for (Action action : plan) {
        Task t = new Task(action.toString(),
                new SimpleTimePeriod(action.getStartMoment(), action.getFinishMoment()));
        ts.add(t);
    }
    collection.add(ts);
    ChartFactory.setChartTheme(StandardChartTheme.createLegacyTheme());

    final JFreeChart chart = ChartFactory.createGanttChart(null, // chart title
            "Actions", // domain axis label
            "Time", // range axis label
            collection, // data
            false, // include legend
            true, // tooltips
            false // urls
    );
    CategoryPlot plot = chart.getCategoryPlot();
    DateAxis da = (DateAxis) plot.getRangeAxis();
    SimpleDateFormat sdfmt = new SimpleDateFormat();
    sdfmt.applyPattern("S");
    da.setDateFormatOverride(sdfmt);
    ((GanttRenderer) plot.getRenderer()).setShadowVisible(false);
    int width = 500 + 10 * plan.getDuration();
    int height = 50 + 20 * plan.size();
    try {
        switch (fmt) {
        case png:
            ChartUtilities.saveChartAsPNG(new File(out), chart, width, height);
            break;
        case jpg:
            ChartUtilities.saveChartAsJPEG(new File(out), chart, width, height);
            break;
        }
    } catch (IOException e) {
        Plan.logger.error(e.getMessage(), e);
        return false;
    }
    return true;
}

From source file:com.kanchi.periyava.Fragments.Dashboard.java

private void init() {
    if (UserProfile.getUserProfile().isLoggedIn == false) {
        return;/* w w w .  j  a  va 2 s  .  c  om*/
    }
    rootView.findViewById(R.id.japaminfo)
            .setVisibility(UserProfile.getUserProfile().isLoggedIn == true ? View.VISIBLE : View.GONE);
    ((TextView) rootView.findViewById(R.id.japam_count_over_all))
            .setText("" + UserProfile.getUserProfile().japam_count_over_all);
    ((TextView) rootView.findViewById(R.id.japam_count_satsang))
            .setText(UserProfile.getInstance().isjoinedsatsang == false ? "Not Joined to Satsang"
                    : "" + UserProfile.getUserProfile().japam_count_satsang);
    ((TextView) rootView.findViewById(R.id.japam_count)).setText("" + UserProfile.getUserProfile().japam_count);

    final String NEW_FORMAT = "dd-MMM-yyyy";
    final String OLD_FORMAT = "yyyy-MM-dd HH:mm:ss";

    // August 12, 2010
    String oldDateString = UserProfile.getUserProfile().japam_last_updated_date;
    String newDateString = "";

    SimpleDateFormat sdf = new SimpleDateFormat(OLD_FORMAT);
    Date d = null;
    try {
        d = sdf.parse(oldDateString);
        sdf.applyPattern(NEW_FORMAT);
        newDateString = sdf.format(d);
    } catch (ParseException e) {
        e.printStackTrace();
    }

    ((TextView) rootView.findViewById(R.id.japam_last_updated_date)).setText(newDateString);
}

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

/**
 * ?//from   w w  w  .j a  va2 s  .  c  o m
 * 
 * @param dateString 
 * @return 
 */
public Date toDate(String dateString) {
    if (StringUtils.isBlank(dateString)) {
        return null;
    }
    SimpleDateFormat df = new SimpleDateFormat(this.getDateType(), Locale.CHINA);
    df.applyPattern(this.getDateType());
    Date date = null;
    try {
        date = df.parse(dateString);
    } catch (ParseException e) {
        log.error(e.getMessage(), e);
    }
    return date;
}