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

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

Introduction

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

Prototype

public static boolean startsWith(String str, String prefix) 

Source Link

Document

Check if a String starts with a specified prefix.

Usage

From source file:net.bible.service.device.speak.TextToSpeechController.java

@Override
public void onUtteranceCompleted(String utteranceId) {
    Log.d(TAG, "onUtteranceCompleted:" + utteranceId);
    // pause/rew/ff can sometimes allow old messages to complete so need to prevent move to next sentence if completed utterance is out of date 
    if ((!isPaused && isSpeaking) && StringUtils.startsWith(utteranceId, UTTERANCE_PREFIX)) {
        long utteranceNo = Long.valueOf(StringUtils.removeStart(utteranceId, UTTERANCE_PREFIX));
        if (utteranceNo == uniqueUtteranceNo - 1) {
            mSpeakTextProvider.finishedUtterance(utteranceId);

            // estimate cps
            mSpeakTiming.finished(utteranceId);

            // ask TTs to say the text
            if (mSpeakTextProvider.isMoreTextToSpeak()) {
                speakNextChunk();//w  ww  . ja  v a 2 s.co m
            } else {
                Log.d(TAG, "Shutting down TTS");
                shutdown();
            }
        }
    }
}

From source file:com.htmlhifive.tools.rhino.Util.java

public static boolean isVSDoc(String str) {

    return StringUtils.startsWith(str, "///");
}

From source file:hydrograph.ui.perspective.ApplicationWorkbenchWindowAdvisor.java

private static String getInstallationConfigPath() {
    String path = Platform.getInstallLocation().getURL().getPath();
    if (StringUtils.isNotBlank(path) && StringUtils.startsWith(path, "/") && OSValidator.isWindows()) {
        path = StringUtils.substring(path, 1);
    }//from  w w  w  .  j  av  a 2  s. c  o  m

    return path + "config/service/config";
}

From source file:edu.cornell.kfs.vnd.batch.service.impl.VendorBatchServiceImpl.java

private boolean maintainVendors(String fileName, BatchInputFileType batchInputFileType,
        StringBuilder processResults) {
    boolean result = true;

    //  load up the file into a byte array 
    byte[] fileByteContent = safelyLoadFileBytes(fileName);

    LOG.info("Attempting to parse the file");
    Object parsedObject = null;/*from  w  w w .j  a v a2s .c o  m*/
    try {
        parsedObject = batchInputFileService.parse(batchInputFileType, fileByteContent);
    } catch (ParseException e) {
        String errorMessage = "Error parsing batch file: " + e.getMessage();
        LOG.error(errorMessage, e);
        throw new RuntimeException(errorMessage);
    }

    //  make sure we got the type we expected, then cast it
    if (!(parsedObject instanceof List)) {
        String errorMessage = "Parsed file was not of the expected type.  Expected [" + List.class
                + "] but got [" + parsedObject.getClass() + "].";
        criticalError(errorMessage);
    }

    List<VendorBatchDetail> vendors = (List<VendorBatchDetail>) parsedObject;

    for (VendorBatchDetail vendorBatch : vendors) {
        // process each line to add/update vendor accordingly 
        String returnVal = KFSConstants.EMPTY_STRING;
        if (StringUtils.isBlank(vendorBatch.getVendorNumber())) {
            processResults.append("add vendor : " + vendorBatch.getLogData() + NEW_LINE);
            returnVal = addVendor(vendorBatch);
        } else {
            processResults.append("update vendor : " + vendorBatch.getLogData() + NEW_LINE);
            returnVal = updateVendor(vendorBatch);
        }
        if (StringUtils.startsWith(returnVal, "Failed request")) {
            // TODO : there is error.  need to handle here or before exit
            LOG.error(returnVal);
            result = false;
            processResults.append(returnVal + NEW_LINE);
        } else {
            LOG.info("Document " + returnVal + " routed.");
            processResults.append("Document " + returnVal + " routed." + NEW_LINE);
        }
    }

    return result;
}

From source file:com.xx_dev.apn.proxy.ApnProxyUserAgentForwardHandler.java

