Example usage for org.apache.commons.lang StringUtils stripToNull

List of usage examples for org.apache.commons.lang StringUtils stripToNull

Introduction

In this page you can find the example usage for org.apache.commons.lang StringUtils stripToNull.

Prototype

public static String stripToNull(String str) 

Source Link

Document

Strips whitespace from the start and end of a String returning null if the String is empty ("") after the strip.

Usage

From source file:edu.ku.brc.specify.datamodel.WorkbenchRow.java

/**
 * @param latEntry//from   w  w  w.j a va2  s .c o m
 * @return a formatted string for use by specify.plugins.latlon  plugin
 */
@Transient
protected String getLatString(final String latEntry) {
    String ddString = null;
    try {
        GeoRefConverter geoConverter = new GeoRefConverter();
        LatLonConverter.FORMAT fmt = geoConverter.getLatLonFormat(StringUtils.stripToNull(latEntry));
        int decimalSize = geoConverter.getDecimalSize(StringUtils.stripToNull(latEntry));
        if (fmt.equals(LatLonConverter.FORMAT.None)) {
            return null;
        }
        ddString = geoConverter.convert(StringUtils.stripToNull(latEntry), GeoRefFormat.D_PLUS_MINUS.name());
        BigDecimal bigD = UIHelper.parseDoubleToBigDecimal(ddString);
        return LatLonConverter.ensureFormattedString(bigD, null, fmt, LatLonConverter.LATLON.Latitude,
                decimalSize);
    } catch (NumberFormatException ex) {
        //ignore
    } catch (Exception ex) {
        //ignore;
    }
    return null;
}

From source file:edu.ku.brc.specify.datamodel.WorkbenchRow.java

/**
 * @param longEntry/*from   w  w w. j  a va2s  .c o m*/
 * @return a formatted string for use by specify.plugins.latlon  plugin
 */
@Transient
protected String getLongString(final String longEntry) {
    String ddString = null;
    try {
        GeoRefConverter geoConverter = new GeoRefConverter();
        LatLonConverter.FORMAT fmt = geoConverter.getLatLonFormat(StringUtils.stripToNull(longEntry));
        int decimalSize = geoConverter.getDecimalSize(StringUtils.stripToNull(longEntry));
        if (fmt.equals(LatLonConverter.FORMAT.None)) {
            return null;
        }
        ddString = geoConverter.convert(StringUtils.stripToNull(longEntry), GeoRefFormat.D_PLUS_MINUS.name());
        BigDecimal bigD = UIHelper.parseDoubleToBigDecimal(ddString);
        return LatLonConverter.ensureFormattedString(bigD, null, fmt, LatLonConverter.LATLON.Longitude,
                decimalSize);
    } catch (NumberFormatException ex) {
        //ignore
    } catch (Exception ex) {
        //ignore;
    }
    return null;
}

From source file:com.adobe.acs.tools.csv_asset_importer.impl.CsvAssetImporterServlet.java

/**
 * Checks if the Row should be skipped//from   w w w  .j a va2 s. co  m
 * *
 * @param params  the CSV Asset Importer params
 * @param columns the Columns of the CSV
 * @param row     a row in the CSV
 * @return true if the row should be skipped
 */
private boolean isSkippedRow(final Parameters params, final Map<String, Column> columns, final String[] row) {

    if (StringUtils.isNotBlank(params.getSkipProperty())) {
        Column column = columns.get(params.getSkipProperty());
        if (column != null) {
            String value = StringUtils.stripToNull(row[column.getIndex()]);
            return StringUtils.equalsIgnoreCase(Boolean.TRUE.toString(), value);
        } else {
            log.warn("Could not find the Skip column at key [ {} ]", params.getSkipProperty());
        }
    }

    return false;
}

From source file:com.atlassian.jira.functest.framework.AdministrationImpl.java

public File exportDataToFile(final String fileName) {
    final FuncTestTimer timer = TestInformationKit.pullTimer("XML Export");

    final String realFileName = FilenameUtils.getName(fileName);

    log("Backing up data to '" + realFileName + "'");
    tester.gotoPage("secure/admin/XmlBackup!default.jspa");
    tester.setWorkingForm("jiraform");
    tester.setFormElement("filename", realFileName);
    tester.submit();//  w  w w  . j  ava2 s . co  m
    if (new IdLocator(tester, "replace_submit").exists()) {
        tester.setWorkingForm("jiraform");
        tester.submit();
    }

    final String text = StringUtils.stripToNull(new IdLocator(tester, "backup-file").getText());
    if (text == null) {
        Assert.fail("The restore did not redirect to the result page.");
    }
    timer.end();

    final File file = new File(text);
    Assert.assertTrue("Backup returned '" + text + "' which is not an absolute file.", file.isAbsolute());
    return file;
}

