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:gov.nih.nci.cabig.caaers.rules.business.service.CaaersRulesEngineService.java

@Transactional
public void saveOrUpdateRuleSet(gov.nih.nci.cabig.caaers.domain.RuleSet domainRuleSet, RuleSet ruleSet) {

    saveOrUpdateRuleSet(domainRuleSet);/*  w w  w  . j ava2 s . c  o m*/

    //add imports if necessary
    if (CollectionUtils.isEmpty(ruleSet.getImport())) {
        ruleSet.getImport().add("gov.nih.nci.cabig.caaers.domain.*");
    }

    //correct package names
    RuleType ruleType = domainRuleSet.getRuleType();
    RuleLevel ruleLevel = domainRuleSet.getRuleLevel();
    Integer orgId = domainRuleSet.getOrganization() == null ? null : domainRuleSet.getOrganization().getId();
    Integer studyId = domainRuleSet.getStudy() == null ? null : domainRuleSet.getStudy().getId();
    String packageName = constructPackageName(domainRuleSet.getRuleType(), domainRuleSet.getRuleLevel(), orgId,
            studyId);
    ruleSet.setName(packageName);

    //correct subject
    String nciCode = domainRuleSet.getOrganization() == null ? ""
            : domainRuleSet.getOrganization().getNciInstituteCode();
    String studyPrimaryId = domainRuleSet.getStudy() == null ? ""
            : domainRuleSet.getStudy().getPrimaryIdentifierValue();
    String newSubject = constructSubject(ruleType, ruleLevel, nciCode, studyPrimaryId);
    ruleSet.setSubject(newSubject);

    //correct description
    ruleSet.setDescription(ruleType.getName());

    List<Rule> rules = ruleSet.getRule();

    // delete columns which are marked as delete .
    for (Rule rule : rules) {
        List<Column> colsToDelete = new ArrayList<Column>();
        for (Column col : rule.getCondition().getColumn()) {
            if (col.isMarkedDelete())
                colsToDelete.add(col);
        }
        if (!colsToDelete.isEmpty())
            rule.getCondition().getColumn().removeAll(colsToDelete);
    }

    for (Rule rule : rules) {

        //add rule-id if it is empty
        if (rule.getId() == null)
            rule.setId("r-" + UUID.randomUUID().toString());

        String categoryId = "0";
        String expression = CaaersRuleUtil.fetchFieldExpression(rule, "term");
        if (StringUtils.contains(expression, "ctepCode")) {
            //new pattern
            String termCtepCode = CaaersRuleUtil.fetchFieldValue(rule, "term");
            if (termCtepCode != null) {
                String ctcVersion = "0";
                if (domainRuleSet.getStudy() != null) {
                    ctcVersion = domainRuleSet.getStudy().getCtcVersion() != null
                            ? domainRuleSet.getStudy().getCtcVersion().getName()
                            : "0";
                }

                if (ctcVersion != null) {
                    List<CtcTerm> terms = ctcTermDao.getByCtepCodeandVersion(termCtepCode, ctcVersion);
                    if (terms != null && !terms.isEmpty()) {
                        categoryId = terms.get(0).getCategory().getId() + "";
                    }
                }
            }
        } else {
            //old pattern
            String termName = CaaersRuleUtil.fetchFieldReadableValue(rule, "term");
            String categoryName = CaaersRuleUtil.fetchFieldReadableValue(rule, "category");
            if (StringUtils.isNotEmpty(termName)) {
                Integer ctcVersionId = null;
                if (domainRuleSet.getStudy() != null) {
                    ctcVersionId = domainRuleSet.getStudy().getCtcVersion() != null
                            ? domainRuleSet.getStudy().getCtcVersion().getId()
                            : null;
                }
                List<CtcTerm> terms = ctcTermDao.getBySubname(new String[] { termName }, ctcVersionId, null);
                CtcTerm term = findTerm(terms, categoryName);
                if (term != null) {
                    categoryId = term.getCategory().getId() + "";
                    CaaersRuleUtil.updateTermField(rule, term.getCtepCode());
                }
            }

        }

        CaaersRuleUtil.updateCategoryField(rule, categoryId);

        replaceCommaSeperatedStringToList(rule.getCondition());

        if (!hasFactResolverColumn(rule.getCondition()))
            rule.getCondition().getColumn().add(createCriteriaForFactResolver());

        if (rule.getMetaData() == null)
            rule.setMetaData(new MetaData());
        rule.getMetaData().setPackageName(packageName);
        rule.getMetaData().setDescription("Setting Description since its mandatory by JBoss Repository config");
        if (ruleLevel != null) {

            String organizationName = (domainRuleSet.getOrganization() != null)
                    ? StringEscapeUtils.escapeXml(domainRuleSet.getOrganization().getName())
                    : null;
            String sponsorName = null;
            String institutionName = null;

            if (ruleLevel.isInstitutionBased())
                institutionName = organizationName;
            if (ruleLevel.isSponsorBased())
                sponsorName = organizationName;

            String studyShortTitle = (domainRuleSet.getStudy() != null)
                    ? domainRuleSet.getStudy().getShortTitle()
                    : null;

            populateCategoryBasedColumns(rule, ruleLevel.getName(), sponsorName, institutionName,
                    studyShortTitle);
        }

    }

    //save the rules in staging area.
    ruleEngineService.saveOrUpdateRuleSet(domainRuleSet.getRuleBindURI(), ruleSet);
}

