Example usage for java.text DateFormat setLenient

List of usage examples for java.text DateFormat setLenient

Introduction

In this page you can find the example usage for java.text DateFormat setLenient.

Prototype

public void setLenient(boolean lenient) 

Source Link

Document

Specify whether or not date/time parsing is to be lenient.

Usage

From source file:com.haulmont.chile.core.datatypes.impl.DateDatatype.java

@Override
public Date parse(String value) throws ParseException {
    if (StringUtils.isBlank(value)) {
        return null;
    }//from ww  w .  j  a  v a2 s.c om

    DateFormat format;
    if (formatPattern != null) {
        format = new SimpleDateFormat(formatPattern);
        format.setLenient(false);
    } else {
        format = DateFormat.getDateInstance();
    }
    return normalize(format.parse(value.trim()));
}

From source file:ubic.gemma.core.analysis.preprocess.batcheffects.AgilentScanDateExtractor.java

@Override
public Date extract(InputStream is) {
    BufferedReader reader = null;
    try {//from ww w  . j a  v a  2s .  c o m
        /*
         * Read the first three characters. IF they are ATF, it's a Axon file. If it's TYPE then it's probably an
         * agilent file.
         */
        reader = new BufferedReader(new InputStreamReader(is));

        String line = reader.readLine();

        if (line.startsWith("ATF")) {
            return this.extractGenePix(reader);
        } else if (line.startsWith("TYPE")) {
            line = reader.readLine();
            if (line.startsWith("FEPARAMS")) {
                int dateField = -1;

                // Agilent.
                String[] fields = StringUtils.split(line, '\t');
                for (int i = 0; i < fields.length; i++) {
                    if (fields[i].equalsIgnoreCase("Scan_date")) {
                        dateField = i;
                    }
                }

                if (dateField < 0) {
                    throw new IllegalStateException("Could not recognize the scan_date field");
                }

                // next line down has the data.
                line = reader.readLine();

                if (!line.startsWith("DATA")) {
                    throw new IllegalStateException("Could not understand Agilent scanner format");
                }

                fields = StringUtils.split(line, '\t');
                String date = fields[dateField];

                Date d;

                DateFormat f = new SimpleDateFormat("MM-dd-yyyy hh:mm:ss"); // 10-18-2005 13:02:36
                f.setLenient(true);
                d = f.parse(date);

                return d;
            }
        } else {
            throw new UnsupportedRawdataFileFormatException("Unknown agilent array file format.");
        }

    } catch (IOException | ParseException e) {
        throw new RuntimeException(e);
    } finally {
        try {
            if (reader != null)
                reader.close();
        } catch (IOException e) {
            AgilentScanDateExtractor.log.error("Failed to close open file handle: " + e.getMessage());
        }
    }
    return null;
}

From source file:ubic.gemma.analysis.preprocess.batcheffects.AgilentScanDateExtractor.java

@Override
public Date extract(InputStream is) {
    BufferedReader reader = null;
    try {/*from   w  w w  . java2s. c om*/
        /*
         * Read the first three characters. IF they are ATF, it's a Axon file. If it's TYPE then it's probably an
         * agilent file.
         */
        reader = new BufferedReader(new InputStreamReader(is));

        String line = reader.readLine();

        if (line.startsWith("ATF")) {
            return extractGenePix(reader);

        } else if (line.startsWith("TYPE")) {
            line = reader.readLine();
            if (line.startsWith("FEPARAMS")) {
                int dateField = -1;

                // Agilent.
                String[] fields = StringUtils.split(line, '\t');
                for (int i = 0; i < fields.length; i++) {
                    if (fields[i].equalsIgnoreCase("Scan_date")) {
                        dateField = i;
                    }
                }

                if (dateField < 0) {
                    throw new IllegalStateException("Could not recognize the scan_date field");
                }

                line = reader.readLine();

                if (!line.startsWith("DATA")) {
                    throw new IllegalStateException("Could not understand Agilent scanner format");
                }

                fields = StringUtils.split(line, '\t');
                String date = fields[dateField];

                DateFormat f = new SimpleDateFormat("MM-dd-yyyy hh:mm:ss"); // 10-18-2005 13:02:36
                f.setLenient(true);
                Date d = f.parse(date);

                return d;
            }
        } else {
            throw new UnsupportedRawdataFileFormatException("Unknown agilent array file format.");
        }

    } catch (IOException e) {
        throw new RuntimeException(e);
    } catch (ParseException e) {
        throw new RuntimeException(e);
    } finally {
        try {
            if (reader != null)
                reader.close();
        } catch (IOException e) {
            log.error("Failed to close open file handle: " + e.getMessage());
        }
    }
    return null;
}