From source file:com.feedzai.commons.sql.abstraction.engine.AbstractDatabaseEngine.java

/**
 * Drops this table foreign keys./*from  ww  w.ja  v  a2s  . co m*/
 *
 * @param table The table name.
 * @throws Exception
 */
protected void dropFks(final String table) throws DatabaseEngineException {
    String schema = StringUtils.stripToNull(properties.getSchema());
    ResultSet rs = null;
    try {
        getConnection();
        rs = conn.getMetaData().getImportedKeys(null, schema, table);
        Set<String> fks = new HashSet<String>();
        while (rs.next()) {
            fks.add(rs.getString("FK_NAME"));
        }
        for (String fk : fks) {
            try {
                executeUpdate(String.format("ALTER TABLE %s DROP CONSTRAINT %s",
                        quotize(table, escapeCharacter()), quotize(fk, escapeCharacter())));
            } catch (Exception e) {
                logger.warn("Could not drop foreign key '{}' on table '{}'", fk, table);
                logger.debug("Could not drop foreign key.", e);
            }
        }
    } catch (Exception e) {
        throw new DatabaseEngineException("Error dropping foreign key", e);
    } finally {
        try {
            if (rs != null) {
                rs.close();
            }
        } catch (Exception a) {
            logger.trace("Error closing result set.", a);
        }
    }
}

From source file:edu.ku.brc.specify.tasks.subpane.wb.wbuploader.UploadTable.java

/**
 * @param fld//  w  w  w  .j  av a2 s  . com
 * @return values of the correct class for fld's setter.
 * @throws NoSuchMethodException
 * @throws InvocationTargetException
 * @throws IllegalArgumentException
 * @throws IllegalAccessException
 * @throws ParseException
 * 
 * Converts fld's string value to the correct class for the field being uploaded to.
 */
