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

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

Introduction

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

Prototype

public static boolean contains(String str, String searchStr) 

Source Link

Document

Checks if String contains a search String, handling null.

Usage

From source file:edu.ku.brc.af.core.db.MySQLBackupService.java

/**
 * Search for the mysql exes starting at the location of Specify, assuming it was installed
 * into the 'Program Files' location. If it can't find it it just returns empty string.
 * @param doDump true searches for 'mysqldump.exe'; false searches for 'mysql.exe'
 * @return the full path or empty string.
 */// ww  w.j a  v  a 2s .co  m
@SuppressWarnings("unchecked")
private static String searchForWindowsPath(final boolean doDump) {
    String exeName = doDump ? "mysqldump.exe" : "mysql.exe";

    try {
        String programFilesPath = UIRegistry.getDefaultWorkingPath() + File.separator + ".." + File.separator
                + "..";
        File dir = new File(programFilesPath);
        if (dir.exists() && dir.isDirectory()) {
            //System.out.println(dir.getAbsolutePath());
            // First search for the mysql directory
            File mysqlDir = null;
            for (File file : dir.listFiles()) {
                if (StringUtils.contains(file.getName().toLowerCase(), "mysql")) {
                    mysqlDir = file;
                    break;
                }
            }

            // Now search for exes
            if (mysqlDir != null) {
                for (File file : (Collection<File>) FileUtils.listFiles(mysqlDir, new String[] { "exe" },
                        true)) {
                    if (file.getName().equalsIgnoreCase(exeName)) {
                        return file.getAbsolutePath();
                    }
                }
            }
        }

    } catch (Exception ex) {
        // might get an exception on Vista
    }
    return "";
}

From source file:com.impetus.client.redis.RedisClient.java

/**
 * Unwraps redis results into entity.//w w  w .jav a  2  s  .c om
 * 
 * @param entityMetadata
 *            the entity metadata
 * @param results
 *            the results
 * @param key
 *            the key
 * @return the object
 * @throws InstantiationException
 *             the instantiation exception
 * @throws IllegalAccessException
 *             the illegal access exception
 */
private Object unwrap(EntityMetadata entityMetadata, Map<byte[], byte[]> results, Object key)
        throws InstantiationException, IllegalAccessException {

    MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata()
            .getMetamodel(entityMetadata.getPersistenceUnit());

    List<String> relationNames = entityMetadata.getRelationNames();
    EntityType entityType = metaModel.entity(entityMetadata.getEntityClazz());

    Map<String, Object> relations = new HashMap<String, Object>();
    Object entity = null;

    // Set<Attribute> attributes = entityType.getAttributes();

    Set<byte[]> columnNames = results.keySet();
    for (byte[] nameInByte : columnNames) {
        if (entity == null) {
            entity = KunderaCoreUtils.createNewInstance(entityMetadata.getEntityClazz());
        }

        String columnName = PropertyAccessorFactory.STRING.fromBytes(String.class, nameInByte);

        byte[] value = results.get(nameInByte);
        String discriminatorColumn = ((AbstractManagedType) entityType).getDiscriminatorColumn();

        if (columnName != null && !columnName.equals(discriminatorColumn)) {
            String fieldName = entityMetadata.getFieldName(columnName);

            if (fieldName != null) {
                Attribute attribute = entityType.getAttribute(fieldName);

                if (relationNames != null && relationNames.contains(columnName)) {
                    Field field = (Field) attribute.getJavaMember();
                    EntityMetadata associationMetadata = KunderaMetadataManager.getEntityMetadata(
                            kunderaMetadata, ((AbstractAttribute) attribute).getBindableJavaType());
                    relations.put(columnName, PropertyAccessorHelper
                            .getObject(associationMetadata.getIdAttribute().getBindableJavaType(), value));
                } else {
                    PropertyAccessorHelper.set(entity, (Field) attribute.getJavaMember(), value);
                }
            } else {
                // means it might be an embeddable field, if not simply omit
                // this field.

                if (StringUtils.contains(columnName, ":")) {
                    StringTokenizer tokenizer = new StringTokenizer(columnName, ":");
                    while (tokenizer.hasMoreTokens()) {
                        String embeddedFieldName = tokenizer.nextToken();
                        String embeddedColumnName = tokenizer.nextToken();

                        Map<String, EmbeddableType> embeddables = metaModel
                                .getEmbeddables(entityMetadata.getEntityClazz());

                        EmbeddableType embeddableAttribute = embeddables.get(embeddedFieldName);

                        Attribute attrib = embeddableAttribute.getAttribute(embeddedColumnName);

                        Object embeddedObject = PropertyAccessorHelper.getObject(entity,
                                (Field) entityType.getAttribute(embeddedFieldName).getJavaMember());

                        if (embeddedObject == null) {
                            embeddedObject = KunderaCoreUtils.createNewInstance(
                                    ((AbstractAttribute) entityType.getAttribute(embeddedFieldName))
                                            .getBindableJavaType());

                            PropertyAccessorHelper.set(entity,
                                    (Field) entityType.getAttribute(embeddedFieldName).getJavaMember(),
                                    embeddedObject);
                        }

                        PropertyAccessorHelper.set(embeddedObject, (Field) attrib.getJavaMember(), value);
                        // PropertyAccessorHelper.

                    }
                }
                // It might be a case of embeddable attribute.

            }
        }

    }

    if (entity != null) {
        Class javaType = entityMetadata.getIdAttribute().getBindableJavaType();

        if (!metaModel.isEmbeddable(entityMetadata.getIdAttribute().getBindableJavaType())
                && key.getClass().isAssignableFrom(String.class) && !key.getClass().equals(javaType)) {
            key = PropertyAccessorFactory.getPropertyAccessor(javaType).fromString(javaType, key.toString());
        }
        //            PropertyAccessorHelper.set(entity, (Field) entityMetadata.getIdAttribute().getJavaMember(), key);
    }
    if (!relations.isEmpty()) {
        return new EnhanceEntity(entity, key, relations);
    }

    return entity;
}