From source file:org.springframework.springfaces.mvc.bind.ReverseDataBinderTest.java

/**
 * Setup the databinder with a customer date editor and a conversion service
 * @param dataBinder//from w  w w .  ja v  a 2  s  .  c  o  m
 */
private void initBinder(DataBinder dataBinder) {
    DateFormat df = new SimpleDateFormat("yyyy/dd/MM");
    df.setLenient(false);
    dataBinder.registerCustomEditor(Date.class, new CustomDateEditor(df, false));
    dataBinder.setConversionService(this.conversionService);
}

From source file:com.haulmont.chile.core.datatypes.impl.TimeDatatype.java

@Override
public String format(Object value) {
    if (value == null) {
        return "";
    } else {/*from  w w w .java 2s . c  om*/
        DateFormat format;
        if (formatPattern != null) {
            format = new SimpleDateFormat(formatPattern);
        } else {
            format = DateFormat.getTimeInstance();
        }
        format.setLenient(false);
        return format.format(value);
    }
}

From source file:com.cloud.api.ApiDispatcher.java

@SuppressWarnings({ "unchecked", "rawtypes" })
private static void setFieldValue(Field field, BaseCmd cmdObj, Object paramObj, Parameter annotation)
        throws IllegalArgumentException, ParseException {
    try {//from  w  w  w .  jav  a2s  .  c o  m
        field.setAccessible(true);
        CommandType fieldType = annotation.type();
        switch (fieldType) {
        case BOOLEAN:
            field.set(cmdObj, Boolean.valueOf(paramObj.toString()));
            break;
        case DATE:
            // This piece of code is for maintaining backward compatibility
            // and support both the date formats(Bug 9724)
            // Do the date messaging for ListEventsCmd only
            if (cmdObj instanceof ListEventsCmd) {
                boolean isObjInNewDateFormat = isObjInNewDateFormat(paramObj.toString());
                if (isObjInNewDateFormat) {
                    DateFormat newFormat = BaseCmd.NEW_INPUT_FORMAT;
                    synchronized (newFormat) {
                        field.set(cmdObj, newFormat.parse(paramObj.toString()));
                    }
                } else {
                    DateFormat format = BaseCmd.INPUT_FORMAT;
                    synchronized (format) {
                        Date date = format.parse(paramObj.toString());
                        if (field.getName().equals("startDate")) {
                            date = messageDate(date, 0, 0, 0);
                        } else if (field.getName().equals("endDate")) {
                            date = messageDate(date, 23, 59, 59);
                        }
                        field.set(cmdObj, date);
                    }
                }
            } else {
                DateFormat format = BaseCmd.INPUT_FORMAT;
                format.setLenient(false);
                synchronized (format) {
                    field.set(cmdObj, format.parse(paramObj.toString()));
                }
            }
            break;
        case FLOAT:
            // Assuming that the parameters have been checked for required before now,
            // we ignore blank or null values and defer to the command to set a default
            // value for optional parameters ...
            if (paramObj != null && isNotBlank(paramObj.toString())) {
                field.set(cmdObj, Float.valueOf(paramObj.toString()));
            }
            break;
        case INTEGER:
            // Assuming that the parameters have been checked for required before now,
            // we ignore blank or null values and defer to the command to set a default
            // value for optional parameters ...
            if (paramObj != null && isNotBlank(paramObj.toString())) {
                field.set(cmdObj, Integer.valueOf(paramObj.toString()));
            }
            break;
        case LIST:
            List listParam = new ArrayList();
            StringTokenizer st = new StringTokenizer(paramObj.toString(), ",");
            while (st.hasMoreTokens()) {
                String token = st.nextToken();
                CommandType listType = annotation.collectionType();
                switch (listType) {
                case INTEGER:
                    listParam.add(Integer.valueOf(token));
                    break;
                case UUID:
                    if (token.isEmpty())
                        break;
                    Long internalId = translateUuidToInternalId(token, annotation);
                    listParam.add(internalId);
                    break;
                case LONG: {
                    listParam.add(Long.valueOf(token));
                }
                    break;
                case SHORT:
                    listParam.add(Short.valueOf(token));
                case STRING:
                    listParam.add(token);
                    break;
                }
            }
            field.set(cmdObj, listParam);
            break;
        case UUID:
            if (paramObj.toString().isEmpty())
                break;
            Long internalId = translateUuidToInternalId(paramObj.toString(), annotation);
            field.set(cmdObj, internalId);
            break;
        case LONG:
            field.set(cmdObj, Long.valueOf(paramObj.toString()));
            break;
        case SHORT:
            field.set(cmdObj, Short.valueOf(paramObj.toString()));
            break;
        case STRING:
            if ((paramObj != null) && paramObj.toString().length() > annotation.length()) {
                s_logger.error("Value greater than max allowed length " + annotation.length() + " for param: "
                        + field.getName());
                throw new InvalidParameterValueException("Value greater than max allowed length "
                        + annotation.length() + " for param: " + field.getName());
            }
            field.set(cmdObj, paramObj.toString());
            break;
        case TZDATE:
            field.set(cmdObj, DateUtil.parseTZDateString(paramObj.toString()));
            break;
        case MAP:
        default:
            field.set(cmdObj, paramObj);
            break;
        }
    } catch (IllegalAccessException ex) {
        s_logger.error("Error initializing command " + cmdObj.getCommandName() + ", field " + field.getName()
                + " is not accessible.");
        throw new CloudRuntimeException("Internal error initializing parameters for command "
                + cmdObj.getCommandName() + " [field " + field.getName() + " is not accessible]");
    }
}

