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

The following examples show how to use org.apache.commons.lang.StringUtils#removeEnd() . 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: RedirectParameters.java    From oxAuth with MIT License 6 votes vote down vote up
public String buildQueryString() {
    String queryString = "";
    for (Map.Entry<String, Set<String>> param : map.entrySet()) {
        Set<String> values = param.getValue();
        if (StringUtils.isNotBlank(param.getKey()) && values != null && !values.isEmpty()) {
            for (String value : values) {
                if (StringUtils.isNotBlank(value)) {
                    try {
                        queryString += param.getKey() + "=" + URLEncoder.encode(value, "UTF-8") + "&";
                    } catch (UnsupportedEncodingException e) {
                        LOGGER.error("Failed to encode value: " + value, e);
                    }
                }
            }
        }
    }
    queryString = StringUtils.removeEnd(queryString, "&");
    return queryString;
}
 
Example 2
Source File: MessageStructureUtils.java    From rice with Educational Community License v2.0 6 votes vote down vote up
/**
 * Process a piece of the message that has link content by creating an anchor (a tag) with the href set
 *
 * @param messagePiece String piece with link content
 * @param currentMessageComponent the state of the current text based message being built
 * @param view current View
 * @return currentMessageComponent with the new textual content generated by this method appended to its
 *         messageText
 */
private static Message processLinkContent(String messagePiece, Message currentMessageComponent, View view) {
    if (!StringUtils.startsWithIgnoreCase(messagePiece, "/")) {
        //clean up href
        messagePiece = StringUtils.removeStart(messagePiece, KRADConstants.MessageParsing.LINK + "=");
        messagePiece = StringUtils.removeStart(messagePiece, "'");
        messagePiece = StringUtils.removeEnd(messagePiece, "'");
        messagePiece = StringUtils.removeStart(messagePiece, "\"");
        messagePiece = StringUtils.removeEnd(messagePiece, "\"");

        messagePiece = "<a href='" + messagePiece + "' target='_blank'>";
    } else {
        messagePiece = "</a>";
    }

    return concatenateStringMessageContent(currentMessageComponent, messagePiece, view);
}
 
Example 3
Source File: MessageStructureUtils.java    From rice with Educational Community License v2.0 6 votes vote down vote up
/**
 * Process the additional properties beyond index 0 of the tag (that was split into parts).
 *
 * <p>This will evaluate and set each of properties on the component passed in.  This only allows
 * setting of properties that can easily be converted to/from/are String type by Spring.</p>
 *
 * @param component component to have its properties set
 * @param tagParts the tag split into parts, index 0 is ignored
 * @return component with its properties set found in the tag's parts
 */
private static Component processAdditionalProperties(Component component, String[] tagParts) {
    String componentString = tagParts[0];
    tagParts = (String[]) ArrayUtils.remove(tagParts, 0);

    for (String part : tagParts) {
        String[] propertyValue = part.split("=");

        if (propertyValue.length == 2) {
            String path = propertyValue[0];
            String value = propertyValue[1].trim();
            value = StringUtils.removeStart(value, "'");
            value = StringUtils.removeEnd(value, "'");
            ObjectPropertyUtils.setPropertyValue(component, path, value);
        } else {
            throw new RuntimeException(
                    "Invalid Message structure for component defined as " + componentString + " around " + part);
        }
    }

    return component;
}
 
Example 4
Source File: SimpleDdlParser.java    From canal-1.1.3 with Apache License 2.0 5 votes vote down vote up
private static DdlResult parseTableName(String matchString, String schmeaName) {
    Perl5Matcher tableMatcher = new Perl5Matcher();
    matchString = matchString + " ";
    if (tableMatcher.matches(matchString, PatternUtils.getPattern(TABLE_PATTERN))) {
        String tableString = tableMatcher.getMatch().group(3);
        if (StringUtils.isEmpty(tableString)) {
            return null;
        }

        tableString = StringUtils.removeEnd(tableString, ";");
        tableString = StringUtils.removeEnd(tableString, "(");
        tableString = StringUtils.trim(tableString);
        // 特殊处理引号`
        tableString = removeEscape(tableString);
        // 处理schema.table的写法
        String names[] = StringUtils.split(tableString, ".");
        if (names.length == 0) {
            return null;
        }

        if (names != null && names.length > 1) {
            return new DdlResult(removeEscape(names[0]), removeEscape(names[1]));
        } else {
            return new DdlResult(schmeaName, removeEscape(names[0]));
        }
    }

    return null;
}
 
