Example usage for java.text SimpleDateFormat setLenient

List of usage examples for java.text SimpleDateFormat setLenient

Introduction

In this page you can find the example usage for java.text SimpleDateFormat 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:org.pentaho.reporting.engine.classic.core.modules.gui.base.parameters.DatePickerParameterComponent.java

private DateFormat createDateFormat(final String parameterFormatString, final Locale locale,
        final TimeZone timeZone) {
    if (parameterFormatString != null) {
        try {/* w  w w  .  j  av a 2  s . co  m*/
            final SimpleDateFormat dateFormat = new SimpleDateFormat(parameterFormatString, locale);
            dateFormat.setTimeZone(timeZone);
            dateFormat.setLenient(false);
            return dateFormat;
        } catch (Exception e) {
            // boo! Not a valid pattern ...
            // its not a show-stopper either, as the pattern is a mere hint, not a mandatory thing
            logger.warn("Parameter format-string for date-parameter was not a valid date-format-string", e); // NON-NLS
        }
    }

    return DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
}

From source file:com.trenako.web.controllers.admin.AdminRailwaysController.java

@InitBinder
public void initBinder(WebDataBinder binder) {
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    dateFormat.setLenient(false);

    // convert empty String to null
    binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
}

From source file:com.windroilla.invoker.gcm.MyGcmListenerService.java

/**
 * Called when message is received.//from   w  w  w .  j a v a  2 s.c  o m
 *
 * @param from SenderID of the sender.
 * @param data Data bundle containing message data as key/value pairs.
 *             For Set of keys use data.keySet().
 */
// [START receive_message]
@Override
public void onMessageReceived(String from, Bundle data) {
    String message = data.getString("message");
    Log.d(TAG, "From: " + from);
    Log.d(TAG, "Message: " + message);

    if (from.startsWith("/topics/")) {
        // message received from some topic.
    } else {
        Log.i("Device ID ", deviceID);
        // normal downstream message.
        apiService.getBlockTimes(new RequestBlockTimes(deviceID)).subscribeOn(Schedulers.newThread())
                .observeOn(Schedulers.newThread()).subscribe(new Action1<BlockTimeList>() {
                    @Override
                    public void call(BlockTimeList blockTimeList) {
                        Log.d(TAG, blockTimeList.access_time);
                        Vector<ContentValues> cVVector = new Vector<ContentValues>(
                                blockTimeList.getBlockTimes().size());
                        AlarmManager mgrAlarm = (AlarmManager) getApplicationContext()
                                .getSystemService(ALARM_SERVICE);
                        ArrayList<PendingIntent> intentArray = new ArrayList<PendingIntent>();
                        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        formatter.setLenient(false);

                        for (int i = 0; i < blockTimeList.getBlockTimes().size(); i++) {
                            BlockTime blockTime = blockTimeList.getBlockTimes().get(i);
                            Log.d(TAG,
                                    blockTime.getCourse_id() + " " + blockTime.getId() + " "
                                            + blockTime.getStarttime() + " " + blockTime.getEndtime() + " "
                                            + blockTime.getCreated_time());
                            ContentValues blockTimeValues = new ContentValues();
                            blockTimeValues.put(BlocktimeContract.BlocktimeEntry.COLUMN_START_TIME,
                                    blockTime.getStarttime());
                            blockTimeValues.put(BlocktimeContract.BlocktimeEntry.COLUMN_END_TIME,
                                    blockTime.getEndtime());
                            blockTimeValues.put(BlocktimeContract.BlocktimeEntry.COLUMN_CREATED_TIME,
                                    blockTime.getCreated_time());
                            Intent startIntent = new Intent(getBaseContext(), AlarmReceiver.class);
                            startIntent.setAction("com.windroilla.invoker.blockservice.start");
                            Intent endIntent = new Intent(getBaseContext(), AlarmReceiver.class);
                            endIntent.setAction("com.windroilla.invoker.blockservice.stop");
                            PendingIntent pendingStartIntent = PendingIntent.getBroadcast(
                                    getApplicationContext(), blockTime.getId(), startIntent,
                                    PendingIntent.FLAG_UPDATE_CURRENT);
                            PendingIntent pendingEndIntent = PendingIntent.getBroadcast(getApplicationContext(),
                                    -blockTime.getId(), endIntent, PendingIntent.FLAG_UPDATE_CURRENT);
                            try {
                                mgrAlarm.set(AlarmManager.RTC_WAKEUP,
                                        formatter.parse(blockTime.getStarttime()).getTime(),
                                        pendingStartIntent);
                                Log.d(TAG,
                                        formatter.parse(blockTime.getStarttime()).getTime() + " "
                                                + System.currentTimeMillis() + " "
                                                + (formatter.parse(blockTime.getStarttime()).getTime()
                                                        - System.currentTimeMillis()));
                                Log.d(TAG,
                                        formatter.parse(blockTime.getEndtime()).getTime() + " "
                                                + System.currentTimeMillis() + " "
                                                + (formatter.parse(blockTime.getEndtime()).getTime()
                                                        - System.currentTimeMillis()));
                                mgrAlarm.set(AlarmManager.RTC_WAKEUP,
                                        formatter.parse(blockTime.getEndtime()).getTime(), pendingEndIntent);
                            } catch (ParseException e) {
                                Log.e(TAG, e.toString());
                            }
                            intentArray.add(pendingStartIntent);
                            intentArray.add(pendingEndIntent);
                            cVVector.add(blockTimeValues);
                        }
                        Log.d(TAG, intentArray.size() + " PendingIntents have been progressed");
                        int inserted = 0;
                        // add to database
                        if (cVVector.size() > 0) {
                            ContentValues[] cvArray = new ContentValues[cVVector.size()];
                            cVVector.toArray(cvArray);
                            getBaseContext().getContentResolver()
                                    .bulkInsert(BlocktimeContract.BlocktimeEntry.CONTENT_URI, cvArray);
                        }

                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        Log.e(TAG, "BlockTimes Sync failed! " + throwable);
                    }
                });

    }

    // [START_EXCLUDE]
    /**
     * Production applications would usually process the message here.
     * Eg: - Syncing with server.
     *     - Store message in local database.
     *     - Update UI.
     */

    /**
     * In some cases it may be useful to show a notification indicating to the user
     * that a message was received.
     */
    sendNotification(message);
    // [END_EXCLUDE]
}