private String getPartialUrl(String fullUrl) {
    if (StringUtils.startsWith(fullUrl, "http")) {
        int idx = StringUtils.indexOf(fullUrl, "/", 7);
        return idx == -1 ? "/" : StringUtils.substring(fullUrl, idx);
    }/*  ww w.  j a  va 2 s .c o  m*/

    return fullUrl;
}

From source file:com.activecq.tools.errorpagehandler.impl.ErrorPageHandlerImpl.java

/**
 * Filter query results/* w  w  w  . j a v a2 s  . c om*/
 *
 * @param rootPath
 * @param result
 * @return list of resource paths of candidate error pages
 */
private List<String> filterResults(String rootPath, SearchResult result) {
    final List<Node> nodes = IteratorUtils.toList(result.getNodes());
    final List<String> resultPaths = new ArrayList<String>();
    if (StringUtils.isBlank(rootPath)) {
        return resultPaths;
    }

    // Filter results by the searchResource path; All valid results' paths should begin
    // with searchResource.getPath()
    for (Node node : nodes) {
        if (node == null) {
            continue;
        }
        try {
            // Make sure all query results under or equals to the current Search Resource
            if (StringUtils.equals(node.getPath(), rootPath)
                    || StringUtils.startsWith(node.getPath(), rootPath.concat("/"))) {
                resultPaths.add(node.getPath());
            }
        } catch (RepositoryException ex) {
            log.warn("Could not get path for node. {}", ex.getMessage());
            // continue
        }
    }

    return resultPaths;
}

From source file:com.iyonger.apm.web.configuration.Config.java

/**
 * Resolve nGrinder extended home path./*from  w ww . ja va 2 s  .  c om*/
 *
 * @return resolved home
 */
protected Home resolveExHome() {
    String exHomeFromEnv = System.getenv("NGRINDER_EX_HOME");
    String exHomeFromProperty = System.getProperty("ngrinder.ex_home");
    if (!StringUtils.equals(exHomeFromEnv, exHomeFromProperty)) {
        CoreLogger.LOGGER.warn("The path to ngrinder ex home is ambiguous:");
        CoreLogger.LOGGER.warn("    System Environment:  NGRINDER_EX_HOME=" + exHomeFromEnv);
        CoreLogger.LOGGER.warn("    Java System Property:  ngrinder.ex_home=" + exHomeFromProperty);
        CoreLogger.LOGGER.warn("    '" + exHomeFromProperty + "' is accepted.");
    }
    String userHome = StringUtils.defaultIfEmpty(exHomeFromProperty, exHomeFromEnv);

    if (StringUtils.isEmpty(userHome)) {
        userHome = System.getProperty("user.home") + File.separator + NGRINDER_EX_FOLDER;
    } else if (StringUtils.startsWith(userHome, "~" + File.separator)) {
        userHome = System.getProperty("user.home") + File.separator + userHome.substring(2);
    } else if (StringUtils.startsWith(userHome, "." + File.separator)) {
        userHome = System.getProperty("user.dir") + File.separator + userHome.substring(2);
    }

    userHome = FilenameUtils.normalize(userHome);
    File exHomeDirectory = new File(userHome);
    CoreLogger.LOGGER.info("nGrinder ex home directory:{}.", exHomeDirectory);
    try {
        //noinspection ResultOfMethodCallIgnored
        exHomeDirectory.mkdirs();
    } catch (Exception e) {
        // If it's not possible.. do it... without real directory.
        noOp();
    }
    return new Home(exHomeDirectory, false);
}

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  va  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:com.sfs.whichdoctor.formatter.PersonFormatter.java

