Example usage for org.apache.commons.lang3 StringUtils removeStart

List of usage examples for org.apache.commons.lang3 StringUtils removeStart

Introduction

In this page you can find the example usage for org.apache.commons.lang3 StringUtils removeStart.

Prototype

public static String removeStart(final String str, final String remove) 

Source Link

Document

Removes a substring only if it is at the beginning of a source string, otherwise returns the source string.

A null source string will return null .

Usage

From source file:com.github.umeshawasthi.struts2.jsr303.validation.interceptor.JSR303ValidationInterceptor.java

protected ValidationError buildBeanValidationError(ConstraintViolation<Object> violation, String message,
        Object action) {// w  ww.  java 2s.  co m

    if (violation.getPropertyPath().iterator().next().getName() != null) {
        String fieldName = violation.getPropertyPath().toString();
        String finalMessage = StringUtils.removeStart(message, fieldName + ValidatorConstants.FIELD_SEPERATOR);
        return new ValidationError(fieldName, finalMessage);
    }

    return null;

}

From source file:com.amazonaws.service.apigateway.importer.impl.sdk.ApiGatewaySdkApiImporter.java

private String trimSlashes(String path) {
    return StringUtils.removeEnd(StringUtils.removeStart(path, "/"), "/");
}

From source file:ke.co.tawi.babblesms.server.sendsms.tawismsgw.PostSMS.java

/**
 * /*w w  w.j a  v a 2s  .com*/
 */
@Override
public void run() {
    HttpEntity responseEntity = null;
    Map<String, String> params;

    if (urlValidator.isValid(smsGateway.getUrl())) {

        // Prepare the parameters to send
        params = new HashMap<>();

        params.put("username", smsGateway.getUsername());
        params.put("password", smsGateway.getPasswd());
        params.put("source", smsSource.getSource());
        params.put("message", message);

        switch (smsSource.getNetworkuuid()) {
        case Network.SAFARICOM_KE:
            params.put("network", "safaricom_ke");
            break;

        case Network.AIRTEL_KE:
            params.put("network", "safaricom_ke"); // TODO: change to airtel_ke
            break;
        }

        // When setting the destination, numbers beginning with '07' are edited
        // to begin with '254'
        phoneMap = new HashMap<>();
        StringBuffer phoneBuff = new StringBuffer();
        String phoneNum;

        for (Phone phone : phoneList) {
            phoneNum = phone.getPhonenumber();

            if (StringUtils.startsWith(phoneNum, "07")) {
                phoneNum = "254" + StringUtils.substring(phoneNum, 1);
            }

            phoneMap.put(phoneNum, phone);
            phoneBuff.append(phoneNum).append(";");
        }

        params.put("destination", StringUtils.removeEnd(phoneBuff.toString(), ";"));

        // Push to the URL
        try {
            URL url = new URL(smsGateway.getUrl());

            if (StringUtils.equalsIgnoreCase(url.getProtocol(), "http")) {
                responseEntity = doPost(smsGateway.getUrl(), params, retry);

            }
            //            else if(StringUtils.equalsIgnoreCase(url.getProtocol(), "https")) {
            //               doPostSecure(smsGateway.getUrl(), params, retry);
            //            }

        } catch (MalformedURLException e) {
            logger.error("MalformedURLException for URL: '" + smsGateway.getUrl() + "'");
            logger.error(ExceptionUtils.getStackTrace(e));
        }
    } // end 'if(urlValidator.isValid(urlStr))'

    // Process the response from the SMS Gateway
    // Assuming all is ok, it would have the following pattern:
    // requestStatus=ACCEPTED&messageIds=254726176878:b265ce23;254728932844:367941a36d2e4ef195;254724300863:11fca3c5966d4d
    if (responseEntity != null) {

        OutgoingLog outgoingLog;

        try {
            String response = EntityUtils.toString(responseEntity);
            GatewayDAO.getInstance().logResponse(account, response, new Date());

            String[] strTokens = StringUtils.split(response, '&');
            String tmpStr = "", dateStr = "";
            for (String str : strTokens) {
                if (StringUtils.startsWith(str, "messageIds")) {
                    tmpStr = StringUtils.removeStart(str, "messageIds=");
                } else if (StringUtils.startsWith(str, "datetime")) {
                    dateStr = StringUtils.removeStart(str, "datetime=");
                }
            }

            strTokens = StringUtils.split(tmpStr, ';');
            String phoneStr, uuid;
            Phone phone;
            DateTimeFormatter timeFormatter = ISODateTimeFormat.dateTimeNoMillis();

            for (String str : strTokens) {
                phoneStr = StringUtils.split(str, ':')[0];
                uuid = StringUtils.split(str, ':')[1];
                phone = phoneMap.get(phoneStr);

                outgoingLog = new OutgoingLog();
                outgoingLog.setUuid(uuid);
                outgoingLog.setOrigin(smsSource.getSource());
                outgoingLog.setMessage(message);
                outgoingLog.setDestination(phone.getPhonenumber());
                outgoingLog.setNetworkUuid(phone.getNetworkuuid());
                outgoingLog.setMessagestatusuuid(MsgStatus.SENT);
                outgoingLog.setSender(account.getUuid());
                outgoingLog.setPhoneUuid(phone.getUuid());

                // Set the date of the OutgoingLog to match the SMS Gateway time

                LocalDateTime datetime = timeFormatter.parseLocalDateTime(dateStr);
                outgoingLog.setLogTime(datetime.toDate());

                outgoingLogDAO.put(outgoingLog);
            }

        } catch (ParseException e) {
            logger.error("ParseException when reading responseEntity");
            logger.error(ExceptionUtils.getStackTrace(e));

        } catch (IOException e) {
            logger.error("IOException when reading responseEntity");
            logger.error(ExceptionUtils.getStackTrace(e));
        }
    }
}

