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

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

Introduction

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

Prototype

public static int countMatches(String str, String sub) 

Source Link

Document

Counts how many times the substring appears in the larger String.

Usage

From source file:org.kuali.ole.fp.batch.service.impl.ProcurementCardCreateDocumentServiceImpl.java

/**
 * Creates a ProcurementCardDocument from the List of transactions given.
 *
 * @param transactions List of ProcurementCardTransaction objects to be used for creating the document.
 * @return A ProcurementCardDocument populated with the transactions provided.
 *//*from   w  ww . j  a va  2 s. co  m*/
protected ProcurementCardDocument createProcurementCardDocument(List transactions) {
    ProcurementCardDocument pcardDocument = null;

    try {
        // get new document from doc service
        pcardDocument = (ProcurementCardDocument) SpringContext.getBean(DocumentService.class)
                .getNewDocument(PROCUREMENT_CARD);

        List<CapitalAssetInformation> capitalAssets = pcardDocument.getCapitalAssetInformation();
        for (CapitalAssetInformation capitalAsset : capitalAssets) {
            if (ObjectUtils.isNotNull(capitalAsset)
                    && ObjectUtils.isNotNull(capitalAsset.getCapitalAssetInformationDetails())) {
                capitalAsset.setDocumentNumber(pcardDocument.getDocumentNumber());
            }
        }

        ProcurementCardTransaction trans = (ProcurementCardTransaction) transactions.get(0);
        String errors = validateTransaction(trans);
        createCardHolderRecord(pcardDocument, trans);

        // for each transaction, create transaction detail object and then acct lines for the detail
        int transactionLineNumber = 1;
        KualiDecimal documentTotalAmount = KualiDecimal.ZERO;
        String errorText = "";
        for (Iterator iter = transactions.iterator(); iter.hasNext();) {
            ProcurementCardTransaction transaction = (ProcurementCardTransaction) iter.next();

            // create transaction detail record with accounting lines
            errorText += createTransactionDetailRecord(pcardDocument, transaction, transactionLineNumber);

            // update document total
            documentTotalAmount = documentTotalAmount.add(transaction.getFinancialDocumentTotalAmount());

            transactionLineNumber++;
        }

        pcardDocument.getFinancialSystemDocumentHeader().setFinancialDocumentTotalAmount(documentTotalAmount);
        pcardDocument.getDocumentHeader().setDocumentDescription("SYSTEM Generated");

        // Remove duplicate messages from errorText
        String messages[] = StringUtils.split(errorText, ".");
        for (int i = 0; i < messages.length; i++) {
            int countMatches = StringUtils.countMatches(errorText, messages[i]) - 1;
            errorText = StringUtils.replace(errorText, messages[i] + ".", "", countMatches);
        }
        // In case errorText is still too long, truncate it and indicate so.
        Integer documentExplanationMaxLength = dataDictionaryService
                .getAttributeMaxLength(DocumentHeader.class.getName(), OLEPropertyConstants.EXPLANATION);
        if (documentExplanationMaxLength != null
                && errorText.length() > documentExplanationMaxLength.intValue()) {
            String truncatedMessage = " ... TRUNCATED.";
            errorText = errorText.substring(0, documentExplanationMaxLength - truncatedMessage.length())
                    + truncatedMessage;
        }
        pcardDocument.getDocumentHeader().setExplanation(errorText);
    } catch (WorkflowException e) {
        LOG.error("Error creating pcdo documents: " + e.getMessage(), e);
        throw new RuntimeException("Error creating pcdo documents: " + e.getMessage(), e);
    }

    return pcardDocument;
}

From source file:org.kuali.rice.krad.demo.uif.components.ComponentLibraryView.java

/**
 * Translates the source by removing chracters that the dom will misinterpret as html and to ensure
 * source spacing is correct//from w ww  . j  a  v  a2 s . c o m
 *
 * @param source the original source
 * @return that translated source used in the SyntaxHighlighter of the exhibit
 */
private String translateSource(String source) {
    //convert characters to ascii equivalent
    source = source.replace("<", "&lt;");
    source = source.replace(">", "&gt;");
    source = source.replaceAll("[ \\t]", "&#32;");

    Pattern linePattern = Pattern.compile("((&#32;)*).*?(\\n)+");
    Matcher matcher = linePattern.matcher(source);
    int toRemove = -1;

    //find the line with the least amount of spaces
    while (matcher.find()) {
        String spaces = matcher.group(1);

        int count = StringUtils.countMatches(spaces, "&#32;");
        if (toRemove == -1 || count < toRemove) {
            toRemove = count;
        }
    }

    matcher.reset();
    String newSource = "";

    //remove the min number of spaces from each line to get them to align left properly in the viewer
    while (matcher.find()) {
        String line = matcher.group();
        newSource = newSource + line.replaceFirst("(&#32;){" + toRemove + "}", "");
    }

    //remove very last newline
    newSource = newSource.replaceAll("\\n$", "");
    //replace remaining newlines with ascii equivalent
    newSource = newSource.replace("\n", "&#010;");

    return newSource;
}

From source file:org.kuali.rice.krad.uif.service.impl.ExpressionEvaluatorServiceImpl.java

/**
 * Retrieves the Map from the given object that containing the property expressions that should
 * be evaluated. Each expression is then evaluated and the result is used to set the property value
 *
 * <p>//w w  w .j  a  va  2  s . co m
 * If the expression is an el template (part static text and part expression), only the expression
 * part will be replaced with the result. More than one expressions may be contained within the template
 * </p>
 *
 * @param object - object instance to evaluate expressions for
 * @param contextObject - object providing the default context for expressions
 * @param evaluationParameters - map of additional parameters that may be used within the expressions
 */
protected void evaluatePropertyExpressions(Object object, Object contextObject,
        Map<String, Object> evaluationParameters) {
    Map<String, String> propertyExpressions = new HashMap<String, String>();
    if (Configurable.class.isAssignableFrom(object.getClass())) {
        propertyExpressions = ((Configurable) object).getPropertyExpressions();
    }

    for (Entry<String, String> propertyExpression : propertyExpressions.entrySet()) {
        String propertyName = propertyExpression.getKey();
        String expression = propertyExpression.getValue();

        // check whether expression should be evaluated or property should retain the expression
        if (CloneUtils.fieldHasAnnotation(object.getClass(), propertyName, KeepExpression.class)) {
            // set expression as property value to be handled by the component
            ObjectPropertyUtils.setPropertyValue(object, propertyName, expression);
            continue;
        }

        Object propertyValue = null;

        // determine whether the expression is a string template, or evaluates to another object type
        if (StringUtils.startsWith(expression, UifConstants.EL_PLACEHOLDER_PREFIX)
                && StringUtils.endsWith(expression, UifConstants.EL_PLACEHOLDER_SUFFIX)
                && (StringUtils.countMatches(expression, UifConstants.EL_PLACEHOLDER_PREFIX) == 1)) {
            propertyValue = evaluateExpression(contextObject, evaluationParameters, expression);
        } else {
            // treat as string template
            propertyValue = evaluateExpressionTemplate(contextObject, evaluationParameters, expression);
        }

        ObjectPropertyUtils.setPropertyValue(object, propertyName, propertyValue);
    }
}

