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.wso2.carbon.appmgt.rest.api.store.impl.AppsApiServiceImpl.java

@Override
public Response appsMobileScheduleUpdatePost(String contentType, ScheduleDTO schedule,
        SecurityContext securityContext) {
    String username = RestApiUtil.getLoggedInUsername();
    try {//from w w  w .  j  a  v a 2 s.  c o m
        Map<String, String> searchTerms = new HashMap<String, String>();
        searchTerms.put("id", schedule.getAppId());

        APIProvider apiProvider = RestApiUtil.getLoggedInUserProvider();
        List<App> result = apiProvider.searchApps(AppMConstants.MOBILE_ASSET_TYPE, searchTerms);
        if (result.isEmpty()) {
            String errorMessage = "Could not find requested application.";
            return RestApiUtil.buildNotFoundException(errorMessage, schedule.getAppId()).getResponse();
        }

        String tenantDomainName = MultitenantUtils.getTenantDomain(username);
        int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager()
                .getTenantId(tenantDomainName);
        String tenantUserName = MultitenantUtils.getTenantAwareUsername(username);
        String appId = schedule.getAppId();
        Operations mobileOperation = new Operations();
        String action = "update";
        String type = "device";
        String[] parameters;
        parameters = Arrays.copyOf(schedule.getDeviceIds().toArray(), schedule.getDeviceIds().toArray().length,
                String[].class);
        if (parameters == null) {
            RestApiUtil.handleBadRequest("Device IDs should be provided to perform device app installation",
                    log);
        }
        String scheduleTime = schedule.getScheduleTime();

        SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
        sdf.setLenient(false);
        Date date = sdf.parse(scheduleTime);

        JSONObject user = new JSONObject();
        user.put("username", tenantUserName);
        user.put("tenantDomain", tenantDomainName);
        user.put("tenantId", tenantId);

        String activityId = mobileOperation.performAction(user.toString(), action, tenantId, type, appId,
                parameters, scheduleTime, null);
        JSONObject response = new JSONObject();
        response.put("activityId", activityId);

        return Response.ok().entity(response.toString()).build();

    } catch (AppManagementException e) {
        RestApiUtil.handleInternalServerError("Internal Error occurred while installing", e, log);
    } catch (MobileApplicationException e) {
        RestApiUtil.handleBadRequest(e.getMessage(), log);
    } catch (UserStoreException e) {
        RestApiUtil.handleInternalServerError("User store related Error occurred while installing", e, log);
    } catch (JSONException e) {
        RestApiUtil.handleInternalServerError("Json casting Error occurred while installing", e, log);
    } catch (ParseException e) {
        RestApiUtil.handleBadRequest("Invalid schedule date format", log);
    }
    return Response.ok().build();
}

From source file:org.wso2.carbon.appmgt.rest.api.store.impl.AppsApiServiceImpl.java

@Override
public Response appsMobileScheduleInstallPost(String contentType, ScheduleDTO schedule,
        SecurityContext securityContext) {
    String username = RestApiUtil.getLoggedInUsername();
    try {/*w  w w.  ja  v a 2  s .  c o m*/
        Map<String, String> searchTerms = new HashMap<String, String>();
        searchTerms.put("id", schedule.getAppId());

        APIProvider apiProvider = RestApiUtil.getLoggedInUserProvider();
        List<App> result = apiProvider.searchApps(AppMConstants.MOBILE_ASSET_TYPE, searchTerms);
        if (result.isEmpty()) {
            String errorMessage = "Could not find requested application.";
            return RestApiUtil.buildNotFoundException(errorMessage, schedule.getAppId()).getResponse();
        }

        String tenantDomainName = MultitenantUtils.getTenantDomain(username);
        int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager()
                .getTenantId(tenantDomainName);
        String tenantUserName = MultitenantUtils.getTenantAwareUsername(username);
        String appId = schedule.getAppId();
        Operations mobileOperation = new Operations();
        String action = "install";
        String type = "device";
        String[] parameters;
        parameters = Arrays.copyOf(schedule.getDeviceIds().toArray(), schedule.getDeviceIds().toArray().length,
                String[].class);
        if (parameters == null) {
            RestApiUtil.handleBadRequest("Device IDs should be provided to perform device app installation",
                    log);
        }
        String scheduleTime = schedule.getScheduleTime();

        SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
        sdf.setLenient(false);
        Date date = sdf.parse(scheduleTime);

        JSONObject user = new JSONObject();
        user.put("username", tenantUserName);
        user.put("tenantDomain", tenantDomainName);
        user.put("tenantId", tenantId);

        String activityId = mobileOperation.performAction(user.toString(), action, tenantId, type, appId,
                parameters, scheduleTime, null);

        JSONObject response = new JSONObject();
        response.put("activityId", activityId);

        return Response.ok().entity(response.toString()).build();

    } catch (AppManagementException e) {
        RestApiUtil.handleInternalServerError("Internal Error occurred while installing", e, log);
    } catch (MobileApplicationException e) {
        RestApiUtil.handleBadRequest(e.getMessage(), log);
    } catch (UserStoreException e) {
        RestApiUtil.handleInternalServerError("User store related Error occurred while installing", e, log);
    } catch (JSONException e) {
        RestApiUtil.handleInternalServerError("Json casting Error occurred while installing", e, log);
    } catch (ParseException e) {
        RestApiUtil.handleBadRequest("Invalid schedule date format", log);
    }
    return Response.ok().build();
}

From source file:org.nuclos.client.wizard.steps.NuclosEntityAttributeCommonPropertiesStep.java