From source file:edu.ku.brc.specify.tools.datamodelgenerator.DatamodelGenerator.java

/**
 * Reads in hbm files and generates datamodel tree.
 * @return List datamodel tree// w  w  w . j  av a 2 s  .  c om
 */
@SuppressWarnings({ "unchecked", "cast" })
public List<Table> generateDatamodelTree(final List<Table> tableList, final String dataModelPath) {
    try {
        log.debug("Preparing to read in DataModel Classes files from  path: " + dataModelPath);

        srcCodeDir = new File(dataModelPath);

        String path = srcCodeDir.getAbsolutePath();
        log.info(path);
        //dir = new File(path.substring(0, path.lastIndexOf(File.separator)));

        // This filter only returns directories
        FileFilter fileFilter = new FileFilter() {
            public boolean accept(File file) {
                return file.toString().indexOf(".java") != -1;
            }
        };

        String PACKAGE = "package ";
        String CLASS = "public class ";

        File[] files = srcCodeDir.listFiles(fileFilter);
        int count = 0;
        for (File file : files) {
            if (showDebug)
                log.debug("Reading    " + file.getAbsolutePath());
            List<?> lines = FileUtils.readLines(file);
            count++;
            if (showDebug)
                log.debug("Processing " + count + " of " + files.length + "  " + file.getAbsolutePath());

            String className = null;

            for (Object lineObj : lines) {
                String line = ((String) lineObj).trim();
                //System.out.println(line);
                if (line.startsWith(PACKAGE)) {
                    packageName = line.substring(PACKAGE.length(), line.length() - 1);
                }
                if (StringUtils.contains(line, CLASS)) {
                    String str = line.substring(CLASS.length());
                    while (str.charAt(0) == ' ') {
                        str = str.substring(1);
                    }

                    int eInx = str.indexOf(' ');
                    if (eInx == -1) {
                        className = str;
                    } else {
                        className = str.substring(0, eInx);
                    }
                    break;
                }
            }

            if (className != null) {
                if (!StringUtils.contains(className, "SpUI")) {
                    processClass(className, tableList);
                }

                // These were used for correcting Cascading rules
                // Eventually these can be removed along with the methods.
                //processCascade(className, tableList);
                //processCascadeAddCascade(className, tableList);
            } else {
                String fileName = file.getName();
                if (!StringUtils.contains(fileName, "DataModelObjBase")
                        && !StringUtils.contains(fileName, "CollectionMember")
                        && !StringUtils.contains(fileName, "DisciplineMember")
                        && !StringUtils.contains(fileName, "UserGroupScope")
                        && !StringUtils.contains(fileName, "Treeable")
                        && !StringUtils.contains(fileName, "SpLocaleBase")
                        && !StringUtils.contains(fileName.toLowerCase(), "iface")
                        && !StringUtils.contains(fileName, "BaseTreeDef")
                        && !StringUtils.contains(fileName, "TreeDefItemStandardEntry")) {
                    throw new RuntimeException("Couldn't locate class name for " + file.getAbsolutePath());
                }
            }
        }
        System.out.println(missing);
        return tableList;

    } catch (Exception ex) {
        edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
        edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(DatamodelGenerator.class, ex);
        ex.printStackTrace();
        log.fatal(ex);
    }
    return null;
}