From source file:FormatTest.java

public FormatTestFrame() {
    setTitle("FormatTest");
    setSize(WIDTH, HEIGHT);/*from www .ja  va  2s .  c o m*/

    JPanel buttonPanel = new JPanel();
    okButton = new JButton("Ok");
    buttonPanel.add(okButton);
    add(buttonPanel, BorderLayout.SOUTH);

    mainPanel = new JPanel();
    mainPanel.setLayout(new GridLayout(0, 3));
    add(mainPanel, BorderLayout.CENTER);

    JFormattedTextField intField = new JFormattedTextField(NumberFormat.getIntegerInstance());
    intField.setValue(new Integer(100));
    addRow("Number:", intField);

    JFormattedTextField intField2 = new JFormattedTextField(NumberFormat.getIntegerInstance());
    intField2.setValue(new Integer(100));
    intField2.setFocusLostBehavior(JFormattedTextField.COMMIT);
    addRow("Number (Commit behavior):", intField2);

    JFormattedTextField intField3 = new JFormattedTextField(
            new InternationalFormatter(NumberFormat.getIntegerInstance()) {
                protected DocumentFilter getDocumentFilter() {
                    return filter;
                }

                private DocumentFilter filter = new IntFilter();
            });
    intField3.setValue(new Integer(100));
    addRow("Filtered Number", intField3);

    JFormattedTextField intField4 = new JFormattedTextField(NumberFormat.getIntegerInstance());
    intField4.setValue(new Integer(100));
    intField4.setInputVerifier(new FormattedTextFieldVerifier());
    addRow("Verified Number:", intField4);

    JFormattedTextField currencyField = new JFormattedTextField(NumberFormat.getCurrencyInstance());
    currencyField.setValue(new Double(10));
    addRow("Currency:", currencyField);

    JFormattedTextField dateField = new JFormattedTextField(DateFormat.getDateInstance());
    dateField.setValue(new Date());
    addRow("Date (default):", dateField);

    DateFormat format = DateFormat.getDateInstance(DateFormat.SHORT);
    format.setLenient(false);
    JFormattedTextField dateField2 = new JFormattedTextField(format);
    dateField2.setValue(new Date());
    addRow("Date (short, not lenient):", dateField2);

    try {
        DefaultFormatter formatter = new DefaultFormatter();
        formatter.setOverwriteMode(false);
        JFormattedTextField urlField = new JFormattedTextField(formatter);
        urlField.setValue(new URL("http://java.sun.com"));
        addRow("URL:", urlField);
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }

    try {
        MaskFormatter formatter = new MaskFormatter("###-##-####");
        formatter.setPlaceholderCharacter('0');
        JFormattedTextField ssnField = new JFormattedTextField(formatter);
        ssnField.setValue("078-05-1120");
        addRow("SSN Mask:", ssnField);
    } catch (ParseException exception) {
        exception.printStackTrace();
    }

    JFormattedTextField ipField = new JFormattedTextField(new IPAddressFormatter());
    ipField.setValue(new byte[] { (byte) 130, 65, 86, 66 });
    addRow("IP Address:", ipField);
}