From source file:org.kuali.rice.krad.uif.view.DefaultExpressionEvaluator.java

/**
 * {@inheritDoc}/*w  w w  . j  a  v  a  2s.c om*/
 */
@Override
public void evaluatePropertyExpression(View view, Map<String, Object> evaluationParameters,
        UifDictionaryBean expressionConfigurable, String propertyName, boolean removeExpression) {

    Map<String, String> propertyExpressions = expressionConfigurable.getPropertyExpressions();
    if ((propertyExpressions == null) || !propertyExpressions.containsKey(propertyName)) {
        return;
    }

    String expression = propertyExpressions.get(propertyName);

    // check whether expression should be evaluated or property should retain the expression
    if (CopyUtils.fieldHasAnnotation(expressionConfigurable.getClass(), propertyName, KeepExpression.class)) {
        // set expression as property value to be handled by the component
        ObjectPropertyUtils.setPropertyValue(expressionConfigurable, propertyName, expression);
        return;
    }

    Object propertyValue = null;

    // replace binding prefixes (lp, dp, fp) in expression before evaluation
    String adjustedExpression = replaceBindingPrefixes(view, expressionConfigurable, expression);

    // determine whether the expression is a string template, or evaluates to another object type
    if (StringUtils.startsWith(adjustedExpression, UifConstants.EL_PLACEHOLDER_PREFIX)
            && StringUtils.endsWith(adjustedExpression, UifConstants.EL_PLACEHOLDER_SUFFIX)
            && (StringUtils.countMatches(adjustedExpression, UifConstants.EL_PLACEHOLDER_PREFIX) == 1)) {
        propertyValue = evaluateExpression(evaluationParameters, adjustedExpression);
    } else {
        // treat as string template
        propertyValue = evaluateExpressionTemplate(evaluationParameters, adjustedExpression);
    }

    // if property name has the special indicator then we need to add the expression result to the property
    // value instead of replace
    if (StringUtils.endsWith(propertyName, ExpressionEvaluator.EMBEDDED_PROPERTY_NAME_ADD_INDICATOR)) {
        StringUtils.removeEnd(propertyName, ExpressionEvaluator.EMBEDDED_PROPERTY_NAME_ADD_INDICATOR);

        Collection collectionValue = ObjectPropertyUtils.getPropertyValue(expressionConfigurable, propertyName);
        if (collectionValue == null) {
            throw new RuntimeException("Property name: " + propertyName
                    + " with collection type was not initialized. Cannot add expression result");
        }
        collectionValue.add(propertyValue);
    } else {
        ObjectPropertyUtils.setPropertyValue(expressionConfigurable, propertyName, propertyValue);
    }

    if (removeExpression) {
        propertyExpressions.remove(propertyName);
    }
}

From source file:org.kuali.rice.krad.util.UrlFactoryTest.java

/**
 * Test that what is returned from url factory matches the url we expect.
 *//*from  w  w w.  j  a  va  2  s .  c o m*/
@Test
public void testFactoryMatch() throws Exception {
    String basePath = "http://localhost:8080/";
    String actionPath = "kr/lookup.do";
    String testUrl = basePath + actionPath + "?" + KRADConstants.DISPATCH_REQUEST_PARAMETER + "=start" + "&"
            + KRADConstants.DOC_FORM_KEY + "=903" + KRADConstants.LOOKUPABLE_IMPL_ATTRIBUTE_NAME
            + "=accountLookupableImpl" + KRADConstants.RETURN_LOCATION_PARAMETER + "=" + basePath + "ib.do";
    testUrl = UrlFactory.encode(testUrl);

    // construct lookup url
    Properties parameters = new Properties();
    parameters.put(KRADConstants.DISPATCH_REQUEST_PARAMETER, "start");
    parameters.put(KRADConstants.DOC_FORM_KEY, "903");
    parameters.put(KRADConstants.LOOKUPABLE_IMPL_ATTRIBUTE_NAME, "accountLookupableImpl");
    parameters.put(KRADConstants.RETURN_LOCATION_PARAMETER, basePath + "ib.do");

    String returnedUrl = UrlFactory.parameterizeUrl(basePath + actionPath, parameters);

    assertTrue("Returned url is empty", StringUtils.isNotBlank(returnedUrl));
    assertTrue("Returned url has incorrect base", returnedUrl.startsWith(basePath + actionPath + "?"));
    assertTrue("Returned url does not have correct # of &", StringUtils.countMatches(returnedUrl, "&") == 3);
    assertTrue("Returned url missing parameter 1",
            StringUtils.contains(returnedUrl, KRADConstants.DISPATCH_REQUEST_PARAMETER + "=start"));
    assertTrue("Returned url missing parameter 2",
            StringUtils.contains(returnedUrl, KRADConstants.DOC_FORM_KEY + "=903"));
    assertTrue("Returned url missing parameter 3", StringUtils.contains(returnedUrl,
            KRADConstants.LOOKUPABLE_IMPL_ATTRIBUTE_NAME + "=accountLookupableImpl"));
    // assertTrue("Returned url missing parameter 4",StringUtils.contains(returnedUrl,
    // UrlFactory.encode(KRADConstants.RETURN_LOCATION_PARAMETER + "=" + basePath + "ib.do")));
}

From source file:org.languagetool.tools.RuleAsXmlSerializerTest.java

@Test
public void testLanguageAttributes() throws IOException {
    final String xml1 = SERIALIZER.ruleMatchesToXml(Collections.<RuleMatch>emptyList(), "Fake", 5, NORMAL_XML,
            LANG, Collections.<String>emptyList());
    assertTrue(xml1.contains("shortname=\"xx-XX\""));
    assertTrue(xml1.contains("name=\"Testlanguage\""));
    final String xml2 = SERIALIZER.ruleMatchesToXml(Collections.<RuleMatch>emptyList(), "Fake", 5, LANG,
            new FakeLanguage());
    assertTrue(xml2.contains("shortname=\"xx-XX\""));
    assertTrue(xml2.contains("name=\"Testlanguage\""));
    assertTrue(xml2.contains("shortname=\"yy\""));
    assertTrue(xml2.contains("name=\"FakeLanguage\""));
    assertThat(StringUtils.countMatches(xml2, "<matches"), is(1));
    assertThat(StringUtils.countMatches(xml2, "</matches>"), is(1));
}

From source file:org.languagetool.tools.RuleAsXmlSerializerTest.java

