Example usage for java.lang StringBuilder indexOf

List of usage examples for java.lang StringBuilder indexOf

Introduction

In this page you can find the example usage for java.lang StringBuilder indexOf.

Prototype

@Override
    public int indexOf(String str) 

Source Link

Usage

From source file:com.bazaarvoice.seo.sdk.BVManagedUIContent.java

public String getReviews(BVParameters bvQueryParams) {
    long startTime = System.currentTimeMillis();
    postProcess(bvQueryParams);//from  www  . j av  a  2  s.c om

    StringBuilder uiContent = null;
    if (StringUtils.isBlank(validationError)) {

        if (bvUiContentService.isSdkEnabled()) {
            uiContent = bvUiContentService.executeCall(reloadContent);
        } else {
            _logger.info(BVMessageUtil.getMessage("MSG0003"));
            uiContent = new StringBuilder();
        }

        if (uiContent != null) {
            int startIndex = uiContent.indexOf("<!--begin-aggregate-rating-->");

            if (startIndex != -1) {
                String endReviews = "<!--end-aggregate-rating-->";
                int endIndex = uiContent.indexOf(endReviews) + endReviews.length();
                uiContent.delete(startIndex, endIndex);
            }

            startIndex = uiContent.indexOf("<!--begin-reviews-->");
            if (startIndex == -1 && bvUiContentService.getMessage().length() == 0) {
                message.append(BVMessageUtil.getMessage("ERR0013"));
            }
        } else {
            uiContent = new StringBuilder();
        }

        bvFooter.addMessage(bvUiContentService.getMessage().toString());
        bvFooter.addMessage(message.toString());
    } else {
        uiContent = new StringBuilder();
        bvFooter.addMessage(validationError);
    }

    /*
     * Remove schema.org text from reviews if one exists
     * itemscope itemtype="http://schema.org/Product"
     */
    String schemaOrg = "itemscope itemtype=\"http://schema.org/Product\"";
    int startIndex = uiContent.indexOf(schemaOrg);
    if (startIndex != -1) {
        uiContent.delete(startIndex, startIndex + schemaOrg.length());
    }

    bvFooter.setExecutionTime(System.currentTimeMillis() - startTime);
    uiContent.append(bvFooter.displayFooter("getReviews"));

    return uiContent.toString();
}

From source file:com.orange.mmp.mvc.ota.Controller.java

/**
 * Redirect client on same ticket using ".jad" extension (WM/JBed workaround)
 * @param ticketId The ID of the delivery ticket
 * @param userAgent The client UA//from www .  ja v  a 2 s.c o  m
 * @param request The incoming HTTP request
 * @param response The outgoing HTTP response
 */
