Example usage for org.apache.commons.lang StringUtils indexOf

List of usage examples for org.apache.commons.lang StringUtils indexOf

Introduction

In this page you can find the example usage for org.apache.commons.lang StringUtils indexOf.

Prototype

public static int indexOf(String str, String searchStr) 

Source Link

Document

Finds the first index within a String, handling null.

Usage

From source file:info.magnolia.cms.core.MetaData.java

/**
 * get property name with the prefix/*from w w w .j  av a2s  .co  m*/
 *
 * @param name
 * @return name with namespace prefix
 */
private String getInternalPropertyName(String name) {
    if (StringUtils.indexOf(name, ContentRepository.NAMESPACE_PREFIX + ":") != 0) {
        return ContentRepository.NAMESPACE_PREFIX + ":" + name;
    }
    return name;
}

From source file:com.mirth.connect.connectors.smtp.SmtpMessageDispatcher.java

@Override
public void doDispatch(UMOEvent event) throws Exception {
    monitoringController.updateStatus(connector, connectorType, Event.BUSY);
    MessageObject mo = messageObjectController.getMessageObjectFromEvent(event);

    if (mo == null) {
        return;//from   w  w  w.  ja  v  a2 s  .  c  o m
    }

    try {
        Email email = null;

        if (connector.isHtml()) {
            email = new HtmlEmail();
        } else {
            email = new MultiPartEmail();
        }

        email.setCharset(connector.getCharsetEncoding());

        email.setHostName(replacer.replaceValues(connector.getSmtpHost(), mo));

        try {
            email.setSmtpPort(Integer.parseInt(replacer.replaceValues(connector.getSmtpPort(), mo)));
        } catch (NumberFormatException e) {
            // Don't set if the value is invalid
        }

        try {
            email.setSocketConnectionTimeout(
                    Integer.parseInt(replacer.replaceValues(connector.getTimeout(), mo)));
        } catch (NumberFormatException e) {
            // Don't set if the value is invalid
        }

        if ("SSL".equalsIgnoreCase(connector.getEncryption())) {
            email.setSSL(true);
        } else if ("TLS".equalsIgnoreCase(connector.getEncryption())) {
            email.setTLS(true);
        }

        if (connector.isAuthentication()) {
            email.setAuthentication(replacer.replaceValues(connector.getUsername(), mo),
                    replacer.replaceValues(connector.getPassword(), mo));
        }

        /*
         * NOTE: There seems to be a bug when calling setTo with a List
         * (throws a java.lang.ArrayStoreException), so we are using addTo
         * instead.
         */

        for (String to : replaceValuesAndSplit(connector.getTo(), mo)) {
            email.addTo(to);
        }

        // Currently unused
        for (String cc : replaceValuesAndSplit(connector.cc(), mo)) {
            email.addCc(cc);
        }

        // Currently unused
        for (String bcc : replaceValuesAndSplit(connector.getBcc(), mo)) {
            email.addBcc(bcc);
        }

        // Currently unused
        for (String replyTo : replaceValuesAndSplit(connector.getReplyTo(), mo)) {
            email.addReplyTo(replyTo);
        }

        for (Entry<String, String> header : connector.getHeaders().entrySet()) {
            email.addHeader(replacer.replaceValues(header.getKey(), mo),
                    replacer.replaceValues(header.getValue(), mo));
        }

        email.setFrom(replacer.replaceValues(connector.getFrom(), mo));
        email.setSubject(replacer.replaceValues(connector.getSubject(), mo));

        String body = replacer.replaceValues(connector.getBody(), mo);

        if (connector.isHtml()) {
            ((HtmlEmail) email).setHtmlMsg(body);
        } else {
            email.setMsg(body);
        }

        /*
         * If the MIME type for the attachment is missing, we display a
         * warning and set the content anyway. If the MIME type is of type
         * "text" or "application/xml", then we add the content. If it is
         * anything else, we assume it should be Base64 decoded first.
         */
        for (Attachment attachment : connector.getAttachments()) {
            String name = replacer.replaceValues(attachment.getName(), mo);
            String mimeType = replacer.replaceValues(attachment.getMimeType(), mo);
            String content = replacer.replaceValues(attachment.getContent(), mo);

            byte[] bytes;

            if (StringUtils.indexOf(mimeType, "/") < 0) {
                logger.warn("valid MIME type is missing for email attachment: \"" + name
                        + "\", using default of text/plain");
                attachment.setMimeType("text/plain");
                bytes = content.getBytes();
            } else if ("application/xml".equalsIgnoreCase(mimeType)
                    || StringUtils.startsWith(mimeType, "text/")) {
                logger.debug("text or XML MIME type detected for attachment \"" + name + "\"");
                bytes = content.getBytes();
            } else {
                logger.debug("binary MIME type detected for attachment \"" + name
                        + "\", performing Base64 decoding");
                bytes = Base64.decodeBase64(content);
            }

            ((MultiPartEmail) email).attach(new ByteArrayDataSource(bytes, mimeType), name, null);
        }

        /*
         * From the Commons Email JavaDoc: send returns
         * "the message id of the underlying MimeMessage".
         */
        String response = email.send();
        messageObjectController.setSuccess(mo, response, null);
    } catch (EmailException e) {
        alertController.sendAlerts(connector.getChannelId(), Constants.ERROR_402,
                "Error sending email message.", e);
        messageObjectController.setError(mo, Constants.ERROR_402, "Error sending email message.", e, null);
        connector.handleException(new Exception(e));
    } finally {
        monitoringController.updateStatus(connector, connectorType, Event.DONE);
    }
}