From source file:com.thoughtworks.go.util.FileUtil.java

public static String subtractPath(File rootPath, File file) {
    String fullPath = FilenameUtils.separatorsToUnix(file.getParentFile().getPath());
    String basePath = FilenameUtils.separatorsToUnix(rootPath.getPath());
    return StringUtils.removeStart(StringUtils.removeStart(fullPath, basePath), "/");
}

From source file:de.doering.dwca.arkive.ChecklistBuilder.java

private Image parseHtml(String html) {
    Matcher m = imgParser.matcher(html);
    if (m.find()) {
        Image img = new Image();
        img.setLink(m.group(1));/*from   w  w w.  j a  v a  2s  . co m*/
        img.setTitle(StringUtils.removeStart(m.group(2), "ARKive image - "));
        img.setImage(thumbnailToImageUrl(m.group(3)));
        return img;
    }

    return null;
}

From source file:com.thruzero.common.core.infonode.builder.TokenStreamInfoNodeBuilder.java

protected InfoNodeElement initLeafNode(final String tokenStream, final String separator,
        final InfoNodeElement targetNode) {
    // TODO-p1(george) Rewrite this using RegEx
    String attributeStream = StringUtils.substringBetween(tokenStream, "[@", "]");
    String elementName;// w ww .ja v a  2 s  .  c  o  m
    String elementValue;

    // handle the attributes
    if (StringUtils.isEmpty(attributeStream)) {
        elementName = StringUtils.trimToNull(StringUtils.substringBefore(tokenStream, "="));
        elementValue = StringUtils.trimToNull(StringUtils.substringAfter(tokenStream, "="));
    } else {
        StringTokenizer st1 = new StringTokenizer(attributeStream, separator);

        while (st1.hasMoreTokens()) {
            String attributeSpec = st1.nextToken();
            StringTokenizer st2 = new StringTokenizer(attributeSpec, "=");

            if (!st2.hasMoreTokens()) {
                throw new TokenStreamException(
                        "Malformed Token Stream (missing attribute name and value): " + tokenStream);
            }
            String attributeName = StringUtils.removeStart(st2.nextToken().trim(), "@");

            String attributeValue = null;
            if (st2.hasMoreTokens()) {
                attributeValue = trimQuotes(st2.nextToken().trim());
            }

            if (StringUtils.isEmpty(attributeValue)) {
                throw new TokenStreamException(
                        "Malformed Token Stream (missing attribute value): " + tokenStream);
            }

            targetNode.setAttribute(attributeName, attributeValue);
        }

        elementName = StringUtils.trimToNull(StringUtils.substringBefore(tokenStream, "["));
        elementValue = StringUtils.trimToNull(StringUtils.substringAfter(tokenStream, "]"));
    }

    // set the element name
    if (elementName == null) {
        throw new TokenStreamException("Malformed Token Stream (missing element name): " + tokenStream);
    }
    targetNode.setName(elementName);

    // set the element value
    if (elementValue != null) {
        elementValue = StringUtils.removeStart(elementValue, "=");
        targetNode.setText(elementValue);
    }

    return targetNode;
}