@SuppressWarnings("unchecked")
private ModelAndView redirectJadDownload(Service service, String ticketId, String userAgent,
        HttpServletRequest request, HttpServletResponse response) throws MMPException {
    ExecutionContext executionContext = ExecutionContext.getInstance();
    executionContext.addInfoMsg("Redirect JAD download. Ticket ID = " + ticketId + ", service = "
            + (service != null ? service.getId() : "null"));

    URL deliveryURL = null;
    String signParameter = request.getParameter(Constants.HTTP_PARAMETER_SIGN);
    Mobile currentMobile = new Mobile();
    currentMobile.setUserAgent(userAgent);
    Mobile mobiles[] = ((Dao<Mobile>) DaoManagerFactory.getInstance().getDaoManager().getDao("mobile"))
            .find(currentMobile);
    if (mobiles.length == 0) {
        // Log UA if mobile not supported
        LogManagerFactory.getInstance().getLogManager().log("unsupported_ua", LogManager.LEVEL_INFO,
                service.getId() + ";\"" + userAgent + "\"");
        if (service.getUsedefault()) {
            try {
                DeliveryTicket deliveryTicket = new DeliveryTicket();
                deliveryTicket.setId(ticketId);
                deliveryTicket.setUaKey(com.orange.mmp.midlet.Constants.DEFAULT_MOBILE);
                deliveryTicket.setServiceId(service.getId());
                deliveryURL = DeliveryManager.getInstance().getDeliveryTicketURL(deliveryTicket);
            } catch (MMPException me) {
                // Ticket not found
                ModelAndView modelAndView = new ModelAndView(goneView);
                return modelAndView;
            }
            ModelAndView modelAndView = new ModelAndView(defaultView);
            StringBuilder newURL = new StringBuilder(ticketId)
                    .append(com.orange.mmp.midlet.Constants.JAD_FILE_EXTENSION);
            if (newURL.indexOf("?") > 0)
                newURL.append("&").append(Constants.HTTP_PARAMETER_DEFAULT).append("=true");
            else
                newURL.append("?").append(Constants.HTTP_PARAMETER_DEFAULT).append("=true");

            if (signParameter != null) {
                newURL.append("&").append(Constants.HTTP_PARAMETER_SIGN).append("=").append(signParameter);
            }
            modelAndView.addObject("url", newURL.toString());
            return modelAndView;
        } else {
            ModelAndView modelAndView = new ModelAndView(notFoundView);
            return modelAndView;
        }
    } else {
        try {
            DeliveryTicket deliveryTicket = new DeliveryTicket();
            deliveryTicket.setId(ticketId);
            deliveryTicket.setUaKey(mobiles[0].getKey());
            deliveryTicket.setServiceId(service.getId());
            deliveryURL = DeliveryManager.getInstance().getDeliveryTicketURL(deliveryTicket);
        } catch (MMPException me) {
            // Ticket not found
            ModelAndView modelAndView = new ModelAndView(goneView);
            return modelAndView;
        }
    }

    try {
        if (signParameter != null) {
            if (deliveryURL.toString().indexOf("?") > 0)
                response.sendRedirect(deliveryURL.toString()
                        .concat(com.orange.mmp.midlet.Constants.JAD_FILE_EXTENSION).concat("&")
                        .concat(Constants.HTTP_PARAMETER_SIGN).concat("=").concat(signParameter));
            else
                response.sendRedirect(deliveryURL.toString()
                        .concat(com.orange.mmp.midlet.Constants.JAD_FILE_EXTENSION).concat("?")
                        .concat(Constants.HTTP_PARAMETER_SIGN).concat("=").concat(signParameter));
        } else
            response.sendRedirect(
                    deliveryURL.toString().concat(com.orange.mmp.midlet.Constants.JAD_FILE_EXTENSION));
    } catch (IOException ioe) {
        throw new MMPException("Failed to redirect client", ioe);
    }

    return null;
}

From source file:org.wso2.am.integration.ui.tests.APIMANAGER3272ExternalLogoutPageTestCase.java

private boolean editStoreConfig(String externalLogoutPage) {
    String serverRoot = System.getProperty(ServerConstants.CARBON_HOME);
    String deploymentPath = serverRoot + getStoreSiteConfPath();
    File file = new File(deploymentPath);
    StringBuilder content = new StringBuilder();
    try {/*from w  w w  . j ava  2s  .  c  o m*/
        if (file.exists()) {
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(new FileInputStream(file), "UTF-8"));
            try {
                while (reader.ready()) {
                    content.append(reader.readLine() + "\r\n");
                }
            } finally {
                reader.close();
            }

            int ssoConfigIndex = content.indexOf("ssoConfiguration");

            if (ssoConfigIndex > -1) {
                String ssoConfigElement = content.substring(ssoConfigIndex);
                log.debug("SSO Configuration before editing : " + ssoConfigElement);
                int originalLength = ssoConfigElement.length();
                ssoConfigElement = ssoConfigElement
                        .replaceFirst("\"enabled\" : \"false\"", "\"enabled\" : \"true\"")
                        .replaceAll("\"keyStorePassword\" : \"[a-zA-Z0-9]*\"", "\"keyStorePassword\" : \"\"");
                ssoConfigElement.concat("\"externalLogoutPage\" : " + externalLogoutPage);
                content.replace(ssoConfigIndex, originalLength, ssoConfigElement);
                String jsonConfig = content.toString();
                log.debug("SSO Configuration after editing : " + jsonConfig);

                OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
                try {
                    writer.write(jsonConfig);
                } finally {
                    writer.close();
                }
                return true;
            }
        }

    } catch (IOException ex) {
        log.error("Exception occurred while file reading or writing " + ex);
    }

    return false;
}

From source file:au.org.ala.delta.directives.DirectiveParser.java

private boolean isDelimited(AbstractDirective<C> directive, StringBuilder data) {

    if (!directive.canSpecifyTextDelimiter()) {
        return false;
    }//from  w  ww.ja  v a  2s .  c  o  m

    // Read the first 'word'
    String word = readWord(data, 0, true);
    if (word.length() == 1 && ILLEGAL_TEXT_DELIMITERS.indexOf(word.charAt(0)) < 0) {
        char delim = word.charAt(0);
        boolean inDelim = false;
        for (int i = data.indexOf(word) + 1; i < data.length(); ++i) {
            if (data.charAt(i) == delim) {
                inDelim = !inDelim;
            }
        }
        return inDelim;
    }

    return false;
}