From source file:gnete.card.web.merch.MerchAction.java

@Override
public String execute() throws Exception {
    this.statusList = MerchState.getWithOutCheck();
    this.yesOrNoFlagList = YesOrNoFlag.getAll();

    Map<String, Object> params = new HashMap<String, Object>();

    boolean isUserOfLimitedTransQuery = isUserOfLimitedTransQuery();
    if (isUserOfLimitedTransQuery) {
        params.put("isUserOfLimitedTransQuery", isUserOfLimitedTransQuery);
        params.put("limitedExcludeManageBranchCodes",
                UserOfLimitedTransQueryUtil.getExcludeManageBranchCodes());
    }//from www.  ja va2 s.c  om

    if (merchInfo != null) {
        String type = merchInfo.getMerchType();
        if (CommonHelper.isNotEmpty(type)) {
            type = StringUtils.substring(type, 0, StringUtils.indexOf(type, "|"));
        }
        params.put("merchId", merchInfo.getMerchId());
        params.put("merchName", MatchMode.ANYWHERE.toMatchString(merchInfo.getMerchName()));
        params.put("cardBranchCode", cardBranchCode);// ??-
        params.put("manageBranch", merchInfo.getManageBranch());
        params.put("status", merchInfo.getStatus());
        params.put("merchType", type);
        params.put("singleProduct", merchInfo.getSingleProduct());
        DatePair datePair = new DatePair(this.startDate, this.endDate);
        datePair.setTruncatedTimeDate(params);
    }
    if (CommonHelper.isNotEmpty(checkStartDate)) {
        Date otherSDate = DateUtil.formatDate(checkStartDate, "yyyyMMdd");
        params.put("checkStartDate", otherSDate);
    }
    if (CommonHelper.isNotEmpty(checkEndDate)) {
        Date otherEDate = DateUtil.formatDate(checkEndDate, "yyyyMMdd");
        params.put("checkEndDate", otherEDate);
    }

    showCardBranch = false; // ????

    if (isCenterOrCenterDeptRoleLogined()) {// ??
        showCardBranch = true;
        showCenter = true;
    } else if (isFenzhiRoleLogined()) {// 
        params.put("manageBranch", this.getLoginBranchCode());
        showCardBranch = true;
    } else if (isAgentRoleLogined()) {// ???
        params.put("agentBranchCode", getLoginBranchCode());

    } else if (isCardRoleLogined() || isCardDeptRoleLogined()) {// ??
        this.cardBranchCode = this.getLoginBranchCode();
        params.put("cardBranchCode", cardBranchCode);
        this.setCardBranchName(NameTag.getBranchName(cardBranchCode));
    } else if (isMerchantRoleLogined()) {// 
        params.put("merchId", this.getSessionUser().getMerchantNo());
    } else {
        throw new BizException("???");
    }
    this.page = this.merchInfoDAO.find(params, this.getPageNumber(), this.getPageSize());

    return LIST;
}