From source file:com.adobe.acs.tools.explain_query.impl.ExplainQueryServlet.java

private JSONObject explainQuery(final Session session, final String statement, final String language)
        throws RepositoryException, JSONException {
    final QueryManager queryManager = session.getWorkspace().getQueryManager();
    final JSONObject json = new JSONObject();
    final String collectorKey = startCollection();
    final QueryResult queryResult;
    final String effectiveLanguage;
    final String effectiveStatement;

    if (language.equals(QUERY_BUILDER)) {
        effectiveLanguage = XPATH;//  w w w.j  av  a 2  s . com
        final String[] lines = StringUtils.split(statement, '\n');
        final Map<String, String> params = OsgiPropertyUtil.toMap(lines, "=", false, null, true);

        final com.day.cq.search.Query query = queryBuilder.createQuery(PredicateGroup.create(params), session);
        effectiveStatement = query.getResult().getQueryStatement();
    } else {
        effectiveStatement = statement;
        effectiveLanguage = language;
    }
    try {
        final Query query = queryManager.createQuery("explain " + effectiveStatement, effectiveLanguage);
        queryResult = query.execute();
    } finally {
        synchronized (this.logCollector) {
            if (this.logCollector != null) {
                List<String> logs = this.logCollector.getLogs(collectorKey);
                json.put("logs", this.logCollector.getLogs(collectorKey));

                if (logs.size() == this.logCollector.msgCountLimit) {
                    json.put("logsTruncated", true);
                }
            }
            stopCollection(collectorKey);
        }
    }

    final RowIterator rows = queryResult.getRows();
    final Row firstRow = rows.nextRow();

    final String plan = firstRow.getValue("plan").getString();
    json.put("plan", plan);

    final JSONArray propertyIndexes = new JSONArray();

    final Matcher propertyMatcher = PROPERTY_INDEX_PATTERN.matcher(plan);
    /* Property Index */
    while (propertyMatcher.find()) {
        final String match = propertyMatcher.group(1);
        if (StringUtils.isNotBlank(match)) {
            propertyIndexes.put(StringUtils.stripToEmpty(match));
        }
    }

    if (propertyIndexes.length() > 0) {
        json.put("propertyIndexes", propertyIndexes);
    }

    final Matcher filterMatcher = FILTER_PATTERN.matcher(plan);
    if (filterMatcher.find()) {
        /* Filter (nodeType index) */

        propertyIndexes.put("nodeType");
        json.put("propertyIndexes", propertyIndexes);
        json.put("slow", true);
    }

    if (StringUtils.contains(plan, " /* traverse ")) {
        /* Traversal */
        json.put("traversal", true);
        json.put("slow", true);
    }

    if (StringUtils.contains(plan, " /* aggregate ")) {
        /* Aggregate - Fulltext */
        json.put("aggregate", true);
    }

    return json;
}

From source file:com.impetus.client.rdbms.query.RDBMSEntityReader.java

/**
 * //from   ww  w  . j av  a2s  .  co  m
 * @param entityMetadata
 * @param primaryKeys
 * @param aliasName
 * @param queryBuilder
 * @param entityType
 */