public static String getField(final PersonBean person, final String field, final String format,
        final PreferencesBean preferences) {

    String value = "";
    if (person == null || field == null) {
        return value;
    }//  w w w . j av  a 2  s .  c o  m

    if (field.compareTo("Tags") == 0) {
        value = OutputFormatter.toTagList(person.getTags());
    }

    if (field.compareTo("GUID") == 0) {
        if (person.getGUID() > 0) {
            value = String.valueOf(person.getGUID());
        }
    }

    if (field.compareTo("PersonId") == 0) {
        if (person.getId() > 0) {
            value = String.valueOf(person.getId());
        }
    }

    if (field.compareTo("Gender") == 0) {
        value = person.getGender();
    }

    if (StringUtils.equals(field, "Title") || StringUtils.equals(field, "SALUTATION-1")) {
        value = person.getTitle();
    }
    if (field.compareTo("First Name") == 0) {
        value = person.getFirstName();
    }
    if (StringUtils.equals(field, "INVESTOR-GIVENNAME-1")) {
        value = person.getFirstName();
        if (StringUtils.isNotBlank(person.getMiddleName())) {
            value += " " + person.getMiddleName();
        }
    }
    if (StringUtils.equals(field, "Preferred Name") || StringUtils.equals(field, "INVESTOR-PREFERREDNAME-1")) {
        value = person.getPreferredName();
    }
    if (field.compareTo("Middle Name") == 0) {
        value = person.getMiddleName();
    }
    if (StringUtils.equals(field, "Last Name") || StringUtils.equals(field, "INVESTOR-SURNAME-1")) {
        value = person.getLastName();
    }
    if (field.compareTo("Maiden Name") == 0) {
        value = person.getMaidenName();
    }
    if (field.compareTo("Formatted Name") == 0) {
        value = OutputFormatter.toFormattedName(person);
    }
    if (field.compareTo("Honors") == 0) {
        value = person.getHonors();
    }
    if (field.compareTo("Age") == 0) {
        value = person.getAge();
    }
    if (StringUtils.equals(field, "MIN") || StringUtils.equals(field, "HOLDER-NUMBER")
            || StringUtils.equals(field, "ALTERNATE-ID")) {
        value = String.valueOf(person.getPersonIdentifier());
    }

    String status = "";

    if (person.getPrimaryMembership() != null) {
        MembershipBean membership = person.getPrimaryMembership();
        status = membership.getField("Status");

        if (StringUtils.equals(field, "Candidate Number")) {
            value = membership.getField("Candidate Number");
        }

        if (StringUtils.equals(field, "Status")) {
            value = status;
        }

        if (StringUtils.equals(field, "Membership Class")) {
            ObjectTypeBean object = membership.getObjectTypeField("Membership Type");
            value = object.getClassName();
        }

        if (StringUtils.equals(field, "Membership Type") || StringUtils.equals(field, "RACP-MEMBERSHIP-TYPE")) {
            ObjectTypeBean object = membership.getObjectTypeField("Membership Type");
            value = object.getName();
        }

        if (StringUtils.equals(field, "Date Registered")) {
            if (membership.getJoinedDate() != null) {
                value = Formatter.conventionalDate(membership.getJoinedDate());
            }
        }

        if (StringUtils.equals(field, "Date Retired")) {
            if (membership.getLeftDate() != null) {
                value = Formatter.conventionalDate(membership.getLeftDate());
            }
        }

        if (StringUtils.equals(field, "Financial Exemption")) {
            value = membership.getField("Financial Excemption");
        }

        if (StringUtils.equals(field, "Division")) {
            value = membership.getField("Division");
        }

        if (StringUtils.equals(field, "Supervisor Status")) {
            value = membership.getField("Supervisor Status");
        }

        if (StringUtils.equals(field, "Training Type")) {
            value = membership.getField("Training Type");
        }
    }

    if (StringUtils.equals(field, "Works Overseas")) {
        value = Formatter.convertBoolean(person.getWorksOverseas());
    }
    if (StringUtils.equals(field, "Exam Deadline")) {
        value = Formatter.conventionalDate(person.getExamDeadline());
    }
    if (StringUtils.equals(field, "Birthdate") && person.getBirthDate() != null) {
        value = Formatter.conventionalDate(person.getBirthDate());
    }

    if (StringUtils.equals(field, "DATE-OF-BIRTH") && person.getBirthDate() != null) {
        value = Formatter.numericDate(person.getBirthDate(), "yyyyMMdd");
    }

    if (StringUtils.equals(field, "Date Deceased") && person.getDeceasedDate() != null) {
        value = Formatter.conventionalDate(person.getDeceasedDate());
    }

    if (StringUtils.equals(field, "INVESTOR-DECEASED")) {
        value = "N";
        if (person.getDeceasedDate() != null) {
            value = "Y";
        }
    }

    /** Training curriculum year **/
    if (field.compareTo("Training Curriculum Year") == 0 && person.getSpecialtyList() != null) {
        value = person.getCurriculumYear();
    }

    if (field.compareTo("Training Status") == 0) {
        value = person.getTrainingStatus();
        if (StringUtils.isNotBlank(person.getTrainingStatusDetail())) {
            value += " - " + person.getTrainingStatusDetail();
        }
    }

    if (field.compareTo("CHCCH-TRAINEE") == 0) {
        value = "N";

        if (isCCHTrainee(person)) {
            value = "Y";
        }
    }

    /** Fellowship information **/

    if (person.getMembershipDetails() != null) {
        for (MembershipBean membership : person.getMembershipDetails()) {
            if (StringUtils.equals(membership.getMembershipClass(), "RACP")
                    && StringUtils.equals(membership.getMembershipType(), "Fellowship Details")) {

                if (StringUtils.equals(field, "FRACP")) {
                    if (value.length() > 0) {
                        value += " and ";
                    }
                    value += membership.getField("FRACP");
                }
                if (StringUtils.equals(field, "Admitting S.A.C.")) {
                    if (value.length() > 0) {
                        value += " and ";
                    }
                    value += membership.getField("Admitting SAC");
                }
                if (StringUtils.equals(field, "Admitting Country")
                        || StringUtils.equals(field, "RACP-ADMITTING-COUNTRY")) {
                    if (value.length() > 0) {
                        value += " and ";
                    }
                    value += membership.getField("Admitting Country");
                }
                if (StringUtils.equals(field, "Fellowship Date")
                        && membership.getDateField("Fellowship Date") != null) {
                    if (value.length() > 0) {
                        value += " and ";
                    }
                    value += Formatter.conventionalDate(membership.getDateField("Fellowship Date"));
                }

                if (StringUtils.equals(field, "DATE-FIRST-REGISTERED")
                        && membership.getDateField("Fellowship Date") != null) {
                    value = Formatter.numericDate(membership.getDateField("Fellowship Date"), "yyyyMMdd");
                }
            }

            if (StringUtils.equals(membership.getMembershipClass(), "RACP")
                    && StringUtils.equals(membership.getMembershipType(), "Affiliation")) {

                if (StringUtils.equals(field, "RACP-FACULTY")) {
                    ObjectTypeBean affiliation = membership.getObjectTypeField("Affiliation");
                    if (value.length() > 0) {
                        value += " and ";
                    }
                    value = affiliation.getAbbreviation();
                }
            }
        }
    }

    if (StringUtils.equals(field, "CLASSIFICATION-CODE")) {
        String subType = "";

        // Is a trainee
        if (person.getPrimaryMembership() != null) {
            String membershipType = person.getPrimaryMembership().getObjectTypeField("Membership Type")
                    .getName();

            if (StringUtils.containsIgnoreCase(membershipType, "Trainee")) {
                subType = "C";

                if (StringUtils.equalsIgnoreCase(person.getTrainingStatus(), "Training")
                        && StringUtils.equalsIgnoreCase(person.getTrainingStatusDetail(), "Post-FRACP")) {
                    // The person is a Post-FRACP trainee, so they qualify as a 'B'
                    subType = "B";
                }
            }

        }

        // Is a Fellow
        if (person.getMembershipDetails() != null) {
            for (MembershipBean membership : person.getMembershipDetails()) {
                if (StringUtils.equals(membership.getMembershipClass(), "RACP")
                        && StringUtils.equals(membership.getMembershipType(), "Fellowship Details")) {

                    if (StringUtils.startsWith(status, "Active")
                            || StringUtils.equalsIgnoreCase(status, "Life Fellow")
                            || StringUtils.equalsIgnoreCase(status, "Retired")
                            || StringUtils.equalsIgnoreCase(status, "Semi-retired")) {
                        subType = "B";
                    }
                }
            }
        }

        // Is a Community Child Health trainee
        if (isCCHTrainee(person)) {
            subType = "D";
        }

        // Is an Honorary Fellow
        if (person.getTags() != null) {
            for (TagBean tag : person.getTags()) {
                if (StringUtils.equalsIgnoreCase(tag.getTagName(), "Honorary Fellow")) {
                    subType = "A";
                }
            }
        }

        if (StringUtils.isNotBlank(subType)) {
            value = "RACP-" + subType;
        }
    }

    if (field.compareTo("Last Workplace") == 0 && person.getEmployers() != null) {
        String workplaceName = "";
        for (String identifier : person.getEmployers().keySet()) {
            final ItemBean workplace = person.getEmployers().get(identifier);
            if (workplace != null && StringUtils.isBlank(workplaceName)) {
                workplaceName = workplace.getName();
            }
        }
        value = workplaceName;
    }

    if (field.compareTo("Last Rotation Description") == 0 && person.getRotations() != null) {
        for (RotationBean rotation : person.getRotations()) {
            if (rotation.getDescription() != null) {
                value = rotation.getDescription();
            }
        }
    }

    if (field.compareTo("Last Rotation Date") == 0 && person.getRotations() != null) {
        for (RotationBean rotation : person.getRotations()) {
            if (rotation.getEndDate() != null) {
                value = Formatter.conventionalDate(rotation.getEndDate());
            }
        }
    }

    if (field.compareTo("Accred: Basic (wks)") == 0) {
        value = calculateTrainingSummaryTotal(person.getTrainingSummary("Basic Training"), false);
    }

    if (field.compareTo("Accred: Basic (mths)") == 0) {
        value = calculateTrainingSummaryTotal(person.getTrainingSummary("Basic Training"), true);
    }

    if (field.compareTo("Accred: Advanced (wks)") == 0) {
        value = calculateTrainingSummaryTotal(person.getTrainingSummary("Advanced Training"), false);
    }

    if (field.compareTo("Accred: Advanced (mths)") == 0) {
        value = calculateTrainingSummaryTotal(person.getTrainingSummary("Advanced Training"), true);
    }

    if (field.compareTo("Accred: Post-FRACP (wks)") == 0) {
        value = calculateTrainingSummaryTotal(person.getTrainingSummary("Post-FRACP Training"), false);
    }

    if (field.compareTo("Accred: Post-FRACP (mths)") == 0) {
        value = calculateTrainingSummaryTotal(person.getTrainingSummary("Post-FRACP Training"), true);
    }

    if (field.compareTo("Opening Balance") == 0) {
        FinancialSummaryBean openResults = person.getFinancialSummary();
        FinancialSummaryBean restrictedResults = person.getRestrictedFinancialSummary();

        double balance = 0;
        if (openResults != null) {
            balance += openResults.getOpeningBalance();
        }
        if (restrictedResults != null) {
            balance += restrictedResults.getOpeningBalance();
        }
        value = Formatter.toCurrency(balance, "$");
    }

    if (field.compareTo("Closing Balance") == 0) {
        FinancialSummaryBean openResults = person.getFinancialSummary();
        FinancialSummaryBean restrictedResults = person.getRestrictedFinancialSummary();

        double balance = 0;
        if (openResults != null) {
            balance += openResults.getClosingBalance();
        }
        if (restrictedResults != null) {
            balance += restrictedResults.getClosingBalance();
        }
        value = Formatter.toCurrency(balance, "$");
    }

    if (field.compareTo("Outstanding Summary") == 0) {
        final StringBuffer debits = new StringBuffer();
        if (person.getDebits() != null) {
            for (DebitBean debit : person.getDebits()) {
                if (debits.length() > 0) {
                    debits.append(", ");
                }
                debits.append(debit.getAbbreviation());
                debits.append(" ");
                debits.append(debit.getNumber());
            }
        }
        value = debits.toString();
    }

    if (field.compareTo("Country B.M.Q. Awarded") == 0 && person.getQualifications() != null) {
        for (QualificationBean qualification : person.getQualifications()) {
            if (StringUtils.equalsIgnoreCase(qualification.getQualificationSubType(),
                    "Basic medical qualification")) {
                // Qualification is flagged as BMQ, record value of BMQ country
                if (value.compareTo("") != 0 && value.compareTo(qualification.getCountry()) != 0) {
                    // BMQ country has already been set, add an ' and ' as a delimiter
                    value += " and ";
                }
                if (value.compareTo(qualification.getCountry()) != 0) {
                    // Only add to value if qualification country is unique
                    value += qualification.getCountry();
                }
            }
        }
    }
    if (field.compareTo("Year B.M.Q. Awarded") == 0 && person.getQualifications() != null) {
        for (QualificationBean qualification : person.getQualifications()) {
            if (StringUtils.equalsIgnoreCase(qualification.getQualificationSubType(),
                    "Basic medical qualification")) {
                // Qualification is flagged as BMQ, record value of BMQ year
                if (value.compareTo("") != 0 && value.compareTo(String.valueOf(qualification.getYear())) != 0) {
                    // BMQ year has already been set, add an ' and ' as a delimiter
                    value += " and ";
                }
                if (value.compareTo(String.valueOf(qualification.getYear())) != 0) {
                    // Only add to value if qualification year is unique
                    value += qualification.getYear();
                }
            }
        }
    }
    if (field.compareTo("ISB Targets") == 0) {
        if (person.getIsbEntities() != null) {
            for (IsbEntityBean isbEntity : person.getIsbEntities()) {
                if (value.length() > 0) {
                    value += ", ";
                }
                value += isbEntity.getTarget();
            }
        }
    }

    // Contact details
    if (person.getFirstEmailAddress() != null) {

        if (StringUtils.equals(field, "Email Address") || StringUtils.equals(field, "EMAIL-ADDR")) {
            value = person.getFirstEmailAddress().getEmail();
            if (StringUtils.equals(format, "html")) {
                value = "<a href=\"mailto:" + value + "\">" + value + "</a>";
            }
        }
    }

    if (field.compareTo("Phone Number") == 0 && person.getFirstPhoneNo() != null) {
        value = Formatter.getPhone(String.valueOf(person.getFirstPhoneNo().getCountryCode()),
                String.valueOf(person.getFirstPhoneNo().getAreaCode()), person.getFirstPhoneNo().getNumber());
    }

    if (StringUtils.equals(field, "PHONE-NO") || StringUtils.equals(field, "MOBILE-NO")
            || StringUtils.equals(field, "FAX-NO")) {

        String phoneNumber = "";
        boolean phonePreferred = false;
        String mobileNumber = "";
        boolean mobilePreferred = false;
        String faxNumber = "";
        boolean faxPreferred = false;

        if (person.getPhone() != null) {
            for (PhoneBean phone : person.getPhone()) {
                String type = phone.getContactType();
                StringBuffer number = new StringBuffer();

                if (phone.getCountryCode() > 0) {
                    number.append(phone.getCountryCode());
                    number.append(" ");
                }
                if (phone.getAreaCode() > 0) {
                    number.append(phone.getAreaCode());
                    number.append(" ");
                }
                if (StringUtils.isNotBlank(phone.getNumber())) {
                    number.append(phone.getNumber());
                }

                if (StringUtils.equalsIgnoreCase(type, "Home") || StringUtils.equalsIgnoreCase(type, "Work")) {
                    if (!phonePreferred) {
                        phoneNumber = number.toString();
                        if (phone.getPrimary()) {
                            phonePreferred = true;
                        }
                    }
                }
                if (StringUtils.equalsIgnoreCase(type, "Mobile")) {
                    if (!mobilePreferred) {
                        mobileNumber = number.toString();
                        if (phone.getPrimary()) {
                            mobilePreferred = true;
                        }
                    }
                }
                if (StringUtils.equalsIgnoreCase(type, "Home Fax")
                        || StringUtils.equalsIgnoreCase(type, "Work Fax")) {
                    if (!faxPreferred) {
                        faxNumber = number.toString();
                        if (phone.getPrimary()) {
                            faxPreferred = true;
                        }
                    }
                }
            }
        }

        if (StringUtils.equals(field, "PHONE-NO")) {
            value = phoneNumber;
        }
        if (StringUtils.equals(field, "MOBILE-NO")) {
            value = mobileNumber;
        }
        if (StringUtils.equals(field, "FAX-NO")) {
            value = faxNumber;
        }
    }

    if (StringUtils.equals(field, "Region")) {
        value = person.getRegion();
    }

    if (StringUtils.equals(field, "Resident Country") || StringUtils.equals(field, "RESIDENT-COUNTRY")) {
        value = person.getResidentCountry();
    }

    if (person.getFirstAddress() != null) {
        if (field.compareTo("Street Address") == 0) {
            AddressBean address = person.getFirstAddress();
            for (int y = 0; y < address.getAddressFieldCount(); y++) {
                if (value.compareTo("") != 0) {
                    value += ", ";
                }
                value += address.getAddressField(y);
            }
        }

        if (field.compareTo("State") == 0) {
            value = person.getFirstAddress().getState();
        }

        if (StringUtils.equals(field, "STATE-CODE")) {
            if (StringUtils.isNotBlank(person.getFirstAddress().getState())) {
                value = person.getFirstAddress().getState();
            }
            if (StringUtils.isNotBlank(person.getFirstAddress().getStateAbbreviation())) {
                value = person.getFirstAddress().getStateAbbreviation();
            }
        }

        if (field.compareTo("Country") == 0) {
            value = person.getFirstAddress().getCountry();
        }

        if (StringUtils.equals(field, "DOMICILE-CODE")) {
            value = person.getFirstAddress().getCountryAbbreviation();
        }

        if (StringUtils.equals(field, "Postcode") || StringUtils.equals(field, "POST-CODE")) {
            value = person.getFirstAddress().getPostCode();
        }

        if (field.compareTo("Formatted Address") == 0) {
            value = OutputFormatter.toAddress(person.getFirstAddress(), preferences);
        }

        if (field.compareTo("Address (mail merge)") == 0) {
            value = OutputFormatter.toAddress(person.getFirstAddress(), preferences);
        }

        if (field.compareTo("Street Address (mail merge)") == 0) {
            value = OutputFormatter.toStreetAddress(person.getFirstAddress(), preferences);
        }

        if (StringUtils.equals(field, "ADDR-LINE-1")) {
            if (displayAddressField(person.getFirstAddress(), 0)) {
                value = person.getFirstAddress().getAddressField(0);
            }
        }

        if (StringUtils.equals(field, "ADDR-LINE-2")) {
            if (displayAddressField(person.getFirstAddress(), 1)) {
                value = person.getFirstAddress().getAddressField(1);
            }
        }

        if (StringUtils.equals(field, "ADDR-LINE-3")) {
            if (displayAddressField(person.getFirstAddress(), 2)) {
                value = person.getFirstAddress().getAddressField(2);
            }
        }

        if (StringUtils.equals(field, "ADDR-LINE-4")) {
            if (displayAddressField(person.getFirstAddress(), 3)) {
                value = person.getFirstAddress().getAddressField(3);
            }
        }

        if (StringUtils.equals(field, "SUBURB")) {
            value = PersonFormatter.getCityValue(person.getFirstAddress());
        }

        if (StringUtils.equals(field, "RETURN-MAIL")) {
            value = "N";
            if (person.getFirstAddress().getReturnedMail() || person.getFirstAddress().getRequestNoMail()) {
                value = "Y";
            }
        }

        if (StringUtils.equals(field, "NO-MAIL-FLAG")) {
            value = "N";
            if (person.getFirstAddress().getRequestNoMail()) {
                value = "Y";
            }
        }
    }

    if (field.compareTo("Created By") == 0) {
        value = person.getCreatedBy();
    }

    if (field.compareTo("Date Created") == 0 && person.getCreatedDate() != null) {
        value = Formatter.conventionalDate(person.getCreatedDate());
    }

    if (field.compareTo("Modified By") == 0) {
        value = person.getModifiedBy();
    }

    if (field.compareTo("Date Modified") == 0 && person.getModifiedDate() != null) {
        value = Formatter.conventionalDate(person.getModifiedDate());
    }

    if (value == null) {
        value = "";
    }
    return value.trim();
}