From source file:org.betaconceptframework.astroboa.portal.utility.CalendarUtils.java

/**
 * Get a string of a certain date pattern form (e.g. YYYY-MM-DD i.e. 2008-03-29) and converts it to
 * a calendar object. //from  ww  w .j  av  a2  s.  com
 * @param dateString
 * @param dateFormatPattern
 * @return
 */
public Calendar convertDateStringToCalendar(String dateString, String dateFormatPattern, TimeZone zone,
        Locale locale) {
    SimpleDateFormat dateFormat = (SimpleDateFormat) DateFormat.getDateInstance();
    dateFormat.setLenient(false); // be strict in the formatting
    // apply accepted pattern
    dateFormat.applyPattern(dateFormatPattern);

    // get a date object
    try {
        Date date = dateFormat.parse(dateString);
        if (date != null) {
            Calendar calendar = new GregorianCalendar(zone, locale);
            calendar.setTime(date);
            return calendar;
        } else {
            return null;
        }
    } catch (Exception e) {
        logger.warn("The date string:" + dateString + " has an invalid format. The valid form is:"
                + dateFormatPattern, e);
        return null;
    }

}

From source file:eu.apenet.dpt.standalone.gui.eaccpf.EacCpfPanel.java

/***
 * Checks if there is a valid ISO date candidate
 * @param date date to check/*from w w w.  j a v a  2  s.  c o m*/
 * @param type only a year (yyyy), year with month (yyyy-MM) or a complete date (yyyy-MM-dd)
 * @return true if there is a valid candidate or false if not
 */
public static boolean isValidDate(String date, String type) {
    SimpleDateFormat dateFormat = null;

    dateFormat = checkDateFormat(type);

    dateFormat.setLenient(false);
    java.util.Date testDate = null;

    try {
        testDate = dateFormat.parse(date);
    } catch (ParseException e) {
        return false;
    }

    if (!dateFormat.format(testDate).equals(date))
        return false;

    return true;
}

From source file:org.ohmage.validator.prompt.TimestampPromptValidator.java

/**
 * Validates that the value in the promptResponse contains a timestamp of the form yyyy-MM-ddThh:mm:ss.
 *///from   www.j ava  2s.com