@Override
public void prepare() {
    super.prepare();

    cbMandatory.setEnabled(true);/*from  www  . jav  a  2 s  . c  o m*/

    fillCalcFunctionBox();

    if (!this.parentWizardModel.isStateModel()) {
        cbxAttributeGroup.setEnabled(false);
    } else {
        fillAttributeGroupBox();
    }

    if (getModel().getAttribute().getDatatyp().getJavaType().equals("java.lang.Integer")) {
        final NumericFormatDocument nfd = new NumericFormatDocument();
        nfd.addDocumentListener(new DefaultValueDocumentListener());
        tfDefaultValue.setDocument(nfd);

        final NumericFormatDocument nfdMandatory = new NumericFormatDocument();
        nfdMandatory.addDocumentListener(new MandatoryValueDocumentListener());
        tfMandatory.setDocument(nfdMandatory);
    } else if (getModel().getAttribute().getDatatyp().getJavaType().equals("java.lang.Double")) {
        final DoubleFormatDocument dfd = new DoubleFormatDocument();
        dfd.addDocumentListener(new DefaultValueDocumentListener());
        tfDefaultValue.setDocument(dfd);

        final DoubleFormatDocument dfdMandatory = new DoubleFormatDocument();
        dfdMandatory.addDocumentListener(new MandatoryValueDocumentListener());
        tfMandatory.setDocument(dfdMandatory);

    }

    if (getModel().isEditMode()) {
        tfLabel.setText(getModel().getAttribute().getInternalName());
        cbxCalcFunction.setSelectedItem(getModel().getAttribute().getCalcFunction());
        cbxAttributeGroup.setSelectedItem(getModel().getAttribute().getAttributeGroup());
        cbDistinct.setSelected(getModel().getAttribute().isDistinct());
        ItemListener ilArray[] = cbMandatory.getItemListeners();
        for (ItemListener il : ilArray) {
            cbMandatory.removeItemListener(il);
        }
        cbMandatory.setSelected(getModel().getAttribute().isMandatory());
        for (ItemListener il : ilArray) {
            cbMandatory.addItemListener(il);
        }
        cbLogBook.setSelected(getModel().getAttribute().isLogBook());
        cbIndexed.setSelected(getModel().getAttribute().isIndexed());
        if (getModel().getAttribute().getDatatyp().getJavaType().equals("java.util.Date")) {
            String str = getModel().getAttribute().getDefaultValue();
            if (RelativeDate.today().toString().equals(str)) {
                dateDefaultValue.setDate(new Date(System.currentTimeMillis()));
                dateDefaultValue.getJTextField().setText("Heute");
            } else if ("Heute".equalsIgnoreCase(str)) {
                dateDefaultValue.setDate(new Date(System.currentTimeMillis()));
                dateDefaultValue.getJTextField().setText("Heute");
            } else {
                SimpleDateFormat result = new SimpleDateFormat("dd.MM.yyyy", Locale.GERMANY);
                result.setLenient(false);
                try {
                    dateDefaultValue.setDate(result.parse(str));
                } catch (Exception e) {
                    // set no day
                    LOG.warn("prepare failed: " + e, e);
                }
            }
        } else if (getModel().getAttribute().getDatatyp().getJavaType().equals("java.lang.Boolean")) {
            String value = getModel().getAttribute().getDefaultValue();
            if (value != null && value.equalsIgnoreCase("ja")) {
                cbDefaultValue.setSelected(true);
            } else {
                cbDefaultValue.setSelected(false);
            }
        } else {
            tfDefaultValue.setText(getModel().getAttribute().getDefaultValue());
        }

        if (getModel().getAttribute().getDbName() != null) {
            String sModifiedDBName = new String(getModel().getAttribute().getDbName());

            tfDBFieldName.setText(sModifiedDBName.replaceFirst("^STRVALUE_", "").replaceFirst("^INTID_", ""));
            if (getModel().getAttribute().getMetaVO() != null && getModel().getAttribute().getField() != null) {
                tfDBFieldNameComplete.setText("STRVALUE_" + getModel().getAttribute().getDbName());
            } else if (getModel().getAttribute().getMetaVO() != null
                    && getModel().getAttribute().getField() == null) {
                tfDBFieldNameComplete.setText("INTID_" + getModel().getAttribute().getDbName());
            }
        }
    } else {
        if (!blnLabelModified)
            tfLabel.setText(getModel().getName().toLowerCase());

        if (getModel().getAttributeCount() == 0 && !blnDefaultSelected) {
            cbDistinct.setSelected(true);
            cbMandatory.setSelected(true);
            blnDefaultSelected = true;
        }
        cbDistinct.setEnabled(!this.parentWizardModel.hasRows());

        cbIndexed.setSelected(getModel().isRefernzTyp());

        if (cbxAttributeGroup.getModel().getSize() > 1) {
            if (this.parentWizardModel.isStateModel())
                cbxAttributeGroup.setSelectedIndex(1);
        }

        if (getModel().getAttribute().getDbName() != null) {
            String sModifiedDBName = new String(getModel().getAttribute().getDbName());

            tfDBFieldName.setText(sModifiedDBName.replaceFirst("^STRVALUE_", "").replaceFirst("^INTID_", ""));
            if (getModel().getAttribute().getMetaVO() != null && getModel().getAttribute().getField() != null) {
                tfDBFieldNameComplete.setText("STRVALUE_" + getModel().getAttribute().getDbName());
            } else if (getModel().getAttribute().getMetaVO() != null
                    && getModel().getAttribute().getField() == null) {
                tfDBFieldNameComplete.setText("INTID_" + getModel().getAttribute().getDbName());
            }
        }
    }

    Object objMandatoryValue = getModel().getAttribute().getMandatoryValue();

    if (getModel().isRefernzTyp() || getModel().isLookupTyp()) {

        ItemListener listener[] = cbxDefaultValue.getItemListeners();
        for (ItemListener il : listener) {
            cbxDefaultValue.removeItemListener(il);
        }
        ItemListener listenerMandatory[] = cbxDefaultValue.getItemListeners();
        for (ItemListener il : listenerMandatory) {
            cbxMandatory.removeItemListener(il);
        }
        boolean isValueList = getModel().getAttribute().isValueListProvider();

        cbxDefaultValue.setVisible(!isValueList);
        lovDefaultValue.setVisible(isValueList);
        tfDefaultValue.setVisible(false);
        dateDefaultValue.setVisible(false);
        cbDefaultValue.setVisible(false);

        cbxMandatory.setVisible(!isValueList && this.parentWizardModel.isEditMode());
        lovMandatory.setVisible(isValueList && this.parentWizardModel.isEditMode());
        tfMandatory.setVisible(false);
        dateMandatory.setVisible(false);
        cbMandatoryValue.setVisible(false);

        List<DefaultValue> defaultModel = new ArrayList<DefaultValue>();
        List<DefaultValue> mandatoryModel = new ArrayList<DefaultValue>();

        DefaultValue mandatoryValue = null;
        final String sEntity = !getModel().isLookupTyp() ? getModel().getAttribute().getMetaVO().getEntity()
                : getModel().getAttribute().getLookupMetaVO().getEntity();

        if (!isValueList) {
            Collection<MasterDataVO> colVO = MasterDataDelegate.getInstance().getMasterData(sEntity);
            for (MasterDataVO vo : colVO) {
                String sField = getModel().getAttribute().getField();
                if (sField == null)
                    break;
                Pattern referencedEntityPattern = Pattern.compile("[$][{][\\w\\[\\]]+[}]");
                Matcher referencedEntityMatcher = referencedEntityPattern.matcher(sField);
                StringBuffer sb = new StringBuffer();

                while (referencedEntityMatcher.find()) {
                    Object value = referencedEntityMatcher.group().substring(2,
                            referencedEntityMatcher.group().length() - 1);

                    String sName = value.toString();
                    Object fieldValue = vo.getField(sName);
                    if (fieldValue != null)
                        referencedEntityMatcher.appendReplacement(sb, fieldValue.toString());
                    else
                        referencedEntityMatcher.appendReplacement(sb, "");
                }

                // complete the transfer to the StringBuffer
                referencedEntityMatcher.appendTail(sb);
                sField = sb.toString();
                DefaultValue dv = new DefaultValue(vo.getIntId(), sField);
                defaultModel.add(dv);
                mandatoryModel.add(dv);
                if (dv.getId().equals(objMandatoryValue)) {
                    mandatoryValue = dv;
                }
            }

            Collections.sort(defaultModel);
            Collections.sort(mandatoryModel);

            defaultModel.add(0, new DefaultValue(null, null));
            mandatoryModel.add(0, new DefaultValue(null, null));

            cbxDefaultValue.setModel(new ListComboBoxModel<DefaultValue>(defaultModel));
            cbxDefaultValue.setSelectedItem(getModel().getAttribute().getIdDefaultValue());

            cbxMandatory.setModel(new ListComboBoxModel<DefaultValue>(mandatoryModel));
            if (mandatoryValue != null) {
                cbxMandatory.setSelectedItem(mandatoryValue);
            }

            for (ItemListener il : listener) {
                cbxDefaultValue.addItemListener(il);
            }

            for (ItemListener il : listenerMandatory) {
                cbxMandatory.addItemListener(il);
            }
        } else {
            final EntityFieldMetaDataVO efMetaDataVO = new EntityFieldMetaDataVO();
            efMetaDataVO.setField(sEntity);
            efMetaDataVO.setDataType(String.class.getName());
            efMetaDataVO.setForeignEntity(sEntity);
            efMetaDataVO.setForeignEntityField(getModel().getAttribute().getField());

            lovDefaultValue.setModel(getModel());
            lovDefaultValue.setEfMetaDataVO(efMetaDataVO);
            lovDefaultValue.setSelectedListener(new ListOfValues.SelectedListener() {
                @Override
                public void actionPerformed(CollectableValueIdField itemSelected) {
                    if (itemSelected == null) {
                        getModel().getAttribute().setIdDefaultValue(new DefaultValue(null, null));
                    } else {
                        getModel().getAttribute().setIdDefaultValue(
                                new DefaultValue(IdUtils.unsafeToId(itemSelected.getValueId()),
                                        (String) itemSelected.getValue()));
                    }
                }
            });
            lovMandatory.setModel(getModel());
            lovMandatory.setEfMetaDataVO(efMetaDataVO);
            lovMandatory.setSelectedListener(new ListOfValues.SelectedListener() {
                @Override
                public void actionPerformed(CollectableValueIdField itemSelected) {
                    if (itemSelected == null) {
                        getModel().getAttribute().setMandatoryValue(new DefaultValue(null, null).getId());
                    } else {
                        getModel().getAttribute().setMandatoryValue(
                                new DefaultValue(IdUtils.unsafeToId(itemSelected.getValueId()),
                                        (String) itemSelected.getValue()).getId());
                    }
                }
            });
        }
    } else if (getModel().getAttribute().getDatatyp().getJavaType().equals("java.util.Date")) {
        dateDefaultValue.setVisible(true);
        cbxDefaultValue.setVisible(false);
        lovDefaultValue.setVisible(false);
        tfDefaultValue.setVisible(false);
        cbDefaultValue.setVisible(false);

        cbxMandatory.setVisible(false);
        lovMandatory.setVisible(false);
        tfMandatory.setVisible(false);
        dateMandatory.setVisible(this.parentWizardModel.isEditMode());
        if (objMandatoryValue != null && objMandatoryValue instanceof Date) {
            dateMandatory.setDate((Date) objMandatoryValue);
        }

        cbMandatoryValue.setVisible(false);
    } else if (getModel().getAttribute().getDatatyp().getJavaType().equals("java.lang.Boolean")) {
        cbxDefaultValue.setVisible(false);
        lovDefaultValue.setVisible(false);
        tfDefaultValue.setVisible(false);
        dateDefaultValue.setVisible(false);
        cbDefaultValue.setVisible(true);

        cbxMandatory.setVisible(false);
        lovMandatory.setVisible(false);
        tfMandatory.setVisible(false);
        dateMandatory.setVisible(false);
        cbMandatoryValue.setVisible(this.parentWizardModel.isEditMode());
        if (objMandatoryValue != null && objMandatoryValue instanceof Boolean) {
            cbMandatoryValue.setSelected((Boolean) objMandatoryValue);
        }
    } else if (getModel().getAttribute().isValueList()) {
        ItemListener listener[] = cbxDefaultValue.getItemListeners();
        for (ItemListener il : listener) {
            cbxDefaultValue.removeItemListener(il);
        }

        cbxCalcFunction.setEnabled(false);
        cbxDefaultValue.setVisible(true);
        lovDefaultValue.setVisible(false);
        tfDefaultValue.setVisible(false);
        dateDefaultValue.setVisible(false);
        cbDefaultValue.setVisible(false);

        cbxDefaultValue.removeAllItems();
        cbxDefaultValue.addItem(new DefaultValue(null, null));
        cbxMandatory.addItem(new DefaultValue(null, null));
        for (ValueList valueList : getModel().getAttribute().getValueList()) {
            cbxDefaultValue.addItem(new DefaultValue(
                    valueList.getId() != null ? valueList.getId().intValue() : null, valueList.getLabel()));
        }

        cbxDefaultValue.setSelectedItem(getModel().getAttribute().getDefaultValue());
        for (ItemListener il : listener) {
            cbxDefaultValue.addItemListener(il);
        }

        listener = cbxMandatory.getItemListeners();
        for (ItemListener il : listener) {
            cbxMandatory.removeItemListener(il);
        }

        for (ValueList valueList : getModel().getAttribute().getValueList()) {
            DefaultValue dv = new DefaultValue(valueList.getId() != null ? valueList.getId().intValue() : null,
                    valueList.getLabel());
            cbxMandatory.addItem(dv);
            if (dv.getId() != null && dv.getId().equals(objMandatoryValue)) {
                cbxMandatory.setSelectedItem(dv);
            }
        }

        for (ItemListener il : listener) {
            cbxMandatory.addItemListener(il);
        }

        cbMandatory.setEnabled(getModel().getAttribute().getId() != null);
        cbxMandatory.setVisible(true);
        lovMandatory.setVisible(parentWizardModel.isEditMode() && getModel().getAttribute().getId() != null);
        tfMandatory.setVisible(false);
        dateMandatory.setVisible(false);
        cbMandatoryValue.setVisible(false);
    } else if (getModel().getAttribute().isImage() || getModel().getAttribute().isPasswordField()
            || getModel().getAttribute().isFileType()) {
        cbMandatory.setEnabled(false);
        cbxMandatory.setVisible(false);
        lovMandatory.setVisible(false);
        tfMandatory.setVisible(false);
        dateMandatory.setVisible(false);
        cbMandatoryValue.setVisible(false);
    } else {
        cbxDefaultValue.setVisible(false);
        lovDefaultValue.setVisible(false);
        tfDefaultValue.setVisible(true);
        dateDefaultValue.setVisible(false);
        cbDefaultValue.setVisible(false);
        cbxMandatory.setVisible(false);
        lovMandatory.setVisible(false);
        tfMandatory.setVisible(this.parentWizardModel.isEditMode());
        if (objMandatoryValue != null) {
            tfMandatory.setText(objMandatoryValue.toString());
        }
        dateMandatory.setVisible(false);
        cbMandatoryValue.setVisible(false);
    }

    Attribute attr = NuclosEntityAttributeCommonPropertiesStep.this.getModel().getAttribute();
    if (NuclosEntityAttributeCommonPropertiesStep.this.parentWizardModel.hasRows() && attr.getId() != null) {
        boolean blnAllowed = StringUtils.isEmpty(attr.getInternalName()) ? false
                : MetaDataDelegate.getInstance().isChangeDatabaseColumnToUniqueAllowed(
                        NuclosEntityAttributeCommonPropertiesStep.this.parentWizardModel.getEntityName(),
                        attr.getInternalName());

        if (!blnAllowed && !attr.isDistinct()) {
            cbDistinct.setSelected(false);
            cbDistinct.setEnabled(false);
            cbDistinct.setToolTipText(SpringLocaleDelegate.getInstance().getMessage(
                    "wizard.step.entitysqllayout.6",
                    "Das Feld {0} kann nicht auf ein eindeutiges Feld umgestellt werden.", attr.getLabel()));
        }
    }

    if (parentWizardModel.isVirtual()) {
        cbDistinct.setSelected(false);
        cbDistinct.setEnabled(false);
        tfMandatory.setEnabled(false);
        dateMandatory.setEnabled(false);
        cbMandatory.setEnabled(false);
        cbxMandatory.setEnabled(false);
        cbMandatoryValue.setEnabled(false);
        cbxCalcFunction.setEnabled(false);
        tfDBFieldName.setEnabled(false);
        cbIndexed.setEnabled(false);
        tfDefaultValue.setEnabled(false);
        dateDefaultValue.setEnabled(false);
        cbxDefaultValue.setEnabled(false);
        cbDefaultValue.setEnabled(false);
        cbLogBook.setEnabled(false);
    }
}

