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

The following examples show how to use org.apache.commons.lang.StringUtils#remove() . These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: rest-client   File: APIUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
* 
* @Title: isAlpha 
* @Description: Check if the string is made up of letters or underscores 
* @param @param str
* @param @return 
* @return boolean
* @throws
 */
public static boolean isAlpha(String str)
{
    if (null == str)
    {
        return false;
    }

    String rmStr = StringUtils.remove(str, "_");
    if (StringUtils.isAlpha(str) || StringUtils.isAlpha(rmStr))
    {
        return true;
    }

    return false;
}
 
Example 2
Source Project: smarthome   File: MetadataUtils.java    License: Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Returns the device name for the given device type.
 */
public static String getDeviceName(HmDevice device) {
    if (device.isGatewayExtras()) {
        return getDescription(HmDevice.TYPE_GATEWAY_EXTRAS);
    }

    String deviceDescription = null;
    boolean isTeam = device.getType().endsWith("-Team");
    String type = isTeam ? StringUtils.remove(device.getType(), "-Team") : device.getType();
    deviceDescription = getDescription(type);

    if (deviceDescription != null && isTeam) {
        deviceDescription += " Team";
    }

    return deviceDescription == null ? "No Description" : deviceDescription;
}
 
Example 3
/**
 * 
 * @see org.kuali.kfs.sys.batch.BatchInputFileType#getFileName(org.kuali.rice.kim.api.identity.Person, java.lang.Object, java.lang.String)
 */
public String getFileName(String principalName, Object parsedFileContents, String fileUserIdentifer) {
    
    //  start with the batch-job-prefix
    StringBuilder fileName = new StringBuilder(FILE_NAME_PREFIX);
    
    //  add the logged-in user name if there is one, otherwise use a sensible default
    fileName.append(FILE_NAME_DELIM + principalName);
    
    //  if the user specified an identifying label, then use it
    if (StringUtils.isNotBlank(fileUserIdentifer)) {
        fileName.append(FILE_NAME_DELIM + fileUserIdentifer);
    }
    
    //  stick a time stamp on the end
    fileName.append(FILE_NAME_DELIM + dateTimeService.toString(dateTimeService.getCurrentTimestamp(), "yyyyMMdd_HHmmss"));

    //  stupid spaces, begone!
    return StringUtils.remove(fileName.toString(), " ");
}
 
Example 4
protected boolean compareStrings(String aString1, String aString2) {
	aString1 = StringUtils.remove(aString1, (char) 13);
	aString1 = StringUtils.remove(aString1, (char) 10);

	aString2 = StringUtils.remove(aString2, (char) 13);
	aString2 = StringUtils.remove(aString2, (char) 10);

	System.out.println(aString1 + "\n" + aString1.length());
	System.out.println(aString2 + "\n" + aString2.length());

	return aString1.equals(aString2);
}
 
Example 5
/**
 * Splits a JSON JavaScript entry.
 */
private String[] handleStringTable(String line) {
    line = StringUtils.remove(line, "    \"");
    line = StringUtils.remove(line, "\",");
    line = StringUtils.remove(line, "\"");

    String[] splitted = StringUtils.split(line, ":", 2);
    return splitted.length != 2 ? null : splitted;
}
 
Example 6
/**
 * No additional information is added to procurment card batch files.
 * 
 * @see org.kuali.kfs.sys.batch.BatchInputFileType#getFileName(org.kuali.rice.kim.api.identity.Person, java.lang.Object,
 *      java.lang.String)
 */
public String getFileName(String principalName, Object parsedFileContents, String userIdentifier) {
    String fileName = "pcdo_" + principalName;
    if (StringUtils.isNotBlank(userIdentifier)) {
        fileName += "_" + userIdentifier;
    }
    fileName += "_" + dateTimeService.toDateTimeStringForFilename(dateTimeService.getCurrentDate());

    // remove spaces in filename
    fileName = StringUtils.remove(fileName, " ");

    return fileName;
}
 