From source file:com.microsoft.alm.plugin.idea.ui.pullrequest.PullRequestHelper.java

/**
 * Parse the exception we got when generating pull request
 * <p/>/* w  ww .  ja  va 2  s .  c o  m*/
 * if we have a duplicate pr on server, try locate its id and generate a link to it
 *
 * @return status and string message as a pair
 */
public Pair<PRCreateStatus, String> parseException(final Throwable t, final String sourceBranch,
        final GitRemoteBranch targetBranch, final ServerContext context, final GitHttpClient gitClient) {
    if (t == null) {
        // if there is no throwale, why are we here?
        return Pair.create(PRCreateStatus.UNKNOWN, StringUtils.EMPTY);
    }

    if (StringUtils.indexOf(t.getMessage(), PR_EXISTS_EXEPTION_NAME) > -1) {
        try {
            // look for the existing PR
            final UUID repoId = context.getGitRepository().getId();
            final GitPullRequestSearchCriteria searchCriteria = new GitPullRequestSearchCriteria();
            searchCriteria.setRepositoryId(repoId);
            searchCriteria.setStatus(PullRequestStatus.ACTIVE);
            searchCriteria.setSourceRefName(getVSORefName(sourceBranch));
            searchCriteria.setTargetRefName(getVSORefName(targetBranch.getNameForRemoteOperations()));
            List<GitPullRequest> pullRequests = gitClient.getPullRequests(repoId, searchCriteria, null, 0, 1);

            if (pullRequests != null && pullRequests.size() > 0) {
                final String repositoryRemoteUrl = context.getGitRepository().getRemoteUrl();
                final String notifyMsgInHtml = getHtmlMsg(repositoryRemoteUrl,
                        pullRequests.get(0).getPullRequestId());

                return Pair.create(PRCreateStatus.DUPLICATE, notifyMsgInHtml);
            }
        } catch (Throwable innerT) {
            logger.error("Failed to retrieve existing pull request", innerT);

            // since we are making server calls, it's possible this call will fail, in that case, just return
            // the original exception, never let any exception bubble up to intellij
            return Pair.create(PRCreateStatus.FAILED, t.getMessage());
        }
    }

    return Pair.create(PRCreateStatus.FAILED, t.getMessage());
}

From source file:net.dstc.mkts.data.jcr.JcrSurveyDAO.java

private String getId(String id) {
    if (StringUtils.indexOf(id, "/survey/") != 0) {
        return "/survey/" + id;
    }/* w ww .  j  av a2  s  .com*/
    return id;
}

From source file:com.hangum.tadpole.rdb.core.editors.main.utils.ExtMakeContentAssistUtil.java

/**
 * // www  .  j  a  v  a  2s.  co m
 * @param userDB
 * @param strQuery
 * @param strCursor
 */