@Test
public void testApiModes() throws IOException {
    String xmlStart = SERIALIZER.ruleMatchesToXml(Collections.<RuleMatch>emptyList(), "Fake", 5, START_XML,
            LANG, Collections.<String>emptyList());
    assertThat(StringUtils.countMatches(xmlStart, "<matches"), is(1));
    assertThat(StringUtils.countMatches(xmlStart, "</matches>"), is(0));
    String xmlMiddle = SERIALIZER.ruleMatchesToXml(Collections.<RuleMatch>emptyList(), "Fake", 5, CONTINUE_XML,
            LANG, Collections.<String>emptyList());
    assertThat(StringUtils.countMatches(xmlMiddle, "<matches"), is(0));
    assertThat(StringUtils.countMatches(xmlMiddle, "</matches>"), is(0));
    String xmlEnd = SERIALIZER.ruleMatchesToXml(Collections.<RuleMatch>emptyList(), "Fake", 5, END_XML, LANG,
            Collections.<String>emptyList());
    assertThat(StringUtils.countMatches(xmlEnd, "<matches"), is(0));
    assertThat(StringUtils.countMatches(xmlEnd, "</matches>"), is(1));
    String xml = SERIALIZER.ruleMatchesToXml(Collections.<RuleMatch>emptyList(), "Fake", 5, NORMAL_XML, LANG,
            Collections.<String>emptyList());
    assertThat(StringUtils.countMatches(xml, "<matches"), is(1));
    assertThat(StringUtils.countMatches(xml, "</matches>"), is(1));
}

From source file:org.medici.bia.common.search.AdvancedSearchDocument.java

/**
 * {@inheritDoc}/*from  w ww .  j  av  a  2 s  .  co  m*/
 */