From source file:org.pentaho.di.core.Const.java

public static int decodeTime(String s, String DateFormat) throws Exception {
    SimpleDateFormat f = new SimpleDateFormat(DateFormat);
    TimeZone utcTimeZone = TimeZone.getTimeZone("UTC");
    f.setTimeZone(utcTimeZone);//from  w  ww .j  a v a  2  s.c om
    f.setLenient(false);
    ParsePosition p = new ParsePosition(0);
    Date d = f.parse(s, p);
    if (d == null) {
        throw new Exception("Invalid time value " + DateFormat + ": \"" + s + "\".");
    }
    return (int) d.getTime();
}

From source file:org.LexGrid.LexBIG.gui.ValueSetDefinitionDetails.java

private boolean isDateValid(String dateStr) {
    String format = "M/d/yyyy";
    String reFormat = Pattern.compile("d+|M+").matcher(Matcher.quoteReplacement(format))
            .replaceAll("\\\\d{1,2}");
    reFormat = Pattern.compile("y+").matcher(reFormat).replaceAll("\\\\d{4}");
    if (Pattern.compile(reFormat).matcher(dateStr).matches()) {

        // date string matches format structure, 
        // - now test it can be converted to a valid date
        SimpleDateFormat sdf = (SimpleDateFormat) DateFormat.getDateInstance();
        sdf.setLenient(false);
        sdf.applyPattern(format);//from   w  ww  . j av  a2  s.  com
        try {
            sdf.parse(dateStr);
            return true;
        } catch (ParseException e) {
            return false;
        }
    }
    return false;
}