@Override
public boolean validate(Prompt prompt, JSONObject promptResponse) {
    if (isNotDisplayed(prompt, promptResponse)) {
        return true;
    }

    if (isSkipped(prompt, promptResponse)) {
        return isValidSkipped(prompt, promptResponse);
    }

    String timestamp = JsonUtils.getStringFromJsonObject(promptResponse, JsonInputKeys.PROMPT_VALUE);
    if (StringUtils.isEmptyOrWhitespaceOnly(timestamp)) {
        if (logger.isDebugEnabled()) {
            logger.debug("Missing or empty value for prompt " + prompt.getId());
        }
        return false;
    }

    SimpleDateFormat tsFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); // the DateFormat classes are not threadsafe
                                                                               // so they must be created for each run of this 
                                                                               // method
    tsFormat.setLenient(false);

    try {

        tsFormat.parse(timestamp);

    } catch (ParseException pe) {

        if (logger.isDebugEnabled()) {
            logger.debug("unparseable timestamp " + timestamp + " for prompt id " + prompt.getId());
        }

        return false;
    }

    return true;
}

From source file:org.onebusaway.nyc.vehicle_tracking.webapp.controllers.VehicleLocationSimulationController.java

@InitBinder
public void initBinder(WebDataBinder binder) {
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd_HH:mm");
    dateFormat.setLenient(false);
    binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
}

From source file:ru.codeinside.gses.webui.form.EFormBuilder.java

private eform.Form createExternalForm() {
    final PropertyTree propertyTree = formValue.getFormDefinition();
    final eform.Form form = new eform.Form() {
        @Override//from ww w. j  av  a 2 s .  c  om
        public Map<String, Property> plusBlock(String login, String name, String suffix, Integer newVal) {
            BlockNode cloneNode = ((BlockNode) propertyTree.getIndex().get(name));
            List<PropertyValue<?>> clones = ActivitiService.INSTANCE.get().withEngine(new Fetcher(login),
                    formId, cloneNode, suffix + "_" + newVal);

            Map<String, Property> map = new LinkedHashMap<String, Property>();
            for (PropertyValue<?> propertyValue : clones) {
                Property property = propertyToTree(propertyValue, suffix + "_" + newVal, eForm.fields);
                if (property != null) {
                    map.put(propertyValue.getNode().getId() + suffix + "_" + newVal, property);
                }
            }
            Property cloneProperty = this.getProperty(name + suffix);
            cloneProperty.updateValue(newVal.toString());
            if (cloneProperty.children == null) {
                cloneProperty.children = new ArrayList<Map<String, Property>>();
            }
            cloneProperty.children.add(map);
            return map;
        }

        @Override
        public void minusBlock(String name, String suffix, Integer newVal) {
            Property cloneProperty = this.getProperty(name + suffix);
            cloneProperty.updateValue(newVal.toString());
            if (cloneProperty.children != null) {
                Map<String, Property> map = cloneProperty.children.remove(newVal.intValue());
                for (String key : propertyKeySet(map)) {
                    eForm.fields.remove(key);
                }
            }
        }

        @Override
        public List<String> save() {
            List<String> messages = new ArrayList<String>();
            String taskId = formId.taskId;
            if (taskId != null) {
                for (EField eField : eForm.fields.values()) {
                    Property property = eField.property;

                    // ? ? ?    boolean ?  false
                    if ("boolean".equals(property.type) && !property.isObtained()) {
                        property.updateValue("false");
                    }

                    if (property.isModified()) {
                        String value = property.value;
                        if (eField.node.getVariableType().getJavaType() == FileValue.class) {
                            File file = (File) property.content()[0];
                            String mime = (String) property.content()[1];
                            ExecutorService.INSTANCE.get().saveBytesBuffer(taskId, eField.id, property.value,
                                    mime, file);
                        } else if (eField.node.getVariableType().getJavaType() == Long.class) {
                            try {
                                ExecutorService.INSTANCE.get().saveBuffer(taskId, eField.id,
                                        Strings.isNullOrEmpty(value) ? null : Long.parseLong(value));
                            } catch (NumberFormatException e) {
                                messages.add(e.getMessage());
                            }
                        } else if (eField.node.getVariableType().getJavaType() == Date.class) {
                            Date parse = null;
                            if (!Strings.isNullOrEmpty(value)) {
                                String pattern = StringUtils.trimToNull(eField.node.getPattern()) == null
                                        ? DateType.PATTERN1
                                        : eField.node.getPattern();
                                try {
                                    SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat(pattern);
                                    simpleDateFormat1.setLenient(false);
                                    parse = simpleDateFormat1.parse(value);
                                } catch (ParseException e1) {
                                    try {
                                        SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat(
                                                DateType.PATTERN2);
                                        simpleDateFormat1.setLenient(false);
                                        parse = simpleDateFormat1.parse(value);
                                    } catch (ParseException e) {
                                        messages.add(e.getMessage());
                                        continue;
                                    }
                                }
                            }
                            ExecutorService.INSTANCE.get().saveBuffer(taskId, eField.id,
                                    parse == null ? null : parse.getTime());
                        } else if (eField.node.getVariableType().getJavaType() == Boolean.class) {
                            ExecutorService.INSTANCE.get().saveBuffer(taskId, eField.id,
                                    Boolean.TRUE.equals(Boolean.parseBoolean(value)) ? 1L : 0L);
                        } else {
                            ExecutorService.INSTANCE.get().saveBuffer(taskId, eField.id, value);
                        }
                        property.setSaved();
                    }
                }
            }
            return messages;
        }
    };
    for (PropertyValue propertyValue : formValue.getPropertyValues()) {
        Property property = propertyToTree(propertyValue, "", null);
        if (property != null) {
            form.props.put(propertyValue.getNode().getId(), property);
        }
    }
    return form;
}