From source file:com.primovision.lutransport.service.ImportMainSheetServiceImpl.java

@Override
@Transactional(readOnly = false, propagation = Propagation.REQUIRED)
public List<String> importAccidentNotReportedData(InputStream is, Long createdBy) throws Exception {
    SimpleDateFormat accidentDateFormat = new SimpleDateFormat("MM-dd-yyyy");

    List<String> errorList = new ArrayList<String>();

    int recordCount = 0;
    int errorCount = 0;
    int successCount = 0;
    try {//www. j a  v a  2  s .c  om
        POIFSFileSystem fs = new POIFSFileSystem(is);
        HSSFWorkbook wb = new HSSFWorkbook(fs);
        HSSFSheet sheet = wb.getSheetAt(0);

        Map<String, Integer> colMapping = WorkerCompUtils.getAccidentNotReportedColMapping();

        Iterator<Row> rows = sheet.rowIterator();
        int recordsToBeSkipped = 1;
        while (rows.hasNext()) {
            HSSFRow row = (HSSFRow) rows.next();

            recordCount++;
            System.out.println("Processing record No: " + recordCount);
            if (recordCount <= recordsToBeSkipped) {
                continue;
            }

            boolean recordError = false;
            StringBuffer recordErrorMsg = new StringBuffer();
            Accident currentAccident = null;
            try {
                String endOfData = ((String) getCellValue(row.getCell(0)));
                if (StringUtils.equals("END_OF_DATA", endOfData)) {
                    break;
                }

                currentAccident = new Accident();

                Integer driverNameCol = colMapping.get(WorkerCompUtils.ACCIDENT_NOT_REPORTED_COL_NAME);
                String driverName = ((String) getCellValue(row.getCell(driverNameCol)));
                driverName = StringUtils.trimToEmpty(driverName);
                Driver driver = null;
                if (StringUtils.contains(driverName, ",")) {
                    driver = WorkerCompUtils.retrieveDriverByCommaSep(driverName, genericDAO);
                } else {
                    driver = WorkerCompUtils.retrieveDriver(driverName, genericDAO, true);
                }
                if (driver == null) {
                    recordError = true;
                    recordErrorMsg.append("Employee Name, ");
                } else {
                    currentAccident.setDriver(driver);
                }

                Integer incidentDateCol = colMapping
                        .get(WorkerCompUtils.ACCIDENT_NOT_REPORTED_COL_INCIDENT_DATE);
                Object incidentDateObj = getCellValue(row.getCell(incidentDateCol), true);
                if (incidentDateObj == null) {
                    recordError = true;
                    recordErrorMsg.append("Incident Date, ");
                } else if (incidentDateObj instanceof Date) {
                    currentAccident.setIncidentDate((Date) incidentDateObj);
                } else {
                    String incidentDateStr = incidentDateObj.toString();
                    incidentDateStr = StringUtils.trimToEmpty(incidentDateStr);
                    Date incidentDate = accidentDateFormat.parse(incidentDateStr);
                    currentAccident.setIncidentDate(incidentDate);
                }

                Accident existingAccident = WorkerCompUtils.retrieveMatchingAccident(currentAccident,
                        genericDAO);
                if (existingAccident == null) {
                    recordError = true;
                    recordErrorMsg.append("No matching existing Accident record found to update costs, ");

                    errorList.add("Line " + recordCount + ": " + recordErrorMsg.toString() + "<br/>");
                    errorCount++;
                    continue;
                }

                Integer totalCostCol = colMapping.get(WorkerCompUtils.ACCIDENT_NOT_REPORTED_COL_TOTAL_COST);
                Object totalCostObj = getCellValue(row.getCell(totalCostCol), true);
                Double totalCost = null;
                if (totalCostObj != null) {
                    if (totalCostObj instanceof Double) {
                        totalCost = (Double) totalCostObj;
                    } else {
                        String totalCostStr = (String) totalCostObj;
                        if (StringUtils.isNotEmpty(totalCostStr)) {
                            totalCost = Double.valueOf(totalCostStr);
                        }
                    }
                    existingAccident.setTotalCost(totalCost);
                }

                if (recordError) {
                    errorList.add("Line " + recordCount + ": " + recordErrorMsg.toString() + "<br/>");
                    errorCount++;
                    continue;
                }

                existingAccident.setModifiedBy(createdBy);
                existingAccident.setModifiedAt(Calendar.getInstance().getTime());
                genericDAO.saveOrUpdate(existingAccident);

                successCount++;
            } catch (Exception ex) {
                log.warn("Error while processing Accident Not Reported record: " + recordCount + ". " + ex);

                recordError = true;
                errorCount++;
                recordErrorMsg.append("Error while processing record: " + recordCount + ", ");
                errorList.add("Line " + recordCount + ": " + recordErrorMsg.toString() + "<br/>");
            }
        }

        System.out.println("Done processing accidents not reported...Total record count: " + recordCount
                + ". Error count: " + errorCount + ". Number of records loaded: " + successCount);
    } catch (Exception ex) {
        errorList.add("Not able to upload XL!!! Please try again.");
        log.warn("Error while importing Accident Not Reported data: " + ex);
    }

    return errorList;
}