From source file:hydrograph.ui.propertywindow.widgets.customwidgets.operational.TransformDialog.java

private boolean validate(String value, String dataType) {
    if (StringUtils.isNotBlank(value)) {
        try {// w  w w. j  a v  a  2s  .c  om
            if (dataType.equals(Messages.DATATYPE_INTEGER)) {
                Integer.valueOf(value);
                return true;
            } else if (dataType.equals(Messages.DATATYPE_STRING)) {
                String.valueOf(value);
                return true;
            } else if (dataType.equals(Messages.DATATYPE_DOUBLE)) {
                Double.valueOf(value);
                return true;
            } else if (dataType.equals(Messages.DATATYPE_FLOAT)) {
                Float.valueOf(value);
                return true;
            } else if (dataType.equals(Messages.DATATYPE_SHORT)) {
                Short.valueOf(value);
                return true;
            } else if (Boolean.FALSE.toString().equalsIgnoreCase(value)
                    || Boolean.TRUE.toString().equalsIgnoreCase(value)) {
                return true;
            } else if (dataType.equals(Messages.DATATYPE_BIGDECIMAL)) {
                new BigDecimal(value);
                return true;
            } else if (dataType.equals(Messages.DATATYPE_LONG)) {
                Long.valueOf(value);
                return true;
            } else if (dataType.equals(Messages.DATATYPE_DATE)) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                sdf.setLenient(false);
                sdf.parse(value);
                return true;
            } else {
                return false;
            }
        } catch (Exception exception) {
            return false;
        }
    } else {
        return false;
    }
}