protected Object[] getArgForSetter(final UploadField ufld)
        throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, UploaderException {
    try {
        Object arg[] = new Object[1];
        Class<?> fldClass;
        //            if (tblClass.equals(DeterminationStatus.class) && ufld.getField().getName().equalsIgnoreCase("type"))
        //            {
        //                fldClass = Boolean.class;
        //            }
        //            else
        {
            fldClass = ufld.getSetter().getParameterTypes()[0];
        }
        String fldStr;
        if (ufld.getValueObject() == null) {
            fldStr = null;
        } else {
            fldStr = fldClass.equals(String.class) ? ufld.getValueObject() : ufld.getValueObject().trim();
        }
        if (fldClass == java.util.Calendar.class || fldClass == java.util.Date.class) {
            // There are problems with DateConverter (see DateConverter)
            if (fldStr == null || fldStr.equals("")) {
                arg[0] = null;
            } else {
                if (isDateWithPrecision(ufld.getField().getFieldInfo())) {
                    fldStr = dateConverter.adjustForPrecision(fldStr);
                } else {
                    //need to do this because even with lenient = false, Calendar.parse
                    //will still interpret '00/Jun/2004' as '31/May/2004'.
                    try {
                        UIFieldFormatterIFace.PartialDateEnum prec = dateConverter.getDatePrecision(fldStr);
                        if (prec.equals(UIFieldFormatterIFace.PartialDateEnum.Month)
                                || prec.equals(UIFieldFormatterIFace.PartialDateEnum.Year)) {
                            ParseException pex = new ParseException(
                                    UIRegistry.getResourceString("WB_UPLOAD_INVALID_FORMAT"), 0);
                            throw new UploaderException(pex, UploaderException.INVALID_DATA);
                        }
                    } catch (ParseException pex) {
                        //ignore. Problem should get caught in dateConverter.convert call below.
                    }
                }

                arg[0] = dateConverter.convert(fldStr);
            }
        } else if (fldClass == BigDecimal.class) {
            if (fldStr == null || fldStr.equals("")) {
                arg[0] = null;
            } else {
                if (!isLatLongFld(ufld)) {
                    if (!ufld.checkPrecisionAndScale(fldStr)) {
                        //System.out.println("bam");
                        throw new UploaderException(
                                String.format(getResourceString("WB_UPLOAD_INVALID_PREC_SCALE"),
                                        ufld.getPrecision() - ufld.getScale(), ufld.getScale()),
                                UploaderException.INVALID_DATA);
                    }
                } else {
                    boolean gotANumber = UIHelper.parseDoubleToBigDecimal(fldStr) != null;
                    if (!gotANumber) {
                        try {
                            fldStr = geoRefConverter.convert(StringUtils.stripToNull(fldStr),
                                    GeoRefFormat.D_PLUS_MINUS.name());
                        } catch (Exception ex) {
                            throw new UploaderException(ex, UploaderException.INVALID_DATA);
                        }
                    }
                }
                BigDecimal val = UIHelper.parseDoubleToBigDecimal(fldStr);
                if (StringUtils.isNotEmpty(fldStr) && val == null) {
                    throw new UploaderException(UIRegistry.getResourceString("WB_UPLOAD_INVALID_FORMAT"),
                            UploaderException.INVALID_DATA);
                }
                if (isLatLongFld(ufld)) {
                    Double maxVal = isLatFld(ufld) ? new Double("90") : new Double("180");
                    if (Math.abs(val.doubleValue()) > maxVal) {
                        throw new UploaderException(getResourceString("WB_UPLOAD_INVALID_GEOREF_VALUE"),
                                UploaderException.INVALID_DATA);
                    }
                }
                arg[0] = val;

            }
        } else if (fldClass == Boolean.class) {
            if (fldStr == null || fldStr.equals("")) {
                arg[0] = null;
            } else {
                int i;
                for (i = 0; i < WorkbenchTask.boolStrings.length; i++) {
                    if (fldStr.equalsIgnoreCase(WorkbenchTask.boolStrings[i]))
                        break;
                }
                if (i == WorkbenchTask.boolStrings.length) {
                    throw new UploaderException(getResourceString("WB_INVALID_BOOL_CELL_VALUE"),
                            UploaderException.INVALID_DATA);
                }
                arg[0] = i % 2 == 0 ? true : false;
            }
            //grotesquery
            //sorry, too much extra processing involved with maintaining one and only one current determination
            //to mess around with the isCurrent workbench mapping. An uploaded co is current or not current.
            //                if (tblClass.equals(DeterminationStatus.class)
            //                        && ufld.getField().getName().equalsIgnoreCase("type"))
            //                {
            //                    if (arg[0] == null) { throw new UploaderException(
            //                            getResourceString("WB_INVALID_BOOL_CELL_VALUE"),
            //                            UploaderException.INVALID_DATA); }
            //                    Boolean c = (Boolean) arg[0];
            //                    if (c)
            //                    {
            //                        arg[0] = DeterminationStatus.CURRENT;
            //                    }
            //                    else
            //                    {
            //                        arg[0] = DeterminationStatus.NOTCURRENT;
            //                    }
            //                }
        } else if (fldClass != String.class) {
            Class<?> stringArg[] = new Class<?>[1];
            stringArg[0] = String.class;
            Method converter = fldClass.getMethod("valueOf", stringArg);
            Object converterArg[] = new Object[1];
            converterArg[0] = fldStr;
            if (converterArg[0] != null) {
                arg[0] = converter.invoke(fldClass, converterArg);
            } else {
                arg[0] = null;
            }
        } else {
            UIFieldFormatterIFace formatter = ufld.getField().getFieldInfo().getFormatter();
            if (StringUtils.isBlank(fldStr)
                    && (formatter == null || !formatter.isIncrementer()/* || !formatter.isNumeric()*/)) {
                arg[0] = null;
            } else {
                Object val = fldStr;
                if (ufld.getField().getFieldInfo() != null) {
                    if (formatter != null) {
                        if (isUploadRoot && StringUtils.isBlank(fldStr) && formatter.isIncrementer()
                                && ufld.isAutoAssignForUpload()) {
                            if (!this.validatingValues || autoAssignedVal == null) {
                                if (autoAssignedVal == null) {
                                    if (prevAutoAssignedVal != null) {
                                        val = formatter.getNextNumber(formatter
                                                .formatFromUI(prevAutoAssignedVal.toString()).toString(), true);
                                    } else {
                                        val = formatter.getNextNumber(formatter.formatToUI("").toString());
                                    }
                                    // XXX timo - Need to check here for a null return value.
                                    autoAssignedVal = formatter.formatToUI(val);
                                    prevAutoAssignedVal = autoAssignedVal;
                                } else if (!this.validatingValues) {
                                    val = formatter.formatFromUI(autoAssignedVal);
                                }

                            }
                            if (autoAssignedField == null) {
                                autoAssignedField = ufld;
                            }
                        } else {
                            if (StringUtils.isBlank(fldStr)) {
                                if (ufld.isAutoAssignable()) {
                                    val = formatter.getNextNumber(formatter.formatToUI("").toString());
                                } else {
                                    val = null;
                                }
                            } else {
                                val = formatter.formatFromUI(fldStr);
                                if (!formatter.isValid((String) val)) {
                                    throw new UploaderException(
                                            UIRegistry.getResourceString("WB_UPLOAD_INVALID_FORMAT"),
                                            UploaderException.INVALID_DATA);
                                }
                            }
                        }
                    }
                }
                arg[0] = val;
            }
        }
        return arg;
    } catch (IllegalArgumentException ex) {
        throw new UploaderException(ex, UploaderException.INVALID_DATA);
    } catch (ParseException ex) {
        throw new UploaderException(ex, UploaderException.INVALID_DATA);
    }
}

