Example usage for org.joda.time.format DateTimeFormat forPattern

List of usage examples for org.joda.time.format DateTimeFormat forPattern

Introduction

In this page you can find the example usage for org.joda.time.format DateTimeFormat forPattern.

Prototype

public static DateTimeFormatter forPattern(String pattern) 

Source Link

Document

Factory to create a formatter from a pattern string.

Usage

From source file:com.nesscomputing.mojo.numbers.DateField.java

License:Apache License

@Override
public String getPropertyValue() {
    final DateTimeZone timeZone = dateDefinition.getTimezone() == null ? DateTimeZone.getDefault()
            : DateTimeZone.forID(dateDefinition.getTimezone());

    DateTime date = getDateTime(valueProvider.getValue(), timeZone);

    if (date == null && dateDefinition.getValue() != null) {
        date = new DateTime(dateDefinition.getValue(), timeZone);
    }//from   w  ww  .  ja  va  2  s.  c  o m

    if (date == null) {
        date = new DateTime(timeZone);
    }

    final String format = dateDefinition.getFormat();

    if (format == null) {
        return date.toString();
    } else {
        final DateTimeFormatter formatter = DateTimeFormat.forPattern(format);
        return formatter.print(date);
    }
}

From source file:com.nestedbird.components.bridges.JodaDateTimeSplitBridge.java

License:Open Source License

@Override
public Object get(final String name, final Document document) {
    final IndexableField stringDateTime = document.getField(name);

    if (stringDateTime != null) {
        return DateTime.parse(stringDateTime.stringValue(), DateTimeFormat.forPattern(DATETIME_FORMAT));
    } else {//ww w.ja  v a  2 s.  c  o m
        return null;
    }
}

From source file:com.nestedbird.components.bridges.JodaDateTimeSplitBridge.java

License:Open Source License

@Override
public String objectToString(final Object value) {
    final DateTime dateTime = (DateTime) Optional.ofNullable(value).orElse(new DateTime(0));

    return dateTime.toString(DateTimeFormat.forPattern(DATETIME_FORMAT));
}

From source file:com.nestedbird.modules.formparser.FormParse.java

License:Open Source License

/**
 * Parse JODA DateTime// ww  w  .j  a  v a 2s  . co  m
 *
 * @param value joda datetime value
 * @return new Joda DateTime
 */