From source file:edu.harvard.iq.dataverse.ingest.tabulardata.impl.plugins.csv.CSVFileReader.java

public int readFile(BufferedReader csvReader, DataTable dataTable, PrintWriter finalOut) throws IOException {

    List<DataVariable> variableList = new ArrayList<>();
    CSVParser parser = new CSVParser(csvReader, inFormat.withHeader());
    Map<String, Integer> headers = parser.getHeaderMap();

    int i = 0;/*www . j a v  a 2  s.  c om*/
    for (String varName : headers.keySet()) {
        if (varName == null || varName.isEmpty()) {
            // TODO:
            // Add a sensible variable name validation algorithm.
            // -- L.A. 4.0 alpha 1
            throw new IOException(BundleUtil.getStringFromBundle("ingest.csv.invalidHeader"));
        }

        DataVariable dv = new DataVariable();
        dv.setName(varName);
        dv.setLabel(varName);
        dv.setInvalidRanges(new ArrayList<>());
        dv.setSummaryStatistics(new ArrayList<>());
        dv.setUnf("UNF:6:NOTCALCULATED");
        dv.setCategories(new ArrayList<>());
        variableList.add(dv);

        dv.setTypeCharacter();
        dv.setIntervalDiscrete();
        dv.setFileOrder(i);
        dv.setDataTable(dataTable);
        i++;
    }

    dataTable.setVarQuantity((long) variableList.size());
    dataTable.setDataVariables(variableList);

    boolean[] isNumericVariable = new boolean[headers.size()];
    boolean[] isIntegerVariable = new boolean[headers.size()];
    boolean[] isTimeVariable = new boolean[headers.size()];
    boolean[] isDateVariable = new boolean[headers.size()];

    for (i = 0; i < headers.size(); i++) {
        // OK, let's assume that every variable is numeric;
        // but we'll go through the file and examine every value; the
        // moment we find a value that's not a legit numeric one, we'll
        // assume that it is in fact a String.
        isNumericVariable[i] = true;
        isIntegerVariable[i] = true;
        isDateVariable[i] = true;
        isTimeVariable[i] = true;
    }

    // First, "learning" pass.
    // (we'll save the incoming stream in another temp file:)
    SimpleDateFormat[] selectedDateTimeFormat = new SimpleDateFormat[headers.size()];
    SimpleDateFormat[] selectedDateFormat = new SimpleDateFormat[headers.size()];

    File firstPassTempFile = File.createTempFile("firstpass-", ".csv");

    try (CSVPrinter csvFilePrinter = new CSVPrinter(
            // TODO allow other parsers of tabular data to use this parser by changin inFormat
            new FileWriter(firstPassTempFile.getAbsolutePath()), inFormat)) {
        //Write  headers
        csvFilePrinter.printRecord(headers.keySet());
        for (CSVRecord record : parser.getRecords()) {
            // Checks if #records = #columns in header
            if (!record.isConsistent()) {
                List<String> args = Arrays.asList(new String[] { "" + (parser.getCurrentLineNumber() - 1),
                        "" + headers.size(), "" + record.size() });
                throw new IOException(BundleUtil.getStringFromBundle("ingest.csv.recordMismatch", args));
            }

            for (i = 0; i < headers.size(); i++) {
                String varString = record.get(i);
                isIntegerVariable[i] = isIntegerVariable[i] && varString != null
                        && (varString.isEmpty() || varString.equals("null")
                                || (firstNumCharSet.contains(varString.charAt(0))
                                        && StringUtils.isNumeric(varString.substring(1))));
                if (isNumericVariable[i]) {
                    // If variable might be "numeric" test to see if this value is a parsable number:
                    if (varString != null && !varString.isEmpty()) {

                        boolean isNumeric = false;
                        boolean isInteger = false;

                        if (varString.equalsIgnoreCase("NaN") || varString.equalsIgnoreCase("NA")
                                || varString.equalsIgnoreCase("Inf") || varString.equalsIgnoreCase("+Inf")
                                || varString.equalsIgnoreCase("-Inf") || varString.equalsIgnoreCase("null")) {
                            continue;
                        } else {
                            try {
                                Double testDoubleValue = new Double(varString);
                                continue;
                            } catch (NumberFormatException ex) {
                                // the token failed to parse as a double
                                // so the column is a string variable.
                            }
                        }
                        isNumericVariable[i] = false;
                    }
                }

                // If this is not a numeric column, see if it is a date collumn
                // by parsing the cell as a date or date-time value:
                if (!isNumericVariable[i]) {

                    Date dateResult = null;

                    if (isTimeVariable[i]) {
                        if (varString != null && !varString.isEmpty()) {
                            boolean isTime = false;

                            if (selectedDateTimeFormat[i] != null) {
                                ParsePosition pos = new ParsePosition(0);
                                dateResult = selectedDateTimeFormat[i].parse(varString, pos);

                                if (dateResult != null && pos.getIndex() == varString.length()) {
                                    // OK, successfully parsed a value!
                                    isTime = true;
                                }
                            } else {
                                for (SimpleDateFormat format : TIME_FORMATS) {
                                    ParsePosition pos = new ParsePosition(0);
                                    dateResult = format.parse(varString, pos);
                                    if (dateResult != null && pos.getIndex() == varString.length()) {
                                        // OK, successfully parsed a value!
                                        isTime = true;
                                        selectedDateTimeFormat[i] = format;
                                        break;
                                    }
                                }
                            }
                            if (!isTime) {
                                isTimeVariable[i] = false;
                                // if the token didn't parse as a time value,
                                // we will still try to parse it as a date, below.
                                // unless this column is NOT a date.
                            } else {
                                // And if it is a time value, we are going to assume it's
                                // NOT a date.
                                isDateVariable[i] = false;
                            }
                        }
                    }

                    if (isDateVariable[i]) {
                        if (varString != null && !varString.isEmpty()) {
                            boolean isDate = false;

                            // TODO:
                            // Strictly speaking, we should be doing the same thing
                            // here as with the time formats above; select the
                            // first one that works, then insist that all the
                            // other values in this column match it... but we
                            // only have one, as of now, so it should be ok.
                            // -- L.A. 4.0 beta
                            for (SimpleDateFormat format : DATE_FORMATS) {
                                // Strict parsing - it will throw an
                                // exception if it doesn't parse!
                                format.setLenient(false);
                                try {
                                    format.parse(varString);
                                    isDate = true;
                                    selectedDateFormat[i] = format;
                                    break;
                                } catch (ParseException ex) {
                                    //Do nothing
                                }
                            }
                            isDateVariable[i] = isDate;
                        }
                    }
                }
            }

            csvFilePrinter.printRecord(record);
        }
    }
    dataTable.setCaseQuantity(parser.getRecordNumber());
    parser.close();
    csvReader.close();

    // Re-type the variables that we've determined are numerics:
    for (i = 0; i < headers.size(); i++) {
        if (isNumericVariable[i]) {
            dataTable.getDataVariables().get(i).setTypeNumeric();

            if (isIntegerVariable[i]) {
                dataTable.getDataVariables().get(i).setIntervalDiscrete();
            } else {
                dataTable.getDataVariables().get(i).setIntervalContinuous();
            }
        } else if (isDateVariable[i] && selectedDateFormat[i] != null) {
            // Dates are still Strings, i.e., they are "character" and "discrete";
            // But we add special format values for them:
            dataTable.getDataVariables().get(i).setFormat(DATE_FORMATS[0].toPattern());
            dataTable.getDataVariables().get(i).setFormatCategory("date");
        } else if (isTimeVariable[i] && selectedDateTimeFormat[i] != null) {
            // Same for time values:
            dataTable.getDataVariables().get(i).setFormat(selectedDateTimeFormat[i].toPattern());
            dataTable.getDataVariables().get(i).setFormatCategory("time");
        }
    }
    // Second, final pass.
    try (BufferedReader secondPassReader = new BufferedReader(new FileReader(firstPassTempFile))) {
        parser = new CSVParser(secondPassReader, inFormat.withHeader());
        String[] caseRow = new String[headers.size()];

        for (CSVRecord record : parser) {
            if (!record.isConsistent()) {
                List<String> args = Arrays.asList(new String[] { "" + (parser.getCurrentLineNumber() - 1),
                        "" + headers.size(), "" + record.size() });
                throw new IOException(BundleUtil.getStringFromBundle("ingest.csv.recordMismatch", args));
            }

            for (i = 0; i < headers.size(); i++) {
                String varString = record.get(i);
                if (isNumericVariable[i]) {
                    if (varString == null || varString.isEmpty() || varString.equalsIgnoreCase("NA")) {
                        // Missing value - represented as an empty string in
                        // the final tab file
                        caseRow[i] = "";
                    } else if (varString.equalsIgnoreCase("NaN")) {
                        // "Not a Number" special value:
                        caseRow[i] = "NaN";
                    } else if (varString.equalsIgnoreCase("Inf") || varString.equalsIgnoreCase("+Inf")) {
                        // Positive infinity:
                        caseRow[i] = "Inf";
                    } else if (varString.equalsIgnoreCase("-Inf")) {
                        // Negative infinity:
                        caseRow[i] = "-Inf";
                    } else if (varString.equalsIgnoreCase("null")) {
                        // By request from Gus - "NULL" is recognized as a
                        // numeric zero:
                        caseRow[i] = isIntegerVariable[i] ? "0" : "0.0";
                    } else {
                        /* No re-formatting is done on any other numeric values.
                         * We'll save them as they were, for archival purposes.
                         * The alternative solution - formatting in sci. notation
                         * is commented-out below.
                         */
                        caseRow[i] = varString;
                        /*
                         if (isIntegerVariable[i]) {
                        try {
                            Integer testIntegerValue = new Integer(varString);
                            caseRow[i] = testIntegerValue.toString();
                        } catch (NumberFormatException ex) {
                            throw new IOException("Failed to parse a value recognized as an integer in the first pass! (?)");
                        }
                        } else {
                        try {
                            Double testDoubleValue = new Double(varString);
                            if (testDoubleValue.equals(0.0)) {
                                caseRow[i] = "0.0";
                            } else {
                                                                    // One possible implementation:
                                //
                                // Round our fractional values to 15 digits
                                // (minimum number of digits of precision guaranteed by
                                // type Double) and format the resulting representations
                                // in a IEEE 754-like "scientific notation" - for ex.,
                                // 753.24 will be encoded as 7.5324e2
                                BigDecimal testBigDecimal = new BigDecimal(varString, doubleMathContext);
                                caseRow[i] = String.format(FORMAT_IEEE754, testBigDecimal);
                                
                                // Strip meaningless zeros and extra + signs:
                                caseRow[i] = caseRow[i].replaceFirst("00*e", "e");
                                caseRow[i] = caseRow[i].replaceFirst("\\.e", ".0e");
                                caseRow[i] = caseRow[i].replaceFirst("e\\+00", "");
                                caseRow[i] = caseRow[i].replaceFirst("^\\+", "");
                            }
                        } catch (NumberFormatException ex) {
                            throw new IOException("Failed to parse a value recognized as numeric in the first pass! (?)");
                        }
                        }
                         */
                    }
                } else if (isTimeVariable[i] || isDateVariable[i]) {
                    // Time and Dates are stored NOT quoted (don't ask).
                    if (varString != null) {
                        // Dealing with quotes:
                        // remove the leading and trailing quotes, if present:
                        varString = varString.replaceFirst("^\"*", "");
                        varString = varString.replaceFirst("\"*$", "");
                        caseRow[i] = varString;
                    } else {
                        caseRow[i] = "";
                    }
                } else {
                    // Treat as a String:
                    // Strings are stored in tab files quoted;
                    // Missing values are stored as an empty string
                    // between two tabs (or one tab and the new line);
                    // Empty strings stored as "" (quoted empty string).
                    // For the purposes  of this CSV ingest reader, we are going
                    // to assume that all the empty strings in the file are
                    // indeed empty strings, and NOT missing values:
                    if (varString != null) {
                        // escape the quotes, newlines, and tabs:
                        varString = varString.replace("\"", "\\\"");
                        varString = varString.replace("\n", "\\n");
                        varString = varString.replace("\t", "\\t");
                        // final pair of quotes:
                        varString = "\"" + varString + "\"";
                        caseRow[i] = varString;
                    } else {
                        caseRow[i] = "\"\"";
                    }
                }
            }
            finalOut.println(StringUtils.join(caseRow, "\t"));
        }
    }
    long linecount = parser.getRecordNumber();
    finalOut.close();
    parser.close();
    dbglog.fine("Tmp File: " + firstPassTempFile);
    // Firstpass file is deleted to prevent tmp from filling up.
    firstPassTempFile.delete();
    if (dataTable.getCaseQuantity().intValue() != linecount) {
        List<String> args = Arrays
                .asList(new String[] { "" + dataTable.getCaseQuantity().intValue(), "" + linecount });
        throw new IOException(BundleUtil.getStringFromBundle("ingest.csv.line_mismatch", args));
    }
    return (int) linecount;
}