From source file:info.magnolia.security.setup.migration.MoveAclPermissionsBetweenWorkspaces.java

/**
 * Iterate the subPaths list and try to found a valid one.
 *
 * @return the first valid path found or null otherwise.
 *///from  w w w. j  av  a2 s. c  om
private String getValidPathWithSubPath(Session targetSession, String originalPath) throws RepositoryException {
    for (String subPath : subPaths) {
        String migratedPath = PathUtil.createPath(StringUtils.removeEnd(subPath, "/"),
                StringUtils.removeStart(originalPath, "/"));
        log.debug("Check if the following migrated path exist {}", migratedPath);
        if (targetSession.itemExists(migratedPath)) {
            return migratedPath;
        }
    }
    return null;
}

From source file:annis.libgui.Helper.java

/**
 * Parses the fragment./*  www  .j  a  va2  s. c  o m*/
 * 
 * Fragments have the form key1=value&key2=test ...
 * @param fragment
 * @return 
 */
public static Map<String, String> parseFragment(String fragment) {
    Map<String, String> result = new TreeMap<String, String>();

    fragment = StringUtils.removeStart(fragment, "!");

    String[] split = StringUtils.split(fragment, "&");
    for (String s : split) {
        String[] parts = s.split("=", 2);
        String name = parts[0].trim();
        String value = "";
        if (parts.length == 2) {
            try {
                // every name that starts with "_" is base64 encoded
                if (name.startsWith("_")) {
                    value = new String(Base64.decodeBase64(parts[1]), "UTF-8");
                } else {
                    value = URLDecoder.decode(parts[1], "UTF-8");
                }
            } catch (UnsupportedEncodingException ex) {
                log.error(ex.getMessage(), ex);
            }
        }
        name = StringUtils.removeStart(name, "_");

        result.put(name, value);
    }
    return result;
}

From source file:com.thruzero.common.core.infonode.builder.TokenStreamInfoNodeBuilder.java

/** Remove single quotes from start and end of the given string. */
private String trimQuotes(String value) {
    // TODO-p1(george) Rewrite this using RegEx
    value = StringUtils.trimToNull(value);
    value = StringUtils.removeStart(value, "'");
    value = StringUtils.removeStart(value, "\"");
    value = StringUtils.removeEnd(value, "'");
    value = StringUtils.removeEnd(value, "\"");

    return value;
}

From source file:it.attocchi.utils.jdbc.QueryBuilderSqlServer.java

/**
 * Supporta la ricerca str* *str str che corrisponde a like %%
 * //from  ww  w . j a  va2 s  . c  o  m
 * @param campo
 * @param semeRicerca
 * @return
 */
public static String likeSimple(String campo, String semeRicerca) {
    StringBuilder res = new StringBuilder();

    if (semeRicerca.startsWith(QueryBuilderSqlServer.RICERCA_STRING_CHAR)
            && semeRicerca.endsWith(QueryBuilderSqlServer.RICERCA_STRING_CHAR)) {
        /* CASO "ciao" */
        semeRicerca = StringUtils.removeStart(semeRicerca, QueryBuilderSqlServer.RICERCA_STRING_CHAR);
        semeRicerca = StringUtils.removeEnd(semeRicerca, QueryBuilderSqlServer.RICERCA_STRING_CHAR);

        res.append(campo + " = '" + encodeStringSQL(semeRicerca) + "'");
    } else if (semeRicerca.endsWith(QueryBuilderSqlServer.RICERCA_JOLLY_CHAR)) {
        /* CASO ciao* */
        semeRicerca = semeRicerca.replace(QueryBuilderSqlServer.RICERCA_JOLLY_CHAR, "");

        res.append(campo + " LIKE '" + encodeStringSQL(semeRicerca) + "%'");
    } else if (semeRicerca.startsWith(QueryBuilderSqlServer.RICERCA_JOLLY_CHAR)) {
        /* CASO *ciao */
        semeRicerca = semeRicerca.replace(QueryBuilderSqlServer.RICERCA_JOLLY_CHAR, "");

        res.append(campo + " LIKE '%" + encodeStringSQL(semeRicerca) + "'");
    } else {
        /* CASO ciao */
        res.append(campo + " LIKE '%" + encodeStringSQL(semeRicerca) + "%'");
    }

    return res.toString();
}