From source file:it.govpay.web.rs.dars.anagrafica.tributi.TributiHandler.java

@Override
public void checkEntry(Tributo entry, Tributo oldEntry) throws ValidationException {
    if (entry == null || entry.getIdTipoTributo() == 0) {
        throw new ValidationException(Utils.getInstance(this.getLanguage())
                .getMessageFromResourceBundle(this.nomeServizio + ".creazione.erroreTipoObbligatorio"));
    }/*from w  w  w.j a  v  a  2  s.  c  o m*/
    if (entry == null || entry.getIdDominio() == 0) {
        throw new ValidationException(Utils.getInstance(this.getLanguage())
                .getMessageFromResourceBundle(this.nomeServizio + ".creazione.erroreDominioObbligatorio"));
    }
    if (!entry.getCodTributo().equals(it.govpay.model.Tributo.BOLLOT) && entry.getIdIbanAccredito() == null) {
        throw new ValidationException(Utils.getInstance(this.getLanguage()).getMessageFromResourceBundle(
                this.nomeServizio + ".creazione.erroreIbanAccreditoObbligatorio"));
    }
    //      if(entry == null || entry.getTipoContabilita() == null) throw new ValidationException(Utils.getInstance(this.getLanguage()).getMessageFromResourceBundle(this.nomeServizio + ".creazione.erroreTipoContabilitaObbligatorio"));
    //      if(entry == null || entry.getCodContabilita() == null || entry.getCodContabilita().isEmpty()) throw new ValidationException(Utils.getInstance(this.getLanguage()).getMessageFromResourceBundle(this.nomeServizio + ".creazione.erroreCodContabilitaObbligatorio"));
    if (entry.getCodContabilitaCustom() != null && StringUtils.contains(entry.getCodContabilitaCustom(), " ")) {
        throw new ValidationException(Utils.getInstance(this.getLanguage())
                .getMessageFromResourceBundle(this.nomeServizio + ".creazione.erroreCodContabilitaNoSpazi"));
    }

    if (oldEntry != null) {
        if (entry.getIdTipoTributo() != oldEntry.getIdTipoTributo()) {
            throw new ValidationException(Utils.getInstance(this.getLanguage())
                    .getMessageFromResourceBundle(this.nomeServizio + ".aggiornamento.erroreTipoModificato"));
        }
        if (entry.getIdDominio() != oldEntry.getIdDominio()) {
            throw new ValidationException(Utils.getInstance(this.getLanguage()).getMessageFromResourceBundle(
                    this.nomeServizio + ".aggiornamento.erroreDominioModificato"));
        }
    }
}

From source file:edu.ku.brc.specify.conversion.BasicSQLUtils.java

/**
 * @param connection/*from   w w  w .  j a v  a 2  s.co m*/
 * @param tableName
 * @return
 */