Example 5
Source File: BankChangeHistory.java    From kfs with GNU Affero General Public License v3.0 5 votes vote down vote up
public String getOriginalBankCodeList() {
    String commaSeparatedOriginalBankCodeList = "";
    
    for (PaymentGroupHistory paymentGroupHistory : this.getPaymentGroup().getPaymentGroupHistory()) {
        if ( !StringUtils.isEmpty(paymentGroupHistory.getOrigBankCode()) ) commaSeparatedOriginalBankCodeList = commaSeparatedOriginalBankCodeList + paymentGroupHistory.getOrigBankCode() + ", ";
    }
    
    commaSeparatedOriginalBankCodeList = StringUtils.strip(commaSeparatedOriginalBankCodeList);
    commaSeparatedOriginalBankCodeList = StringUtils.removeEnd(commaSeparatedOriginalBankCodeList, ",");
    
    return commaSeparatedOriginalBankCodeList;
}
 
Example 6
Source File: KRADUtils.java    From rice with Educational Community License v2.0 5 votes vote down vote up
/**
 * Retrieves parameter values from the request that match the requested
 * names. In addition, based on the object class an authorization check is
 * performed to determine if the values are secure and should be decrypted.
 * If true, the value is decrypted before returning
 *
 * @param parameterNames - names of the parameters whose values should be retrieved
 * from the request
 * @param parentObjectClass - object class that contains the parameter names as properties
 * and should be consulted for security checks
 * @param requestParameters - all request parameters to pull from
 * @return Map<String, String> populated with parameter name/value pairs
 * pulled from the request
 */
public static Map<String, String> getParametersFromRequest(List<String> parameterNames, Class<?> parentObjectClass,
        Map<String, String> requestParameters) {
    Map<String, String> parameterValues = new HashMap<String, String>();

    for (Iterator<String> iter = parameterNames.iterator(); iter.hasNext(); ) {
        String keyPropertyName = iter.next();

        if (requestParameters.get(keyPropertyName) != null) {
            String keyValue = requestParameters.get(keyPropertyName);

            // check security on field
            boolean isSecure = isSecure(keyPropertyName, parentObjectClass);

            if (StringUtils.endsWith(keyValue, EncryptionService.ENCRYPTION_POST_PREFIX)) {
                keyValue = StringUtils.removeEnd(keyValue, EncryptionService.ENCRYPTION_POST_PREFIX);
                isSecure = true;
            }

            // decrypt if the value is secure
            if (isSecure) {
                try {
                    if (CoreApiServiceLocator.getEncryptionService().isEnabled()) {
                        keyValue = CoreApiServiceLocator.getEncryptionService().decrypt(keyValue);
                    }
                } catch (GeneralSecurityException e) {
                    String message = "Data object class " + parentObjectClass + " property " + keyPropertyName
                            + " should have been encrypted, but there was a problem decrypting it.";
                    LOG.error(message);

                    throw new RuntimeException(message, e);
                }
            }

            parameterValues.put(keyPropertyName, keyValue);
        }
    }

    return parameterValues;
}
 
Example 7
Source File: DataObjectMetaDataServiceImpl.java    From rice with Educational Community License v2.0 5 votes vote down vote up
/**
    * @see org.kuali.rice.krad.service.DataObjectMetaDataService#getDataObjectIdentifierString
    */
   @Override