private DateTime parseDateTime(final Object value) {
    return DateTime.parse(value.toString(), DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss"));
}

From source file:com.netcrest.pado.biz.file.CsvFileLoader.java

License:Open Source License

/**
 * Loads data into the grid by reading each row from the specified text
 * reader./*  w  ww.  j ava 2  s .com*/
 * 
 * @param textReader
 *            Text reader.
 * @param temporalTime
 *            Temporal time to be used to create "forever" records if
 *            schemaInfo.isHistory() and schemaInfo.isTemporal() are true.
 *            If -1 then the current time.
 * @return Number of entries put into the grid. Note that the returned value
 *         is not the actual number of entries in the file. For example, if
 *         IsHistory is true then only non-duplicate entries will be put
 *         into the grid and therefore the number of entries will be less
 *         than the number of records in the file.
 * @throws FileLoaderException
 * @throws InstantiationException
 * @throws IllegalAccessException
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
private int loadData(Reader textReader, long temporalTime)
        throws FileLoaderException, InstantiationException, IllegalAccessException {
    IBulkLoader bulkLoader;
    ITemporalAdminBizLink temporalAdminBiz = null;

    // For server-side, do not use IBiz which fails due to class loader
    // conflicts.
    if (PadoServerManager.getPadoServerManager() != null) {
        bulkLoader = schemaInfo.createBulkLoader();
        bulkLoader.setPath(schemaInfo.getGridPath());
        bulkLoader.setBatchSize(schemaInfo.getBatchSize());
    } else {
        if (schemaInfo.isTemporal()) {
            temporalAdminBiz = pado.getCatalog().newInstance(ITemporalAdminBiz.class, schemaInfo.getGridPath());
            bulkLoader = temporalAdminBiz.createBulkLoader(schemaInfo.getBatchSize());
            ((ITemporalBulkLoader) bulkLoader).setDiffEnabled(schemaInfo.isHistory());
            ((ITemporalBulkLoader) bulkLoader).setDiffTemporalTime(temporalTime);
        } else {
            IGridMapBiz gridMapBiz = pado.getCatalog().newInstance(IGridMapBiz.class, schemaInfo.getGridPath());
            bulkLoader = gridMapBiz.getBulkLoader(schemaInfo.getBatchSize());
        }
    }
    EntryCountListener entryCountListener = new EntryCountListener();
    bulkLoader.addBulkLoaderListener(entryCountListener);

    String pkPropertyName = null;
    if (schemaInfo.getPkColumnNames().length == 1) {
        pkPropertyName = schemaInfo.getPkColumnNames()[0];
    }
    Field pkValueField = getField(schemaInfo.getValueClass(), pkPropertyName);
    Method pkDataMethod = getGetterMethod(schemaInfo.getValueClass(), pkPropertyName);

    if (pkValueField == null && pkDataMethod == null && schemaInfo.getPkColumnNames() == null) {
        throw new FileLoaderException("Primary key schema information undefined.");
    }
    if (pkValueField == null && pkDataMethod == null && schemaInfo.getKeyClass() == null) {
        throw new FileLoaderException(
                "The passed in primary key field, method, and class are null. One of them must be non-null.");
    }
    dateFormatter = new SimpleDateFormat(schemaInfo.getDateFormat());
    jodaFormatter = DateTimeFormat.forPattern(schemaInfo.getDateFormat());

    Object[] valueClassSetters = getFieldMethodList(schemaInfo.getValueClass(),
            schemaInfo.getValueColumnNames(), "set", 1);
    Object[] pkClassSetters = getFieldMethodList(schemaInfo.getKeyClass(), schemaInfo.getPkColumnNames(), "set",
            1);
    Object[] valueClassGetters = getFieldMethodList(schemaInfo.getValueClass(),
            schemaInfo.getValueColumnNames(), "get", 0);
    boolean isKeyColumns = schemaInfo.isKeyColumns();
    int keyStartIndex = schemaInfo.getKeyStartIndex();
    int valueStartIndex = schemaInfo.getValueStartIndex();
    int temporalStartIndex = schemaInfo.getTemporalStartIndex();

    // Temporal attributes
    long startValidTime = schemaInfo.getTemporalStartTime().getTime();
    long endValidTime = schemaInfo.getTemporalEndTime().getTime();
    long writtenTime;
    if (schemaInfo.getTemporalWrittenTime() == null) {
        writtenTime = System.currentTimeMillis();
    } else {
        writtenTime = schemaInfo.getTemporalWrittenTime().getTime();
    }

    // User
    String username;
    if (schemaInfo.getUsername() == null) {
        username = System.getProperty("user.name");
    } else {
        username = schemaInfo.getUsername();
    }

    IRowFilter rowFilter = null;
    IEntryFilter entryFilter = null;
    Class clazz = schemaInfo.getRowFilterClass();
    if (clazz != null) {
        if (IRowFilter.class.isAssignableFrom(clazz)) {
            rowFilter = (IRowFilter) clazz.newInstance();
        } else {
            if (verbose) {
                System.err.println("Invalid row filter type. " + clazz.getName() + " does not implement "
                        + IRowFilter.class.getName() + ". Row filter ignored.");
            }
        }
    }
    clazz = schemaInfo.getEntryFilterClass();
    if (clazz != null) {
        if (IEntryFilter.class.isAssignableFrom(clazz)) {
            entryFilter = (IEntryFilter) clazz.newInstance();
        } else {
            if (verbose) {
                System.err.println("Invalid entry filter type. " + clazz.getName() + " does not implement "
                        + IEntryFilter.class.getName() + ". Entry filter ignored.");
            }
        }
    }

    int lineNumber = 0;
    int count = 0;
    BufferedReader reader = null;
    String line = null;
    try {
        reader = new BufferedReader(textReader);
        // skip the rows before the start row
        for (int i = 1; i < schemaInfo.getStartRow(); i++) {
            line = reader.readLine();
            lineNumber++;
        }
        while ((line = readLine(reader)) != null) {
            lineNumber++;
            String line2 = line.trim();
            if (line2.startsWith("#") || line2.length() == 0) {
                continue;
            }
            // String[] tokens =
            // line.split(String.valueOf(schemaInfo.getDelimiter()));
            String tokens[] = getTokens(line, schemaInfo.getDelimiter());
            if (tokens == null) {
                continue;
            }
            if (tokens.length < 0) {
                continue;
            }

            Object keyObject = null;
            Object dataObject = null;

            if (rowFilter != null) {
                keyObject = rowFilter.filterKey(tokens);
                if (keyObject == null) {
                    continue;
                }
                dataObject = rowFilter.filterValue(tokens);
                if (dataObject == null) {
                    continue;
                }
            } else {
                if (KeyMap.class.isAssignableFrom(schemaInfo.getValueClass())) {
                    dataObject = createKeyMap(schemaInfo.getKeyType(), schemaInfo.getValueClass(),
                            schemaInfo.getValueColumnNames(), schemaInfo.getValueColumnTypes(), tokens,
                            valueStartIndex);
                } else {
                    dataObject = createObject(schemaInfo.getValueClass(), valueClassSetters, tokens,
                            valueStartIndex);
                }
                keyObject = null;
                // If valueStartIndex begins from the first index then
                // the key object must be obtained from the value object.
                if (valueStartIndex == 0) {
                    if (dataObject instanceof IPrimaryKey) {
                        keyObject = ((IPrimaryKey) dataObject).getPrimaryKey();
                    } else if (schemaInfo.getPkColumnNames().length > 0) {
                        if (isKeyColumns) {
                            keyObject = createObject(schemaInfo.getKeyClass(), pkClassSetters, tokens,
                                    keyStartIndex);
                        } else {
                            // IsKeyAutoGen overrides primary keys
                            if (schemaInfo.isKeyAutoGen()) {
                                keyObject = UUID.randomUUID().toString();
                            } else {
                                if (dataObject instanceof KeyMap) {
                                    keyObject = createKey(schemaInfo.getKeyClass(),
                                            schemaInfo.getPkColumnNames(), (KeyMap) dataObject);
                                } else {
                                    keyObject = createKey(schemaInfo.getKeyClass(), pkClassSetters,
                                            schemaInfo.getPkColumnNames(), schemaInfo.getValueClass(),
                                            valueClassGetters, dataObject);
                                }
                            }
                        }
                    } else {
                        if (schemaInfo.isKeyAutoGen()) {
                            keyObject = UUID.randomUUID().toString();
                        } else {
                            throw new FileLoaderException(
                                    "Unable to determine key object. Check the schema file format.");
                        }
                    }
                } else {
                    keyObject = createObject(schemaInfo.getKeyClass(), pkClassSetters, tokens,
                            schemaInfo.getKeyStartIndex());
                }
            }

            if (schemaInfo.isTemporal()) {
                ITemporalKey tk;
                ITemporalData td;
                // If the temporal start index is a non-negative number then
                // the temporal attributes are part of the the columns.
                if (temporalStartIndex != -1) {
                    tk = createTemporalKey(keyObject, tokens, temporalStartIndex);
                } else {
                    tk = new GemfireTemporalKey(keyObject, startValidTime, endValidTime, writtenTime, username);
                }
                td = new GemfireTemporalData(tk, dataObject);
                if (entryFilter != null) {
                    IEntryFilter.Entry entry = entryFilter.filterEntry(new IEntryFilter.Entry(tk, td));
                    if (entry != null && entry.getKey() != null && entry.getValue() != null) {
                        Object key = entry.getKey();
                        Object data = entry.getValue();
                        if (key instanceof ITemporalKey && data instanceof ITemporalData) {
                            bulkLoader.put((ITemporalKey) key, (ITemporalData) data);
                        } else {
                            bulkLoader.put(key, data);
                        }
                    }
                } else {
                    bulkLoader.put(tk, td);
                }
            } else {
                if (entryFilter != null) {
                    IEntryFilter.Entry entry = entryFilter
                            .filterEntry(new IEntryFilter.Entry(keyObject, dataObject));
                    if (entry != null && entry.getKey() != null && entry.getValue() != null) {
                        bulkLoader.put(entry.getKey(), entry.getValue());
                    }
                } else {
                    bulkLoader.put(keyObject, dataObject);
                }
            }
            count++;

            if (verbose) {
                if (count % bulkLoader.getBatchSize() == 0) {
                    System.out.println("   " + verboseTag + " Read: " + count + ", Loaded: "
                            + entryCountListener.getTotalCount());
                }
            }
        }

        bulkLoader.flush();

    } catch (Exception ex) {
        Logger.error(ex);
        throw new FileLoaderException(
                "Error occured while loading data: " + ex.getClass() + ", line=" + lineNumber + ": " + line,
                ex);
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                // ignore
            }
        }
    }

    return entryCountListener.getTotalCount();
}