From source file:edu.ku.brc.specify.tasks.subpane.wb.WorkbenchPaneSS.java

/**
 * Show a map for any number of selected records.
 *///  w w  w. j a v  a 2s.  co m
protected void showMapOfSelectedRecords() {
    UsageTracker.incrUsageCount("WB.MapRows");

    log.debug("Showing map of selected records");
    //showMapBtn.setEnabled(false);
    int[] selection = spreadSheet.getSelectedRowModelIndexes();
    if (selection.length == 0) {
        // if none are selected, map all of them
        int rowCnt = spreadSheet.getRowCount();
        selection = new int[rowCnt];
        for (int i = 0; i < rowCnt; ++i) {
            selection[i] = spreadSheet.convertRowIndexToModel(i);
        }
    }

    DBTableIdMgr databaseSchema = WorkbenchTask.getDatabaseSchema();
    // build up a list of temporary MapLocationIFace records to feed to the LocalityMapper
    List<MapLocationIFace> mapLocations = new Vector<MapLocationIFace>(selection.length);
    List<WorkbenchRow> rows = workbench.getWorkbenchRowsAsList();
    int localityTableId = databaseSchema.getIdByClassName(Locality.class.getName());
    int lat1Index = workbench.getColumnIndex(localityTableId, "latitude1");
    int lon1Index = workbench.getColumnIndex(localityTableId, "longitude1");
    int lat2Index = workbench.getColumnIndex(localityTableId, "latitude2");
    int lon2Index = workbench.getColumnIndex(localityTableId, "longitude2");
    for (int i = 0; i < selection.length; ++i) {
        int index = selection[i];

        WorkbenchRow row = rows.get(index);

        String lat1 = row.getData(lat1Index);
        String lon1 = row.getData(lon1Index);
        Double latitude = null;
        Double longitude = null;
        try {
            GeoRefConverter converter = new GeoRefConverter();
            lat1 = converter.convert(StringUtils.stripToNull(lat1), GeoRefFormat.D_PLUS_MINUS.name());
            latitude = new Double(lat1);
            lon1 = converter.convert(StringUtils.stripToNull(lon1), GeoRefFormat.D_PLUS_MINUS.name());
            longitude = new Double(lon1);
        } catch (Exception e) {
            //UsageTracker.incrHandledUsageCount();
            //edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(WorkbenchPaneSS.class, e);
            // this could be a number format exception
            // or a null pointer exception if the field was empty
            // either way, we skip this record
            continue;
        }

        SimpleMapLocation newLoc = null;

        // try to use a bounding box
        if (lat2Index != -1 && lon2Index != -1) {
            String lat2 = row.getData((short) lat2Index);
            String lon2 = row.getData((short) lon2Index);
            Double latitude2 = null;
            Double longitude2 = null;

            try {
                latitude2 = new Double(lat2);
                longitude2 = new Double(lon2);
            } catch (Exception e) {
                // this could be a number format exception
                // or a null pointer exception if the field was empty
                // either way, we'll just treat this record as though it only has lat1 and lon1
            }
            if ((latitude2 == null) ^ (longitude2 == null)) {
                latitude2 = null;
                longitude2 = null;
            }
            newLoc = new SimpleMapLocation(latitude, longitude, latitude2, longitude2);
        } else // use just the point
        {
            // we only have lat1 and long2
            newLoc = new SimpleMapLocation(latitude, longitude, null, null);
        }

        // add the storage to the list
        mapLocations.add(newLoc);
    }

    LocalityMapper mapper = new LocalityMapper(mapLocations);
    mapper.setMaxMapHeight(500);
    mapper.setMaxMapWidth(500);
    mapper.setShowArrows(false);
    mapper.setDotColor(new Color(64, 220, 64));
    MapperListener mapperListener = new MapperListener() {
        @SuppressWarnings("synthetic-access")
        public void exceptionOccurred(Exception e) {
            String errorMsg = null;
            if (e instanceof ConnectException) {
                errorMsg = getResourceString("WB_MAP_SERVICE_CONNECTION_FAILURE");
            } else {
                // in the future, we may want a different message for non-connection exceptions
                //errorMsg = getResourceString("WB_MAP_SERVICE_CONNECTION_FAILURE");
                errorMsg = e.getLocalizedMessage();
            }
            JStatusBar statusBar = UIRegistry.getStatusBar();
            statusBar.setErrorMessage(errorMsg, e);
            statusBar.setProgressDone(WorkbenchTask.WORKBENCH);
            showMapBtn.setEnabled(true);
            log.error("Exception while grabbing map from service", e);
        }

        public void mapReceived(Icon map) {
            mapImageReceived(map);
        }
    };

    //FileCache imageCache = UIRegistry.getLongTermFileCache();
    //imageCache.clear();
    mapper.getMap(mapperListener);

    JStatusBar statusBar = UIRegistry.getStatusBar();
    statusBar.setIndeterminate(WorkbenchTask.WORKBENCH, true);
    statusBar.setText(getResourceString("WB_CREATINGMAP"));
}

