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

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

Introduction

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

Prototype

public static String replaceOnce(String text, String searchString, String replacement) 

Source Link

Document

Replaces a String with another String inside a larger String, once.

Usage

From source file:org.kuali.ole.sys.service.impl.ReportAggregatorServiceTextImpl.java

protected int dumpFileContents(Writer outputWriter, File file, int currentPageNumber) {
    try {/*from   w w  w .java  2 s.c om*/
        BufferedReader reader = new BufferedReader(new FileReader(file));
        while (reader.ready()) {
            String line = reader.readLine();
            while (line.contains(OLEConstants.REPORT_WRITER_SERVICE_PAGE_NUMBER_PLACEHOLDER)) {
                line = StringUtils.replaceOnce(line, OLEConstants.REPORT_WRITER_SERVICE_PAGE_NUMBER_PLACEHOLDER,
                        String.valueOf(currentPageNumber));
                currentPageNumber++;
            }
            outputWriter.write(line);
            outputWriter.write(newLineCharacter);
        }
        reader.close();
        return currentPageNumber;
    } catch (IOException e) {
        throw new RuntimeException("Error reading or writing file", e);
    }
}

From source file:org.kuali.rice.krad.uif.container.MaintenanceActiveCollectionFilter.java

/**
 * Iterates through the collection and if the collection line type implements <code>Inactivatable</code>
 * active indexes are added to the show indexes list
 *
 * <p>//from   w w w.  jav  a  2 s  . c  o m
 * In the case of a new line being added, the user is not allowed to hide the record (even if it is inactive).
 * Likewise in the case of an edit where the active flag has changed between the old and new side, the user
 * is not allowed to hide
 * </p>
 *
 * {@inheritDoc}
 */
@Override
public List<Integer> filter(View view, Object model, CollectionGroup collectionGroup) {

    // get the collection for this group from the model
    List<Object> newCollection = ObjectPropertyUtils.getPropertyValue(model,
            collectionGroup.getBindingInfo().getBindingPath());

    // Get collection from old data object
    List<Object> oldCollection = null;
    String oldCollectionBindingPath = null;
    oldCollectionBindingPath = StringUtils.replaceOnce(collectionGroup.getBindingInfo().getBindingPath(),
            collectionGroup.getBindingInfo().getBindingObjectPath(), oldBindingObjectPath);
    oldCollection = ObjectPropertyUtils.getPropertyValue(model, oldCollectionBindingPath);

    // iterate through and add only active indexes
    List<Integer> showIndexes = new ArrayList<Integer>();
    for (int i = 0; i < newCollection.size(); i++) {
        Object line = newCollection.get(i);
        if (line instanceof Inactivatable) {
            boolean active = ((Inactivatable) line).isActive();
            if ((oldCollection != null) && (oldCollection.size() > i)) {
                // if active status has changed, show record
                Inactivatable oldLine = (Inactivatable) oldCollection.get(i);
                if (oldLine.isActive()) {
                    showIndexes.add(i);
                }
            } else {
                // TODO: if newly added line, show record
                // If only new and no old add the newline
                if (active) {
                    showIndexes.add(i);
                }
            }
        }
    }

    return showIndexes;
}

From source file:org.kuali.rice.krad.uif.modifier.CompareFieldCreateModifier.java

/**
 * For each attribute field in the compare item, retrieves the field value and compares against the value for the
 * main comparable. If the value is different, adds script to the field on ready event to add the change icon to
 * the field and the containing group header
 *
 * @param group group that contains the item and whose header will be highlighted for changes
 * @param compareItem the compare item being generated and to pull attribute fields from
 * @param model object containing the data
 * @param compareValueObjectBindingPath object path for the comparison item
 * @return true if the value in the field represented by compareItem is equal to the comparison items value, false
 *         otherwise// w ww  .j  a va 2  s  .c  o m
 */
protected boolean performValueComparison(Group group, Component compareItem, Object model,
        String compareValueObjectBindingPath) {
    // get any attribute fields for the item so we can compare the values
    List<DataField> itemFields = ViewLifecycleUtils.getElementsOfTypeDeep(compareItem, DataField.class);
    boolean valueChanged = false;
    for (DataField field : itemFields) {
        String fieldBindingPath = field.getBindingInfo().getBindingPath();
        Object fieldValue = ObjectPropertyUtils.getPropertyValue(model, fieldBindingPath);

        String compareBindingPath = StringUtils.replaceOnce(fieldBindingPath,
                field.getBindingInfo().getBindingObjectPath(), compareValueObjectBindingPath);
        Object compareValue = ObjectPropertyUtils.getPropertyValue(model, compareBindingPath);

        if (!((fieldValue == null) && (compareValue == null))) {
            // if one is null then value changed
            if ((fieldValue == null) || (compareValue == null)) {
                valueChanged = true;
            } else {
                // both not null, compare values
                valueChanged = !fieldValue.equals(compareValue);
            }
        }
        if (valueChanged) {
            // add script to show change icon
            String onReadyScript = "showChangeIcon('" + field.getId() + "');";
            field.setRenderMarkerIconSpan(true);
            field.setOnDocumentReadyScript(onReadyScript);
        }
        // TODO: add script for value changed?
    }
    return valueChanged;
}