From source file:com.netflix.dynomitemanager.sidecore.backup.S3Restore.java

License:Apache License

private long restoreTime(String dateString) {
    logger.info("Date to restore to: " + dateString);

    DateTimeFormatter formatter = null;
    try {/*w w  w. ja  v a2 s.co m*/
        formatter = DateTimeFormat.forPattern("yyyyMMdd");
    } catch (Exception e) {
        logger.error("Restore fast property not formatted properly " + e.getMessage());
        return -1;
    }

    DateTime dt = formatter.parseDateTime(dateString);
    DateTime dateBackup = dt.withTimeAtStartOfDay();
    return dateBackup.getMillis();

}

From source file:com.netflix.raigad.backup.S3RepositorySettingsParams.java

License:Apache License

public String formatDate(DateTime dateTime, String dateFormat) {
    DateTimeFormatter fmt = DateTimeFormat.forPattern(dateFormat);
    return dateTime.toString(fmt);
}

From source file:com.netflix.raigad.indexmanagement.indexfilters.DailyIndexNameFilter.java

License:Apache License

@Override
public boolean filter(String name) {
    if (name.length() < 9) {
        return false;
    }/*ww  w  .  j  a  va 2s.  c  o  m*/
    String date = name.substring(name.length() - 8, name.length());
    try {
        DateTime.parse(date, DateTimeFormat.forPattern("YYYYMMdd"));
        return true;
    } catch (Exception e) {
        return false;
    }
}