From source file:edu.harvard.iq.dataverse.ingest.IngestServiceBean.java

private void calculateUNF(DataFile dataFile, int varnum, String[] dataVector) throws IOException {
    String unf = null;/*from  www .  j a v a2  s.  com*/

    String[] dateFormats = null;

    // Special handling for Character strings that encode dates and times:

    if ("time".equals(dataFile.getDataTable().getDataVariables().get(varnum).getFormatCategory())) {
        dateFormats = new String[dataVector.length];
        String savedDateTimeFormat = dataFile.getDataTable().getDataVariables().get(varnum).getFormat();
        String timeFormat = null;
        if (savedDateTimeFormat != null && !savedDateTimeFormat.equals("")) {
            timeFormat = savedDateTimeFormat;
        } else {
            timeFormat = dateTimeFormat_ymdhmsS;
        }

        /* What follows is special handling of a special case of time values
         * non-uniform precision; specifically, when some have if some have 
         * milliseconds, and some don't. (and that in turn is only 
         * n issue when the timezone is present... without the timezone
         * the time string would still evaluate to the end, even if the 
         * format has the .SSS part and the string does not.
         * This case will be properly handled internally, once we permanently
         * switch to UNF6.
         * -- L.A. 4.0 beta 8
         */
        String simplifiedFormat = null;
        SimpleDateFormat fullFormatParser = null;
        SimpleDateFormat simplifiedFormatParser = null;

        if (timeFormat.matches(".*\\.SSS z$")) {
            simplifiedFormat = timeFormat.replace(".SSS", "");

            fullFormatParser = new SimpleDateFormat(timeFormat);
            simplifiedFormatParser = new SimpleDateFormat(simplifiedFormat);
        }

        for (int i = 0; i < dataVector.length; i++) {
            if (dataVector[i] != null) {

                if (simplifiedFormatParser != null) {
                    // first, try to parse the value against the "full" 
                    // format (with the milliseconds part):
                    fullFormatParser.setLenient(false);

                    try {
                        logger.fine("trying the \"full\" time format, with milliseconds: " + timeFormat + ", "
                                + dataVector[i]);
                        fullFormatParser.parse(dataVector[i]);
                    } catch (ParseException ex) {
                        // try the simplified (no time zone) format instead:
                        logger.fine("trying the simplified format: " + simplifiedFormat + ", " + dataVector[i]);
                        simplifiedFormatParser.setLenient(false);
                        try {
                            simplifiedFormatParser.parse(dataVector[i]);
                            timeFormat = simplifiedFormat;
                        } catch (ParseException ex1) {
                            logger.warning(
                                    "no parseable format found for time value " + i + " - " + dataVector[i]);
                            throw new IOException(
                                    "no parseable format found for time value " + i + " - " + dataVector[i]);
                        }
                    }

                }
                dateFormats[i] = timeFormat;
            }
        }
    } else if ("date".equals(dataFile.getDataTable().getDataVariables().get(varnum).getFormatCategory())) {
        dateFormats = new String[dataVector.length];
        String savedDateFormat = dataFile.getDataTable().getDataVariables().get(varnum).getFormat();
        for (int i = 0; i < dataVector.length; i++) {
            if (dataVector[i] != null) {
                if (savedDateFormat != null && !savedDateFormat.equals("")) {
                    dateFormats[i] = savedDateFormat;
                } else {
                    dateFormats[i] = dateFormat_ymd;
                }
            }
        }
    }

    try {
        if (dateFormats == null) {
            logger.fine("calculating the UNF value for string vector; first value: " + dataVector[0]);
            unf = UNFUtil.calculateUNF(dataVector);
        } else {
            unf = UNFUtil.calculateUNF(dataVector, dateFormats);
        }
    } catch (IOException iex) {
        logger.warning("IO exception thrown when attempted to calculate UNF signature for (character) variable "
                + varnum);
    } catch (UnfException uex) {
        logger.warning(
                "UNF Exception: thrown when attempted to calculate UNF signature for (character) variable "
                        + varnum);
    }

    if (unf != null) {
        dataFile.getDataTable().getDataVariables().get(varnum).setUnf(unf);
    } else {
        logger.warning("failed to calculate UNF signature for variable " + varnum);
    }
}

