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

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

Introduction

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

Prototype

public static String substring(final String str, int start) 

Source Link

Document

Gets a substring from the specified String avoiding exceptions.

A negative start position can be used to start n characters from the end of the String.

A null String will return null .

Usage

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

/**
 * /*from w w  w.ja  va 2s . c o m*/
 */
@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.dgtlrepublic.anitomyj.Parser.java

/** Search for anime keywords. */
private void searchForKeywords() {
    for (int i = 0; i < tokens.size(); i++) {
        Token token = tokens.get(i);//from  w  w  w . ja v a  2 s  .c o m
        if (token.getCategory() != kUnknown)
            continue;

        String word = token.getContent();
        word = StringHelper.trimAny(word, " -");
        if (word.isEmpty())
            continue;

        // Don't bother if the word is a number that cannot be CRC
        if (word.length() != 8 && StringHelper.isNumericString(word))
            continue;

        String keyword = KeywordManager.normalzie(word);
        AtomicReference<ElementCategory> category = new AtomicReference<>(kElementUnknown);
        AtomicReference<KeywordOptions> options = new AtomicReference<>(new KeywordOptions());

        if (KeywordManager.getInstance().findAndSet(keyword, category, options)) {
            if (!this.options.parseReleaseGroup && category.get() == kElementReleaseGroup)
                continue;
            if (!ParserHelper.isElementCategorySearchable(category.get()) || !options.get().isSearchable())
                continue;
            if (ParserHelper.isElementCategorySingular(category.get()) && !empty(category.get()))
                continue;
            if (category.get() == kElementAnimeSeasonPrefix) {
                parserHelper.checkAndSetAnimeSeasonKeyword(token, i);
                continue;
            } else if (category.get() == kElementEpisodePrefix) {
                if (options.get().isValid()) {
                    parserHelper.checkExtentKeyword(kElementEpisodeNumber, i, token);
                    continue;
                }
            } else if (category.get() == kElementReleaseVersion) {
                word = StringUtils.substring(word, 1);
            } else if (category.get() == kElementVolumePrefix) {
                parserHelper.checkExtentKeyword(kElementVolumeNumber, i, token);
                continue;
            }
        } else {
            if (empty(kElementFileChecksum) && ParserHelper.isCrc32(word)) {
                category.set(kElementFileChecksum);
            } else if (empty(kElementVideoResolution) && ParserHelper.isResolution(word)) {
                category.set(kElementVideoResolution);
            }
        }

        if (category.get() != kElementUnknown) {
            elements.add(new Element(category.get(), word));
            if (options.get() != null && options.get().isIdentifiable()) {
                token.setCategory(kIdentifier);
            }
        }
    }
}

From source file:com.mirth.connect.plugins.datatypes.hl7v2.HL7v2ResponseValidator.java