private String getTableColumnAlias(final UserDBDAO userDB, final String strQuery, final String strCursor) {
    List<String> listName = new ArrayList<>();

    TadpoleMetaData dbMetaData = TadpoleSQLManager.getDbMetadata(userDB);
    String strQuote = dbMetaData.getIdentifierQuoteString();
    String strSeparator = ".";
    String strAlias = "";
    if (StringUtils.indexOf(strCursor, strSeparator) != -1) {
        strAlias = StringUtils.substring(strCursor, 0, StringUtils.indexOf(strCursor, strSeparator));
    }

    if (logger.isDebugEnabled()) {
        logger.debug("query is [" + strQuery + "]");
        logger.debug("[quote]" + strQuote + " [alias]" + strAlias);
    }

    String tableNamePattern = "((?:" + strQuote + "(?:[.[^" + strQuote + "]]+)" + strQuote + ")|(?:[\\w"
            + Pattern.quote(strSeparator) + "]+))";
    String structNamePattern;
    if (StringUtils.isEmpty(strAlias)) {
        structNamePattern = "(?:from|update|join|into)\\s*" + tableNamePattern;
    } else {
        structNamePattern = tableNamePattern + "(?:\\s*\\.\\s*" + tableNamePattern + ")?" + "\\s+(?:(?:AS)\\s)?"
                + strAlias + "[\\s,]+";
    }

    try {
        Pattern aliasPattern = Pattern.compile(structNamePattern, Pattern.CASE_INSENSITIVE);
        Matcher matcher = aliasPattern.matcher(strQuery);
        if (!matcher.find()) {
            if (logger.isDebugEnabled())
                logger.debug("=====> Not found match");
            return "";
        }

        if (matcher.groupCount() > 0) {
            for (int i = 1; i <= matcher.groupCount(); i++) {
                listName.add(matcher.group(i));
            }
        } else {
            if (logger.isDebugEnabled())
                logger.debug("=====> Not found object name");
            return "";
        }

    } catch (PatternSyntaxException e) {
        if (logger.isDebugEnabled())
            logger.error("=====> find pattern exception");
        return "";
    }

    // find object column
    StringBuffer strColumnList = new StringBuffer();
    for (String tblName : listName) {
        strColumnList.append(getAssistColumnList(userDB, tblName)).append(_PRE_GROUP);
    }
    return strColumnList.toString();
}

From source file:gov.nih.nci.cabig.caaers.security.SecurityUtils.java

/**
 * Will split the protection group into 2 parts.
 * Eg: Study.NCCTG N06C6.1 will result in {Study, NCCTG N06C6.1}
 * @param pgName//  w  ww.j  av  a  2  s  .co  m
 * @return
 */
public static String[] splitProtectionGroup(String pgName) {
    int index = StringUtils.indexOf(pgName, '.');
    if (index > 0) {
        String part1 = pgName.substring(0, index);
        String part2 = pgName.substring(index + 1);

        if (part1.equals(ORGANIZATION_PE) || part1.equals(STUDY_PE)) {
            return new String[] { part1, part2 };
        }

    }

    return new String[0];

}

From source file:gov.nih.nci.caarray.plugins.affymetrix.AffymetrixTsvFileReader.java

/**
 * Read the next data line from the file.  If the headers haven't been loaded yet, they will be before the
 * next data line is read./*from  w w w  .  j  av  a 2s. co  m*/
 * @return the next data record
 * @throws IOException on error reading from the file
 */
public Record readNextDataLine() throws IOException {
    if (columnHeaders.isEmpty()) {
        loadHeaders();
    }
    String trimmedLine;
    do {
        currentLine = fileReader.readLine();
        trimmedLine = StringUtils.trim(currentLine);
    } while ("".equals(currentLine) || StringUtils.indexOf(trimmedLine, FILE_HEADER_MARKER) > -1
            || StringUtils.indexOf(trimmedLine, COMMENT_MARKER) > -1);

    return parseDataLine();
}

From source file:edu.stanford.base.batch.RawCollectionsExample.java

/**
 * @param subcat//from  w  w w  .  ja v  a 2 s . c  o m
 * @throws IOException
 * @throws HttpException
 * @throws JsonParseException
 * @throws URISyntaxException 
 */