Example 7
Source Project: atlas   File: ElementProcessors.java    License: Apache License 2.0 5 votes vote down vote up
private String[] getNonPrimitiveMapKeyFromLabel(Vertex v, String label) {
    if (!v.property(ENTITY_TYPE_PROPERTY_KEY).isPresent()) {
        return null;
    }

    String typeName = (String) v.property(ENTITY_TYPE_PROPERTY_KEY).value();

    if(!postProcessMap.containsKey(typeName)) {
        return null;
    }

    if(!postProcessMap.get(typeName).containsKey(NON_PRIMITIVE_MAP_CATEGORY)) {
        return null;
    }

    String       propertyName = StringUtils.remove(label, Constants.INTERNAL_PROPERTY_KEY_PREFIX);
    List<String> properties   = postProcessMap.get(typeName).get(NON_PRIMITIVE_MAP_CATEGORY);

    for (String p : properties) {
        if (propertyName.startsWith(p)) {
            return getLabelKeyPair(
                    String.format("%s%s", Constants.INTERNAL_PROPERTY_KEY_PREFIX, p),
                    StringUtils.remove(propertyName, p).substring(1).trim());
        }
    }

    return null;
}
 
Example 8
String getHiddenFieldValue(final String fieldName, final String value) {
    if (value == null) {
        return "";
    }
    final String str = value;
    if (StringUtils.isBlank(str)) {
        return "";
    }
    return "<input type='hidden' name='" + fieldName + "' value='" + StringUtils.remove(value, '\'') + "'>\n";
}
 
Example 9
private PublicKey initializePublicKey(String data) {
	try {
		data = StringUtils.remove(data, "-----BEGIN PUBLIC KEY-----");
		data = StringUtils.remove(data, "-----END PUBLIC KEY-----");
		X509EncodedKeySpec keySpec = new X509EncodedKeySpec(Base64.decodeBase64(data));
		KeyFactory keyFactory = KeyFactory.getInstance("RSA");
		return keyFactory.generatePublic(keySpec);
	}
	catch (Exception e) {
		throw new IllegalArgumentException("Invalid public key: ", e);
	}
}
 
Example 10
@NonNull
@Override
public List<String> getNames() {
    final Class c = category.getClass();
    final Symbol symbol = (Symbol) c.getAnnotation(Symbol.class);
    if (symbol != null) return asList(symbol.value());

    String name = c.getSimpleName();
    name = StringUtils.remove(name, "Global");
    name = StringUtils.remove(name, "Configuration");
    name = StringUtils.remove(name, "Category");
    return singletonList(name.toLowerCase());
}
 
Example 11
/**
 * 清除无关的不可见空白字符
 * @param str
 * @return
 */
protected String cleanInvisibleChar(String str) {
    if (str != null) {
        str = StringUtils.remove(str, (char) 160);
        //str = StringUtils.remove(str, " ");
        str = StringUtils.remove(str, "\r");
        str = StringUtils.remove(str, "\n");
        str = StringUtils.remove(str, "\t");
        str = StringUtils.remove(str, "\\s*");
        str = StringUtil.cleanField(str);
        str = str.trim();
    }
    return str;
}
 
Example 12
/**
 * Changes ranged search fields like from/to dates into the range operators the lookupable dao expects
 * ("..",">" etc) this method modifies the passed in map and returns a list containing only the modified fields
 *
 * This method does not handle document searchable attributes.  This is handled in a second pass by the docsearch-specific
 * DocumentSearchCriteriaTranslator
 */
public static Map<String, String> preProcessRangeFields(Map<String, String> lookupFormFields) {
    Map<String, String> fieldsToUpdate = new HashMap<String, String>();
    Set<String> fieldsForLookup = lookupFormFields.keySet();
    for (String propName : fieldsForLookup) {
        if (propName.startsWith(KRADConstants.LOOKUP_RANGE_LOWER_BOUND_PROPERTY_PREFIX)) {
            String rangedLowerBoundValue = lookupFormFields.get(propName);
            String rangedFieldName = StringUtils.remove(propName, KRADConstants.LOOKUP_RANGE_LOWER_BOUND_PROPERTY_PREFIX);
            String rangedValue = lookupFormFields.get(rangedFieldName);

            Range range = new Range();
            // defaults for general lookup/search
            range.setLowerBoundInclusive(true);
            range.setUpperBoundInclusive(true);
            range.setLowerBoundValue(rangedLowerBoundValue);
            range.setUpperBoundValue(rangedValue);

             String expr = range.toString();
            if (StringUtils.isEmpty(expr)) {
                expr = rangedValue;
            }

            fieldsToUpdate.put(rangedFieldName, expr);
        }
    }
    //update lookup values from found ranged values to update
    Set<String> keysToUpdate = fieldsToUpdate.keySet();
    for (String updateKey : keysToUpdate) {
        lookupFormFields.put(updateKey, fieldsToUpdate.get(updateKey));
    }
    return fieldsToUpdate;
}
 