public static List<FieldMetaData> getFieldMetaDataFromSchema(final Connection connection,
        final String tableName) {
    try {
        ArrayList<FieldMetaData> fields = new ArrayList<FieldMetaData>();

        DatabaseMetaData mdm = connection.getMetaData();
        ResultSet rs = mdm.getColumns(connection.getCatalog(), connection.getCatalog(), tableName, null);
        while (rs.next()) {
            /*System.out.println("-------- " + rs.getString("COLUMN_NAME")+" ----------");
            for (int i=1;i<=rs.getMetaData().getColumnCount();i++)
            {
            System.out.println(rs.getMetaData().getColumnName(i)+"="+rs.getObject(i));
                    
            }*/

            String typeStr = rs.getString("TYPE_NAME");
            FieldMetaData fmd = new FieldMetaData(rs.getString("COLUMN_NAME"), typeStr,
                    typeStr.startsWith("DATE"), false, StringUtils.contains(typeStr.toLowerCase(), "varchar"));
            fmd.setSqlType(rs.getInt("DATA_TYPE"));
            fields.add(fmd);
        }
        rs.close();
        return fields;

    } catch (SQLException ex) {
        ex.printStackTrace();
    }
    return null;
}

From source file:adalid.commons.util.StrUtils.java

/**
 * Replaces all occurrences of a String within another String that are found between another two Strings.
 *
 * @param text the String to search and replace in
 * @param search the String to search for
 * @param replacement the String to replace it with
 * @param preceding the String used as lower boundary of the search; if it is null or empty, the search begins at the beginning of text
 * @param following the String used as upper boundary of the search; if it is null or empty, the search ends at the end of text
 * @return the text with any replacements processed
 *//*w  w w.ja  v  a  2s.com*/
public static String replaceBetween(String text, String search, String replacement, String preceding,
        String following) {
    final String turbofan = "\t\r\b\f\n";
    if (text != null && search != null && replacement != null && text.length() > 0 && search.length() > 0
            && text.contains(search)) {
        boolean preceded = preceding != null && preceding.length() > 0;
        if (preceded && !text.contains(preceding)) {
            return text;
        }
        boolean followed = following != null && following.length() > 0;
        if (followed && !text.contains(following)) {
            return text;
        }
        if (preceded || followed) {
            String searchless = text.replace(search, turbofan);
            String beforePreceding = preceded ? StringUtils.substringBefore(searchless, preceding) : "";
            String afterPreceding = preceded ? StringUtils.substringAfter(searchless, preceding) : "";
            String beforeFollowing = followed
                    ? StringUtils.substringBefore(preceded ? afterPreceding : searchless, following)
                    : "";
            String afterFollowing = followed
                    ? StringUtils.substringAfter(preceded ? afterPreceding : searchless, following)
                    : "";
            String inBetween = preceded && followed
                    ? StringUtils.substringBetween(searchless, preceding, following)
                    : "";
            String substring = preceded && followed ? inBetween : preceded ? afterPreceding : beforeFollowing;
            if (StringUtils.contains(substring, turbofan)) {
                String string = substring.replace(turbofan, replacement);
                String concat = beforePreceding + (preceded ? preceding : "") + string
                        + (followed ? following : "") + afterFollowing;
                String result = concat.replace(turbofan, search);
                return result;
            }
        } else {
            return text.replace(search, replacement);
        }
    }
    return text;
}

From source file:edu.ku.brc.specify.datamodel.busrules.BaseTreeBusRules.java

@Override
public boolean isOkToSave(Object dataObj, DataProviderSessionIFace session) {
    boolean result = super.isOkToSave(dataObj, session);
    if (result && dataObj != null && !StringUtils.contains(formViewObj.getView().getName(), "TreeDef")
            && BaseTreeBusRules.ALLOW_CONCURRENT_FORM_ACCESS) {
        if (!getRequiredLocks(dataObj)) {
            result = false;/*from w  w w  . ja va2s  . c o  m*/
            reasonList.add(getUnableToLockMsg());
        }
    }
    return result;
}

From source file:com.greenline.guahao.web.module.home.controllers.my.reservation.ReservationProcess.java