public String getDataObjectIdentifierString(Object dataObject) {
       String identifierString = "";

       if (dataObject == null) {
           identifierString = "Null";
           return identifierString;
       }

       Class<?> dataObjectClass = dataObject.getClass();

       // if PBO, use object id property
       if (PersistableBusinessObject.class.isAssignableFrom(dataObjectClass)) {
           String objectId = ObjectPropertyUtils.getPropertyValue(dataObject, UifPropertyPaths.OBJECT_ID);
           if (StringUtils.isBlank(objectId)) {
               objectId = UUID.randomUUID().toString();
               ObjectPropertyUtils.setPropertyValue(dataObject, UifPropertyPaths.OBJECT_ID, objectId);
           }

           identifierString = objectId;
       } else {
           // build identifier string from primary key values
           Map<String, ?> primaryKeyFieldValues = getPrimaryKeyFieldValues(dataObject, true);
           for (Map.Entry<String, ?> primaryKeyValue : primaryKeyFieldValues.entrySet()) {
               if (primaryKeyValue.getValue() == null) {
                   identifierString += "Null";
               } else {
                   identifierString += primaryKeyValue.getValue();
               }
               identifierString += ":";
           }
           identifierString = StringUtils.removeEnd(identifierString, ":");
       }

       return identifierString;
   }
 
Example 8
Source File: FileEnterpriseFeederServiceImpl.java    From kfs with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Given the doneFile, this method finds the data file corresponding to the done file
 * 
 * @param doneFile
 * @return a File for the data file, or null if the file doesn't exist or is not readable
 */
protected File getDataFile(File doneFile) {
    String doneFileAbsPath = doneFile.getAbsolutePath();
    if (!doneFileAbsPath.endsWith(DONE_FILE_SUFFIX)) {
        LOG.error("Done file name must end with " + DONE_FILE_SUFFIX);
        throw new IllegalArgumentException("Done file name must end with " + DONE_FILE_SUFFIX);
    }
    String dataFileAbsPath = StringUtils.removeEnd(doneFileAbsPath, DONE_FILE_SUFFIX) + DATA_FILE_SUFFIX;
    File dataFile = new File(dataFileAbsPath);
    if (!dataFile.exists() || !dataFile.canRead()) {
        LOG.error("Cannot find/read data file " + dataFileAbsPath);
        return null;
    }
    return dataFile;
}
 
Example 9
Source File: KualiMaintenanceDocumentAction.java    From rice with Educational Community License v2.0 5 votes vote down vote up
protected Map<String, String> getRequestParameters(List keyFieldNames, Maintainable maintainable, HttpServletRequest request){

		Map<String, String> requestParameters = new HashMap<String, String>();


		for (Iterator iter = keyFieldNames.iterator(); iter.hasNext();) {
			String keyPropertyName = (String) iter.next();

			if (request.getParameter(keyPropertyName) != null) {
				String keyValue = request.getParameter(keyPropertyName);

				// Check if this element was encrypted, if it was decrypt it
                if (getBusinessObjectAuthorizationService().attributeValueNeedsToBeEncryptedOnFormsAndLinks(maintainable.getBoClass(), keyPropertyName)) {
					try {
                    	keyValue = StringUtils.removeEnd(keyValue, EncryptionService.ENCRYPTION_POST_PREFIX);
                        if(CoreApiServiceLocator.getEncryptionService().isEnabled()) {
						    keyValue = encryptionService.decrypt(keyValue);
                        }
					}
					catch (GeneralSecurityException e) {
						throw new RuntimeException(e);
					}
				}


				requestParameters.put(keyPropertyName, keyValue);
			}
		}

		return requestParameters;

	}
 
Example 10
Source File: HTTPRequest.java    From zulip-android with Apache License 2.0 5 votes vote down vote up
private String generateURL(String url, HashMap<String, String> properties) {
    if (properties.isEmpty()) return url;
    String encodedUrl = url + "?";
    for (Map.Entry<String, String> map : properties.entrySet()) {
        try {
            encodedUrl += URLEncoder.encode(map.getKey(), ("utf-8")) + "=" + URLEncoder.encode(map.getValue(), "utf-8") + "&";
        } catch (UnsupportedEncodingException e) {
            ZLog.logException(e);
        }
    }
    StringUtils.removeEnd(encodedUrl, "&");
    return encodedUrl;
}
 
Example 11
Source File: DataTools.java    From util4j with Apache License 2.0 5 votes vote down vote up
/**
 * 根据字节数组拆分若干个字字节数组
 * @param data
 * @param separator
 * @return
 */