@Override
public void initFromAdvancedSearchCommand(AdvancedSearchCommand command) {
    //Words
    if ((command.getWord() != null) && (command.getWord().size() > 0)) {
        wordsTypes = new ArrayList<WordType>(command.getWord().size());
        words = new ArrayList<String>(command.getWord().size());

        for (String singleWord : command.getWord()) {
            //MD: This is for refine search when the URLencoder change the space in "+"
            singleWord = singleWord.replace("+", "%20");
            singleWord = singleWord.replace("\"", "%22");
            singleWord = singleWord.replace("'", "%27");
            //RR: And this is for replacing special characters with unicode values
            singleWord = URLTransformer.decode(singleWord);
            StringTokenizer stringTokenizer = new StringTokenizer(singleWord, "|");
            try {
                if (stringTokenizer.countTokens() == 2) {
                    wordsTypes.add(WordType.valueOf(stringTokenizer.nextToken()));
                    StringBuffer tempString = new StringBuffer(
                            URIUtil.decode(stringTokenizer.nextToken(), "UTF-8"));
                    if (StringUtils.countMatches(tempString.toString(), "\"") % 2 != 0) {
                        tempString.setCharAt(tempString.lastIndexOf("\""), ' ');
                    }
                    words.add(tempString.toString());

                } else {
                    continue;
                }
            } catch (URIException uriException) {
                logger.debug(uriException);
                wordsTypes.remove(wordsTypes.size() - 1);
            }
        }
    } else {
        wordsTypes = new ArrayList<WordType>(0);
        words = new ArrayList<String>(0);
    }

    // Person
    if ((command.getPerson() != null) && (command.getPerson().size() > 0)) {
        personId = new ArrayList<Integer>(command.getPerson().size());
        person = new ArrayList<String>(command.getPerson().size());

        for (String singleWord : command.getPerson()) {
            //MD: This is for refine search when the URLencoder change the space in "+"
            singleWord = singleWord.replace("+", "%20");
            //RR: And this is for replacing special characters with unicode values
            singleWord = URLTransformer.decode(singleWord);

            StringTokenizer stringTokenizer = new StringTokenizer(singleWord, "|");
            try {
                if (stringTokenizer.countTokens() == 0) {
                    continue;
                } else if (stringTokenizer.countTokens() == 1) {
                    // string format is |text
                    personId.add(new Integer(0));
                    try {
                        person.add(URIUtil.decode(stringTokenizer.nextToken(), "UTF-8"));
                    } catch (URIException uriException) {
                        logger.debug(uriException);
                    }
                } else if (stringTokenizer.countTokens() == 2) {
                    // string format is number|text

                    String singleId = stringTokenizer.nextToken();
                    String singleText = stringTokenizer.nextToken();
                    // Check if field is correct
                    if (NumberUtils.isNumber(singleId)) {
                        personId.add(NumberUtils.createInteger(singleId));
                    } else {
                        //Empty personId is equal to 0
                        personId.add(new Integer(0));
                    }
                    try {
                        person.add(URIUtil.decode(singleText, "UTF-8"));
                    } catch (URIException uriException) {
                        logger.debug(uriException);
                        personId.remove(personId.size() - 1);
                    }
                }
            } catch (NumberFormatException nex) {
                logger.error(nex);
            }
        }
    } else {
        personId = new ArrayList<Integer>(0);
        person = new ArrayList<String>(0);
    }

    // Place
    if ((command.getPlace() != null) && (command.getPlace().size() > 0)) {
        placeId = new ArrayList<Integer>(command.getPlace().size());
        place = new ArrayList<String>(command.getPlace().size());

        for (String singleWord : command.getPlace()) {
            //MD: This is for refine search when the URLencoder change the space in "+"
            singleWord = singleWord.replace("+", "%20");
            //RR: And this is for replacing special characters with unicode values
            singleWord = URLTransformer.decode(singleWord);

            StringTokenizer stringTokenizer = new StringTokenizer(singleWord, "|");
            try {
                if (stringTokenizer.countTokens() == 0) {
                    continue;
                } else if (stringTokenizer.countTokens() == 1) {
                    // string format is |text
                    placeId.add(new Integer(0));
                    place.add(URIUtil.decode(stringTokenizer.nextToken(), "UTF-8"));
                } else if (stringTokenizer.countTokens() == 2) {
                    // string format is number|text
                    String singleId = stringTokenizer.nextToken();
                    String singleText = stringTokenizer.nextToken();
                    // Check if field is correct
                    if (NumberUtils.isNumber(singleId)) {
                        placeId.add(NumberUtils.createInteger(singleId));
                    } else {
                        //Empty placeId is equal to 0
                        placeId.add(new Integer(0));
                    }
                    place.add(URIUtil.decode(singleText, "UTF-8"));
                }
            } catch (NumberFormatException nex) {
                logger.debug(nex);
            } catch (URIException uriException) {
                logger.debug(uriException);
                placeId.remove(placeId.size() - 1);
            }
        }
    } else {
        placeId = new ArrayList<Integer>(0);
        place = new ArrayList<String>(0);
    }

    // Sender
    if ((command.getSender() != null) && (command.getSender().size() > 0)) {
        senderId = new ArrayList<Integer>(command.getSender().size());
        sender = new ArrayList<String>(command.getSender().size());

        for (String singleWord : command.getSender()) {
            StringTokenizer stringTokenizer = new StringTokenizer(singleWord, "|");
            try {
                if (stringTokenizer.countTokens() == 0) {
                    continue;
                } else if (stringTokenizer.countTokens() == 1) {
                    // string format is |text
                    senderId.add(new Integer(0));
                    sender.add(URIUtil.decode(stringTokenizer.nextToken(), "UTF-8"));
                } else if (stringTokenizer.countTokens() == 2) {
                    // string format is number|text
                    String singleId = stringTokenizer.nextToken();
                    String singleText = stringTokenizer.nextToken();
                    // Check if field is correct
                    if (NumberUtils.isNumber(singleId)) {
                        senderId.add(NumberUtils.createInteger(singleId));
                    } else {
                        //Empty senderId is equal to 0
                        senderId.add(new Integer(0));
                    }
                    sender.add(URIUtil.decode(singleText, "UTF-8"));
                }
            } catch (NumberFormatException nex) {
                logger.debug(nex);
            } catch (URIException uriException) {
                logger.debug(uriException);
                senderId.remove(senderId.size() - 1);
            }
        }
    } else {
        senderId = new ArrayList<Integer>(0);
        sender = new ArrayList<String>(0);
    }

    // From
    if ((command.getFrom() != null) && (command.getFrom().size() > 0)) {
        fromId = new ArrayList<Integer>(command.getFrom().size());
        from = new ArrayList<String>(command.getFrom().size());

        for (String singleWord : command.getFrom()) {
            //MD: This is for refine search when the URLencoder change the space in "+"
            singleWord = singleWord.replace("+", "%20");
            //RR: And this is for replacing special characters with unicode values
            singleWord = URLTransformer.decode(singleWord);

            StringTokenizer stringTokenizer = new StringTokenizer(singleWord, "|");
            try {
                if (stringTokenizer.countTokens() == 0) {
                    continue;
                } else if (stringTokenizer.countTokens() == 1) {
                    // string format is |text
                    fromId.add(new Integer(0));
                    from.add(stringTokenizer.nextToken());
                } else if (stringTokenizer.countTokens() == 2) {
                    // string format is number|text
                    String singleId = stringTokenizer.nextToken();
                    String singleText = stringTokenizer.nextToken();
                    // Check if field is correct
                    if (NumberUtils.isNumber(singleId)) {
                        fromId.add(NumberUtils.createInteger(singleId));
                    } else {
                        //Empty fromId is equal to 0
                        fromId.add(new Integer(0));
                    }
                    from.add(URIUtil.decode(singleText, "UTF-8"));
                }
            } catch (NumberFormatException numberFormatException) {
                logger.debug(numberFormatException);
            } catch (URIException uriException) {
                logger.debug(uriException);
                fromId.remove(fromId.size() - 1);
            }
        }
    } else {
        fromId = new ArrayList<Integer>(0);
        from = new ArrayList<String>(0);
    }

    // Recipient
    if ((command.getRecipient() != null) && (command.getRecipient().size() > 0)) {
        recipientId = new ArrayList<Integer>(command.getRecipient().size());
        recipient = new ArrayList<String>(command.getRecipient().size());

        for (String singleWord : command.getRecipient()) {
            StringTokenizer stringTokenizer = new StringTokenizer(singleWord, "|");
            try {
                if (stringTokenizer.countTokens() == 0) {
                    continue;
                } else if (stringTokenizer.countTokens() == 1) {
                    // string format is |text
                    recipientId.add(new Integer(0));
                    recipient.add(URIUtil.decode(stringTokenizer.nextToken(), "UTF-8"));
                } else if (stringTokenizer.countTokens() == 2) {
                    // string format is number|text
                    String singleId = stringTokenizer.nextToken();
                    String singleText = stringTokenizer.nextToken();
                    // Check if field is correct
                    if (NumberUtils.isNumber(singleId)) {
                        recipientId.add(NumberUtils.createInteger(singleId));
                    } else {
                        //Empty recipientId is equal to 0
                        recipientId.add(new Integer(0));
                    }
                    recipient.add(URIUtil.decode(singleText, "UTF-8"));
                }
            } catch (NumberFormatException numberFormatException) {
                logger.debug(numberFormatException);
            } catch (URIException uriException) {
                logger.debug(uriException);
                recipientId.remove(recipientId.size() - 1);
            }
        }
    } else {
        recipientId = new ArrayList<Integer>(0);
        recipient = new ArrayList<String>(0);
    }

    // To
    if ((command.getTo() != null) && (command.getTo().size() > 0)) {
        toId = new ArrayList<Integer>(command.getTo().size());
        to = new ArrayList<String>(command.getTo().size());

        for (String singleWord : command.getTo()) {
            //MD: This is for refine search when the URLencoder change the space in "+"
            singleWord = singleWord.replace("+", "%20");
            //RR: And this is for replacing special characters with unicode values
            singleWord = URLTransformer.decode(singleWord);

            StringTokenizer stringTokenizer = new StringTokenizer(singleWord, "|");
            try {
                if (stringTokenizer.countTokens() == 0) {
                    continue;
                } else if (stringTokenizer.countTokens() == 1) {
                    // string format is |text
                    toId.add(new Integer(0));
                    to.add(URIUtil.decode(stringTokenizer.nextToken(), "UTF-8"));
                } else if (stringTokenizer.countTokens() == 2) {
                    // string format is number|text
                    String singleId = stringTokenizer.nextToken();
                    String singleText = stringTokenizer.nextToken();
                    // Check if field is correct
                    if (NumberUtils.isNumber(singleId)) {
                        toId.add(NumberUtils.createInteger(singleId));
                    } else {
                        //Empty toId is equal to 0
                        toId.add(new Integer(0));
                    }
                    to.add(URIUtil.decode(singleText, "UTF-8"));
                }
            } catch (NumberFormatException numberFormatException) {
                logger.debug(numberFormatException);
            } catch (URIException uriException) {
                logger.debug(uriException);
                toId.remove(toId.size() - 1);
            }
        }
    } else {
        toId = new ArrayList<Integer>(0);
        to = new ArrayList<String>(0);
    }

    // ResTo;
    if ((command.getRefersTo() != null) && (command.getRefersTo().size() > 0)) {
        refersToId = new ArrayList<Integer>(command.getRefersTo().size());
        refersTo = new ArrayList<String>(command.getRefersTo().size());

        for (String singleWord : command.getRefersTo()) {
            StringTokenizer stringTokenizer = new StringTokenizer(singleWord, "|");
            // string format is number|text
            try {
                if (stringTokenizer.countTokens() == 0) {
                    continue;
                } else if (stringTokenizer.countTokens() == 1) {
                    // string format is |text
                    refersToId.add(new Integer(0));
                    refersTo.add(stringTokenizer.nextToken());
                } else if (stringTokenizer.countTokens() == 2) {
                    String singleId = stringTokenizer.nextToken();
                    String singleText = stringTokenizer.nextToken();
                    // Check if field is correct
                    if (NumberUtils.isNumber(singleId)) {
                        refersToId.add(NumberUtils.createInteger(singleId));
                    } else {
                        //Empty refersToId is equal to 0
                        refersToId.add(new Integer(0));
                    }
                    refersTo.add(URIUtil.decode(singleText, "UTF-8"));
                }
            } catch (NumberFormatException numberFormatException) {
                logger.debug(numberFormatException);
            } catch (URIException uriException) {
                logger.debug(uriException);
                refersToId.remove(refersToId.size() - 1);
            }
        }
    } else {
        refersToId = new ArrayList<Integer>(0);
        refersTo = new ArrayList<String>(0);
    }

    // Extract
    if ((command.getExtract() != null) && (command.getExtract().size() > 0)) {
        extract = new ArrayList<String>(command.getExtract().size());

        for (String singleWord : command.getExtract()) {
            //MD: This is for refine search when the URLencoder change the space in "+"
            singleWord = singleWord.replace("+", "%20");
            singleWord = singleWord.replace("\"", "%22");
            singleWord = singleWord.replace("'", "%27");
            //RR: And this is for replacing special characters with unicode values
            singleWord = URLTransformer.decode(singleWord);
            try {
                extract.add(URIUtil.decode(singleWord, "UTF-8"));
            } catch (NumberFormatException numberFormatException) {
                logger.debug(numberFormatException);
            } catch (URIException uriException) {
                logger.debug(uriException);
            }
        }
    } else {
        extract = new ArrayList<String>(0);
    }

    // Synopsis
    if ((command.getSynopsis() != null) && (command.getSynopsis().size() > 0)) {
        synopsis = new ArrayList<String>(command.getSynopsis().size());

        for (String singleWord : command.getSynopsis()) {
            singleWord = singleWord.replace("+", "%20");
            singleWord = singleWord.replace("\"", "%22");
            singleWord = singleWord.replace("'", "%27");
            singleWord = URLTransformer.decode(singleWord);
            try {
                synopsis.add(URIUtil.decode(singleWord, "UTF-8"));
            } catch (NumberFormatException numberFormatException) {
                logger.debug(numberFormatException);
            } catch (URIException uriException) {
                logger.debug(uriException);
            }
        }
    } else {
        synopsis = new ArrayList<String>(0);
    }

    // Topics
    if ((command.getTopic() != null) && (command.getTopic().size() > 0)) {
        topicsId = new ArrayList<Integer>(command.getTopic().size());
        topics = new ArrayList<String>(command.getTopic().size());
        topicsPlaceId = new ArrayList<Integer>(command.getTopic().size());
        topicsPlace = new ArrayList<String>(command.getTopic().size());

        for (String singleWord : command.getTopic()) {
            singleWord = singleWord.replace("+", "%20");

            StringTokenizer stringTokenizer = new StringTokenizer(singleWord, "|");
            try {
                if (stringTokenizer.countTokens() == 0) {
                    continue;
                } else if (stringTokenizer.countTokens() == 1) {
                    // string format is number
                    String topicId = stringTokenizer.nextToken();
                    if (NumberUtils.isNumber(topicId)) {
                        topicsId.add(NumberUtils.createInteger(topicId));
                    } else {
                        //Empty topicsId is equal to 0
                        topicsId.add(new Integer(0));
                    }
                    //                  topics.add(URIUtil.decode(stringTokenizer.nextToken(), "UTF-8"));
                } else if (stringTokenizer.countTokens() == 2) {
                    // string format is number|text
                    String topicId = stringTokenizer.nextToken();
                    String topicText = stringTokenizer.nextToken();
                    // Check if field is correct
                    if (NumberUtils.isNumber(topicId)) {
                        topicsId.add(NumberUtils.createInteger(topicId));
                    } else {
                        //Empty topicsId is equal to 0
                        topicsId.add(new Integer(0));
                    }
                    topics.add(URIUtil.decode(topicText, "UTF-8"));
                } else if (stringTokenizer.countTokens() == 3) {
                    //string format is number|text|number
                    String singleId = stringTokenizer.nextToken();
                    String topicText = stringTokenizer.nextToken();
                    String placeId = stringTokenizer.nextToken();

                    if (NumberUtils.isNumber(singleId)) {
                        topicsId.add(NumberUtils.createInteger(singleId));
                    } else {
                        topicsId.add(new Integer(0));
                    }
                    topics.add(URIUtil.decode(topicText, "UTF-8"));
                    if (NumberUtils.isNumber(placeId)) {
                        topicsPlaceId.add(NumberUtils.createInteger(placeId));
                    } else {
                        topicsPlaceId.add(new Integer(0));
                    }
                } else if (stringTokenizer.countTokens() == 4) {
                    //string format is number|text|number|text
                    String singleId = stringTokenizer.nextToken();
                    String topicText = stringTokenizer.nextToken();
                    String placeId = stringTokenizer.nextToken();
                    String placeText = stringTokenizer.nextToken();

                    if (NumberUtils.isNumber(singleId)) {
                        topicsId.add(NumberUtils.createInteger(singleId));
                    } else {
                        topicsId.add(new Integer(0));
                    }
                    topics.add(URIUtil.decode(topicText, "UTF-8"));
                    if (NumberUtils.isNumber(placeId)) {
                        topicsPlaceId.add(NumberUtils.createInteger(placeId));
                    } else {
                        topicsPlaceId.add(new Integer(0));
                    }
                    topicsPlace.add(URIUtil.decode(placeText, "UTF-8"));
                }
            } catch (NumberFormatException numberFormatException) {
                logger.debug(numberFormatException);
            } catch (URIException uriException) {
                logger.debug(uriException);
                topicsId.remove(topicsId.size() - 1);
                topicsPlaceId.remove(topicsPlaceId.size() - 1);
            }
        }
    } else {
        topicsId = new ArrayList<Integer>(0);
        topics = new ArrayList<String>(0);
    }

    //Topics Place
    // Place
    //      if ((command.getTopicPlace() != null) && (command.getTopicPlace().size() >0)) {
    //         topicsPlaceId = new ArrayList<Integer>(command.getTopicPlace().size());
    //         topicsPlace = new ArrayList<String>(command.getTopicPlace().size());
    //         
    //         for (String singleWord : command.getTopicPlace()) {
    //            //MD: This is for refine search when the URLencoder change the space in "+" and the special character "\u00E7" in "%E7"
    //            singleWord = singleWord.replace("+", "%20");
    //            singleWord = singleWord.replace("%E7", "\u00E7");
    //            
    //            StringTokenizer stringTokenizer = new StringTokenizer(singleWord, "|");
    //            try {
    //               if (stringTokenizer.countTokens() == 0) {
    //                  continue;
    //               } else if (stringTokenizer.countTokens() == 1) {
    //                  // string format is |text
    //                  topicsPlaceId.add(new Integer(0));
    //                  topicsPlace.add(URIUtil.decode(stringTokenizer.nextToken(), "UTF-8"));
    //               } else if (stringTokenizer.countTokens() == 2) {
    //                  // string format is number|text
    //                  String singleId = stringTokenizer.nextToken();
    //                  String singleText = stringTokenizer.nextToken();
    //                  // Check if field is correct
    //                  if (NumberUtils.isNumber(singleId)) { 
    //                     topicsPlaceId.add(NumberUtils.createInteger(singleId));
    //                  } else {
    //                     //Empty placeId is equal to 0
    //                     topicsPlaceId.add(new Integer(0));
    //                  }
    //                  topicsPlace.add(URIUtil.decode(singleText, "UTF-8"));
    //               }
    //            } catch (NumberFormatException numberFormatException) {
    //               logger.debug(numberFormatException);
    //            } catch (URIException uriException) {
    //               logger.debug(uriException);
    //               topicsPlaceId.remove(topicsPlaceId.size()-1);
    //            }
    //         }
    //      } else {
    //         topicsPlaceId = new ArrayList<Integer>(0);
    //         topicsPlace = new ArrayList<String>(0);
    //      }

    //Date
    if ((command.getDate() != null) && (command.getDate().size() > 0)) {
        datesTypes = new ArrayList<DateType>(command.getDate().size());
        datesYear = new ArrayList<Integer>(command.getDate().size());
        datesMonth = new ArrayList<Integer>(command.getDate().size());
        datesDay = new ArrayList<Integer>(command.getDate().size());
        datesYearBetween = new ArrayList<Integer>(command.getDate().size());
        datesMonthBetween = new ArrayList<Integer>(command.getDate().size());
        datesDayBetween = new ArrayList<Integer>(command.getDate().size());

        for (String singleWord : command.getDate()) {
            //e.g. After|1222|01|12|1223|12|12
            String[] fields = StringUtils.splitPreserveAllTokens(singleWord, "|");
            datesTypes.add(DateType.valueOf(fields[0]));
            datesYear.add(DateUtils.getDateYearFromString(fields[1]));
            datesMonth.add(DateUtils.getDateMonthFromString(fields[2]));
            datesDay.add(DateUtils.getDateDayFromString(fields[3]));
            datesYearBetween.add(DateUtils.getDateYearFromString(fields[4]));
            datesMonthBetween.add(DateUtils.getDateMonthFromString(fields[5]));
            datesDayBetween.add(DateUtils.getDateDayFromString(fields[6]));
        }
    } else {
        datesTypes = new ArrayList<DateType>(0);
        datesYear = new ArrayList<Integer>(0);
        datesMonth = new ArrayList<Integer>(0);
        datesDay = new ArrayList<Integer>(0);
        datesYearBetween = new ArrayList<Integer>(0);
        datesMonthBetween = new ArrayList<Integer>(0);
        datesDayBetween = new ArrayList<Integer>(0);
    }

    //Date Created
    if ((command.getDateCreated() != null) && (command.getDateCreated().size() > 0)) {
        datesCreatedTypes = new ArrayList<DateType>(command.getDateCreated().size());
        datesCreated = new ArrayList<Date>(command.getDateCreated().size());
        datesCreatedBetween = new ArrayList<Date>(command.getDateCreated().size());

        for (String singleWord : command.getDateCreated()) {
            //e.g. After|20120112|20120112
            String[] fields = StringUtils.splitPreserveAllTokens(singleWord, "|");
            datesCreatedTypes.add(DateType.valueOf(fields[0]));
            datesCreated.add(DateUtils.getDateFromString(fields[1]));
            datesCreatedBetween.add(DateUtils.getDateFromString(fields[2]));
        }
    } else {
        datesCreatedTypes = new ArrayList<DateType>(0);
        datesCreated = new ArrayList<Date>(0);
        datesCreatedBetween = new ArrayList<Date>(0);
    }

    //Date lastUpdate
    if ((command.getDateLastUpdate() != null) && (command.getDateLastUpdate().size() > 0)) {
        datesLastUpdateTypes = new ArrayList<DateType>(command.getDateLastUpdate().size());
        datesLastUpdate = new ArrayList<Date>(command.getDateLastUpdate().size());
        datesLastUpdateBetween = new ArrayList<Date>(command.getDateLastUpdate().size());

        for (String singleWord : command.getDateLastUpdate()) {
            //e.g. After|20120112|20120112
            String[] fields = StringUtils.splitPreserveAllTokens(singleWord, "|");
            datesLastUpdateTypes.add(DateType.valueOf(fields[0]));
            datesLastUpdate.add(DateUtils.getDateFromString(fields[1]));
            datesLastUpdateBetween.add(DateUtils.getDateFromString(fields[2]));
        }
    } else {
        datesLastUpdateTypes = new ArrayList<DateType>(0);
        datesLastUpdate = new ArrayList<Date>(0);
        datesLastUpdateBetween = new ArrayList<Date>(0);
    }

    //Volume
    if ((command.getVolume() != null) && (command.getVolume().size() > 0)) {
        volumesTypes = new ArrayList<VolumeType>(command.getVolume().size());
        volumes = new ArrayList<String>(command.getVolume().size());
        volumesBetween = new ArrayList<String>(command.getVolume().size());

        for (String singleWord : command.getVolume()) {
            StringTokenizer stringTokenizer = new StringTokenizer(singleWord, "|");
            if ((stringTokenizer.countTokens() == 0) || (stringTokenizer.countTokens() == 1)) {
                continue;
            } else if (stringTokenizer.countTokens() == 2) {
                // string format is Exactly|12
                volumesTypes.add(VolumeType.valueOf(stringTokenizer.nextToken()));
                volumes.add(stringTokenizer.nextToken());
                volumesBetween.add("0");
            } else if (stringTokenizer.countTokens() == 3) {
                // string format is Exactly|12|16
                volumesTypes.add(VolumeType.valueOf(stringTokenizer.nextToken()));
                volumes.add(stringTokenizer.nextToken());
                volumesBetween.add(stringTokenizer.nextToken());
            }
        }
    } else {
        volumesTypes = new ArrayList<VolumeType>(0);
        volumes = new ArrayList<String>(0);
        volumesBetween = new ArrayList<String>(0);
    }

    // Insert
    if ((command.getInsert() != null && command.getInsert().size() > 0)) {
        insertNums = new ArrayList<String>(command.getInsert().size());

        for (String insert : command.getInsert()) {
            insertNums.add(insert);
        }
    } else {
        insertNums = new ArrayList<String>(0);
    }

    //Folio
    if ((command.getFolio() != null) && (command.getFolio().size() > 0)) {
        foliosTypes = new ArrayList<AdvancedSearchAbstract.FolioType>(command.getFolio().size());
        folios = new ArrayList<String>(command.getFolio().size());
        foliosBetween = new ArrayList<String>(command.getFolio().size());

        for (String singleWord : command.getFolio()) {
            StringTokenizer stringTokenizer = new StringTokenizer(singleWord, "|");
            if ((stringTokenizer.countTokens() == 0) || (stringTokenizer.countTokens() == 1)) {
                continue;
            } else if (stringTokenizer.countTokens() == 2) {
                foliosTypes.add(FolioType.valueOf(stringTokenizer.nextToken()));
                folios.add(stringTokenizer.nextToken());
                foliosBetween.add("0");
            } else if (stringTokenizer.countTokens() == 3) {
                foliosTypes.add(FolioType.valueOf(stringTokenizer.nextToken()));
                folios.add(stringTokenizer.nextToken());
                foliosBetween.add(stringTokenizer.nextToken());
            }
        }
    } else {
        foliosTypes = new ArrayList<AdvancedSearchAbstract.FolioType>(0);
        folios = new ArrayList<String>(0);
        foliosBetween = new ArrayList<String>(0);
    }

    //FolioMod
    if (command.getFolioMod() != null && command.getFolioMod().size() > 0) {
        folioMods = new ArrayList<String>(command.getFolioMod().size());
        folioMods.addAll(command.getFolioMod());
    } else {
        folioMods = new ArrayList<String>(0);
    }

    //EntryId
    if ((command.getDocId() != null) && (command.getDocId().size() > 0)) {
        docIds = new ArrayList<String>(command.getDocId().size());

        for (String singleWord : command.getDocId()) {
            try {
                docIds.add(URIUtil.decode(singleWord, "UTF-8"));
            } catch (NumberFormatException numberFormatException) {
                logger.debug(numberFormatException);
            } catch (URIException uriException) {
                logger.debug(uriException);
            }
        }
    } else {
        docIds = new ArrayList<String>(0);
    }

    //LogicalDelete
    if (command.getLogicalDelete() != null) {
        if (command.getLogicalDelete().equals("true")) {
            logicalDelete = Boolean.TRUE;
        } else {
            logicalDelete = Boolean.FALSE;
        }
    }

    //Users
    if (command.getUser() != null) {
        userActionTypes = new ArrayList<UserActionType>(command.getUser().size());
        users = new ArrayList<String>(command.getUser().size());

        for (String singleUser : command.getUser()) {
            //MD: This is for refine search when the URLencoder change the space in "+"
            singleUser = singleUser.replace("+", "%20");
            singleUser = singleUser.replace("\"", "%22");
            singleUser = singleUser.replace("'", "%27");
            //RR: And this is for replacing special characters with unicode values
            singleUser = URLTransformer.decode(singleUser);
            StringTokenizer stringTokenizer = new StringTokenizer(singleUser, "|");
            try {
                if (stringTokenizer.countTokens() == 2) {
                    userActionTypes.add(UserActionType.valueOf(stringTokenizer.nextToken()));
                    StringBuffer tempString = new StringBuffer(
                            URIUtil.decode(stringTokenizer.nextToken(), "UTF-8"));
                    if (StringUtils.countMatches(tempString.toString(), "\"") % 2 != 0) {
                        tempString.setCharAt(tempString.lastIndexOf("\""), ' ');
                    }
                    users.add(tempString.toString());

                } else {
                    continue;
                }
            } catch (URIException uriException) {
                logger.debug(uriException);
                wordsTypes.remove(wordsTypes.size() - 1);
            }
        }
    } else {
        userActionTypes = new ArrayList<UserActionType>(0);
        users = new ArrayList<String>(0);
    }

}