From source file:es.pode.modificador.presentacion.configurar.objetos.buscar.BuscarObjetoControllerImpl.java

/**
 * @see es.pode.modificador.presentacion.configurar.objetos.buscar.BuscarObjetoController#selectAction(org.apache.struts.action.ActionMapping, es.pode.modificador.presentacion.configurar.objetos.buscar.SelectActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 */// www  .ja  va2s .  co  m
public final java.lang.String selectAction(ActionMapping mapping,
        es.pode.modificador.presentacion.configurar.objetos.buscar.SelectActionForm form,
        HttpServletRequest request, HttpServletResponse response) throws Exception {
    java.util.Locale locale = (java.util.Locale) request.getSession()
            .getAttribute(ConstantesAgrega.DEFAULT_LOCALE);
    ResourceBundle i18n = ResourceBundle.getBundle("application-resources", locale);

    String volver = "Volver";
    String buscar = i18n.getString("buscarObjeto.Buscar");
    String action = form.getAction();
    if (action == null) {
        return volver;
    }
    if (action.equals(buscar)) {

        // Guarda datos bsqueda en sesin
        BusquedaSession sesion = getBusquedaSession(request);
        boolean alMenosUnParametro = false;
        boolean parteFecha = false;

        if (vacia(form.getIdioma())) {
            throw new ValidatorException("{buscarObjeto.msgErrorIdioma}");
        }
        if (!vacia(form.getAutor())) {

            alMenosUnParametro = true;
        }
        if (!vacia(form.getIdentificador())) {

            alMenosUnParametro = true;
        }
        if (!vacia(form.getTitulo())) {

            alMenosUnParametro = true;
        }
        if (fechaValida(
                form.getAnyoDesde())/*&&fechaValida(form.getDiaDesde())&&fechaValida(form.getMesDesde())*/) {

            alMenosUnParametro = true;
            parteFecha = true;
        }
        if (fechaValida(
                form.getAnyoHasta())/*&&fechaValida(form.getDiaHasta())&&fechaValida(form.getMesHasta())*/) {

            alMenosUnParametro = true;
            parteFecha = true;
        }
        if (fechaValida(form.getDiaDesde())) {

            alMenosUnParametro = true;
            parteFecha = true;
        }
        if (fechaValida(form.getDiaHasta())) {

            alMenosUnParametro = true;
            parteFecha = true;
        }
        if (fechaValida(form.getMesDesde())) {

            alMenosUnParametro = true;
            parteFecha = true;
        }
        if (fechaValida(form.getMesHasta())) {

            alMenosUnParametro = true;
            parteFecha = true;
        }

        //Si al menos uno de los campos de una fecha se ha introducido, se da error si falta otro

        if (parteFecha) {
            if (!fechaValida(form.getDiaDesde())) {
                throw new ValidatorException("{buscarObjeto.msgErrorDiaDesde}");
            } else if (!fechaValida(form.getMesDesde())) {
                throw new ValidatorException("{buscarObjeto.msgErrorMesDesde}");
            } else if (!fechaValida(form.getAnyoDesde())) {
                throw new ValidatorException("{buscarObjeto.msgErrorAnyoDesde}");
            } else if (!fechaValida(form.getDiaHasta())) {
                throw new ValidatorException("{buscarObjeto.msgErrorDiaHasta}");
            } else if (!fechaValida(form.getMesHasta())) {
                throw new ValidatorException("{buscarObjeto.msgErrorMesHasta}");
            } else if (!fechaValida(form.getAnyoHasta())) {
                throw new ValidatorException("{buscarObjeto.msgErrorAnyoHasta}");
            }
        }

        if (!alMenosUnParametro) {
            throw new ValidatorException("{buscarObjeto.exception}");
        }

        //Vuelco el form a la sesion
        sesion.setAutor(form.getAutor());
        sesion.setIdentificador(form.getIdentificador());
        sesion.setTitulo(form.getTitulo());
        sesion.setIdioma(form.getIdioma());

        if (fechaValida(form.getDiaDesde()) && fechaValida(form.getMesDesde())
                && fechaValida(form.getAnyoDesde()) && fechaValida(form.getDiaHasta())
                && fechaValida(form.getMesHasta()) && fechaValida(form.getAnyoHasta())) {
            //Comprobaciones de la fecha
            SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
            format.setLenient(false);

            String guion = "-";
            int dayFrom, dayTo, yearFrom, yearTo, monthFrom, monthTo;
            try {
                dayFrom = Integer.valueOf(form.getDiaDesde()).intValue();
                dayTo = Integer.valueOf(form.getDiaHasta()).intValue();
                yearFrom = Integer.valueOf(form.getAnyoDesde()).intValue();
                yearTo = Integer.valueOf(form.getAnyoHasta()).intValue();
                monthFrom = Integer.valueOf(form.getMesDesde()).intValue();
                monthTo = Integer.valueOf(form.getMesHasta()).intValue();
            } catch (Exception e) {
                throw new ValidatorException("{buscarObjetos.msgErrorFormato}");
            }
            StringBuffer fechaFromStr = new StringBuffer();
            fechaFromStr.append(dayFrom).append(guion).append(monthFrom).append(guion).append(yearFrom);

            Date fechaFrom;
            Date fechaTo;

            try {
                fechaFrom = format.parse(fechaFromStr.toString());
                StringBuffer fechaToStr = new StringBuffer();
                fechaToStr.append(dayTo).append(guion).append(monthTo).append(guion).append(yearTo);

                fechaTo = format.parse(fechaToStr.toString());
                if (fechaTo.before(fechaFrom)) {
                    throw new ValidatorException("{buscarObjetos.msgErrorFormato}");
                }
            } catch (Exception e) {
                throw new ValidatorException("{buscarObjetos.msgErrorFormato}");
            }
            //Saco ahora campos de fecha a sesion
            String[] partes = format.format(fechaFrom).split("-");
            sesion.setDiaDesde(partes[0]);
            sesion.setMesDesde(partes[1]);
            sesion.setAnyoDesde(partes[2]);
            partes = format.format(fechaTo).split("-");
            sesion.setDiaHasta(partes[0]);
            sesion.setMesHasta(partes[1]);
            sesion.setAnyoHasta(partes[2]);
        } else {
            //Actualizamos los campos de fecha en sesion aunque no sean buenos
            sesion.setDiaDesde(form.getDiaDesde());
            sesion.setMesDesde(form.getMesDesde());
            sesion.setAnyoDesde(form.getAnyoDesde());
            sesion.setDiaHasta(form.getDiaHasta());
            sesion.setMesHasta(form.getMesHasta());
            sesion.setAnyoHasta(form.getAnyoHasta());
        }
        sesion.setResultados(null);
        return "Buscar";
    }

    return volver;
}

From source file:gestionale.persistence.DAOCliente.java

public Calendar trasformaData(String stringa) {

    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
    try {/*from w  w  w.  j  a  v a  2 s  . co m*/
        sdf.setLenient(false);
        Date data = sdf.parse(stringa);
        Calendar c = Calendar.getInstance();
        c.setTime(data);
        return c;

    } catch (ParseException pae) {
        //System.out.println("Si e' verificata una ParseException: " + pae.getMessage());
        return null;
    }
}