From source file:edu.ku.brc.specify.tasks.subpane.wb.WorkbenchPaneSS.java

/**
 * Converts the column contents from on format of Lat/Lon to another
 * @param columnIndex the index of the column being converted
 * @param converter the converter to use
 * @param outputFormat the format string
 * //  w ww.  j  a  va 2  s.  co  m
 * return number of non-blank cells that were NOT converted
 */
protected List<CellPosition> convertColumnContents(int columnIndex, int[] rows, GeoRefConverter converter,
        String outputFormat, LatLonConverter.LATLON latOrLon, LatLonConverter.DEGREES_FORMAT degFmt) {
    List<CellPosition> unconverted = new Vector<CellPosition>();

    if (columnIndex == -1) {
        return unconverted;
    }

    final int[] selectedRows = spreadSheet.getSelectedRows();
    final int[] selectedCols = spreadSheet.getSelectedColumns();
    for (int index = 0; index < rows.length; ++index) {
        int rowIndex = rows[index];
        String currentValue = null;
        //check backup col for original value before any conversions...
        currentValue = getLatLonSrc(columnIndex, rowIndex);
        if (currentValue != null) {
            currentValue = currentValue.replace("  ", " ");
        }
        if (StringUtils.isBlank(currentValue)) {
            currentValue = (String) model.getValueAt(rowIndex, columnIndex);
        }

        if (StringUtils.isBlank(currentValue)) {
            continue;
        }

        String convertedValue;
        try {
            convertedValue = converter.convert(StringUtils.stripToNull(currentValue), outputFormat, latOrLon,
                    degFmt);

        } catch (Exception e) {
            //UsageTracker.incrHandledUsageCount();
            //edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(WorkbenchPaneSS.class, e);
            // this value didn't convert correctly
            // it would be nice to highlight that cell, but I don't know how we could do that
            log.warn("Could not convert contents of cell (" + (rowIndex + 1) + "," + (columnIndex + 1) + ")");
            unconverted.add(new CellPosition(rowIndex, columnIndex));
            continue;
        }

        model.setValueAt(convertedValue, rowIndex, columnIndex, !(converter instanceof GeoRefConverter));
        if (!currentValue.equals(convertedValue)) {
            setChanged(true);
        }
    }

    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            ListSelectionModel selModel = spreadSheet.getSelectionModel();
            for (int rowIndex : selectedRows) {
                selModel.addSelectionInterval(rowIndex, rowIndex);
            }
            ListSelectionModel colSelModel = spreadSheet.getColumnModel().getSelectionModel();
            for (int colIndex : selectedCols) {
                colSelModel.addSelectionInterval(colIndex, colIndex);
            }
        }
    });
    return unconverted;
}

From source file:edu.ku.brc.specify.tasks.subpane.wb.wbuploader.UploadTable.java

/**
 * @param row/*  w  w w  . j a  v a  2 s  .  com*/
 * @param uploadData
 * @param invalidValues
 * 
 * Validates user-entered fields for the row.
 * Validation issues are added to invalidValues vector.
 */