public void tumorInfoBackfill(OperationJsonObject json, String patientUserId) {
    if (StringUtils.isBlank(patientUserId)) {
        return;//www .j  a  va2  s  .c  o m
    }
    // ?
    PatientInfoDO patientInfoDO = patientManager.getPatientByPatientId(Long.parseLong(patientUserId));
    if (null == patientInfoDO) {
        return;
    } else {
        Long userId = UserCookieUtil.getUserId(request);
        if (!userId.toString().equals(String.valueOf(patientInfoDO.getUser_id()))) {
            return;
        }
    }

    Map<String, PostTumorInfoVO> jsonMap = new HashMap<String, PostTumorInfoVO>(0);
    PostTumorInfoVO tumorInfo = new PostTumorInfoVO();
    BasicInfoDTO basic = healthMgr.getBasicInfo(Long.valueOf(patientUserId));
    if (null != basic) {
        tumorInfo.setPatientId(String.valueOf(basic.getUserId()));
        tumorInfo.setAddrs(basic.getAddress());
        tumorInfo.setEducation(basic.getEducationalStatus());
        tumorInfo.setEmail(basic.getEmail());
        tumorInfo.setFax(basic.getFax());
        tumorInfo.setNationality(basic.getNationality());
        tumorInfo.setProfession(basic.getJob());
        tumorInfo.setReligion(basic.getReligion());
    }

    PastMedicalHisDTO pastGmsHis = healthMgr.getPastMedicalHis(Long.valueOf(patientUserId),
            ReservationConstants.TUMOR_HIS_GMS);
    if (null != pastGmsHis) {
        List<PastMedicalHisDetailDTO> detailList = pastGmsHis.getMedicalHisList();
        for (int i = 0; i < detailList.size(); i++) {
            PastMedicalHisDetailDTO detail = detailList.get(i);
            if (ReservationConstants.TUMOR_HIS_GMS_NAME.equals(detail.getDisease())) {
                tumorInfo.setHisOfDrugAllergyStatus(ReservationConstants.TUMOR_HIS_FOR_YES);
                tumorInfo.setHisOfDrugAllergy(detail.getDrugName());
                tumorInfo.setHealthRecordIdForDrugAllergy(detail.getId());
                break;
            }
        }
    }

    PastMedicalHisDTO pastJzsHis = healthMgr.getPastMedicalHis(Long.valueOf(patientUserId),
            ReservationConstants.TUMOR_HIS_JZS);
    if (null != pastJzsHis) {
        List<PastMedicalHisDetailDTO> detailList = pastJzsHis.getMedicalHisList();
        for (int i = 0; i < detailList.size(); i++) {
            PastMedicalHisDetailDTO detail = detailList.get(i);
            if (ReservationConstants.TUMOR_HIS_JZS_NAME.equals(detail.getDisease())) {
                tumorInfo.setFamilyHistoryStatus(ReservationConstants.TUMOR_HIS_FOR_YES);
                tumorInfo.setFamilyHistory(detail.getDesc());
                tumorInfo.setHealthRecordIdForFamilyHistory(detail.getId());
            } else if (ReservationConstants.TUMOR_HIS_ZLS_NAME.equals(detail.getDisease())) {
                tumorInfo.setHisOfCancerDiseaseStatus(ReservationConstants.TUMOR_HIS_FOR_YES);
                tumorInfo.setHisOfCancerDisease(detail.getDesc());
                tumorInfo.setHealthRecordIdForCancerDisease(detail.getId());
            }
        }
    }

    List<TreatmentHisDTO> treatList = healthMgr.listTreatmentHis(Long.valueOf(patientUserId));
    if (CollectionUtils.isEmpty(treatList)) {
        tumorInfo.setDiseaseHisExist(ReservationConstants.TUMOR_DISEASE_EXIST_NO);
    } else {
        TreatmentHisDTO treatDo = null;
        for (TreatmentHisDTO treat : treatList) {
            if (ReservationConstants.TUMOR_HOSP_NAME.equals(treat.getTreatOrg())) {
                treatDo = treat;
                break;
            }
        }

        if ((null == treatDo) || StringUtils.isBlank(treatDo.getDisease())) {
            tumorInfo.setDiseaseHisExist(ReservationConstants.TUMOR_DISEASE_EXIST_NO);
        } else {
            String disease = treatDo.getDisease();
            String[] diseaseArr = disease.split(";");
            for (String disName : diseaseArr) {
                if (StringUtils.isBlank(disName)) {
                    continue;
                }

                if (ReservationConstants.TUMOR_DISEASE_NAME_TNB.equals(StringUtils.trim(disName))) {
                    // 
                    tumorInfo.setDiabetesHis(ReservationConstants.TUMOR_HIS_FOR_YES);
                } else if (ReservationConstants.TUMOR_DISEASE_NAME_GXY.equals(StringUtils.trim(disName))) {
                    // 
                    tumorInfo.setHypertensionHis(ReservationConstants.TUMOR_HIS_FOR_YES);
                } else if (ReservationConstants.TUMOR_DISEASE_NAME_FQZ.equals(StringUtils.trim(disName))) {
                    // 
                    tumorInfo.setEmphysemaHis(ReservationConstants.TUMOR_HIS_FOR_YES);
                } else if (StringUtils.contains(disName, ReservationConstants.TUMOR_HIS_CHRONIC_OTHERS)) {
                    // 
                    tumorInfo.setOtherHisStatus(ReservationConstants.TUMOR_HIS_FOR_YES);
                    tumorInfo.setOtherHis(StringUtils.substring(disName, disName.indexOf(":") + 1));
                }
            }
            tumorInfo.setHealthRecordIdForChronicDisease(treatDo.getId());
            tumorInfo.setDiseaseHisExist(ReservationConstants.TUMOR_DISEASE_EXIST_YES);
        }
    }

    jsonMap.put("postTumorInfoVO", tumorInfo);
    json.setData(jsonMap);
}