public byte[][] getsonArrays(byte[] data,byte[] separator)
{
	if(data==null||data.length<=0||separator==null||separator.length<=0)
	{
		System.out.println("data||separator数据无效!");
		return null;
	}
	String[] dataHexArray=byteArrayToHexArray(data);
	String dataHexStr=StringUtils.substringBetween(Arrays.toString(dataHexArray), "[", "]").replaceAll("\\s","");
	//System.out.println("待拆分字符串:"+dataHexStr);
	String[] separatorHexhArray=byteArrayToHexArray(separator);
	String separatorHexStr=StringUtils.substringBetween(Arrays.toString(separatorHexhArray), "[", "]").replaceAll("\\s","");
	//System.out.println("字符串拆分符:"+separatorHexStr);
	//得到拆分后的数组
	String[] arrays=StringUtils.splitByWholeSeparator(dataHexStr, separatorHexStr);
	//System.out.println("拆分后的数组:"+Arrays.toString(arrays));
	if(arrays==null||arrays.length<=0)
	{
		System.out.println("注意:数组拆分为0");
		return null;
	}
	byte[][] result=new byte[arrays.length][];
	//对子数组进行重组
	for(int i=0;i<arrays.length;i++)
	{
		String arrayStr=arrays[i];
		arrayStr=StringUtils.removeStart(arrayStr, ",");//去掉两端的逗号
		arrayStr=StringUtils.removeEnd(arrayStr, ",");//去掉两端的逗号
		String[] array=arrayStr.split(",");//根据子字符串中间剩余的逗号重组为hex字符串
		result[i]=hexArrayToBtyeArray(array);
	}
	return result;
}
 
Example 12
Source File: TrpRegionType.java    From TranskribusCore with GNU General Public License v3.0 4 votes vote down vote up
@Override
public String getName() {
	XmlType t = this.getClass().getAnnotation(XmlType.class);
			
	return t!=null ? StringUtils.removeEnd(t.name(), "Type") : "UnknownRegion";
}
 
Example 13
Source File: AmqpSubscriberTest.java    From attic-stratos with Apache License 2.0 4 votes vote down vote up
private static String getResourcesFolderPath() {
    String path = AmqpSubscriberTest.class.getResource("/").getPath();
    return StringUtils.removeEnd(path, File.separator);
}
 
Example 14
Source File: DisjunctiveNormalFormConverter.java    From rya with Apache License 2.0 4 votes vote down vote up
/**
 * Creates a document visibility boolean expression string into Disjunctive
 * Normal Form (DNF).  Expressions use this format in DNF:<pre>
 * (P1 & P2 & P3 ... Pn) | (Q1 & Q2 ... Qm) ...
 * </pre>
 * @param documentVisibility the {@link DocumentVisibility}.
 * @return a new {@link DocumentVisibility} with its expression in DNF.
 */