From source file:org.wso2.carbon.identity.governance.store.InMemoryIdentityDataStore.java

@Override
public void store(UserIdentityClaim userIdentityDTO, UserStoreManager userStoreManager)
        throws IdentityException {

    try {//  w w  w .  j  av  a  2  s  . co  m
        PrivilegedCarbonContext.startTenantFlow();
        PrivilegedCarbonContext.getThreadLocalCarbonContext()
                .setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(MultitenantConstants.SUPER_TENANT_ID);
        if (userIdentityDTO != null && userIdentityDTO.getUserName() != null) {
            String userName = userIdentityDTO.getUserName();
            if (userStoreManager instanceof org.wso2.carbon.user.core.UserStoreManager) {
                if (!IdentityUtil.isUserStoreCaseSensitive(
                        (org.wso2.carbon.user.core.UserStoreManager) userStoreManager)) {
                    if (log.isDebugEnabled()) {
                        log.debug("Case insensitive user store found. Changing username from : " + userName
                                + " to : " + userName.toLowerCase());
                    }
                    userName = userName.toLowerCase();
                }
            }

            if (log.isDebugEnabled()) {
                StringBuilder data = new StringBuilder("{");
                if (userIdentityDTO.getUserIdentityDataMap() != null) {
                    for (Map.Entry<String, String> entry : userIdentityDTO.getUserIdentityDataMap()
                            .entrySet()) {
                        data.append("[").append(entry.getKey()).append(" = ").append(entry.getValue())
                                .append("], ");
                    }
                }
                if (data.indexOf(",") >= 0) {
                    data.deleteCharAt(data.lastIndexOf(","));
                }
                data.append("}");
                log.debug("Storing UserIdentityClaimsDO to cache for user: " + userName + " with claims: "
                        + data);
            }

            org.wso2.carbon.user.core.UserStoreManager store = (org.wso2.carbon.user.core.UserStoreManager) userStoreManager;
            String domainName = store.getRealmConfiguration()
                    .getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_DOMAIN_NAME);

            String key = domainName + userStoreManager.getTenantId() + userName;

            Cache<String, UserIdentityClaim> cache = getCache();
            if (cache != null) {
                cache.put(key, userIdentityDTO);
            }
        }
    } catch (UserStoreException e) {
        log.error("Error while obtaining tenant ID from user store manager", e);
    } finally {
        PrivilegedCarbonContext.endTenantFlow();
    }
}

From source file:com.rvantwisk.gcodeparser.GCodeParser.java

private void parseLine() throws SimException {
    // Remove comments between () and all comments after ;
    final StringBuilder parsedLine = new StringBuilder(
            COMMENTS2.matcher(COMMENTS1.matcher(currentLine).replaceAll("")).replaceAll(""));

    // A map that holds all parsed codes
    Map<String, ParsedWord> block = new HashMap<>(10);

    // Hold's the current parsed word
    ParsedWord thisWord;//from  ww w.  j a  v  a 2 s . com
    while ((thisWord = findWordInBlock(parsedLine)) != null) {

        final int pos = parsedLine.indexOf(thisWord.asRead);
        parsedLine.replace(pos, pos + thisWord.asRead.length(), "");

        // We can have multiple G/M words within a block, so we move them to the 'key'
        String blockKey = thisWord.word;
        if (blockKey.equals("G") || blockKey.equals("M")) {
            blockKey = thisWord.parsed.replace('.', '_'); // Store gwords with a . as _
        }

        if (block.containsKey(blockKey)) {
            throw new SimValidationException("Multiple " + thisWord.word + " words on one line.");
        } else {
            block.put(blockKey, thisWord);
        }
    }

    // First verify if the block itself is valid before we process it
    if (machineValidator != null)
        machineValidator.preVerify(block);

    // Copy to intermediate status to ensure our machine status is always valid
    intermediateStatus.copyFrom(machineStatus);
    // Notify the controller that we are about to start a new block, the block itself is valid, for example there we be no G1's and G0 on one line
    for (MachineController controller : this.machineController) {
        controller.startBlock(this, intermediateStatus, Collections.unmodifiableMap(block));
    }
    intermediateStatus.startBlock();

    // Copy the block to the machine
    intermediateStatus.setBlock(block);

    // Block en, no more data will come in for this block
    intermediateStatus.endBlock();

    // Verify machine's state, for example if a R was found, do we also have a valid G to accompany with it?
    if (machineValidator != null)
        machineValidator.postVerify(intermediateStatus);

    // Notify the controller that everything was ok, now teh controller start 'running' the data
    for (MachineController controller : this.machineController) {
        controller.endBlock(this, intermediateStatus, Collections.unmodifiableMap(block));
    }

    // setup new and valid machine status
    machineStatus.copyFrom(intermediateStatus);
}