From source file:org.medici.bia.controller.search.AjaxController.java

/**
 * //  w ww .  j  a v a 2 s  .  c om
 * @param simpleSearchPerimeter
 * @param uuid
 * @param sortingColumnNumber
 * @param sortingDirection
 * @param firstRecord
 * @param length
 * @return
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
@RequestMapping(value = "/src/ExpandResultsAdvancedSearch.json", method = RequestMethod.GET)
public ModelAndView expandResultsAdvancedSearch(HttpSession httpSession,
        @RequestParam(value = "simpleSearchPerimeter") SimpleSearchPerimeter simpleSearchPerimeter,
        @RequestParam(value = "sSearch") String uuid,
        @RequestParam(value = "iSortCol_0", required = false) Integer sortingColumnNumber,
        @RequestParam(value = "sSortDir_0", required = false) String sortingDirection,
        @RequestParam(value = "iDisplayStart") Integer firstRecord,
        @RequestParam(value = "iDisplayLength") Integer length) {
    Map<String, Object> model = new HashMap<String, Object>(0);
    Map<String, SearchFilter> searchFilterMap = (Map<String, SearchFilter>) httpSession
            .getAttribute("searchFilterMap");
    SearchFilter searchFilter = searchFilterMap.get(uuid);

    PaginationFilter paginationFilter = new PaginationFilter(firstRecord, length, sortingColumnNumber,
            sortingDirection, simpleSearchPerimeter);

    Page page = null;

    try {
        page = getSearchService().searchAdvancedDocuments(searchFilter.getFilterData(), paginationFilter);
    } catch (ApplicationThrowable aex) {
        page = new Page(paginationFilter);
    }

    List resultList = new ArrayList();
    for (Document currentDocument : (List<Document>) page.getList()) {
        List singleRow = new ArrayList();
        if (currentDocument.getSenderPeople() != null) {
            if (!currentDocument.getSenderPeople().getMapNameLf()
                    .equals("Person Name Lost, Not Indicated or Unidentifiable"))
                singleRow.add(currentDocument.getSenderPeople().getMapNameLf());
            else
                singleRow.add("Person Name Lost");
        } else
            singleRow.add("");

        if (currentDocument.getRecipientPeople() != null) {
            if (!currentDocument.getRecipientPeople().getMapNameLf()
                    .equals("Person Name Lost, Not Indicated or Unidentifiable"))
                singleRow.add(currentDocument.getRecipientPeople().getMapNameLf());
            else
                singleRow.add("Person Name Lost");
        } else
            singleRow.add("");

        if (currentDocument.getYearModern() != null) {
            singleRow.add(DateUtils.getStringDateHTMLForTable(currentDocument.getYearModern(),
                    currentDocument.getDocMonthNum(), currentDocument.getDocDay()));
        } else {
            singleRow.add(DateUtils.getStringDateHTMLForTable(currentDocument.getDocYear(),
                    currentDocument.getDocMonthNum(), currentDocument.getDocDay()));
        }

        if (currentDocument.getSenderPlace() != null) {
            if (!currentDocument.getSenderPlace().getPlaceName()
                    .equals("Place Name Lost, Not Indicated or Unidentifable"))
                singleRow.add(currentDocument.getSenderPlace().getPlaceName());
            else
                singleRow.add("Place Name Lost");
        } else
            singleRow.add("");

        if (currentDocument.getRecipientPlace() != null) {
            if (!currentDocument.getRecipientPlace().getPlaceName()
                    .equals("Place Name Lost, Not Indicated or Unidentifable"))
                singleRow.add(currentDocument.getRecipientPlace().getPlaceName());
            else
                singleRow.add("Place Name Lost");
        } else
            singleRow.add("");

        String lastColumn = getLastColumn(currentDocument, new StringBuilder());
        singleRow.add(lastColumn);

        AdvancedSearchDocument advancedSearchDocument = (AdvancedSearchDocument) searchFilter.getFilterData();
        StringBuffer yourSearch = new StringBuffer();
        if (simpleSearchPerimeter.equals(SimpleSearchPerimeter.EXTRACT)) {
            if (advancedSearchDocument.getExtract() != null) {
                for (String currentExtract : advancedSearchDocument.getExtract()) {
                    if (StringUtils.countMatches(currentExtract, "\"") % 2 != 0) {
                        StringBuffer tempString = new StringBuffer(currentExtract);
                        tempString.setCharAt(tempString.lastIndexOf("\""), ' ');
                        currentExtract = tempString.toString();
                    }
                    //This code is for highlight the correct words
                    if (currentExtract.contains("\"")) {
                        StringTokenizer stringTokenizer = new StringTokenizer(currentExtract.replace('"', ' '),
                                " ");
                        while (stringTokenizer.hasMoreTokens()) {
                            String currentToken = stringTokenizer.nextToken();
                            if (currentToken.length() > 0 && currentToken != "") {
                                if (yourSearch.toString().length() > 0)
                                    yourSearch.append(" " + currentToken);
                                else
                                    yourSearch.append(currentToken);
                            }
                        }
                    } else {
                        if (yourSearch.toString().length() > 0)
                            yourSearch.append(" " + currentExtract);
                        else
                            yourSearch.append(currentExtract);
                    }

                }
            }
            if (currentDocument.getSynExtract().getDocExtract() != null) {
                if (yourSearch.length() != 0) {
                    String text = DocumentUtils.searchTextResultExpand(
                            currentDocument.getSynExtract().getDocExtract(), yourSearch.toString());
                    singleRow.add(HtmlUtils.highlightText(text, yourSearch.toString()));
                } else {
                    if (currentDocument.getSynExtract().getDocExtract().length() > 200) {
                        String text = currentDocument.getSynExtract().getDocExtract().substring(0, 197);
                        singleRow.add(text.substring(0, text.lastIndexOf(" ")) + " ...");
                    } else {
                        singleRow.add(currentDocument.getSynExtract().getDocExtract());
                    }
                }
            } else
                singleRow.add("");
        } else if (simpleSearchPerimeter.equals(SimpleSearchPerimeter.SYNOPSIS)) {
            if (advancedSearchDocument.getSynopsis() != null) {
                for (String currentSynopsis : advancedSearchDocument.getSynopsis()) {
                    if (StringUtils.countMatches(currentSynopsis, "\"") % 2 != 0) {
                        StringBuffer tempString = new StringBuffer(currentSynopsis);
                        tempString.setCharAt(tempString.lastIndexOf("\""), ' ');
                        currentSynopsis = tempString.toString();
                    }
                    //This code is for highlight the correct words
                    if (currentSynopsis.contains("\"")) {
                        StringTokenizer stringTokenizer = new StringTokenizer(currentSynopsis.replace('"', ' '),
                                " ");
                        while (stringTokenizer.hasMoreTokens()) {
                            String currentToken = stringTokenizer.nextToken();
                            if (currentToken.length() > 0 && currentToken != "") {
                                if (yourSearch.toString().length() > 0)
                                    yourSearch.append(" " + currentToken);
                                else
                                    yourSearch.append(currentToken);
                            }
                        }
                    } else {
                        if (yourSearch.toString().length() > 0)
                            yourSearch.append(" " + currentSynopsis);
                        else
                            yourSearch.append(currentSynopsis);
                    }

                }
            }
            if (currentDocument.getSynExtract().getSynopsis() != null) {
                if (yourSearch.length() != 0) {
                    String text = DocumentUtils.searchTextResultExpand(
                            currentDocument.getSynExtract().getSynopsis(), yourSearch.toString());
                    singleRow.add(HtmlUtils.highlightText(text, yourSearch.toString()));
                } else {
                    if (currentDocument.getSynExtract().getSynopsis().length() > 200) {
                        String text = currentDocument.getSynExtract().getSynopsis().substring(0, 197);
                        singleRow.add(text.substring(0, text.lastIndexOf(" ")) + " ...");
                    } else {
                        singleRow.add(currentDocument.getSynExtract().getSynopsis());
                    }
                }
            } else
                singleRow.add("");
        } else
            singleRow.add("");

        resultList.add(HtmlUtils.showDocumentExpand(singleRow, currentDocument.getEntryId()));
    }

    model.put("iEcho", "1");
    model.put("iTotalDisplayRecords", page.getTotal());
    model.put("iTotalRecords", page.getTotal());
    model.put("aaData", resultList);

    return new ModelAndView("responseOK", model);
}

From source file:org.medici.bia.controller.search.ExpandResultsSimpleSearchController.java

/**
 * This controller act as a dispatcher for result view.
 *  /*from ww w  .j  a va2s. c  om*/
 * @param command
 * @param result
 * @return
 */