From source file:org.kuali.student.cm.course.modifiers.CMCourseFieldCompareModifier.java

/**
 * Copy of the base class implementation but we dont need setting 'showChangeIcon()' JS as the default
 * implementation does.//  www . j av a  2  s  . c  om
 *
 * @param group
 * @param compareItem
 * @param model
 * @param compareValueObjectBindingPath
 * @return
 */
@Override
protected boolean performValueComparison(Group group, Component compareItem, Object model,
        String compareValueObjectBindingPath) {
    // get any attribute fields for the item so we can compare the values
    List<DataField> itemFields = ViewLifecycleUtils.getElementsOfTypeDeep(compareItem, DataField.class);
    boolean valueChanged = false;
    for (DataField field : itemFields) {
        String fieldBindingPath = field.getBindingInfo().getBindingPath();
        Object fieldValue = ObjectPropertyUtils.getPropertyValue(model, fieldBindingPath);

        String compareBindingPath = StringUtils.replaceOnce(fieldBindingPath,
                field.getBindingInfo().getBindingObjectPath(), compareValueObjectBindingPath);
        Object compareValue = ObjectPropertyUtils.getPropertyValue(model, compareBindingPath);

        if (!((fieldValue == null) && (compareValue == null))) {
            // if one is null then value changed
            if ((fieldValue == null) || (compareValue == null)) {
                valueChanged = true;
            } else {
                // both not null, compare values
                valueChanged = !fieldValue.equals(compareValue);
            }
        }
    }
    return valueChanged;
}

From source file:org.mule.modules.quickbooks.online.api.QuickBooksOnlinePaginatedIterable.java

/**
 * Performs the count query to QuickBooks to calculate the total number of results (all pages) for the original paginated query.
 * //  w w  w  .  ja v  a  2s.  co m
 * @return number of total results
 */
public Integer getTotalResultsCount() {
    String cQuery = query.trim();

    Matcher queryMatcher = QuickBooksOnlineQueryEvaluator.matchSelectFieldsPattern(cQuery);

    Validate.isTrue(queryMatcher.matches(), "The query - " + cQuery + " - received is not valid.");

    MatchResult queryMatchResult = queryMatcher.toMatchResult();
    String countQuery = StringUtils.replaceOnce(cQuery, queryMatchResult.group(1), COUNT_QUERY_SELECT_FIELDS);

    try {
        DataService dataService = dataServiceHelper.createIntuitDataService(credentials);
        QueryResult queryResult = dataService.executeQuery(countQuery);

        return queryResult.getTotalCount();
    } catch (FMSException e) {
        throw new QuickBooksRuntimeException(dataServiceHelper.adaptFMSExceptionToExceptionInfo(e), e);
    }
}

From source file:org.openhab.binding.homematic.internal.communicator.parser.CommonRpcParser.java

/**
 * Returns the address of a device, replacing group address identifier.
 *//*w w  w. j a  v  a 2  s.c  o m*/
protected String getAddress(Object object) {
    return StringUtils.replaceOnce(toString(object), "*", "T-");
}

From source file:org.openmrs.module.casereport.TestUtils.java

public static void setOpenHIMPort(Integer port) {
    AdministrationService as = Context.getAdministrationService();
    GlobalProperty gp = as.getGlobalPropertyObject(DocumentConstants.GP_OPENHIM_URL);
    gp.setPropertyValue(StringUtils.replaceOnce(gp.getPropertyValue(), "{{PORT}}", port.toString()));
    as.saveGlobalProperty(gp);//  ww w  . jav a 2s .  co  m
}

From source file:org.projectforge.web.address.PhoneCallPage.java