private void onCondition(EntityMetadata entityMetadata, MetamodelImpl metamodel, Set<String> primaryKeys,
        String aliasName, StringBuilder queryBuilder, EntityType entityType) {
    if (primaryKeys == null) {
        for (Object o : conditions) {
            if (o instanceof FilterClause) {
                FilterClause clause = ((FilterClause) o);
                Object value = clause.getValue().get(0);
                String propertyName = clause.getProperty();
                String condition = clause.getCondition();

                if (StringUtils.contains(propertyName, '.')) {
                    int indexOf = propertyName.indexOf(".");
                    String jpaColumnName = propertyName.substring(0, indexOf);
                    String embeddedColumnName = propertyName.substring(indexOf + 1, propertyName.length());
                    String fieldName = entityMetadata.getFieldName(jpaColumnName);
                    Attribute attribute = entityType.getAttribute(fieldName);
                    EmbeddableType embeddedType = metamodel
                            .embeddable(((AbstractAttribute) attribute).getBindableJavaType());
                    Attribute embeddedAttribute = embeddedType.getAttribute(embeddedColumnName);

                    addClause(entityMetadata, aliasName, queryBuilder, entityType, value, condition, fieldName,
                            embeddedAttribute);
                } else {
                    String fieldName = entityMetadata.getFieldName(propertyName);
                    Attribute attribute = entityType.getAttribute(fieldName);
                    if (metamodel.isEmbeddable(((AbstractAttribute) attribute).getBindableJavaType())) {
                        EmbeddableType embeddedType = metamodel
                                .embeddable(((AbstractAttribute) attribute).getBindableJavaType());
                        Set<Attribute> attributes = embeddedType.getAttributes();
                        for (Attribute embeddedAttribute : attributes) {
                            Object embeddedAttributevalue = PropertyAccessorHelper.getObject(value,
                                    (Field) embeddedAttribute.getJavaMember());
                            addClause(entityMetadata, aliasName, queryBuilder, entityType,
                                    embeddedAttributevalue, condition, propertyName, embeddedAttribute);
                            queryBuilder.append(" and ");
                        }

                        queryBuilder.delete(queryBuilder.lastIndexOf("and"),
                                queryBuilder.lastIndexOf("and") + 3);
                    } else if (((AbstractAttribute) entityMetadata.getIdAttribute()).getJPAColumnName()
                            .equals(propertyName)) {
                        addClause(entityMetadata, aliasName, queryBuilder, entityType, value, condition,
                                propertyName, entityMetadata.getIdAttribute());
                    } else {
                        addClause(entityMetadata, aliasName, queryBuilder, entityType, value, condition,
                                propertyName, attribute);
                    }
                }
            } else {
                queryBuilder.append(" ");
                queryBuilder.append(o);
                queryBuilder.append(" ");
            }
        }
    } else {
        queryBuilder.append(aliasName);
        queryBuilder.append(".");
        queryBuilder.append(((AbstractAttribute) entityMetadata.getIdAttribute()).getJPAColumnName());
        queryBuilder.append(" ");
        queryBuilder.append("IN(");
        int count = 0;
        Attribute col = entityMetadata.getIdAttribute();
        boolean isString = isStringProperty(entityType, col);
        for (String key : primaryKeys) {
            appendStringPrefix(queryBuilder, isString);
            queryBuilder.append(key);
            appendStringPrefix(queryBuilder, isString);
            if (++count != primaryKeys.size()) {
                queryBuilder.append(",");
            } else {
                queryBuilder.append(")");
            }
        }
    }
}

From source file:edu.ku.brc.specify.toycode.mexconabio.CopyPlantsFromGBIF.java

/**
 * /*from w w w.ja  v  a 2  s.co m*/
 */