From source file:adalid.commons.velocity.Writer.java

private void deletePreviouslyGeneratedFiles(String name, String[] stringArray, boolean recursive) {
    String root = getRoot().getPath();
    String raiz = root.replace('\\', '/');
    String path, pathname, wildcard;
    String recursively = recursive ? "and all its subdirectories" : "";
    String slashedPath, regex, pattern, message;
    String hint = "; check property: {0}={1}";
    boolean delete;
    File directory;/*from www  .ja v a  2  s.  c  o  m*/
    IOFileFilter fileFilter;
    IOFileFilter dirFilter = recursive ? ignoreVersionControlFilter : null;
    Collection<File> matchingFiles;
    Arrays.sort(stringArray);
    for (String string : stringArray) {
        pathname = StringUtils.substringBeforeLast(string, SLASH);
        if (StringUtils.isBlank(string) || !StringUtils.contains(string, SLASH)
                || StringUtils.isBlank(pathname)) {
            pattern = "directory is missing or invalid" + hint;
            message = MessageFormat.format(pattern, name, string);
            log(_alertLevel, message);
            warnings++;
            continue;
        }
        wildcard = StringUtils.substringAfterLast(string, SLASH);
        if (StringUtils.isBlank(wildcard)) {
            pattern = "wildcard is missing or invalid" + hint;
            message = MessageFormat.format(pattern, name, string);
            log(_alertLevel, message);
            warnings++;
            continue;
        }
        directory = new File(pathname);
        if (FilUtils.isNotWritableDirectory(directory)) {
            pattern = "{2} is not a writable directory" + hint;
            message = MessageFormat.format(pattern, name, string,
                    StringUtils.removeStartIgnoreCase(pathname, raiz));
            log(_alertLevel, message);
            warnings++;
            continue;
        }
        log(_detailLevel, "deleting files " + wildcard + " from "
                + StringUtils.removeStartIgnoreCase(pathname, raiz) + " " + recursively);
        fileFilter = new WildcardFileFilter(wildcard);
        matchingFiles = FileUtils.listFiles(directory, fileFilter, dirFilter);
        for (File file : matchingFiles) {
            path = file.getPath();
            slashedPath = path.replace('\\', '/');
            delete = true;
            for (Pattern fxp : filePreservationPatterns) {
                regex = fxp.pattern();
                if (slashedPath.matches(regex)) {
                    delete = false;
                    pattern = "file {0} will not be deleted; it matches preservation expression \"{1}\"";
                    message = MessageFormat.format(pattern,
                            StringUtils.removeStartIgnoreCase(slashedPath, raiz), regex);
                    log(_alertLevel, message);
                    warnings++;
                    break;
                }
            }
            if (delete) {
                logger.trace("deleting " + StringUtils.removeStartIgnoreCase(path, root));
                FileUtils.deleteQuietly(file);
            }
        }
    }
}