From source file:com.edgenius.wiki.render.filter.LinkFilter.java

/**
 * Accept <a> or <object file="*"> tags
 *///from   w  w w .j ava  2s  .co  m
@Override
protected void replaceHTML(HTMLNode node, ListIterator<HTMLNode> nodeIter, RenderContext context) {
    if (node.getPair() == null || node.getAttributes() == null) {
        AuditLogger.error("Unexpected case: Unable to find close </a> tag");
        return;
    }
    Map<String, String> atts = node.getAttributes();
    if (atts.get(NameConstants.AID) != null
            //this is special checking for Safari browser, it remove all other attributes if it has "name" attribute.
            || (atts.size() == 1 && atts.containsKey(NameConstants.NAME))) {
        //default link filter won't have "aid" - it should be anchor
        return;
    }

    StringBuffer viewSb = new StringBuffer();

    //whatever internal(wajax) or external link, view always parse out from  tag surrounded text
    HTMLNode cursor = node;
    boolean hasStyleNode = false;
    for (; nodeIter.hasNext() && cursor != node.getPair(); cursor = nodeIter.next()) {
        if (cursor.isTextNode()) {
            viewSb.append(cursor.getText());
        } else {
            hasStyleNode = true;
        }
    }

    LinkModel link = new LinkModel();
    if ("object".equals(node.getTagName())) {
        //pattern ensure it must has "data" attribute
        String fileURL = node.getAttributes().get("data");

        //must root file i.e., file:///myfile.txt
        if (!StringUtils.startsWith(fileURL, "file:///")) {
            log.warn("Object type link has invalid URL {}", fileURL);
            return;
        }
        fileURL = fileURL.substring(8);
        //if it has "/" means it is possible file:///c:/document/myfile.txt format, ignore it 
        if (StringUtils.isBlank(fileURL) || fileURL.indexOf("/") != -1) {
            log.warn("Object type link is not root file {}", fileURL);
            return;
        }

        link.setLink(fileURL);
        link.setView(viewSb.toString());
        link.setType(LinkModel.LINK_TO_ATTACHMENT);
    } else {
        link.fillToObject(node.getText(), viewSb.toString());
        if (LinkUtil.isAttachmentLink(link.getLink())) {
            link.setType(LinkModel.LINK_TO_ATTACHMENT);
            link.setLink(StringEscapeUtils.unescapeHtml(LinkUtil.getAttachmentFile(link.getLink())));
        }
    }

    //as link may contain some style mark up, such as [th%%*is is b*%%old>view], so here won't process view
    //but only if view==link and view is only TextNode, I will reset view TextNode at this case
    node.reset("[", true);

    //this endMarkup only include the part after "view", such as ">link@space]". The part before that "[view" is handled above
    StringBuffer endMarkup = new StringBuffer();
    //only the link is not equals view, [view>link] needs display "view" part
    String escapedLink = EscapeUtil.escapeMarkupLink(link.getLink());
    if (!hasStyleNode || !StringUtils.equals(link.getView(), escapedLink)) {
        endMarkup.append(">");
    } else {
        //clean embedded text of link, as view == link, don't need display
        cursor = node.next();
        for (; cursor != null && cursor != node.getPair(); cursor = cursor.next()) {
            cursor.reset("", true);
        }
    }
    if (!StringUtils.isBlank(link.getLink())) {
        if (link.getType() == LinkModel.LINK_TO_ATTACHMENT) {
            endMarkup.append("^");
        }
        endMarkup.append(escapedLink);
    }
    if (!StringUtils.isBlank(link.getAnchor())) {
        endMarkup.append("#").append(link.getAnchor());
    }
    //only different space, append spaceUname to link
    if (!StringUtils.isBlank(link.getSpaceUname())
            && !StringUtils.equalsIgnoreCase(link.getSpaceUname(), context.getSpaceUname())) {
        endMarkup.append("@").append(link.getSpaceUname());
    }
    endMarkup.append("]");

    node.getPair().reset(endMarkup.toString(), true);

}