public void validateRowValues(int row, UploadData uploadData, Vector<UploadTableInvalidValue> invalidValues) {

    if (uploadData.isEmptyRow(row)) {
        if (attachmentsPresent(uploadData, row)) {
            invalidValues.add(new UploadTableInvalidValue(null, this, this.uploadFields.get(0), row,
                    new Exception(String.format(getResourceString("UploadTable.AttachmentPresentButNoData"),
                            getTable().getTableInfo().getTitle()))));
        }
        return;
    }

    try {
        validatingValues = true;

        int seq = 0;
        boolean gotABlank = false;

        // for Locality table only
        LatLonConverter.FORMAT llFmt1 = null;
        LatLonConverter.FORMAT llFmt2 = null;
        // GeoRefConverter gc = new GeoRefConverter();
        UploadField llFld = null; // for 'generic' latlon errors.

        Vector<UploadTableInvalidValue> invalidNulls = new Vector<UploadTableInvalidValue>();
        Vector<Integer> blankSeqsLocal = new Vector<Integer>();
        for (Vector<UploadField> flds : uploadFields) {
            boolean isBlank = true;
            UploadField currFirstFld = null;
            for (UploadField fld : flds) {
                if (fld.getIndex() != -1) {
                    if (currFirstFld == null) {
                        currFirstFld = fld;
                    }
                    fld.setValue(uploadData.get(row, fld.getIndex()));
                    isBlank &= isBlankVal(fld, seq, row, uploadData);
                    ;
                    try {
                        if (invalidNull(fld, uploadData, row, seq)) {
                            if (shouldEnforceNonNullConstraint(row, uploadData, seq)) {
                                //throw new Exception(
                                //      getResourceString("WB_UPLOAD_FIELD_MUST_CONTAIN_DATA"));
                                invalidNulls.add(new UploadTableInvalidValue(
                                        getResourceString("WB_UPLOAD_FIELD_MUST_CONTAIN_DATA"), this, fld, row,
                                        null));
                                continue;
                            }
                        }
                        if (fld.getValue() != null && !"".equals(fld.getValue())
                                && fld.isAutoAssignForUpload()/* && fld == autoAssignedField*/) {
                            throw new Exception(
                                    UIRegistry.getResourceString("WB_UPLOAD_AutoAssMustBeBlankErrMsg"));
                        }
                        if (!pickListCheck(fld)) {
                            if (!fld.isReadOnlyValidValues()) {
                                if (uploader != Uploader.currentUpload) {
                                    invalidValues.add(new UploadTableInvalidValue(null, this, fld, null, row,
                                            new Exception(getInvalidPicklistValErrMsg(fld)), true));
                                    continue;
                                }
                            } else {
                                throw new Exception(getInvalidPicklistValErrMsg(fld));
                            }
                        }
                        Object[] finalVal = getArgForSetter(fld);
                        if (!updateMatches) {
                            //XXX But what if catnum has been changed... Shouldn't CatNum be made unchangeable???
                            checkUniqueness(finalVal, fld);
                        }
                    } catch (Exception e) {
                        invalidValues.add(new UploadTableInvalidValue(null, this, fld, row, e));
                    }
                }
                if (tblClass.equals(Locality.class)) {
                    // Check row to see that lat/long formats are the same.
                    String fldName = fld.getField().getName();
                    if (fldName.equalsIgnoreCase("latitude1") || fldName.equalsIgnoreCase("latitude2")
                            || fldName.equalsIgnoreCase("longitude1")
                            || fldName.equalsIgnoreCase("longitude2")) {
                        llFld = fld;
                        LatLonConverter.FORMAT fmt = geoRefConverter
                                .getLatLonFormat(StringUtils.stripToNull(fld.getValue()));
                        LatLonConverter.FORMAT llFmt = fldName.endsWith("1") ? llFmt1 : llFmt2;
                        boolean checkDecimalPlaces = true;
                        if (llFmt == null) {
                            llFmt = fmt;
                            if (fldName.endsWith("1")) {
                                llFmt1 = fmt;
                            } else {
                                llFmt2 = fmt;
                            }
                        } else {
                            if (!llFmt.equals(fmt)) {
                                checkDecimalPlaces = false;
                                invalidValues.add(new UploadTableInvalidValue(null, this, getLatLongFlds(), row,
                                        new Exception(
                                                UIRegistry.getResourceString("WB_UPLOADER_INVALID_LATLONG"))));
                            }
                        }
                        if (checkDecimalPlaces && fmt != null && fmt != LatLonConverter.FORMAT.None) {
                            //check decimal places
                            //lame
                            int c = fld.getValue().indexOf(decSep);
                            if (c > -1) {
                                int d;
                                String points = fld.getValue().substring(c + 1);
                                for (d = 0; d < points.length(); d++) {
                                    //System.out.println(points.substring(d, d+1));
                                    if (!"0123456789".contains(points.substring(d, d + 1)))
                                        break;
                                }
                                if (d > LatLonConverter.DECIMAL_SIZES[fmt.ordinal()]) {
                                    invalidValues.add(new UploadTableInvalidValue(null, this, fld, row,
                                            new Exception(String.format(
                                                    UIRegistry.getResourceString(
                                                            "WB_UPLOADER_TOO_MANY_FRACTION_DIGITS"),
                                                    LatLonConverter.DECIMAL_SIZES[fmt.ordinal()]))));
                                }
                            }
                        }
                    }
                    //Check LatLongType
                    if (fldName.equalsIgnoreCase("LatLongType")) {
                        boolean hasLat1 = false, hasLong1 = false, hasLat2 = false, hasLong2 = false;
                        for (UploadField f : getLatLongFlds()) {
                            f.setValue(uploadData.get(row, f.getIndex()));
                            String coordName = f.getField().getName();
                            if (coordName.equalsIgnoreCase("latitude1")
                                    && StringUtils.isNotBlank(f.getValue())) {
                                hasLat1 = true;
                            } else if (coordName.equalsIgnoreCase("longitude1")
                                    && StringUtils.isNotBlank(f.getValue())) {
                                hasLong1 = true;
                            } else if (coordName.equalsIgnoreCase("latitude2")
                                    && StringUtils.isNotBlank(f.getValue())) {
                                hasLat2 = true;
                            } else if (coordName.equalsIgnoreCase("longitude2")
                                    && StringUtils.isNotBlank(f.getValue())) {
                                hasLong2 = true;
                            }
                        }
                        boolean hasCoord1 = hasLat1 && hasLong1;
                        boolean hasCoord2 = hasLat2 && hasLong2;

                        if ((hasCoord1 || hasCoord2) && StringUtils.isBlank(fld.getValue())) {
                            invalidNulls.add(new UploadTableInvalidValue(
                                    getResourceString("WB_UPLOAD_FIELD_MUST_CONTAIN_DATA"), this, fld, row,
                                    null));
                            continue;

                        }

                        if (!hasCoord1 && !hasCoord2 && StringUtils.isBlank(fld.getValue())) {
                            continue;
                        }

                        //Assuming the pick list is localized...
                        String pntStr = UIRegistry.getResourceString("Locality.LL_TYPE_POINT");
                        String lineStr = UIRegistry.getResourceString("Locality.LL_TYPE_LINE");
                        String rectStr = UIRegistry.getResourceString("Locality.LL_TYPE_RECTANGLE");

                        Set<String> validValues = new TreeSet<String>();
                        for (String item : fld.getValidValues().keySet()) {
                            if (item.equals(pntStr) && hasCoord1 && !hasCoord2) {
                                validValues.add(item);
                            } else if ((item.equals(lineStr) || item.equals(rectStr)) && hasCoord1
                                    && hasCoord2) {
                                validValues.add(item);
                            }
                        }
                        if (!validValues.contains(fld.getValue())) {
                            if (uploader != Uploader.currentUpload) {
                                invalidValues.add(new UploadTableInvalidValue(null, this, fld, null, row,
                                        new Exception(getInvalidPicklistValErrMsg(fld, validValues)), false));
                                continue;
                            }
                        }
                    }
                }
            }

            if (tblClass.equals(Locality.class)) {
                if (llFmt1 != llFmt2 && llFmt2 != null && llFmt2 != LatLonConverter.FORMAT.None) {
                    invalidValues.add(new UploadTableInvalidValue(null, this, llFld, row,
                            new Exception(UIRegistry.getResourceString("WB_UPLOADER_INVALID_LATLONG"))));
                }
            }

            if (isBlank) {
                if (attachmentsPresent(uploadData, row)) {
                    invalidValues
                            .add(new UploadTableInvalidValue(null, this, flds, row,
                                    new Exception(String.format(
                                            getResourceString("UploadTable.AttachmentPresentButNoData"),
                                            getTable().getTableInfo().getTitle()))));
                }

            }
            isBlank = isBlankSequence(isBlank, uploadData, row, seq, null);
            blankSeqs.set(seq, isBlank);
            if (isBlank)
            /*
             * Disallow situations where 1-many lists have 'holes' - eg.
             * CollectorLastName2 is blank but CollectorLastName1 and -3 are
             * not.
             */
            {
                gotABlank = true;
                blankSeqsLocal.add(seq);

            } else if (!isBlank && gotABlank && plugHoles) {
                for (Integer blank : blankSeqsLocal) {
                    for (UploadField blankSeqFld : getBlankFields(blank, row, uploadData)) {
                        addInvalidValueMsgForOneToManySkip(invalidValues, blankSeqFld, toString(), row, blank);
                    }
                }
                blankSeqsLocal.clear();
            }

            invalidValues.addAll(invalidNulls);
            invalidNulls.clear();

            seq++;
        }
        if (tblClass.equals(Determination.class)) {
            // check that isCurrent is ok. 1 and only one true.
            boolean isCurrentPresent = false;
            UploadField anIsCurrentFld = null;
            boolean isBlank = true;
            // for (int row = 0; row < uploadData.getRows(); row++)
            // {
            int trueCount = 0;
            for (Vector<UploadField> flds : uploadFields) {
                for (UploadField fld : flds) {
                    if (isBlank && StringUtils.isNotBlank(uploadData.get(row, fld.getIndex()))) {
                        isBlank = false;
                    }
                    if (fld.getField().getName().equalsIgnoreCase("iscurrent")) {
                        isCurrentPresent = true;
                        if (anIsCurrentFld == null) {
                            anIsCurrentFld = fld;
                        }
                        fld.setValue(uploadData.get(row, fld.getIndex()));
                        try {
                            Object[] boolVal = getArgForSetter(fld);
                            if (boolVal[0] != null && (Boolean) boolVal[0]) {
                                trueCount++;
                            }
                        } catch (Exception e) {
                            // ignore. assuming problem was already caught
                            // above.
                        }
                    }
                }
            }
            if (isCurrentPresent && !isBlank && trueCount != 1) {
                invalidValues.add(new UploadTableInvalidValue(null, this, anIsCurrentFld, row,
                        new Exception(getResourceString("WB_UPLOAD_ONE_CURRENT_DETERMINATION"))));
            }
            // }
        }

        if (tblClass.equals(Agent.class)) {
            // check that isCurrent is ok. 1 and only one true.
            boolean nonPersonNonEmpty = false;
            boolean isNonPerson = false;
            Vector<UploadField> personOnlyFlds = new Vector<UploadField>();
            for (Vector<UploadField> flds : uploadFields) {
                for (UploadField fld : flds) {
                    try {
                        if (fld.getField().getName().equalsIgnoreCase("firstName")
                                || fld.getField().getName().equalsIgnoreCase("middleInitial")
                                || fld.getField().getName().equalsIgnoreCase("title")) {
                            Object[] val = getArgForSetter(fld);
                            nonPersonNonEmpty = StringUtils.isNotEmpty((String) val[0]);
                            personOnlyFlds.add(fld);
                        }
                        if (fld.getField().getName().equalsIgnoreCase("agenttype")) {
                            Object[] val = getArgForSetter(fld);
                            isNonPerson = val[0] != null && !((Byte) val[0]).equals(Agent.PERSON);
                            if (!isNonPerson) {
                                break;
                            }
                        }
                    } catch (Exception e) {
                        // ignore. assuming problem was already caught
                        // above.
                    }
                }
                if (isNonPerson && nonPersonNonEmpty) {
                    for (UploadField poFld : personOnlyFlds) {
                        invalidValues.add(new UploadTableInvalidValue(null, this, poFld, row, new Exception(
                                getResourceString("UploadTable.FieldNotApplicableForAgentType"))));
                    }
                }
            }
        }
    } finally {
        validatingValues = false;
    }

}

From source file:nl.knaw.huygens.timbuctoo.tools.importer.DefaultConverter.java

/**
 * Filters a text field by collapsing whitespace and removing leading and trailing whitespace.
 * Returns {@code null} if the remaining text is empty.
 *//*from w  ww  .  ja  v a 2s.  c o m*/
protected String filterField(String text) {
    if (text == null) {
        return null;
    }
    if (text.contains("\\")) {
        text = text.replaceAll("\\\\r", " ");
        text = text.replaceAll("\\\\n", " ");
    }
    text = text.replaceAll("[\\s\\u00A0]+", " ");
    return StringUtils.stripToNull(text);
}