From source file:com.netflix.raigad.indexmanagement.indexfilters.MonthlyIndexNameFilter.java

License:Apache License

@Override
public boolean filter(String name) {
    if (name.length() < 7) {
        return false;
    }//from  w  ww .  j a v a 2 s.c o m

    Pattern pattern = Pattern.compile(MONTHLY_PATTERN);
    Matcher matcher = pattern.matcher(name);
    if (!matcher.matches())
        return false;

    String date = name.substring(name.length() - 6, name.length());
    try {
        DateTime.parse(date, DateTimeFormat.forPattern("YYYYMM"));
        return true;
    } catch (Exception e) {
        return false;
    }
}

From source file:com.netflix.raigad.indexmanagement.indexfilters.YearlyIndexNameFilter.java

License:Apache License

@Override
public boolean filter(String name) {
    if (name.length() < 5) {
        return false;
    }//from w w  w .  j a  v a 2 s. c  om

    Pattern pattern = Pattern.compile(YEARLY_PATTERN);
    Matcher matcher = pattern.matcher(name);
    if (!matcher.matches())
        return false;

    String date = name.substring(name.length() - 4, name.length());
    try {
        DateTime.parse(date, DateTimeFormat.forPattern("YYYY"));
        return true;
    } catch (Exception e) {
        return false;
    }
}