public void processNonNullNonPlantKingdom() {
    PrintWriter pw = null;
    try {
        pw = new PrintWriter("gbif_plants_from_nonnull.log");

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

    System.out.println("----------------------- Search non-Plantae ----------------------- ");

    String gbifWhereStr = "FROM raw WHERE kingdom = '%s'";

    Vector<String> nonPlantKingdoms = new Vector<String>();
    String sqlStr = "SELECT * FROM (select kingdom, count(kingdom) as cnt from plants.raw WHERE kingdom is not null AND NOT (lower(kingdom) like '%plant%') group by kingdom) T1 ORDER BY cnt desc;";
    for (Object[] obj : BasicSQLUtils.query(sqlStr)) {
        String kingdom = (String) obj[0];
        Integer count = (Integer) obj[1];

        System.out.println(kingdom + " " + count);
        pw.println(kingdom + " " + count);
        if (!StringUtils.contains(kingdom.toLowerCase(), "plant")) {
            nonPlantKingdoms.add(kingdom);
        }
    }

    long startTime = System.currentTimeMillis();

    for (String kingdom : nonPlantKingdoms) {
        String where = String.format(gbifWhereStr, kingdom);

        String cntGBIFSQL = "SELECT COUNT(*) " + where;
        String gbifSQL = gbifSQLBase + where;

        System.out.println(cntGBIFSQL);

        long totalRecs = BasicSQLUtils.getCount(srcConn, cntGBIFSQL);
        long procRecs = 0;
        int secsThreshold = 0;

        String msg = String.format("Query: %8.2f secs",
                (double) (System.currentTimeMillis() - startTime) / 1000.0);
        System.out.println(msg);
        pw.println(msg);
        pw.flush();

        startTime = System.currentTimeMillis();

        Statement gStmt = null;
        PreparedStatement pStmt = null;

        try {
            pStmt = dstConn.prepareStatement(pSQL);

            System.out.println("Total Records: " + totalRecs);
            pw.println("Total Records: " + totalRecs);
            pw.flush();

            gStmt = srcConn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
            gStmt.setFetchSize(Integer.MIN_VALUE);

            ResultSet rs = gStmt.executeQuery(gbifSQL);
            ResultSetMetaData rsmd = rs.getMetaData();

            while (rs.next()) {
                String genus = rs.getString(16);
                if (genus == null)
                    continue;

                String species = rs.getString(17);

                if (isPlant(colStmtGN, colStmtGNSP, genus, species)
                        || isPlant(colDstStmtGN, colDstStmtGNSP, genus, species)) {

                    for (int i = 1; i <= rsmd.getColumnCount(); i++) {
                        Object obj = rs.getObject(i);
                        pStmt.setObject(i, obj);
                    }

                    try {
                        pStmt.executeUpdate();

                    } catch (Exception ex) {
                        System.err.println("For Old ID[" + rs.getObject(1) + "]");
                        ex.printStackTrace();
                        pw.print("For Old ID[" + rs.getObject(1) + "] " + ex.getMessage());
                        pw.flush();
                    }

                    procRecs++;
                    if (procRecs % 10000 == 0) {
                        long endTime = System.currentTimeMillis();
                        long elapsedTime = endTime - startTime;

                        double avergeTime = (double) elapsedTime / (double) procRecs;

                        double hrsLeft = (((double) elapsedTime / (double) procRecs) * (double) totalRecs
                                - procRecs) / HRS;

                        int seconds = (int) (elapsedTime / 60000.0);
                        if (secsThreshold != seconds) {
                            secsThreshold = seconds;

                            msg = String.format(
                                    "Elapsed %8.2f hr.mn   Ave Time: %5.2f    Percent: %6.3f  Hours Left: %8.2f ",
                                    ((double) (elapsedTime)) / HRS, avergeTime,
                                    100.0 * ((double) procRecs / (double) totalRecs), hrsLeft);
                            System.out.println(msg);
                            pw.println(msg);
                            pw.flush();
                        }
                    }
                }
            }

        } catch (Exception ex) {
            ex.printStackTrace();

        } finally {
            try {
                if (gStmt != null) {
                    gStmt.close();
                }
                if (pStmt != null) {
                    pStmt.close();
                }
                pw.close();

            } catch (Exception ex) {

            }
        }
    }
    System.out.println("Done transferring.");
    pw.println("Done transferring.");

}

From source file:edu.ku.brc.specify.toycode.L18NStringResApp.java

/**
 * @param file//  www.  j a va 2 s  .  c om
 * @param dstFile
 * @param hash
 */
protected void mergeFile(final File file, final File dstFile,
        final HashMap<String, Pair<String, String>> hash) {
    try {
        List<String> srcLines = (List<String>) FileUtils.readLines(file, "UTF8");
        Vector<String> dstLines = new Vector<String>();
        for (int i = 0; i < srcLines.size(); i++) {
            String line = srcLines.get(i);
            if (StringUtils.contains(line, "<string")) {
                String key = getKey(line);
                String text = null;
                if (key != null && hash.get(key) != null) {
                    text = hash.get(key).first;

                } else {
                    String txt = getText(line);
                    text = translate(txt);
                    System.out.println("[" + txt + "][" + text + "]");
                }
                line = String.format("    <string name=\"%s\">%s</string>", key, text);
            }
            if (line.endsWith("\n")) {
                line = StringUtils.chomp(line);
            }
            dstLines.add(line);
        }

        /*
        System.out.println("----------");
        for (String s : dstLines)
        {
        System.out.print(s);
        }
        */

        FileUtils.writeLines(dstFile, "UTF8", dstLines);

    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:com.sfs.whichdoctor.dao.AccreditationDAOImpl.java

/**
 * Gets the training summary./*from   ww  w.ja va  2  s  . com*/
 *
 * @param guid the guid
 * @param type the type
 *
 * @return the training summary
 *
 * @throws WhichDoctorDaoException the which doctor dao exception
 */
@SuppressWarnings("unchecked")
public final TreeMap<String, AccreditationBean[]> getTrainingSummary(final int guid, final String type)
        throws WhichDoctorDaoException {

    if (type == null) {
        throw new NullPointerException("Training type cannot be null");
    }

    dataLogger.info("Getting " + type + " Training Summary for Member GUID: " + guid);

    TreeMap<String, AccreditationBean[]> summary = new TreeMap<String, AccreditationBean[]>();

    Collection<AccreditationBean> accreditations = new ArrayList<AccreditationBean>();
    try {
        accreditations = this.getJdbcTemplateReader().query(this.getSQL().getValue("accreditation/loadSummary"),
                new Object[] { guid, type }, new RowMapper() {
                    public Object mapRow(final ResultSet rs, final int rowNum) throws SQLException {
                        AccreditationBean accreditation = new AccreditationBean();

                        accreditation.setAbbreviation(rs.getString("AccreditationTypeAbbreviation"));
                        accreditation.setAccreditationType(rs.getString("AccreditationType"));
                        accreditation.setSpecialtyType(rs.getString("SpecialtyTypeClass"));
                        accreditation.setSpecialtySubType(rs.getString("SpecialtyTypeName"));
                        accreditation.setSpecialtyTypeAbbreviation(rs.getString("SpecialtyTypeAbbreviation"));
                        accreditation.setCore(rs.getBoolean("Core"));
                        accreditation.setWeeksApproved(rs.getInt("WeeksApproved"));
                        accreditation.setWeeksCertified(rs.getInt("WeeksCertified"));

                        // The active flag holds whether the accreditation is excess
                        boolean active = true;

                        String trainingClass = rs.getString("TrainingClass");
                        if (StringUtils.contains(trainingClass, "nterrupted")
                                || StringUtils.contains(trainingClass, "ontinuing")) {
                            active = false;
                        }
                        accreditation.setActive(active);

                        return accreditation;
                    }
                });

    } catch (IncorrectResultSizeDataAccessException ie) {
        dataLogger.debug("No results found for search: " + ie.getMessage());
    }

    for (AccreditationBean acrd : accreditations) {
        if (acrd.getActive()) {

            // Generate index key
            String specialtyAbbreviation = acrd.getAccreditationType();
            String specialtyTypeName = acrd.getSpecialtyType();
            if (StringUtils.isNotBlank(acrd.getAbbreviation())) {
                specialtyAbbreviation = acrd.getAbbreviation();
            }
            if (StringUtils.isNotBlank(acrd.getSpecialtySubType())) {
                specialtyTypeName = acrd.getSpecialtyType() + " - " + acrd.getSpecialtySubType();
            }
            String specialtyKey = specialtyAbbreviation + ": " + specialtyTypeName;

            AccreditationBean core = new AccreditationBean();
            core.setAbbreviation(acrd.getAbbreviation());
            core.setAccreditationType(acrd.getAccreditationType());
            core.setCore(true);
            core.setSpecialtyType(acrd.getSpecialtyType());
            core.setSpecialtySubType(acrd.getSpecialtySubType());
            core.setSpecialtyTypeAbbreviation(acrd.getSpecialtyTypeAbbreviation());

            AccreditationBean nonCore = new AccreditationBean();
            nonCore.setAbbreviation(acrd.getAbbreviation());
            nonCore.setAccreditationType(acrd.getAccreditationType());
            nonCore.setCore(false);
            nonCore.setSpecialtyType(acrd.getSpecialtyType());
            nonCore.setSpecialtySubType(acrd.getSpecialtySubType());
            nonCore.setSpecialtyTypeAbbreviation(acrd.getSpecialtyTypeAbbreviation());

            if (summary.containsKey(specialtyKey)) {
                // Specialty exists in TreeMap -> Get array and modify
                try {
                    AccreditationBean[] existing = summary.get(specialtyKey);
                    core = existing[0];
                    nonCore = existing[1];
                } catch (Exception e) {
                    dataLogger.error("Error loading existing training summary item: " + e.getMessage());
                }
            }

            // Add to the relevant core/nonCore running totals
            if (acrd.getCore()) {
                core.setWeeksApproved(core.getWeeksApproved() + acrd.getWeeksApproved());
                core.setWeeksCertified(core.getWeeksCertified() + acrd.getWeeksCertified());
            } else {
                nonCore.setWeeksApproved(nonCore.getWeeksApproved() + acrd.getWeeksApproved());
                nonCore.setWeeksCertified(nonCore.getWeeksCertified() + acrd.getWeeksCertified());
            }

            // Set accreditation details
            AccreditationBean[] details = new AccreditationBean[] { core, nonCore };

            // Add accreditation to map
            summary.put(specialtyKey, details);
        }
    }
    return summary;
}

From source file:com.adobe.acs.commons.wcm.impl.ComponentErrorHandlerImpl.java

protected final boolean accepts(final SlingHttpServletRequest request,
        final SlingHttpServletResponse response) {

    if (!StringUtils.endsWith(request.getRequestURI(), ".html")
            || !StringUtils.contains(response.getContentType(), "html")) {
        // Do not inject around non-HTML requests
        return false;
    }//from  w w  w  .j  a va  2  s .com

    final ComponentContext componentContext = WCMUtils.getComponentContext(request);
    if (componentContext == null // ComponentContext is null
            || componentContext.getComponent() == null // Component is null
            || componentContext.isRoot()) { // Suppress on root context
        return false;
    }

    // Check to make sure the suppress key has not been added to the request
    if (this.isComponentErrorHandlingSuppressed(request)) {
        // Suppress key is detected, skip handling

        return false;
    }

    // Check to make sure the SlingRequest's resource isn't in the suppress list
    final SlingHttpServletRequest slingRequest = (SlingHttpServletRequest) request;
    for (final String suppressedResourceType : suppressedResourceTypes) {
        if (slingRequest.getResource().isResourceType(suppressedResourceType)) {
            return false;
        }
    }

    return true;
}

From source file:com.iyonger.apm.web.model.AgentManager.java

/**
 * Filter the user owned agents from given agents.
 *
 * @param agents all agents//from  w w  w  .  jav a2 s  .  c o m
 * @param userId userId
 * @return userOwned agents.
 */
public Set<AgentIdentity> filterUserAgents(Set<AgentIdentity> agents, String userId) {

    Set<AgentIdentity> userAgent = new HashSet<AgentIdentity>();
    for (AgentIdentity each : agents) {
        String region = ((AgentControllerIdentityImplementation) each).getRegion();
        if (StringUtils.endsWith(region, "owned_" + userId) || !StringUtils.contains(region, "owned_")) {
            userAgent.add(each);
        }
    }
    return userAgent;
}

From source file:eionet.meta.imp.VocabularyRDFImportHandler.java

@Override
public void handleStatement(Statement st) throws RDFHandlerException {
    this.totalNumberOfTriples++;
    Resource subject = st.getSubject();
    URI predicate = st.getPredicate();
    Value object = st.getObject();//from w  w w .j  a  v a  2 s.  c  o  m

    if (!(subject instanceof URI)) {
        // this.logMessages.add(st.toString() + " NOT imported, subject is not a URI");
        return;
    }

    // object should a resource or a literal (value)
    if (!(object instanceof URI) && !(object instanceof Literal)) {
        // this.logMessages.add(st.toString() + " NOT imported, object is not instance of URI or Literal");
        return;
    }

    String conceptUri = subject.stringValue();
    if (!StringUtils.startsWith(conceptUri, this.folderContextRoot)) {
        // this.logMessages.add(st.toString() + " NOT imported, does not have base URI");
        return;
    }

    this.messageDigestInstance.reset();
    byte[] digested;
    try {
        digested = this.messageDigestInstance.digest(st.toString().getBytes(DEFAULT_ENCODING_OF_STRINGS));
    } catch (UnsupportedEncodingException e) {
        throw new RDFHandlerException(e);
    }
    BigInteger statementHashCode = new BigInteger(1, digested);
    if (this.seenStatementsHashCodes.contains(statementHashCode)) {
        // this.logMessages.add(st.toString() + " NOT imported, duplicates a previous triple");
        this.numberOfDuplicatedTriples++;
        return;
    }
    this.seenStatementsHashCodes.add(statementHashCode);

    // if it does not a have conceptIdentifier than it may be an attribute for vocabulary or a wrong record, so just ignore it
    String conceptIdentifier = conceptUri.replace(this.folderContextRoot, "");
    if (StringUtils.contains(conceptIdentifier, "/") || !Util.isValidIdentifier(conceptIdentifier)) {
        // this.logMessages.add(st.toString() + " NOT imported, contains a / in concept identifier or empty");
        return;
    }

    String predicateUri = predicate.stringValue();

    Pair<Class, String> ignoranceRule = PREDICATE_IGNORANCE_RULES.get(predicateUri);
    if (ignoranceRule != null) {
        if (ignoranceRule.getLeft().isInstance(object)
                && object.stringValue().matches(ignoranceRule.getRight())) {
            // ignore value
            return;
        }
    }

    String attributeIdentifier = null;
    String predicateNS = null;

    boolean candidateForConceptAttribute = false;
    if (StringUtils.startsWith(predicateUri, VocabularyOutputHelper.LinkedDataNamespaces.SKOS_NS)) {
        attributeIdentifier = predicateUri.replace(VocabularyOutputHelper.LinkedDataNamespaces.SKOS_NS, "");
        candidateForConceptAttribute = SKOS_CONCEPT_ATTRIBUTES.contains(attributeIdentifier);
        if (candidateForConceptAttribute) {
            predicateNS = SKOS_CONCEPT_ATTRIBUTE_NS;
        }
    }

    if (candidateForConceptAttribute && !(object instanceof Literal)) {
        // this.logMessages.add(st.toString() + " NOT imported, object is not a Literal for concept attribute");
        return;
    }

    if (!candidateForConceptAttribute) {
        for (String key : this.boundURIs.keySet()) {
            if (StringUtils.startsWith(predicateUri, key)) {
                attributeIdentifier = predicateUri.replace(key, "");
                predicateNS = this.boundURIs.get(key);
                if (!this.boundElements.get(predicateNS).contains(attributeIdentifier)) {
                    predicateNS = null;
                }
                break;
            }
        }
    }

    if (StringUtils.isEmpty(predicateNS)) {
        // this.logMessages.add(st.toString() + " NOT imported, predicate is not a bound URI nor a concept attribute");
        this.notBoundPredicates.add(predicateUri);
        return;
    }

    // if execution comes here so we have a valid triple to import
    // first find the concept
    if (!StringUtils.equals(conceptIdentifier, this.prevConceptIdentifier)) {
        this.prevDataElemIdentifier = null;
        this.prevLang = null;
        this.lastFoundConcept = null;
    }
    this.prevConceptIdentifier = conceptIdentifier;

    if (this.lastFoundConcept == null) {
        Pair<VocabularyConcept, Boolean> foundConceptWithFlag = findOrCreateConcept(conceptIdentifier);
        // if vocabulary concept couldnt find or couldnt be created
        if (foundConceptWithFlag == null) {
            return;
        }

        this.lastFoundConcept = foundConceptWithFlag.getLeft();
        if (!foundConceptWithFlag.getRight()) {
            // vocabulary concept found or created, add it to list
            this.toBeUpdatedConcepts.add(this.lastFoundConcept);
        }
    }

    String dataElemIdentifier = predicateNS + ":" + attributeIdentifier;
    if (StringUtils.equals(this.ddNamespace, predicateNS)) {
        dataElemIdentifier = attributeIdentifier;
    }

    // TODO code below can be refactored
    if (candidateForConceptAttribute && !this.conceptsUpdatedForAttributes.get(dataElemIdentifier)
            .contains(this.lastFoundConcept.getId())) {
        this.conceptsUpdatedForAttributes.get(dataElemIdentifier).add(this.lastFoundConcept.getId());
        // update concept value here
        String val = StringUtils.trimToNull(object.stringValue());
        if (StringUtils.equals(attributeIdentifier, NOTATION)) {
            this.lastFoundConcept.setNotation(val);
        } else {
            if (StringUtils.equals(attributeIdentifier, DEFINITION)) {
                this.lastFoundConcept.setDefinition(val);
            } else if (StringUtils.equals(attributeIdentifier, PREF_LABEL)) {
                this.lastFoundConcept.setLabel(val);
            }
            String elemLang = StringUtils.substring(((Literal) object).getLanguage(), 0, 2);
            if (StringUtils.isNotBlank(elemLang)) {
                this.lastCandidateForConceptAttribute.put(this.lastFoundConcept.getId() + dataElemIdentifier,
                        (Literal) object);
                candidateForConceptAttribute = false;
            }
        }
    } else if (candidateForConceptAttribute && this.lastCandidateForConceptAttribute
            .containsKey(this.lastFoundConcept.getId() + dataElemIdentifier)) {
        // check if more prior value received
        Literal previousCandidate = this.lastCandidateForConceptAttribute
                .remove(this.lastFoundConcept.getId() + dataElemIdentifier);

        String elemLang = StringUtils.substring(((Literal) object).getLanguage(), 0, 2);
        boolean updateValue = false;
        if (StringUtils.isEmpty(elemLang)) {
            updateValue = true;
        } else if (StringUtils.equals(elemLang, this.workingLanguage) && !StringUtils
                .equals(StringUtils.substring(previousCandidate.getLanguage(), 0, 2), this.workingLanguage)) {
            updateValue = true;
            candidateForConceptAttribute = false;
            this.lastCandidateForConceptAttribute.put(this.lastFoundConcept.getId() + dataElemIdentifier,
                    (Literal) object);
        } else {
            this.lastCandidateForConceptAttribute.put(this.lastFoundConcept.getId() + dataElemIdentifier,
                    previousCandidate);
            candidateForConceptAttribute = false;
        }

        if (updateValue) {
            String val = StringUtils.trimToNull(object.stringValue());
            if (StringUtils.equals(attributeIdentifier, DEFINITION)) {
                this.lastFoundConcept.setDefinition(val);
            } else if (StringUtils.equals(attributeIdentifier, PREF_LABEL)) {
                this.lastFoundConcept.setLabel(val);
            }
        }
    } else {
        candidateForConceptAttribute = false;
    }

    if (!candidateForConceptAttribute) {
        if (!this.boundElementsIds.containsKey(dataElemIdentifier)) {
            this.notBoundPredicates.add(predicateUri);
            return;
        }

        Set<Integer> conceptIdsUpdatedWithPredicate = this.predicateUpdatesAtConcepts.get(predicateUri);
        if (conceptIdsUpdatedWithPredicate == null) {
            conceptIdsUpdatedWithPredicate = new HashSet<Integer>();
            this.predicateUpdatesAtConcepts.put(predicateUri, conceptIdsUpdatedWithPredicate);
        }
        // find the data element
        if (!this.identifierOfPredicate.containsKey(predicateUri)) {
            this.identifierOfPredicate.put(predicateUri, dataElemIdentifier);
        }
        if (!StringUtils.equals(dataElemIdentifier, this.prevDataElemIdentifier)) {
            elementsOfConcept = getDataElementValuesByName(dataElemIdentifier,
                    lastFoundConcept.getElementAttributes());
            if (createNewDataElementsForPredicates
                    && !conceptIdsUpdatedWithPredicate.contains(lastFoundConcept.getId())) {
                if (this.elementsOfConcept != null) {
                    this.lastFoundConcept.getElementAttributes().remove(this.elementsOfConcept);
                }
                this.elementsOfConcept = null;
            }

            if (this.elementsOfConcept == null) {
                this.elementsOfConcept = new ArrayList<DataElement>();
                this.lastFoundConcept.getElementAttributes().add(this.elementsOfConcept);
            }
        }

        String elementValue = object.stringValue();
        if (StringUtils.isEmpty(elementValue)) {
            // value is empty, no need to continue
            return;
        }
        String elemLang = null;
        VocabularyConcept foundRelatedConcept = null;
        // if object is a resource (i.e. URI), it can be a related concept
        if (object instanceof URI) {
            foundRelatedConcept = findRelatedConcept(elementValue);
        } else if (object instanceof Literal) {
            // it is literal
            elemLang = StringUtils.substring(((Literal) object).getLanguage(), 0, 2);
        }

        if (!StringUtils.equals(dataElemIdentifier, prevDataElemIdentifier)
                || !StringUtils.equals(elemLang, prevLang)) {
            elementsOfConceptByLang = getDataElementValuesByNameAndLang(dataElemIdentifier, elemLang,
                    lastFoundConcept.getElementAttributes());
        }
        this.prevLang = elemLang;
        this.prevDataElemIdentifier = dataElemIdentifier;

        // check for pre-existence of the VCE by attribute value or related concept id
        Integer relatedId = null;
        if (foundRelatedConcept != null) {
            relatedId = foundRelatedConcept.getId();
        }
        for (DataElement elemByLang : elementsOfConceptByLang) {
            String elementValueByLang = elemByLang.getAttributeValue();
            if (StringUtils.equals(elementValue, elementValueByLang)) {
                // vocabulary concept element already in database, no need to continue, return
                return;
            }
            if (relatedId != null) {
                Integer relatedConceptId = elemByLang.getRelatedConceptId();
                if (relatedConceptId != null && relatedConceptId.intValue() == relatedId.intValue()) {
                    // vocabulary concept element already in database, no need to continue, return
                    return;
                }
            }
        }

        // create VCE
        DataElement elem = new DataElement();
        this.elementsOfConcept.add(elem);
        elem.setAttributeLanguage(elemLang);
        elem.setIdentifier(dataElemIdentifier);
        elem.setId(this.boundElementsIds.get(dataElemIdentifier));
        // check if there is a found related concept
        if (foundRelatedConcept != null) {
            elem.setRelatedConceptIdentifier(foundRelatedConcept.getIdentifier());
            int id = foundRelatedConcept.getId();
            elem.setRelatedConceptId(id);
            elem.setAttributeValue(null);
            if (id < 0) {
                addToElementsReferringNotCreatedConcepts(id, elem);
            }
        } else {
            elem.setAttributeValue(elementValue);
            elem.setRelatedConceptId(null);
        }

        conceptIdsUpdatedWithPredicate.add(this.lastFoundConcept.getId());
    }
    this.numberOfValidTriples++;
}

From source file:edu.ku.brc.specify.prefs.MySQLPrefs.java

@Override
public boolean isFormValid() {
    String mysql = mysqlLocBP.getTextField().getText();
    String mysqldump = mysqlDumpLocBP.getTextField().getText();

    return StringUtils.isNotEmpty(mysql) && StringUtils.contains(mysql.toLowerCase(), "mysql")
            && StringUtils.isNotEmpty(mysqldump) && StringUtils.contains(mysqldump.toLowerCase(), "mysqldump")
            && StringUtils.isNotEmpty(backupLocBP.getTextField().getText());
}