Example 13
/**
 * changes from/to dates into the range operators the lookupable dao expects ("..",">" etc) this method modifies the passed in map and returns a list containing only the
 * modified fields
 *
 * @param lookupFormFields
 */
protected Map<String, String> preprocessDateFields(Map lookupFormFields) {
    Map<String, String> fieldsToUpdate = new HashMap<String, String>();
    Set<String> fieldsForLookup = lookupFormFields.keySet();
    for (String propName : fieldsForLookup) {
        if (propName.startsWith(KRADConstants.LOOKUP_RANGE_LOWER_BOUND_PROPERTY_PREFIX)) {
            String fromDateValue = (String) lookupFormFields.get(propName);
            String dateFieldName = StringUtils.remove(propName, KRADConstants.LOOKUP_RANGE_LOWER_BOUND_PROPERTY_PREFIX);
            String dateValue = (String) lookupFormFields.get(dateFieldName);
            String newPropValue = dateValue;// maybe clean above with ObjectUtils.clean(propertyValue)
            if (StringUtils.isNotEmpty(fromDateValue) && StringUtils.isNotEmpty(dateValue)) {
                newPropValue = fromDateValue + ".." + dateValue;
            }
            else if (StringUtils.isNotEmpty(fromDateValue) && StringUtils.isEmpty(dateValue)) {
                newPropValue = ">=" + fromDateValue;
            }
            else if (StringUtils.isNotEmpty(dateValue) && StringUtils.isEmpty(fromDateValue)) {
                newPropValue = "<=" + dateValue;
            } // could optionally continue on else here

            fieldsToUpdate.put(dateFieldName, newPropValue);
        }
    }
    // update lookup values from found date values to update
    Set<String> keysToUpdate = fieldsToUpdate.keySet();
    for (String updateKey : keysToUpdate) {
        lookupFormFields.put(updateKey, fieldsToUpdate.get(updateKey));
    }
    return fieldsToUpdate;
}
 
Example 14
public static String getKeyword(String url) {
	String keywordReg = "(?:yahoo.+?[\\?|&]q=|openfind.+?q=|google.+?q=|lycos.+?query=|onseek.+?keyword=|search\\.tom.+?word=|search\\.qq\\.com.+?word=|zhongsou\\.com.+?word=|search\\.msn\\.com.+?q=|yisou\\.com.+?p=|sina.+?word=|sina.+?query=|sina.+?_searchkey=|sohu.+?word=|sohu.+?key_word=|sohu.+?query=|163.+?q=|baidu.+?wd=|soso.+?w=|3721\\.com.+?p=|Alltheweb.+?q=)([^&]*)";
	String encodeReg = "^(?:[\\x00-\\x7f]|[\\xfc-\\xff][\\x80-\\xbf]{5}|[\\xf8-\\xfb][\\x80-\\xbf]{4}|[\\xf0-\\xf7][\\x80-\\xbf]{3}|[\\xe0-\\xef][\\x80-\\xbf]{2}|[\\xc0-\\xdf][\\x80-\\xbf])+$";
	Pattern keywordPattern = Pattern.compile(keywordReg);
	StringBuffer keywordBuff = new StringBuffer(20);
	Matcher keywordMat = keywordPattern.matcher(url);
	while (keywordMat.find()) {
		keywordMat.appendReplacement(keywordBuff, "$1");
	}
	String keyword = keywordBuff.toString();
	if (StringUtils.isNotBlank(keyword.toString())) {
		keyword = StringUtils.remove(keyword, keyword.substring(0, keyword
				.indexOf(".") + 1));
		Pattern encodePatt = Pattern.compile(encodeReg);
		String unescapeString = ParseURLKeyword.unescape(keyword);
		Matcher encodeMat = encodePatt.matcher(unescapeString);
		String encode = "gbk";
		if (encodeMat.matches())
			encode = "utf-8";
		try {
			return URLDecoder.decode(keyword, encode);
		} catch (UnsupportedEncodingException e) {
			return "";
		}
	}
	return "";
}
 