From source file:us.mn.state.health.lims.common.util.validator.DateValidator.java

/** 
 * &lt;p&gt;Checks if the field is a valid date.  The &lt;code&gt;Locale&lt;/code&gt; is 
 * used with &lt;code&gt;java.text.DateFormat&lt;/code&gt;.  The setLenient method 
 * is set to &lt;code&gt;false&lt;/code&gt; for all.&lt;/p&gt; 
 * //from   w ww.j ava  2  s  . c  o m
 * @param value The value validation is being performed on. 
 * @param locale The locale to use for the date format, defaults to the default 
 * system default if null. 
*/
public boolean isValid(String value, Locale locale) {
    if (value == null) {
        return false;
    }
    //System.out.println("value & locale " + value + " " + locale);

    DateFormat formatter = null;
    if (locale != null) {
        formatter = DateFormat.getDateInstance(DateFormat.SHORT, locale);
    } else {
        formatter = DateFormat.getDateInstance(DateFormat.SHORT, Locale.getDefault());
    }
    formatter.setLenient(false);
    try {
        formatter.parse(value);
    } catch (ParseException e) {
        //bugzilla 2154
        LogEvent.logError("DateValidator", "isValid()", e.toString());
        return false;
    }
    return true;
}

From source file:it.geosdi.era.server.service.implementation.ServerService.java

public StringNodeTemporalLayer refreshTemporalLayer(StringNodeTemporalLayer temporalLayer) {
    URL serverURL;/*ww  w.j  a va 2  s  . c  o m*/

    try {
        serverURL = new URL(temporalLayer.getURLSERVERCAPABILITIES() + temporalLayer.getNameSpace());
        WebMapServer wms = new WebMapServer(serverURL);
        WMSCapabilities capabilities = wms.getCapabilities();
        DateFormat df = new SimpleDateFormat("dd-MM-yyyy-HH-mm");
        df.setLenient(false);

        List<StringNodeTemporalLayer> temporals = new ArrayList<StringNodeTemporalLayer>();

        for (int i = 1; i < capabilities.getLayerList().size(); i++) {
            Layer layer = capabilities.getLayerList().get(i);
            StringNodeTemporalLayer temp = new StringNodeTemporalLayer(temporalLayer.getNameSpace());
            temp.setNomeLayer(layer.getName());
            temp.setNameSpace(temporalLayer.getNameSpace());
            temp.setURLSERVER(temporalLayer.getURLSERVER());
            temp.setURLSERVERCAPABILITIES(temporalLayer.getURLSERVERCAPABILITIES());
            Date dataLayer = df.parse(layer.getTitle().substring(0, 16));
            temp.setDate(dataLayer);

            if (layer.getBoundingBoxes().values().size() != 0) {
                for (Object SRSID : layer.getBoundingBoxes().keySet()) {
                    temp.setBB(this.createBoundBox(layer.getBoundingBoxes().get(SRSID)), (String) SRSID);
                    temp.setSRSID((String) SRSID);
                }
            }
            temporals.add(temp);
        }

        Collections.sort(temporals);

        return temporals.get(0);

    } catch (MalformedURLException e) {
        logger.error(e.getMessage());
        throw new DAOException(e.getMessage());
    } catch (ServiceException e) {
        logger.error(e.getMessage());
        throw new DAOException(e.getMessage());
    } catch (IOException e) {
        logger.error(e.getMessage());
        throw new DAOException(e.getMessage());
    } catch (ParseException e) {
        logger.error(e.getMessage());
        throw new DAOException(e.getMessage());
    }
}

From source file:DateValidator.java

/**
 * <p>Checks if the field is a valid date.  The <code>Locale</code> is
 * used with <code>java.text.DateFormat</code>.  The setLenient method
 * is set to <code>false</code> for all.</p>
 *
 * @param value The value validation is being performed on.
 * @param locale The locale to use for the date format, defaults to the default
 * system default if null.//from w ww. jav  a2s  .c o m
 * @return true if the date is valid.
 */
public boolean isValid(String value, Locale locale) {

    if (value == null) {
        return false;
    }

    DateFormat formatter = null;
    if (locale != null) {
        formatter = DateFormat.getDateInstance(DateFormat.SHORT, locale);
    } else {
        formatter = DateFormat.getDateInstance(DateFormat.SHORT, Locale.getDefault());
    }

    formatter.setLenient(false);

    try {
        formatter.parse(value);
    } catch (ParseException e) {
        return false;
    }

    return true;
}