public static void pullSearsProducts(String subcat)
        throws IOException, HttpException, JsonParseException, URISyntaxException {
    StringBuffer reponse = new StringBuffer();
    //http://api.developer.sears.com/v1/productsearch?apikey=09b9aeb25ff985a9c85d877f8a9c4dd9&store=Sears&verticalName=Appliances&categoryName=Refrigerators&searchType=category&productsOnly=1&contentType=json
    //String request = "http://api.developer.sears.com/v1/productsearch?apikey=09b9aeb25ff985a9c85d877f8a9c4dd9&store=Sears&verticalName=Appliances&categoryName=Refrigerators&subCategoryName=Side-by-Side+Refrigerators&searchType=subcategory&productsOnly=1&endIndex=1000&startIndex=1&contentType=json";
    String request = "http://api.developer.sears.com/v1/productsearch?apikey=09b9aeb25ff985a9c85d877f8a9c4dd9&store=Sears&verticalName=Appliances&categoryName=Refrigerators&subCategoryName="
            + subcat + "&searchType=subcategory&productsOnly=1&contentType=json&endIndex=1000&startIndex=1";

    URI uri = new URI(request);
    URL url = uri.toURL();
    //Compact+Refrigerators
    System.out.println(url);
    HttpClient client = new HttpClient();
    GetMethod method = new GetMethod(request);

    // Send GET request
    int statusCode = client.executeMethod(method);

    if (statusCode != HttpStatus.SC_OK) {
        System.err.println("Method failed: " + method.getStatusLine());
    }
    InputStream rstream = null;

    // Get the response body
    rstream = method.getResponseBodyAsStream();

    // Process the response from Yahoo! Web Services
    BufferedReader br = new BufferedReader(new InputStreamReader(rstream));
    String line;
    while ((line = br.readLine()) != null) {
        reponse.append(line);
        System.out.println(line);
    }
    br.close();
    Gson gson = new Gson();
    /*   // gson.registerTypeAdapter(Event.class, new MyInstanceCreator());
        Collection collection = new ArrayList();
        collection.add("hello");
        collection.add(5);
        collection.add(new Event("GREETINGS", "guest"));
        String json2 = gson.toJson(collection);
        System.out.println("Using Gson.toJson() on a raw collection: " + json2);*/
    JsonParser parser = new JsonParser();
    //JsonArray array = parser.parse(json1).getAsJsonArray();

    String products = StringUtils.remove(reponse.toString(),
            "{\"mercadoresult\":{\"products\":{\"product\":[true,");
    //System.out.println(products);
    String productsList = StringUtils.substring(products, 0, StringUtils.indexOf(products, "productcount") - 3);
    // System.out.println(productsList);
    productsList = "[" + StringUtils.replaceOnce(productsList, "}}]]", "}]]");
    //System.out.println(productsList);
    List<SearsProduct> prodList = new ArrayList<SearsProduct>();

    // Reader reader = new InputStreamReader(productsList);
    Gson gson1 = new GsonBuilder().create();
    JsonArray array1 = parser.parse(productsList).getAsJsonArray();

    JsonArray prodArray = (JsonArray) array1.get(0);

    // prodList= gson1.fromJson(array1.get(2), ArrayList.class);

    for (JsonElement jsonElement : prodArray) {

        prodList.add(gson.fromJson(jsonElement, SearsProduct.class));
        //System.out.println(gson.fromJson(jsonElement, SearsProduct.class));

    }

    PullSearsProductsDAO pullSearsProductsDAO = new PullSearsProductsDAO();

    try {
        pullSearsProductsDAO.pullAllProducts(prodList);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:com.huawei.streaming.cql.DriverContext.java

private ClassLoader addToClassPath(ClassLoader classLoader, String[] newPaths) throws ExecutorException {
    URLClassLoader loader = (URLClassLoader) classLoader;
    List<URL> curPath = Arrays.asList(loader.getURLs());
    List<URL> newPath = Lists.newArrayList();

    for (URL onePath : curPath) {
        newPath.add(onePath);//w  w w  . ja  v  a  2s . c  om
    }
    curPath = newPath;
    if (newPaths != null) {
        for (String onestr : newPaths) {
            if (StringUtils.indexOf(onestr, FILE_PREFIX) == 0) {
                onestr = StringUtils.substring(onestr, CQLConst.I_7);
            }

            URL oneurl = getFileURL(onestr);

            if (!curPath.contains(oneurl)) {
                curPath.add(oneurl);
            }
        }
    }

    return new URLClassLoader(curPath.toArray(new URL[0]), loader);
}