@RequestMapping(method = { RequestMethod.GET })
public ModelAndView processSubmit(@ModelAttribute("command") ExpandResultsSimpleSearchCommand command,
        BindingResult result) {
    Map<String, Object> model = new HashMap<String, Object>(0);

    try {
        command.setsSearch(URIUtil.decode(command.getsSearch(), "UTF-8"));
    } catch (URIException e) {
    }
    if (StringUtils.countMatches(command.getsSearch(), "\"") % 2 != 0) {
        StringBuffer tempString = new StringBuffer(command.getsSearch());
        tempString.setCharAt(tempString.lastIndexOf("\""), ' ');
        command.setsSearch(tempString.toString());
    }
    //This code is for highlight the correct words
    StringBuffer yourSearch = new StringBuffer();
    if (command.getsSearch().contains("\"")) {
        StringTokenizer stringTokenizer = new StringTokenizer(command.getsSearch().replace('"', ' '), " ");
        while (stringTokenizer.hasMoreTokens()) {
            String currentToken = stringTokenizer.nextToken();
            if (currentToken.length() > 0 && currentToken != "") {
                if (yourSearch.toString().length() > 0)
                    yourSearch.append(" " + currentToken);
                else
                    yourSearch.append(currentToken);
            }
        }
    } else {
        yourSearch.append(command.getsSearch());
    }
    model.put("yourSearch", yourSearch.toString());

    if (command.getsSearch().contains("\"")) {
        command.setsSearch(command.getsSearch().replace("\"", "\\\""));
    }

    // This number is used to generate an unique id for new search
    UUID uuid = UUID.randomUUID();
    command.setSearchUUID(uuid.toString());
    model.put("searchUUID", uuid.toString());

    // Add outputFields;
    List<String> outputFields = getOutputFields(command.getSimpleSearchPerimeter());
    model.put("outputFields", outputFields);
    return new ModelAndView("search/ExpandSimpleSearchResult", model);
}