From source file:de.innovationgate.wga.server.api.WGA.java

/**
 * Returns an OpenWGA date format/*from   w  w w  .j a  v  a2 s .c o  m*/
 * @param pattern The date format pattern
 * @param locale A locale to use for locale-dependent date parts. Specify null to let the current WebTML context choose the locale.
 * @throws WGException
 */
public DateFormat getDateFormat(String pattern, Locale locale) throws WGException {

    // Select language for language dependent date formats
    if (locale == null) {
        locale = chooseLocale(locale);
    }

    // Language Fallback(s)

    if (WGUtils.isEmpty(pattern)) {
        return DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM, locale);
    }

    // For default patterns
    String lcPattern = pattern.toLowerCase();
    if (lcPattern.endsWith("date") || lcPattern.endsWith("time")) {
        int patternLength;
        if (lcPattern.startsWith("short")) {
            patternLength = DateFormat.SHORT;
        } else if (lcPattern.startsWith("medium")) {
            patternLength = DateFormat.MEDIUM;
        } else if (lcPattern.startsWith("long")) {
            patternLength = DateFormat.LONG;
        } else {
            patternLength = DateFormat.FULL;
        }

        if (lcPattern.endsWith("datetime")) {
            return new TextualDateFormat(locale,
                    DateFormat.getDateTimeInstance(patternLength, patternLength, locale));
        } else if (lcPattern.endsWith("time")) {
            return new TextualDateFormat(locale, DateFormat.getTimeInstance(patternLength, locale));
        } else {
            return new TextualDateFormat(locale, DateFormat.getDateInstance(patternLength, locale));
        }

    } else if (lcPattern.equals("iso8601")) {
        return new ISO8601DateFormat();
    }

    // For custom patterns
    SimpleDateFormat dateFormat = new SimpleDateFormat(pattern, locale);
    dateFormat.setLenient(false);
    return new TextualDateFormat(locale, dateFormat);

}

From source file:com.ut.healthelink.service.impl.transactionInManagerImpl.java

public String chkMySQLDate(String dateValue) {

    // some regular expression
    String time = "(\\s(([01]?\\d)|(2[0123]))[:](([012345]\\d)|(60))" + "[:](([012345]\\d)|(60)))?"; // with a space before, zero or one time

    // no check for leap years (Schaltjahr)
    // and 31.02.2006 will also be correct
    String day = "(([12]\\d)|(3[01])|(0?[1-9]))"; // 01 up to 31
    String month = "((1[012])|(0\\d))"; // 01 up to 12
    String year = "\\d{4}";

    // define here all date format
    String date = dateValue.replaceAll("/", "-");
    date = date.replaceAll("\\.", "-");
    Pattern pattern = Pattern.compile(year + "-" + month + "-" + day + time);

    // check dates
    if (pattern.matcher(date).matches()) {
        try {/*from  ww w.ja v  a  2 s.c  o  m*/
            SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd");
            dateformat.setLenient(false);
            dateformat.parse(date);
            return "Valid";
        } catch (Exception e) {
            e.printStackTrace();
            return "Error";
        }
    } else {
        return "";
    }
}