public static DocumentVisibility convertToDisjunctiveNormalForm(final DocumentVisibility documentVisibility) {
    // Find all the terms used in the expression
    final List<String> terms = findNodeTerms(documentVisibility.getParseTree(), documentVisibility.getExpression());
    // Create an appropriately sized truth table that has the correct 0's
    // and 1's in place based on the number of terms.
    // This size should be [numberOfTerms][2 ^ numberOfTerms].
    final byte[][] truthTable = createTruthTableInputs(terms);

    // Go through each row in the truth table.
    // If the row has a 1 for the term then create an Authorization for it
    // and test if it works.
    // If the row passes then that means all the terms that were a 1 and
    // were used can be AND'ed together to pass the expression.
    // All the rows that pass can be OR'd together.
    // Disjunction Normal Form: (P1 & P2 & P3 ... Pn) | (Q1 & Q2 ... Qm) ...
    final List<List<String>> termRowsThatPass = new ArrayList<>();
    for (final byte[] row : truthTable) {
        final List<String> termRowToCheck = new ArrayList<>();
        // If the truth table input is a 1 then include the corresponding
        // term that it matches.
        for (int i = 0; i < row.length; i++) {
            final byte entry = row[i];
            if (entry == 1) {
                termRowToCheck.add(terms.get(i));
            }
        }

        final List<String> authList = new ArrayList<>();
        for (final String auth : termRowToCheck) {
            String formattedAuth = auth;
            formattedAuth = StringUtils.removeStart(formattedAuth, "\"");
            formattedAuth = StringUtils.removeEnd(formattedAuth, "\"");
            authList.add(formattedAuth);
        }
        final Authorizations auths = new Authorizations(authList.toArray(new String[0]));
        final boolean hasAccess = DocumentVisibilityUtil.doesUserHaveDocumentAccess(auths, documentVisibility, false);
        if (hasAccess) {
            boolean alreadyCoveredBySimplerTerms = false;
            // If one 'AND' group is (A&C) and another is (A&B&C) then we
            // can drop (A&B&C) since it is already covered by simpler terms
            // (it's a subset)
            for (final List<String> existingTermRowThatPassed : termRowsThatPass) {
                alreadyCoveredBySimplerTerms = termRowToCheck.containsAll(existingTermRowThatPassed);
                if (alreadyCoveredBySimplerTerms) {
                    break;
                }
            }
            if (!alreadyCoveredBySimplerTerms) {
                termRowsThatPass.add(termRowToCheck);
            }
        }
    }

    // Rebuild the term rows that passed as a document visibility boolean
    // expression string.
    final StringBuilder sb = new StringBuilder();
    boolean isFirst = true;
    final boolean hasMultipleGroups = termRowsThatPass.size() > 1;
    for (final List<String> termRowThatPassed : termRowsThatPass) {
        if (isFirst) {
            isFirst = false;
        } else {
            sb.append("|");
        }
        if (hasMultipleGroups && termRowThatPassed.size() > 1) {
            sb.append("(");
        }
        sb.append(Joiner.on("&").join(termRowThatPassed));
        if (hasMultipleGroups && termRowThatPassed.size() > 1) {
            sb.append(")");
        }
    }

    log.trace(sb.toString());
    final DocumentVisibility dnfDv = new DocumentVisibility(sb.toString());
    return dnfDv;
}
 
Example 15
Source File: HeredocSharedImpl.java    From BashSupport with Apache License 2.0 4 votes vote down vote up
private static String trimNewline(String marker) {
    return StringUtils.removeEnd(marker, "\n");
}
 
Example 16
Source File: ZQL.java    From zstack with Apache License 2.0 4 votes vote down vote up
public static String queryTargetNameFromInventoryClass(Class invClass) {
    String name = invClass.getSimpleName().toLowerCase();
    return StringUtils.removeEnd(name, "inventory");
}
 
Example 17
Source File: Api.java    From heimdall with Apache License 2.0 4 votes vote down vote up
private void fixBasePath() {

          if (this.basePath.endsWith(ConstantsPath.PATH_ROOT)) {
               this.basePath = StringUtils.removeEnd(basePath, ConstantsPath.PATH_ROOT);
          }
     }
 
Example 18
Source File: BindingConfigParser.java    From openhab1-addons with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Parses the bindingConfig of an item and returns a AstroBindingConfig.
 */
public AstroBindingConfig parse(Item item, String bindingConfig) throws BindingConfigParseException {
    bindingConfig = StringUtils.trimToEmpty(bindingConfig);
    bindingConfig = StringUtils.removeStart(bindingConfig, "{");
    bindingConfig = StringUtils.removeEnd(bindingConfig, "}");
    String[] entries = bindingConfig.split("[,]");
    AstroBindingConfigHelper helper = new AstroBindingConfigHelper();

    for (String entry : entries) {
        String[] entryParts = StringUtils.trimToEmpty(entry).split("[=]");
        if (entryParts.length != 2) {
            throw new BindingConfigParseException("A bindingConfig must have a key and a value");
        }
        String key = StringUtils.trim(entryParts[0]);

        String value = StringUtils.trim(entryParts[1]);
        value = StringUtils.removeStart(value, "\"");
        value = StringUtils.removeEnd(value, "\"");

        try {
            if ("offset".equalsIgnoreCase(key)) {
                helper.getClass().getDeclaredField(key).set(helper, Integer.valueOf(value.toString()));
            } else {
                helper.getClass().getDeclaredField(key).set(helper, value);
            }
        } catch (Exception e) {
            throw new BindingConfigParseException("Could not set value " + value + " for attribute " + key);
        }
    }

    if (helper.isOldStyle()) {
        logger.warn(
                "Old Astro binding style for item {}, please see Wiki page for new style: https://github.com/openhab/openhab/wiki/Astro-binding",
                item.getName());
        return getOldAstroBindingConfig(helper);
    }

    if (!helper.isValid()) {
        throw new BindingConfigParseException("Invalid binding: " + bindingConfig);
    }

    PlanetName planetName = getPlanetName(helper);
    if (planetName == null) {
        throw new BindingConfigParseException("Invalid binding, unknown planet: " + bindingConfig);
    }

    AstroBindingConfig astroConfig = new AstroBindingConfig(planetName, helper.type, helper.property,
            helper.offset);

    if (!PropertyUtils.hasProperty(context.getPlanet(astroConfig.getPlanetName()),
            astroConfig.getPlanetProperty())) {
        throw new BindingConfigParseException("Invalid binding, unknown type or property: " + bindingConfig);
    }
    return astroConfig;
}
 