@Override
public Response validate(Response response, ConnectorMessage connectorMessage) {
    HL7v2ResponseValidationProperties responseValidationProperties = getReplacedResponseValidationProperties(
            connectorMessage);/*from   ww w .  j a  v  a2s  .  c o m*/
    String[] successfulACKCodes = StringUtils.split(responseValidationProperties.getSuccessfulACKCode(), ',');
    String[] errorACKCodes = StringUtils.split(responseValidationProperties.getErrorACKCode(), ',');
    String[] rejectedACKCodes = StringUtils.split(responseValidationProperties.getRejectedACKCode(), ',');
    boolean validateMessageControlId = responseValidationProperties.isValidateMessageControlId();

    String responseData = response.getMessage();

    if (StringUtils.isNotBlank(responseData)) {
        try {
            if (responseData.trim().startsWith("<")) {
                // XML response received
                Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                        .parse(new InputSource(new CharArrayReader(responseData.toCharArray())));
                String ackCode = XPathFactory.newInstance().newXPath().compile("//MSA.1/text()").evaluate(doc)
                        .trim();

                boolean rejected = Arrays.asList(rejectedACKCodes).contains(ackCode);
                boolean error = rejected || Arrays.asList(errorACKCodes).contains(ackCode);

                if (error || rejected) {
                    String msa3 = StringUtils.trim(
                            XPathFactory.newInstance().newXPath().compile("//MSA.3/text()").evaluate(doc));
                    String err1 = StringUtils.trim(
                            XPathFactory.newInstance().newXPath().compile("//ERR.1/text()").evaluate(doc));
                    handleNACK(response, rejected, msa3, err1);
                } else if (Arrays.asList(successfulACKCodes).contains(ackCode)) {
                    if (validateMessageControlId) {
                        String msa2 = StringUtils.trim(
                                XPathFactory.newInstance().newXPath().compile("//MSA.2/text()").evaluate(doc));
                        String originalControlID = getOriginalControlId(connectorMessage);

                        if (!StringUtils.equals(msa2, originalControlID)) {
                            handleInvalidControlId(response, originalControlID, msa2);
                        } else {
                            response.setStatus(Status.SENT);
                        }
                    } else {
                        response.setStatus(Status.SENT);
                    }
                }
            } else {
                // ER7 response received
                if (serializationProperties.isConvertLineBreaks()) {
                    responseData = StringUtil.convertLineBreaks(responseData, serializationSegmentDelimiter);
                }

                int index = -1;
                boolean valid = true;

                // Attempt to find the MSA segment using the segment delimiters in the serialization properties
                if ((index = responseData.indexOf(serializationSegmentDelimiter + "MSA")) >= 0) {
                    // MSA found; add the length of the segment delimiter, MSA, and field separator to get to the index of MSA.1
                    index += serializationSegmentDelimiter.length() + 4;

                    if (index < responseData.length()) {
                        boolean rejected = startsWithAny(responseData, rejectedACKCodes, index);
                        boolean error = rejected || startsWithAny(responseData, errorACKCodes, index);

                        char fieldSeparator = responseData.charAt(index - 1);
                        if (error || rejected) {
                            String msa3 = null;
                            String err1 = null;

                            // Index of MSA.2
                            index = responseData.indexOf(fieldSeparator, index);
                            if (index >= 0) {
                                // Index of MSA.3
                                index = responseData.indexOf(fieldSeparator, index + 1);
                                if (index >= 0) {
                                    // Find the next index of either the field separator or segment delimiter, and then the resulting substring
                                    String tempSegment = StringUtils.substring(responseData, index + 1);
                                    index = StringUtils.indexOfAny(tempSegment,
                                            fieldSeparator + serializationSegmentDelimiter);

                                    if (index >= 0) {
                                        msa3 = StringUtils.substring(tempSegment, 0, index);
                                    } else {
                                        msa3 = StringUtils.substring(tempSegment, 0);
                                    }
                                }
                            }

                            if ((index = responseData.indexOf(serializationSegmentDelimiter + "ERR")) >= 0) {
                                // ERR found; add the length of the segment delimiter, ERR, and field separator to get to the index of ERR.1
                                index += serializationSegmentDelimiter.length() + 4;
                                // Find the next index of either the field separator or segment delimiter, and then the resulting substring
                                String tempSegment = StringUtils.substring(responseData, index);
                                index = StringUtils.indexOfAny(tempSegment,
                                        fieldSeparator + serializationSegmentDelimiter);

                                if (index >= 0) {
                                    err1 = StringUtils.substring(tempSegment, 0, index);
                                } else {
                                    err1 = StringUtils.substring(tempSegment, 0);
                                }
                            }

                            handleNACK(response, rejected, msa3, err1);
                        } else if (startsWithAny(responseData, successfulACKCodes, index)) {
                            if (validateMessageControlId) {
                                String msa2 = "";
                                index = responseData.indexOf(fieldSeparator, index);

                                if (index >= 0) {
                                    String tempSegment = StringUtils.substring(responseData, index + 1);
                                    index = StringUtils.indexOfAny(tempSegment,
                                            fieldSeparator + serializationSegmentDelimiter);

                                    if (index >= 0) {
                                        msa2 = StringUtils.substring(tempSegment, 0, index);
                                    } else {
                                        msa2 = StringUtils.substring(tempSegment, 0);
                                    }
                                }
                                String originalControlID = getOriginalControlId(connectorMessage);

                                if (!StringUtils.equals(msa2, originalControlID)) {
                                    handleInvalidControlId(response, originalControlID, msa2);
                                } else {
                                    response.setStatus(Status.SENT);
                                }
                            } else {
                                response.setStatus(Status.SENT);
                            }
                        } else {
                            valid = false;
                        }
                    } else {
                        valid = false;
                    }
                } else {
                    valid = false;
                }

                if (!valid) {
                    response.setStatus(Status.QUEUED);
                    response.setStatusMessage("Invalid HL7 v2.x acknowledgement received.");
                    response.setError(response.getStatusMessage());
                }
            }
        } catch (Exception e) {
            response.setStatus(Status.QUEUED);
            response.setStatusMessage("Error validating response: " + e.getMessage());
            response.setError(ErrorMessageBuilder.buildErrorMessage(this.getClass().getSimpleName(),
                    response.getStatusMessage(), e));
        }
    } else {
        response.setStatus(Status.QUEUED);
        response.setStatusMessage("Empty or blank response received.");
        response.setError(response.getStatusMessage());
    }

    return response;
}

From source file:ch.cyberduck.core.b2.B2SearchFeatureTest.java