From source file:de.itsvs.cwtrpc.controller.RemoteServiceControllerServlet.java

protected PreparedRemoteServiceConfig getServiceConfig(HttpServletRequest request) {
    final String contextPath;
    final StringBuilder uri;
    final PreparedRemoteServiceConfig serviceConfig;

    contextPath = request.getContextPath();
    uri = new StringBuilder(request.getRequestURI());
    if ((contextPath.length() > 0) && (uri.indexOf(contextPath) == 0)) {
        uri.delete(0, contextPath.length());
    }//w  w w.j  a  v a  2s. c  o  m
    if ((uri.length() > 0) || (uri.charAt(0) == '/')) {
        uri.deleteCharAt(0);
    }

    if (log.isDebugEnabled()) {
        log.debug("Service URI is '" + uri + "'");
    }
    serviceConfig = getServiceConfigsByUri().get(uri.toString());

    return serviceConfig;
}

From source file:ca.uhn.fhir.rest.method.BaseHttpClientInvocationWithContents.java

@Override
public IHttpRequest asHttpRequest(String theUrlBase, Map<String, List<String>> theExtraParams,
        EncodingEnum theEncoding, Boolean thePrettyPrint) throws DataFormatException {
    StringBuilder url = new StringBuilder();

    if (myUrlPath == null) {
        url.append(theUrlBase);//  www .j  a  v a  2s .  co m
    } else {
        if (!myUrlPath.contains("://")) {
            url.append(theUrlBase);
            if (!theUrlBase.endsWith("/")) {
                url.append('/');
            }
        }
        url.append(myUrlPath);
    }

    appendExtraParamsWithQuestionMark(theExtraParams, url, url.indexOf("?") == -1);
    IHttpClient httpClient = getRestfulClientFactory().getHttpClient(url, myIfNoneExistParams,
            myIfNoneExistString, getRequestType(), getHeaders());

    if (myResource != null && IBaseBinary.class.isAssignableFrom(myResource.getClass())) {
        IBaseBinary binary = (IBaseBinary) myResource;
        if (isNotBlank(binary.getContentType())
                && EncodingEnum.forContentTypeStrict(binary.getContentType()) == null) {
            return httpClient.createBinaryRequest(getContext(), binary);
        }
    }

    EncodingEnum encoding = theEncoding;
    if (myContents != null) {
        encoding = MethodUtil.detectEncoding(myContents);
    }

    if (myParams != null) {
        return httpClient.createParamRequest(getContext(), myParams, encoding);
    } else {
        encoding = ObjectUtils.defaultIfNull(encoding, EncodingEnum.XML);
        String contents = encodeContents(thePrettyPrint, encoding);
        String contentType = getContentType(encoding);
        return httpClient.createByteRequest(getContext(), contents, contentType, encoding);
    }
}

From source file:fr.landel.utils.scripts.ScriptsReplacer.java

private void checkInput(final StringBuilder sb) throws IllegalArgumentException {
    Assertor.that(sb).isNotEmpty().orElseThrow("Input cannot be empty or null");

    int countBracketOpen = 0;
    int countBracketClose = 0;

    // get first/*ww w.  j a va 2 s . c o m*/
    int index = sb.indexOf(this.template.getExpressionOpen());
    int indexStop;

    for (; index > -1;) {

        indexStop = sb.indexOf(this.template.getExpressionClose(), index);
        if (indexStop > -1) {
            countBracketClose++;
        }

        // get next
        index = sb.indexOf(this.template.getExpressionOpen(), index + 1);
        if (index > -1) {
            indexStop = sb.indexOf(this.template.getExpressionClose(), index);
        }

        countBracketOpen++;
    }

    Assertor.that(countBracketOpen).isEqual(countBracketClose).orElseThrow(
            "The count of %s doesn't match the count of %s, input: %s", this.template.getExpressionOpen(),
            this.template.getExpressionClose(), sb);
}

From source file:org.apache.struts2.dispatcher.mapper.DefaultActionMapper.java

protected void handleExtension(ActionMapping mapping, StringBuilder uri) {
    String extension = lookupExtension(mapping.getExtension());

    if (extension != null) {
        if (extension.length() == 0 || (extension.length() > 0 && uri.indexOf('.' + extension) == -1)) {
            if (extension.length() > 0) {
                uri.append(".").append(extension);
            }/*from ww  w.  j  a va  2s.com*/
        }
    }
}