private void callNow() {
    if (StringUtils.isBlank(ConfigXml.getInstance().getTelephoneSystemUrl()) == true) {
        log.error("Telephone system url not configured. Phone calls not supported.");
        return;//from ww w  .  j  a v  a  2  s .  c  o  m
    }
    log.info("User initiates direct call from phone with id '" + form.getMyCurrentPhoneId()
            + "' to destination numer: " + StringHelper.hideStringEnding(form.getPhoneNumber(), 'x', 3));
    result = null;
    final StringBuffer buf = new StringBuffer();
    buf.append(form.getPhoneNumber()).append(SEPARATOR);
    final AddressDO address = form.getAddress();
    if (address != null
            && StringHelper.isIn(form.getPhoneNumber(), extractPhonenumber(address.getBusinessPhone()),
                    extractPhonenumber(address.getMobilePhone()), extractPhonenumber(address.getPrivatePhone()),
                    extractPhonenumber(address.getPrivateMobilePhone())) == true) {
        buf.append(address.getFirstName()).append(" ").append(address.getName());
        if (form.getPhoneNumber().equals(extractPhonenumber(address.getMobilePhone())) == true) {
            buf.append(", ").append(getString("address.phoneType.mobile"));
        } else if (form.getPhoneNumber().equals(extractPhonenumber(address.getPrivatePhone())) == true) {
            buf.append(", ").append(getString("address.phoneType.private"));
        }
        buf.append(" #").append(address.getId());
    } else {
        buf.append("???");
    }
    final HttpClient client = new HttpClient();
    String url = ConfigXml.getInstance().getTelephoneSystemUrl();
    url = StringUtils.replaceOnce(url, "#source", form.getMyCurrentPhoneId());
    url = StringUtils.replaceOnce(url, "#target", form.getPhoneNumber());
    final String urlProtected = StringHelper.hideStringEnding(url, 'x', 3);
    final GetMethod method = new GetMethod(url);
    String errorKey = null;
    try {
        form.lastSuccessfulPhoneCall = new Date();
        client.executeMethod(method);
        final String resultStatus = method.getResponseBodyAsString();
        if ("0".equals(resultStatus) == true) {
            result = DateTimeFormatter.instance().getFormattedDateTime(new Date()) + ": "
                    + getString("address.phoneCall.result.successful");
            form.getRecentSearchTermsQueue().append(buf.toString());
        } else if ("2".equals(resultStatus) == true) {
            errorKey = "address.phoneCall.result.wrongSourceNumber";
        } else if ("3".equals(resultStatus) == true) {
            errorKey = "address.phoneCall.result.wrongDestinationNumber";
        } else {
            errorKey = "address.phoneCall.result.callingError";
        }
    } catch (final HttpException ex) {
        result = "Call failed. Please contact administrator.";
        log.fatal(result + ": " + urlProtected);
        throw new RuntimeException(ex);
    } catch (final IOException ex) {
        result = "Call failed. Please contact administrator.";
        log.fatal(result + ": " + urlProtected);
        throw new RuntimeException(ex);
    }
    if (errorKey != null) {
        form.addError(errorKey);
    }
}

From source file:org.projectforge.web.address.SendSmsPage.java

protected void send() {
    final String number = NumberHelper.extractPhonenumber(getData().getPhoneNumber(),
            Configuration.getInstance().getStringValue(ConfigurationParam.DEFAULT_COUNTRY_PHONE_PREFIX));
    if (StringUtils.isBlank(ConfigXml.getInstance().getSmsUrl()) == true) {
        log.error("Servlet url for sending sms not configured. SMS not supported.");
        return;// w w  w .  ja  va2s  .  c  om
    }
    log.info("User sends message to destination number: '" + StringHelper.hideStringEnding(number, 'x', 3));
    final HttpClient client = new HttpClient();
    String url = ConfigXml.getInstance().getSmsUrl();
    url = StringUtils.replaceOnce(url, "#number", number);
    url = StringUtils.replaceOnce(url, "#message", URLHelper.encode(getData().getMessage()));
    final GetMethod method = new GetMethod(url);
    String errorKey = null;
    result = "";
    try {
        client.executeMethod(method);
        final String response = method.getResponseBodyAsString();
        if (response == null) {
            errorKey = getString("address.sendSms.sendMessage.result.unknownError");
        } else if (response.startsWith("0") == true) {
            result = getLocalizedMessage("address.sendSms.sendMessage.result.successful", number,
                    DateTimeFormatter.instance().getFormattedDateTime(new Date()));
        } else if (response.startsWith("1") == true) {
            errorKey = "address.sendSms.sendMessage.result.messageMissed";
        } else if (response.startsWith("2") == true) {
            errorKey = "address.sendSms.sendMessage.result.wrongOrMissingNumber";
        } else if (response.startsWith("3") == true) {
            errorKey = "address.sendSms.sendMessage.result.messageToLarge";
        } else {
            errorKey = getString("address.sendSms.sendMessage.result.unknownError");
        }
    } catch (final HttpException ex) {
        errorKey = "Call failed. Please contact administrator.";
        log.fatal(errorKey + ": " + ConfigXml.getInstance().getSmsUrl()
                + StringHelper.hideStringEnding(String.valueOf(number), 'x', 3));
        throw new RuntimeException(ex);
    } catch (final IOException ex) {
        errorKey = "Call failed. Please contact administrator.";
        log.fatal(errorKey + ": " + ConfigXml.getInstance().getSmsUrl()
                + StringHelper.hideStringEnding(String.valueOf(number), 'x', 3));
        throw new RuntimeException(ex);
    }
    if (errorKey != null) {
        form.addError(errorKey);
    }
}

From source file:org.sipfoundry.sipxconfig.rest.SipxSpringBeanRouter.java

protected void attachFinder(String uri, Finder finder) {
    attach(uri, finder);/*from   www.  j av a 2s. c o  m*/
    if (uri.startsWith(MY_PREFIX)) {
        String privateUri = StringUtils.replaceOnce(uri, MY_PREFIX, "/private/{puk}");
        attach(privateUri, finder);
    }
    if (uri.startsWith(MY_CALL_PREFIX)) {
        String privateUri = StringUtils.replaceOnce(uri, MY_CALL_PREFIX, "/call");
        attach(privateUri, finder);
    }
}