Example 19
Source File: ConstraintStateUtils.java    From rice with Educational Community License v2.0 4 votes vote down vote up
/**
 * Determines if the constraint passed in applies for the applicableState, based on the stateMapping
 *
 * <p>Note: this method will automatically return TRUE if the stateMapping is null, the Constraint is not a BaseConstraint,
 * if there are no states defined on the Constraint, or if the state it applies to cannot be found in the stateMapping,
 * because in all these cases the Constraint is considered
 * stateless and will apply to any state</p>
 *
 * @param applicableState the state to check to see if the constraint applies
 * @param constraint the Constraint to check
 * @param stateMapping the StateMapping object containing state information
 * @return true if the Constraint applies to the applicableState, false otherwise
 */
public static boolean constraintAppliesForState(String applicableState, Constraint constraint,
        StateMapping stateMapping) {
    List<String> stateOrder = new ArrayList<String>();
    if (stateMapping != null) {
        stateOrder = stateMapping.getStates();
    }

    if (stateMapping == null || !(constraint instanceof BaseConstraint) || StringUtils.isEmpty(applicableState)) {
        //process constraint because it is considered "stateless" if not a BaseConstraint
        //or no associated state mapping or no has no state to compare to
        return true;
    } else if (((BaseConstraint) constraint).getStates() == null || ((BaseConstraint) constraint).getStates()
            .isEmpty()) {
        //simple case - no states for this constraint, so always apply
        return true;
    } else if (((BaseConstraint) constraint).getStates().contains(applicableState) && stateOrder.contains(
            applicableState)) {
        //constraint applies for the applicableState and the state exists for the object
        return true;
    } else {
        for (String constraintState : ((BaseConstraint) constraint).getStates()) {
            //range case
            if (constraintState.contains(">")) {
                String[] rangeArray = constraintState.split(">");
                if (rangeArray[1].endsWith("+")) {
                    //make 2nd part of range current state being checked if nothing is
                    //matched below for the range case
                    constraintState = rangeArray[1];
                    rangeArray[1] = StringUtils.removeEnd(rangeArray[1], "+");
                }
                if (stateOrder.contains(rangeArray[0]) && stateOrder.contains(rangeArray[1])) {
                    for (int i = stateOrder.indexOf(rangeArray[0]); i <= stateOrder.indexOf(rangeArray[1]); i++) {
                        if (stateOrder.get(i).equals(applicableState)) {
                            return true;
                        }
                    }
                } else {
                    throw new RuntimeException("Invalid state range: " + constraintState);
                }
            }

            //+ case (everything after and including this state)
            if (constraintState.contains("+")) {
                constraintState = StringUtils.removeEnd(constraintState, "+");
                if (stateOrder.contains(constraintState)) {
                    for (int i = stateOrder.indexOf(constraintState); i < stateOrder.size(); i++) {
                        if (stateOrder.get(i).equals(applicableState)) {
                            return true;
                        }
                    }
                } else {
                    throw new RuntimeException("Invalid constraint state: " + constraintState);
                }
            }
        }
    }
    //if no case is matched, return false
    return false;
}
 
Example 20
Source File: JavaCartridgeAgentTest.java    From attic-stratos with Apache License 2.0 2 votes vote down vote up
/**
 * Get current folder path
 *
 * @return
 */
private static String getResourcesFolderPath() {
    return StringUtils.removeEnd(JavaCartridgeAgentTest.class.getResource("/").getPath(), File.separator);
}