Example 15
/**
 * Executes the http request and parses the returned stream.
 */
private void executeRequest(Weather weather, String url, LocationConfig locationConfig) throws Exception {
    try {
        logger.trace("{}[{}]: request : {}", getProviderName(), locationConfig.getLocationId(), url);

        String response = StringUtils.trimToEmpty(HttpUtil.executeUrl("GET", url, 15000));

        /**
         * special handling because of identical current and forecast json structure
         * if 'url' contains "forecast" replace data key with forecast
         */
        if ((weather.getProvider() == ProviderName.WEATHERBIT) && StringUtils.contains(url, "forecast/daily")) {
            // replace data with forecast
            response = StringUtils.replace(response, "data", "forecast");
        }

        if (logger.isTraceEnabled()) {
            response = StringUtils.remove(response, "\n");
            response = StringUtils.trim(response);
            logger.trace("{}[{}]: response: {}", getProviderName(), locationConfig.getLocationId(), response);
        }

        if (!response.isEmpty()) {
            parser.parseInto(response, weather);
        }

        // special handling because of bad OpenWeatherMap json structure
        if (weather.getProvider() == ProviderName.OPENWEATHERMAP && weather.getResponseCode() != null
                && weather.getResponseCode() == 200) {
            weather.setError(null);
        }

        if (!weather.hasError() && response.isEmpty()) {
            weather.setError("Error: response is empty!");
        }

        if (weather.hasError()) {
            logger.error("{}[{}]: Can't retrieve weather data: {}", getProviderName(),
                    locationConfig.getLocationId(), weather.getError());
        } else {
            setLastUpdate(weather);
        }
    } catch (Exception ex) {
        logger.error(getProviderName() + ": " + ex.getMessage());
        weather.setError(ex.getClass().getSimpleName() + ": " + ex.getMessage());
        throw ex;
    }
}
 
Example 16
Source Project: GitCommitMessage   File: CommitMessage.java    License: Apache License 2.0 4 votes vote down vote up
public static String replaceVariableWithinTemplate(String templateString, String variable, String variableValue) {
    if (isRegExForVariableInTemplateDefined(templateString, variable)) {
        return templateString.replace(getVariableWithRegex(variable, templateString), variableValue);
    }
    return StringUtils.remove(templateString, "${" + variable + "}");
}
 
Example 17
Source Project: javadoc.chm   File: ClassInfo.java    License: Apache License 2.0 4 votes vote down vote up
public String getPackageName() {
    return StringUtils.remove(this.fullName, "." + this.shortName);
}
 
Example 18
Source Project: oxd   File: Cli.java    License: Apache License 2.0 4 votes vote down vote up
private static String sanitizeOutput(String str) {
    return StringUtils.remove(str, "\"");
}
 
Example 19
private static String sanitizeForTests(String xml) {
    // remove the doctype declaration, else the unit test fails when
    // executed offline
    return StringUtils.remove(xml, CheckstyleProfileExporter.DOCTYPE_DECLARATION);
}
 
Example 20
Source Project: incubator-gobblin   File: PathUtils.java    License: Apache License 2.0 3 votes vote down vote up
/**
 * Removes all <code>extensions</code> from <code>path</code> if they exist.
 *
 * <pre>
 * PathUtils.removeExtention("file.txt", ".txt")                      = file
 * PathUtils.removeExtention("file.txt.gpg", ".txt", ".gpg")          = file
 * PathUtils.removeExtention("file", ".txt")                          = file
 * PathUtils.removeExtention("file.txt", ".tar.gz")                   = file.txt
 * PathUtils.removeExtention("file.txt.gpg", ".txt")                  = file.gpg
 * PathUtils.removeExtention("file.txt.gpg", ".gpg")                  = file.txt
 * </pre>
 *
 * @param path in which the <code>extensions</code> need to be removed
 * @param extensions to be removed
 *
 * @return a new {@link Path} without <code>extensions</code>
 */
public static Path removeExtension(Path path, String... extensions) {
  String pathString = path.toString();
  for (String extension : extensions) {
    pathString = StringUtils.remove(pathString, extension);
  }

  return new Path(pathString);
}