@Test
public void testSearchInDirectory() throws Exception {
    final B2Session session = new B2Session(new Host(new B2Protocol(), new B2Protocol().getDefaultHostname(),
            new Credentials(System.getProperties().getProperty("b2.user"),
                    System.getProperties().getProperty("b2.key"))));
    final LoginConnectionService service = new LoginConnectionService(new DisabledLoginCallback(),
            new DisabledHostKeyCallback(), new DisabledPasswordStore(), new DisabledProgressListener());
    service.connect(session, PathCache.empty(), new DisabledCancelCallback());
    final String name = new AlphanumericRandomStringService().random();
    final Path bucket = new Path("test-cyberduck", EnumSet.of(Path.Type.directory, Path.Type.volume));
    final Path workdir = new B2DirectoryFeature(session).mkdir(new Path(bucket,
            new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory, Path.Type.volume)),
            null, new TransferStatus());
    final Path file = new B2TouchFeature(session).touch(new Path(workdir, name, EnumSet.of(Path.Type.file)),
            new TransferStatus());
    final B2SearchFeature feature = new B2SearchFeature(session);
    assertNotNull(feature.search(workdir, new SearchFilter(name), new DisabledListProgressListener())
            .find(new SimplePathPredicate(file)));
    // Supports prefix matching only
    assertNull(feature.search(workdir, new SearchFilter(StringUtils.substring(name, 2)),
            new DisabledListProgressListener()).find(new SimplePathPredicate(file)));
    {//from ww w .ja  v  a 2s. co  m
        final AttributedList<Path> result = feature.search(workdir,
                new SearchFilter(StringUtils.substring(name, 0, name.length() - 2)),
                new DisabledListProgressListener());
        assertNotNull(result.find(new SimplePathPredicate(file)));
        assertEquals(workdir, result.get(result.indexOf(file)).getParent());
    }
    final Path subdir = new B2DirectoryFeature(session).mkdir(
            new Path(workdir, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory)),
            null, new TransferStatus());
    assertNull(feature.search(subdir, new SearchFilter(name), new DisabledListProgressListener())
            .find(new SimplePathPredicate(file)));
    final Path filesubdir = new B2TouchFeature(session).touch(
            new Path(subdir, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file)),
            new TransferStatus());
    {
        final AttributedList<Path> result = feature.search(workdir, new SearchFilter(filesubdir.getName()),
                new DisabledListProgressListener());
        assertNotNull(result.find(new SimplePathPredicate(filesubdir)));
        assertEquals(subdir, result.find(new SimplePathPredicate(filesubdir)).getParent());
    }
    new B2DeleteFeature(session).delete(Arrays.asList(file, filesubdir, subdir), new DisabledLoginCallback(),
            new Delete.DisabledCallback());
    session.close();
}

From source file:com.sinosoft.one.data.jade.statement.SelectQuerier.java

private String parseCountSql(String sql) {
    //      sql = StringUtils.lowerCase(sql);
    int end = StringUtils.indexOf(sql.toLowerCase(), "from");
    String s = StringUtils.substring(sql, end);
    return "select count(1) " + s;
}

From source file:com.chenyang.proxy.http.HttpUserAgentForwardHandler.java

private String getPartialUrl(String fullUrl) {
    if (StringUtils.startsWith(fullUrl, "http")) {
        int idx = StringUtils.indexOf(fullUrl, "/", 7);
        return idx == -1 ? "/" : StringUtils.substring(fullUrl, idx);
    }/* w  w  w. j a v a 2s  .co m*/

    return fullUrl;
}

From source file:com.lzsoft.rules.core.RulesEngine.java

private List<Object> filterconditionElmt(List<?> objs, ConditionElmt conditionElmt)
        throws Exception, IllegalAccessException, InvocationTargetException, NoSuchMethodException {
    List<Object> conditionRuleResults;
    conditionRuleResults = filterUnderConditionHavntParameter(objs, conditionElmt);
    /**/*from w  ww  .  ja  v a2  s.  c  o m*/
     * After performing the all rule-invoke elementsif the result is null
     * ,then goto the next condition.
     */
    if (!conditionRuleResults.isEmpty()) {

        if (null != conditionElmt.getParameter() && !"".equals(conditionElmt.getParameter())) {//
            String parameterValue = conditionElmt.getParameter();
            String[] paras;
            if (parameterValue.startsWith("@")) {
                paras = StringUtils.split(StringUtils.substring(parameterValue, 2), ":");
                for (String para : paras) {
                    conditionRuleResults = filterResultsByParameterValue(conditionRuleResults, conditionElmt,
                            para);
                }

            } else {
                conditionRuleResults = filterResultsByParameterValue(conditionRuleResults, conditionElmt,
                        parameterValue);
            }
        }
    }
    return conditionRuleResults;
}

From source file:io.lavagna.web.security.PathConfiguration.java

private static String findSubpath(HttpServletRequest req, String firstPath) {
    return StringUtils.substringBefore(StringUtils.substring(req.getServletPath(), firstPath.length() + 1),
            "/");
}

From source file:com.ejisto.modules.dao.db.EmbeddedDatabaseManager.java

private static String decodeContextPath(String encoded) {
    return StringUtils.substring(encoded, CONTEXT_PATH_PREFIX.length());
}

From source file:com.gargoylesoftware.htmlunit.javascript.host.event.EventTarget.java

/**
 * Returns {@code true} if there are any event handlers for the specified event.
 * @param eventName the event name (e.g. "onclick")
 * @return {@code true} if there are any event handlers for the specified event, {@code false} otherwise
 *///from  w  w w. ja va 2s .c  o m
public boolean hasEventHandlers(final String eventName) {
    if (eventListenersContainer_ == null) {
        return false;
    }
    return eventListenersContainer_.hasEventHandlers(StringUtils.substring(eventName, 2));
}