Example usage for org.apache.commons.lang3.time FastDateFormat parse

List of usage examples for org.apache.commons.lang3.time FastDateFormat parse

Introduction

In this page you can find the example usage for org.apache.commons.lang3.time FastDateFormat parse.

Prototype

@Override
    public Date parse(final String source) throws ParseException 

Source Link

Usage

From source file:mServer.tool.MserverDatumZeit.java

/**
 * formats a date/datetime string to the date format used in DatenFilm
 * @param dateValue the date/datetime value
 * @param sdf the format of dateValue/*from   ww w .  ja  va 2s.com*/
 * @return the formatted date string
 */
public static String formatDate(String dateValue, FastDateFormat sdf) {
    try {
        return FDF_OUT_DAY.format(sdf.parse(dateValue));
    } catch (ParseException ex) {
        LOG.debug(String.format("Fehler beim Parsen des Datums %s: %s", dateValue, ex.getMessage()));
    }

    return "";
}

From source file:mServer.tool.MserverDatumZeit.java

/**
 * formats a datetime string to the time format used in DatenFilm
 * @param dateValue the datetime value/*from  ww w .  ja  v  a2  s  . c o m*/
 * @param sdf the format of dateValue
 * @return the formatted time string
 */
public static String formatTime(String dateValue, FastDateFormat sdf) {
    try {
        return FDF_OUT_TIME.format(sdf.parse(dateValue));
    } catch (ParseException ex) {
        LOG.debug(String.format("Fehler beim Parsen des Datums %s: %s", dateValue, ex.getMessage()));
    }

    return "";
}

From source file:de.jlo.talendcomp.json.TypeUtil.java

/**
 * concerts the string format into a Date
 * @param dateString/*w  ww.jav a 2 s.co m*/
 * @param pattern
 * @return the resulting Date
 */
public static Date convertToDate(String dateString, String pattern) throws Exception {
    if (dateString == null || dateString.isEmpty()) {
        return null;
    }
    if (pattern == null) {
        pattern = DEFAULT_DATE_PATTERN;
    }
    try {
        FastDateFormat sdf = FastDateFormat.getInstance(pattern);
        Date date = null;
        try {
            date = sdf.parse(dateString);
        } catch (ParseException pe) {
            date = GenericDateUtil.parseDate(dateString);
        }
        return date;
    } catch (Throwable t) {
        throw new Exception("Failed to convert string to date:" + t.getMessage(), t);
    }
}

From source file:com.loadtesting.showcase.springmvc.model.converter.FastTimeConverter.java

public JavaTimeForm convert(JavaTimeForm form) throws ParseException {
    FastDateFormat format1 = getFormat(form.getFromTimeZone());
    Date date = format1.parse(form.getInputDate());
    FastDateFormat format2 = getFormat(form.getToTimeZone());
    String outputDate = format2.format(date);
    JavaTimeForm resultForm = new JavaTimeForm();
    resultForm.setInputDate(form.getInputDate());
    resultForm.setFromTimeZone(form.getFromTimeZone());
    resultForm.setToTimeZone(form.getToTimeZone());
    resultForm.setOutputDate(outputDate);
    return resultForm;
}

From source file:com.adobe.acs.commons.data.Variant.java

public Date toDate() {
    return dateVal.orElse(longVal.map(Date::new).orElse(stringVal.map(s -> {
        for (FastDateFormat format : DATE_FORMATS) {
            try {
                return format.parse(s);
            } catch (ParseException ex) {
                // No good, go to the next pattern
            }//from   w  w  w  .ja  v a  2s .  co m
        }
        return null;
    }).orElse(null)));
}

From source file:logdruid.util.DataMiner.java

