Java Code Examples for org.apache.commons.lang.StringUtils#replaceOnce()

The following examples show how to use org.apache.commons.lang.StringUtils#replaceOnce() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ReportAggregatorServiceTextImpl.java    From kfs with GNU Affero General Public License v3.0 6 votes vote down vote up
protected int dumpFileContents(Writer outputWriter, File file, int currentPageNumber) {
    try {
        BufferedReader reader = new BufferedReader(new FileReader(file));
        while (reader.ready()) {
            String line = reader.readLine();
            while (line.contains(KFSConstants.REPORT_WRITER_SERVICE_PAGE_NUMBER_PLACEHOLDER)) {
                line = StringUtils.replaceOnce(line, KFSConstants.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);
    }
}
 
Example 2
Source File: PersonFilter.java    From diff-check with GNU Lesser General Public License v2.1 6 votes vote down vote up
@SuppressWarnings("unchecked")
public PersonFilter(MavenProject project, File gitDir, PersonInfo personInfo, List<BlameResult> blameResults) {
    List<String> modules = project.getModules();
    if (project.getParent() != null && CollectionUtils.isNotEmpty(project.getParent().getModules())) {
        modules.addAll(project.getParent().getModules());
    }
    for (BlameResult blameResult : blameResults) {
        String name = blameResult.getResultPath();
        if (CollectionUtils.isNotEmpty(modules)) {
            for (String module : modules) {
                if (name.startsWith(module)) {
                    name = StringUtils.replaceOnce(name, module, "");
                    break;
                }
            }
        }
        if (!name.startsWith(SOURCE_PATH_PREFIX)) {
            continue;
        }
        name = StringUtils.replaceOnce(name, SOURCE_PATH_PREFIX, "");
        classPathBlameResultMap.put(name, blameResult);
    }
    this.personInfo = personInfo;
}
 
Example 3
Source File: BlockImpl.java    From NovaGuilds with GNU General Public License v3.0 5 votes vote down vote up
/**
 * The constructor
 *
 * @param name              exception name
 * @param message           exception message
 * @param stackTraceElement first stacktrace element
 */
public BlockImpl(String name, String message, String stackTraceElement) {
	if(StringUtils.startsWith(stackTraceElement, NovaGuilds.class.getPackage().getName())) {
		StringUtils.replaceOnce(stackTraceElement, NovaGuilds.class.getPackage().getName() + ".", "");
	}

	this.name = name;
	this.message = message;
	this.stackTraceElement = stackTraceElement;
}
 
Example 4
Source File: GenericDaoJpa.java    From ankush with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Convert to count query.
 * 
 * @param query
 *            the query
 * @return the string
 */
private String convertToCountQuery(String query) {
	Pattern pattern = Pattern.compile("select(.+)from");
	Matcher matcher = pattern.matcher(query);
	if (matcher.find()) {
		String s = matcher.group(1).trim();
		query = StringUtils.replaceOnce(query, s, "count(" + s + ")");
	}
	return query;
}
 
Example 5
Source File: UITestPropertyEditor.java    From rice with Educational Community License v2.0 5 votes vote down vote up
/**
 * @see java.beans.PropertyEditorSupport#setAsText(java.lang.String)
 */
@Override
public void setAsText(String text) {
    String value = text;
    if (StringUtils.contains(value, "-")) {
        value = StringUtils.replaceOnce(value, "-", "");
    }

    this.setValue(value);
}
 
Example 6
Source File: MaintenanceActiveCollectionFilter.java    From rice with Educational Community License v2.0 5 votes vote down vote up
/**
 * Iterates through the collection and if the collection line type implements <code>Inactivatable</code>
 * active indexes are added to the show indexes list
 *
 * <p>
 * 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;
}
 
Example 7
Source File: CompareFieldCreateModifier.java    From rice with Educational Community License v2.0 5 votes vote down vote up
/**
 * 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
 */
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();
        if (field.getPropertyName() != null && field.getPropertyName().length() > 0 && !fieldBindingPath.endsWith(field.getPropertyName())) {
            fieldBindingPath += "." + field.getPropertyName();
        }
        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;
}
 
Example 8
Source File: UITestPropertyEditor.java    From rice with Educational Community License v2.0 5 votes vote down vote up
/**
 * @see java.beans.PropertyEditorSupport#setAsText(String)
 */
@Override
public void setAsText(String text) {
    String value = text;
    if (StringUtils.contains(value, "-")) {
        value = StringUtils.replaceOnce(value, "-", "");
    }

    this.setValue(value);
}
 
Example 9
Source File: BatchFileUtils.java    From kfs with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * returns a path relative to the appropriate lookup root directory, while including the name of the root directory for example,
 * if the parameter is "c:\opt\staging\gl\somefile.txt" and the roots are "c:\opt\reports;c:\opt\staging", it will return
 * "staging\gl\somefile.txt" (the system-specific path separator will be used). If there are multiple matching roots, then the
 * first one to be matched will take precedence
 * 
 * @param absolutePath an absolute path for a file/directory
 */
public static String pathRelativeToRootDirectory(String absolutePath) {
    for (File rootDirectory : retrieveBatchFileLookupRootDirectories()) {
        if (absolutePath.startsWith(rootDirectory.getAbsolutePath())) {
            return StringUtils.replaceOnce(absolutePath, rootDirectory.getAbsolutePath(), rootDirectory.getName());
        }
    }
    throw new RuntimeException("Unable to find appropriate root directory)");
}
 
Example 10
Source File: GlobalVariablesExtractHelper.java    From kfs with GNU Affero General Public License v3.0 5 votes vote down vote up
public static String replaceTokens(String line, String ... replacements) {
    int i = 0;
    for (String err : replacements) {
        String repl = "{" + String.valueOf(i++) + "}";
        line = StringUtils.replaceOnce(line, repl, err);
    }
    return line;
}
 
Example 11
Source File: HttpTransportImpl.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
private String addSessionToken(String request, String sessionToken) {
    String correctedRequest = request;
    if (!correctedRequest.contains(ParameterKeys.TOKEN)) {
        if (correctedRequest.contains("?")) {
            correctedRequest = correctedRequest + "&" + ParameterKeys.TOKEN + "=" + sessionToken;
        } else {
            correctedRequest = correctedRequest + "?" + ParameterKeys.TOKEN + "=" + sessionToken;
        }
    } else {
        correctedRequest = StringUtils.replaceOnce(correctedRequest, StringUtils.substringBefore(
                StringUtils.substringAfter(correctedRequest, ParameterKeys.TOKEN + "="), "&"), sessionToken);

    }
    return correctedRequest;
}
 
Example 12
Source File: ClassWrapperRenderer.java    From otroslogviewer with Apache License 2.0 5 votes vote down vote up
protected String abbreviatePackageUsingMappings(String clazz, SortedMap<String, String> abbreviations) {
  for (String s : abbreviations.keySet()) {
    if (StringUtils.startsWith(clazz,s)) {
      return StringUtils.replaceOnce(clazz, s, abbreviations.get(s));
    }
  }
  return clazz;
}
 
Example 13
Source File: KubernetesFolderProperty.java    From kubernetes-plugin with Apache License 2.0 5 votes vote down vote up
@Override
public AbstractFolderProperty<?> reconfigure(StaplerRequest req, JSONObject form) throws FormException {
    if (form == null) {
        return null;
    }

    // ignore modifications silently and return the unmodified object if the user
    // does not have the ADMINISTER Permission
    if (!userHasAdministerPermission()) {
        return this;
    }

    try {
        Set<String> inheritedGrants = new HashSet<>();
        collectAllowedClouds(inheritedGrants, getOwner().getParent());

        Set<String> permittedClouds = new HashSet<>();
        JSONArray names = form.names();
        if (names != null) {
            for (Object name : names) {
                String strName = (String) name;

                if (strName.startsWith(PREFIX_USAGE_PERMISSION) && form.getBoolean(strName)) {
                    String cloud = StringUtils.replaceOnce(strName, PREFIX_USAGE_PERMISSION, "");

                    if (isUsageRestrictedKubernetesCloud(Jenkins.get().getCloud(cloud))
                            && !inheritedGrants.contains(cloud)) {
                        permittedClouds.add(cloud);
                    }
                }
            }
        }
        this.permittedClouds.clear();
        this.permittedClouds.addAll(permittedClouds);
    } catch (JSONException e) {
        LOGGER.log(Level.SEVERE, e, () -> "reconfigure failed: " + e.getMessage());
    }
    return this;
}
 
Example 14
Source File: ServiceMappingContainer.java    From dubbo-plus with Apache License 2.0 5 votes vote down vote up
public void registerService(URL url, Class serviceType, Object impl) {
    String contextPath = url.getParameter(RestfulConstants.CONTEXT_PATH,"/");
    String path  =StringUtils.replaceOnce(url.getPath(),contextPath,"");
    if(StringUtils.startsWith(path,"/")){
        path = StringUtils.replaceOnce(path,"/","");
    }
    SERVICE_MAPPING.putIfAbsent(path,
            new ServiceHandler(url.getParameter(Constants.GROUP_KEY),
                    url.getParameter(Constants.VERSION_KEY),
                    serviceType,path,impl));
}
 
Example 15
Source File: SqlLogFilter.java    From framework with Apache License 2.0 5 votes vote down vote up
/**
 * Description: <br>
 * 
 * @author yang.zhipeng <br>
 * @taskId <br>
 * @param statement <br>
 * @return <br>
 */
private String getExcuteSql(final StatementProxy statement) {
    String sqlStr = statement.getBatchSql();
    if (statement instanceof PreparedStatementProxy) {
        for (JdbcParameter parameter : statement.getParameters().values()) {
            int sqlType = parameter.getSqlType();
            Object value = parameter.getValue();
            String tempValue;
            switch (sqlType) {
                case Types.NULL:
                    tempValue = "NULL";
                    break;
                case Types.CLOB:
                case Types.CHAR:
                case Types.VARCHAR:
                    tempValue = new StringBuilder().append('\'').append(value).append('\'').toString();
                    break;
                default:
                    tempValue = String.valueOf(value);
                    break;
            }
            sqlStr = StringUtils.replaceOnce(sqlStr, "?", tempValue);
        }
    }

    return sqlStr;
}
 
Example 16
Source File: HdfsNameServiceResolver.java    From atlas with Apache License 2.0 5 votes vote down vote up
public static String getPathWithNameServiceID(String path) {
    if (LOG.isDebugEnabled()) {
        LOG.debug("==> HdfsNameServiceResolver.getPathWithNameServiceID({})", path);
    }

    String ret = path;

    // Only handle URLs that begin with hdfs://
    if (path != null && path.indexOf(HDFS_SCHEME) == 0) {
        URI uri = new Path(path).toUri();
        String nsId;

        if (uri.getPort() != -1) {
            nsId = hostToNameServiceMap.get(uri.getAuthority());
        } else {
            nsId = hostToNameServiceMap.get(uri.getHost() + ":" + DEFAULT_PORT);
        }

        if (nsId != null) {
            ret = StringUtils.replaceOnce(path, uri.getAuthority(), nsId);
        }
    }


    if (LOG.isDebugEnabled()) {
        LOG.debug("<== HdfsNameServiceResolver.getPathWithNameServiceID({}) = {}", path, ret);
    }

    return ret;
}
 
Example 17
Source File: Javadoc8Style.java    From javadoc.chm with Apache License 2.0 5 votes vote down vote up
@Override
public String getMethodFullName(String url) {
    String name = StringUtils.substringAfter(url, "#");
    int count = StringUtils.countMatches(name, "-");
    name = StringUtils.replaceOnce(name, "-", "(");
    for (int i = 0; i < count - 2; i++) {
        name = StringUtils.replaceOnce(name, "-", ", ");
    }
    name = StringUtils.replaceOnce(name, "-", ")");
    name = StringUtils.replace(name, ":A", "[]");
    return name;
}
 
Example 18
Source File: ShowCreateTableMyHandler.java    From tddl5 with Apache License 2.0 4 votes vote down vote up
public static void main(String args[]) {
    String str = StringUtils.replaceOnce("CREATE TABLE `test_table_autoinc_onegroup_mutilatom_00` (",
        "test_table_autoinc_onegroup_mutilatom_00",
        "hello");
    System.out.println(str);
}
 
Example 19
Source File: RESTUtil.java    From rest-client with Apache License 2.0 3 votes vote down vote up
/**
* 
* @Title: replacePath 
* @Description: replace file path 
* @param @param path
* @param @return 
* @return String
* @throws
 */
public static String replacePath(String path)
{
    return StringUtils.replaceOnce(path, 
           RESTConst.WISDOM_TOOL,
           RESTConst.WORK + File.separatorChar);
}
 
Example 20
Source File: AccumuloRyaUtils.java    From rya with Apache License 2.0 2 votes vote down vote up
/**
 * Converts a {@link RyaIRI} to the contained data string.
 * @param namespace the namespace.
 * @param ryaIri the {@link RyaIRI} to convert.
 * @return the data value without the namespace.
 */
public static String convertRyaIriToString(final String namespace, final RyaIRI ryaIri) {
    return StringUtils.replaceOnce(ryaIri.getData(), namespace, "");
}