public static FileMineResult fileMine(FileRecord fileRecord, Repository repo, Source source, boolean stats,
        boolean timings) {
    ExtendedTimeSeries ts = null;//from   ww w .  ja v a 2  s. co m
    PatternCache patternCache = new PatternCache();
    Date startDate = null;
    Date endDate = null;

    DecimalFormat decimalFormat = new DecimalFormat("#.#", new DecimalFormatSymbols(Locale.US));

    FastDateFormat fastDateFormat = null;
    FileReader flstr = null;
    BufferedReader buf1st;
    Matcher matcher;
    Matcher matcher2;
    FixedMillisecond fMS = null;
    Boolean successMatch = false;
    DateFormat df = null;
    int statHit = 0;
    int statMatch = 0;
    int eventHit = 0;
    int eventMatch = 0;
    long[] arrayBefore;
    Map<Recording, String> recMatch = new HashMap<Recording, String>();
    Map<String, ExtendedTimeSeries> statMap = new HashMap<String, ExtendedTimeSeries>();
    Map<String, ExtendedTimeSeries> eventMap = new HashMap<String, ExtendedTimeSeries>();
    Map<String, Map<Date, FileLine>> RIFileLineDateMap = new HashMap<String, Map<Date, FileLine>>();
    Map<String, long[]> matchTimings = new HashMap<String, long[]>();

    long recordingMatchStart = 0;
    long recordingMatchEnd = 0;
    try {
        if (logger.isDebugEnabled()) {
            logger.debug("++file: " + repo.getBaseSourcePath() + " + "
                    + (String) fileRecord.getCompletePath().toString());
        }
        flstr = new FileReader(fileRecord.getCompletePath());
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    buf1st = new BufferedReader(flstr);
    String line;
    try {
        recMatch = getRegexp(repo, source);
        int lineCount = 1;
        while ((line = buf1st.readLine()) != null) {
            // check against one Recording pattern at a tim
            // if (logger.isDebugEnabled()) {
            // logger.debug("line " + line);
            // }
            Iterator recMatchIte = recMatch.entrySet().iterator();
            while (recMatchIte.hasNext()) {
                if (timings) {
                    recordingMatchStart = ManagementFactory.getThreadMXBean()
                            .getThreadCpuTime(Thread.currentThread().getId());
                }
                Map.Entry me = (Map.Entry) recMatchIte.next();
                Recording rec = (Recording) me.getKey();
                matcher = patternCache.getPattern((String) (rec.getRegexp())).matcher(line);
                if (matcher.find()) {
                    Boolean isStatRecording = rec.getClass().equals(StatRecording.class);
                    if (stats) {
                        if (isStatRecording) {
                            statMatch++;
                        } else {
                            eventMatch++;
                        }
                    }
                    // logger.info("1**** matched: " + line);
                    ArrayList<RecordingItem> recordingItem = ((Recording) rec).getRecordingItem();
                    int cnt = 0;
                    matcher2 = patternCache.getPattern((String) me.getValue()).matcher(line);
                    successMatch = false;
                    if (matcher2.find()) {
                        if (stats) {
                            if (isStatRecording) {
                                statHit++;
                            } else {
                                eventHit++;
                            }
                        }
                        int count = 1;
                        Date date1 = null;

                        // handling capture for each recording item
                        Iterator<RecordingItem> recItemIte2 = recordingItem.iterator();
                        while (recItemIte2.hasNext()) {
                            RecordingItem recItem2 = recItemIte2.next();
                            // logger.info("3A**** " +
                            // recItem2.getType());
                            if (recItem2.getType().equals("date")) {
                                try {
                                    df = repo.getDateFormat(rec.getDateFormatID());
                                    if (logger.isDebugEnabled())
                                        logger.debug("4**** rec name" + rec.getName() + " df: " + df.getId());
                                    fastDateFormat = FastDateFormat.getInstance(df.getDateFormat());
                                    date1 = fastDateFormat.parse(matcher2.group(count));
                                    if (logger.isDebugEnabled())
                                        logger.debug(
                                                "4b**** " + df.getDateFormat() + " date: " + date1.toString());
                                    // logger.info("4**** " +
                                    // date1.toString());
                                } catch (ParseException e) {
                                    // TODO Auto-generated catch
                                    // block
                                    e.printStackTrace();
                                }
                            } else if (date1 != null) {
                                if (recItem2.isSelected()) {
                                    if (logger.isDebugEnabled()) {
                                        logger.debug("FileRecord: " + fileRecord.getFile().getName()
                                                + ", Source: " + source.getSourceName() + ", "
                                                + recItem2.getName() + ", " + fileRecord.getFile().getName()
                                                + ", " + lineCount);
                                    }
                                    // recording line of match in file in map RIFileLineDateMap - note the FileLine object use an int to identify the files to save memory 
                                    Map<Date, FileLine> dateFileLineMap = null;
                                    if (RIFileLineDateMap.containsKey(recItem2.getName())) {
                                        dateFileLineMap = RIFileLineDateMap.get(recItem2.getName());
                                    } else {
                                        dateFileLineMap = new HashMap<Date, FileLine>();
                                    }
                                    dateFileLineMap.put(date1, new FileLine(fileRecord.getId(), lineCount));
                                    if (logger.isDebugEnabled()) {
                                        logger.debug(fileRecord.getFile().getName() + " dateFileLineMap put: "
                                                + date1 + "fileLine: "
                                                + new FileLine(fileRecord.getId(), lineCount));
                                        logger.debug(fileRecord.getFile().getName() + " FileRecord: "
                                                + fileRecord.getFile().getName() + ", RIFileLineDateMap.put: "
                                                + recItem2.getName() + ", line: " + lineCount
                                                + " RIFileLineDateMap size: " + RIFileLineDateMap.size()
                                                + " dateFileLineMap size: " + dateFileLineMap.size());
                                    }
                                    RIFileLineDateMap.put(recItem2.getName(), dateFileLineMap);

                                    if (startDate == null) {
                                        startDate = date1;
                                    }
                                    if (endDate == null) {
                                        endDate = date1;
                                    }
                                    if (date1.after(startDate)) {
                                        endDate = date1;
                                    } else if (date1.before(startDate)) {
                                        startDate = date1;
                                    }

                                    if (isStatRecording) {
                                        if (statMap.containsKey(recItem2.getName())) {
                                            ts = statMap.get(recItem2.getName());
                                        } else {
                                            ts = new ExtendedTimeSeries(recItem2.getName(),
                                                    FixedMillisecond.class);
                                            if (logger.isDebugEnabled())
                                                logger.debug(
                                                        "5**** Adding record to Map: " + recItem2.getName());
                                        }
                                        fMS = new FixedMillisecond(date1);
                                        if (matcher2.group(count) == null) {
                                            logger.info("null in match on " + recItem2.getName() + " at "
                                                    + fileRecord.getFile().getName() + " line cnt:"
                                                    + lineCount);
                                            logger.info("line : " + line);
                                        }
                                        try {

                                            if (recItem2.getType().equals("long")) {
                                                ts.getTimeSeries().addOrUpdate((new TimeSeriesDataItem(fMS,
                                                        Long.valueOf((String) matcher2.group(count)))));
                                            } else {
                                                ts.getTimeSeries().addOrUpdate((new TimeSeriesDataItem(fMS,
                                                        Double.parseDouble(String.valueOf(decimalFormat
                                                                .parse((String) matcher2.group(count)))))));
                                            }
                                        } catch (ParseException e) {
                                            // TODO Auto-generated catch
                                            // block
                                            e.printStackTrace();
                                        }
                                        if (stats) {
                                            //int[] array = { statMatch, statHit };
                                            int[] array = ts.getStat();
                                            array[1] = array[1] + 1;
                                            array[0] = array[0] + 1;
                                            ts.setStat(array);
                                            if (logger.isDebugEnabled())
                                                logger.debug("stats " + array[0] + " " + array[1]);
                                        }

                                        statMap.put(recItem2.getName(), ts);
                                        // performance: add the
                                        // TmeSeriesDataItem to the
                                        // TimeSeries instead of updating
                                        // the TimeSeries in the Map

                                    } else { // rec.getClass().equals(EventRecording.class)
                                        if (eventMap.containsKey(recItem2.getName())) {
                                            ts = eventMap.get(recItem2.getName());
                                        } else {
                                            ts = new ExtendedTimeSeries(recItem2.getName(),
                                                    FixedMillisecond.class);
                                            if (logger.isDebugEnabled())
                                                logger.debug(
                                                        "5**** Adding record to Map: " + recItem2.getName());
                                        }
                                        fMS = new FixedMillisecond(date1);

                                        if (((RecordingItem) recItem2).getProcessingType()
                                                .equals("occurrences")) {
                                            TimeSeriesDataItem t = ts.getTimeSeries().getDataItem(fMS);
                                            if (t != null) {
                                                ts.getTimeSeries()
                                                        .addOrUpdate((new TimeSeriesDataItem(fMS, 101))); // +
                                                // (double)t.getValue()
                                                // need some way to show several occurrences
                                            } else {
                                                ts.getTimeSeries().add((new TimeSeriesDataItem(fMS, 100)));
                                            }

                                        } else if (((RecordingItem) recItem2).getProcessingType()
                                                .equals("sum")) {
                                            TimeSeriesDataItem t = ts.getTimeSeries().getDataItem(fMS);
                                            if (t != null) {
                                                if (!recItem2.getType().equals("date")) {
                                                    try {
                                                        ts.getTimeSeries().addOrUpdate((new TimeSeriesDataItem(
                                                                fMS,
                                                                Double.parseDouble(String
                                                                        .valueOf(decimalFormat
                                                                                .parse(matcher2.group(count)))
                                                                        + ts.getTimeSeries().getDataItem(fMS)
                                                                                .getValue()))));
                                                        logger.info(
                                                                ts.getTimeSeries().getDataItem(fMS).getValue());
                                                    } catch (ParseException e) {
                                                        // TODO
                                                        // Auto-generated
                                                        // catch block
                                                        e.printStackTrace();
                                                    }
                                                }
                                            } else {
                                                try {
                                                    ts.getTimeSeries()
                                                            .add((new TimeSeriesDataItem(fMS, Double
                                                                    .parseDouble(String.valueOf(decimalFormat
                                                                            .parse(matcher2.group(count)))))));
                                                } catch (ParseException e) {
                                                    // TODO Auto-generated
                                                    // catch block
                                                    e.printStackTrace();
                                                }
                                            }

                                        } else if (((RecordingItem) recItem2).getProcessingType()
                                                .equals("capture")) {

                                        } else {
                                            if (!recItem2.getType().equals("date")) {
                                                try {
                                                    ts.getTimeSeries()
                                                            .addOrUpdate((new TimeSeriesDataItem(fMS, Double
                                                                    .parseDouble(String.valueOf(decimalFormat
                                                                            .parse(matcher2.group(count)))))));
                                                } catch (ParseException e) {
                                                    // TODO Auto-generated
                                                    // catch block
                                                    e.printStackTrace();
                                                }
                                            }
                                            // ts.addOrUpdate((new
                                            // TimeSeriesDataItem(fMS,
                                            // 100)));
                                        }
                                        // logger.debug(recItem2.getName() +
                                        // " " +
                                        // Double.parseDouble((matcher2.group(count))));
                                        if (stats) {
                                            int[] array = ts.getStat();
                                            array[1] = array[1] + 1;
                                            array[0] = array[0] + 1;
                                            ts.setStat(array);
                                            if (logger.isDebugEnabled())
                                                logger.debug("stats " + array[0] + " " + array[1]);
                                        }
                                        eventMap.put(recItem2.getName(), ts);

                                    }
                                }
                            }
                            count++;
                            // logger.info("event statistics: "+eventMatch +
                            // " and " +eventHit +
                            // " ; stat statistics: "+statMatch + " and "
                            // +statHit);
                        }
                    }
                    if (timings) {
                        recordingMatchEnd = ManagementFactory.getThreadMXBean()
                                .getThreadCpuTime(Thread.currentThread().getId());
                        if (matchTimings.containsKey(rec.getName())) {
                            arrayBefore = matchTimings.get(rec.getName());
                            // logger.info(file.getName() + " contains " +
                            // arrayBefore);
                            // 0-> sum of time for success matching of given
                            // recording ; 1-> sum of time for failed
                            // matching ; 2-> count of match attempts,
                            // 3->count of success attempts

                            long[] array = { arrayBefore[0] + recordingMatchEnd - recordingMatchStart,
                                    arrayBefore[1], arrayBefore[2] + 1, arrayBefore[3] + 1 };
                            // logger.info(file.getName() +
                            // " add success to" + rec.getName() + " 0: "+
                            // array[0] + " 1: "+ array[1]+ " 2: "+ array[2]
                            // +" 3: "+ array[3]);
                            matchTimings.put(rec.getName(), array);
                        } else {
                            long[] array = { recordingMatchEnd - recordingMatchStart, 0, 1, 1 };
                            matchTimings.put(rec.getName(), array);
                            // logger.info(file.getName() + " first success"
                            // + rec.getName() + " 0: "+ array[0] + " 1: "+
                            // array[1]+ " 2: "+ array[2] +" 3: "+
                            // array[3]);
                        }
                    }
                } else {
                    if (timings) {
                        recordingMatchEnd = ManagementFactory.getThreadMXBean()
                                .getThreadCpuTime(Thread.currentThread().getId());
                        if (matchTimings.containsKey(rec.getName())) {
                            arrayBefore = matchTimings.get(rec.getName());
                            // 0-> sum of time for success matching of given
                            // recording ; 1-> sum of time for failed
                            // matching ; 2-> count of match attempts,
                            // 3->count of success attempts
                            long[] array = { arrayBefore[0],
                                    arrayBefore[1] + recordingMatchEnd - recordingMatchStart,
                                    arrayBefore[2] + 1, arrayBefore[3] };
                            matchTimings.put(rec.getName(), array);
                        } else {
                            long[] array = { 0, recordingMatchEnd - recordingMatchStart, 1, 0 };
                            matchTimings.put(rec.getName(), array);
                        }
                    }
                }

            }
            lineCount++;

            // timing
        }
    } catch (NumberFormatException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        try {
            buf1st.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /*
     * if (logger.isInfoEnabled()) { Iterator Ite =
     * matchTimings.entrySet().iterator(); long successTotalTime=0; long
     * failedTotalTime=0; // 0-> sum of time for success matching of given
     * // recording ; 1-> sum of time for failed // matching ; 2-> count of
     * match attempts, // 3->count of success attempts // long[] array;
     * while (Ite.hasNext()) { Map.Entry pairs = (Map.Entry) Ite.next();
     * long[] array = (long[]) pairs.getValue(); logger.info(file.getName()
     * + " - "+ pairs.getKey() + " / success all time: " + array[0] +
     * " failed all time: " + array[1] + " attempt count: " + array[2] +
     * " success count: " + array[3] + " failed count:"
     * +(array[2]-array[3])); successTotalTime=successTotalTime+array[0];
     * failedTotalTime=failedTotalTime+array[1]; } logger.info("success: "
     * +successTotalTime + " failed: " + failedTotalTime); Ite =
     * matchTimings.entrySet().iterator(); while (Ite.hasNext()) { Map.Entry
     * pairs = (Map.Entry) Ite.next(); long[] array = (long[])
     * pairs.getValue(); logger.info(file.getName() + " percents - "+
     * pairs.getKey() + " / % success time: " + (( successTotalTime!=0) ?
     * ((double)((double)array[0] / successTotalTime)*100) : 0 ) +
     * " % failed time: " + (( failedTotalTime!=0) ?((double)array[1]/
     * failedTotalTime)*100 :0) + " attempt cost: " + ((array[2]!=0) ?
     * ((double)successTotalTime + failedTotalTime ) /array[2]:0 )+
     * " success cost: " + ((array[3]!=0) ? ((double)successTotalTime )
     * /array[3] : 0) + " failed cost:" + ((array[2]-array[3]!=0) ?
     * ((double)failedTotalTime/(array[2]-array[3])) : 0) ); } }
     */
    return new FileMineResult(fileRecord, statMap, eventMap, matchTimings, RIFileLineDateMap, startDate,
            endDate);
}

From source file:org.apache.kylin.common.util.BasicTest.java

@Test
@Ignore("for dev only")
public void test3() throws Exception {
    FastDateFormat formatter = org.apache.kylin.common.util.DateFormat
            .getDateFormat("MMM dd, yyyy hh:mm:ss aa");
    System.out.println(formatter.format(new Date()));

    String timeStr = "Jul 20, 2016 9:59:17 AM";

    System.out.println(formatter.parse(timeStr).getTime());
}

From source file:org.apache.kylin.source.kafka.job.UpdateTimeRangeStep.java

@Override
protected ExecuteResult doWork(ExecutableContext context) throws ExecuteException {
    final CubeManager cubeManager = CubeManager.getInstance(context.getConfig());
    final CubeInstance cube = cubeManager.getCube(CubingExecutableUtil.getCubeName(this.getParams()));
    final CubeSegment segment = cube.getSegmentById(CubingExecutableUtil.getSegmentId(this.getParams()));
    final TblColRef partitionCol = segment.getCubeDesc().getModel().getPartitionDesc()
            .getPartitionDateColumnRef();
    final String outputPath = this.getParams().get(BatchConstants.CFG_OUTPUT_PATH);
    final Path outputFile = new Path(outputPath, partitionCol.getName());

    String minValue = null, maxValue = null, currentValue = null;
    FSDataInputStream inputStream = null;
    BufferedReader bufferedReader = null;
    try {//from w ww  .j a v  a 2  s  .  co  m
        FileSystem fs = HadoopUtil.getFileSystem(outputPath);
        inputStream = fs.open(outputFile);
        bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        minValue = currentValue = bufferedReader.readLine();
        while (currentValue != null) {
            maxValue = currentValue;
            currentValue = bufferedReader.readLine();
        }
    } catch (IOException e) {
        logger.error("fail to read file " + outputFile, e);
        return new ExecuteResult(ExecuteResult.State.ERROR, e.getLocalizedMessage());
    } finally {
        IOUtils.closeQuietly(bufferedReader);
        IOUtils.closeQuietly(inputStream);
    }

    final DataType partitionColType = partitionCol.getType();
    FastDateFormat dateFormat;
    if (partitionColType.isDate()) {
        dateFormat = DateFormat.getDateFormat(DateFormat.DEFAULT_DATE_PATTERN);
    } else if (partitionColType.isDatetime() || partitionColType.isTimestamp()) {
        dateFormat = DateFormat.getDateFormat(DateFormat.DEFAULT_DATETIME_PATTERN_WITHOUT_MILLISECONDS);
    } else if (partitionColType.isStringFamily()) {
        String partitionDateFormat = segment.getCubeDesc().getModel().getPartitionDesc()
                .getPartitionDateFormat();
        if (StringUtils.isEmpty(partitionDateFormat)) {
            partitionDateFormat = DateFormat.DEFAULT_DATE_PATTERN;
        }
        dateFormat = DateFormat.getDateFormat(partitionDateFormat);
    } else {
        return new ExecuteResult(ExecuteResult.State.ERROR,
                "Type " + partitionColType + " is not valid partition column type");
    }

    try {
        long startTime = dateFormat.parse(minValue).getTime();
        long endTime = dateFormat.parse(maxValue).getTime();
        CubeUpdate cubeBuilder = new CubeUpdate(cube);
        segment.setDateRangeStart(startTime);
        segment.setDateRangeEnd(endTime);
        cubeBuilder.setToUpdateSegs(segment);
        cubeManager.updateCube(cubeBuilder);
        return new ExecuteResult(ExecuteResult.State.SUCCEED, "succeed");
    } catch (Exception e) {
        logger.error("fail to update cube segment offset", e);
        return new ExecuteResult(ExecuteResult.State.ERROR, e.getLocalizedMessage());
    }
}

From source file:org.apache.openmeetings.util.CalendarPatterns.java

private static Date validDate(FastDateFormat sdf, String testdate) {
    Date resultDate = null;/*from   ww  w .  j a v a  2s.co  m*/
    try {
        resultDate = sdf.parse(testdate);
    } catch (ParseException | NumberFormatException e) {
        // if the format of the string provided doesn't match the format we
        // declared in SimpleDateFormat() we will get an exception
        return null;
    }

    if (!sdf.format(resultDate).equals(testdate)) {
        return null;
    }

    return resultDate;
}

From source file:org.apache.openmeetings.webservice.util.DateParamConverter.java

public static Date get(String val) {
    if (Strings.isEmpty(val)) {
        return null;
    }//w  ww . j a va2s . c  o  m
    for (FastDateFormat df : formats) {
        try {
            return df.parse(val);
        } catch (ParseException e) {
            // no-op
        }
    }
    throw new IllegalArgumentException("Unparsable format: " + val);
}