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.panet.imeta.trans.steps.textfileinput.TextFileInput.java

public static final String[] convertLineToStrings(String line, InputFileMetaInterface inf)
        throws KettleException {
    String[] strings = new String[inf.getInputFields().length];
    int fieldnr;/*from w ww  . j  a  v  a 2  s.c  o m*/

    String pol; // piece of line

    try {
        if (line == null)
            return null;

        if (inf.getFileType().equalsIgnoreCase("CSV")) {
            // Split string in pieces, only for CSV!

            fieldnr = 0;
            int pos = 0;
            int length = line.length();
            boolean dencl = false;

            int len_encl = (inf.getEnclosure() == null ? 0 : inf.getEnclosure().length());
            int len_esc = (inf.getEscapeCharacter() == null ? 0 : inf.getEscapeCharacter().length());

            while (pos < length) {
                int from = pos;
                int next;

                boolean encl_found;
                boolean contains_escaped_enclosures = false;
                boolean contains_escaped_separators = false;

                // Is the field beginning with an enclosure?
                // "aa;aa";123;"aaa-aaa";000;...
                if (len_encl > 0
                        && line.substring(from, from + len_encl).equalsIgnoreCase(inf.getEnclosure())) {
                    if (log.isRowLevel())
                        log.logRowlevel(Messages.getString("TextFileInput.Log.ConvertLineToRowTitle"),
                                Messages.getString("TextFileInput.Log.Encloruse",
                                        line.substring(from, from + len_encl)));
                    encl_found = true;
                    int p = from + len_encl;

                    boolean is_enclosure = len_encl > 0 && p + len_encl < length
                            && line.substring(p, p + len_encl).equalsIgnoreCase(inf.getEnclosure());
                    boolean is_escape = len_esc > 0 && p + len_esc < length
                            && line.substring(p, p + len_esc).equalsIgnoreCase(inf.getEscapeCharacter());

                    boolean enclosure_after = false;

                    // Is it really an enclosure? See if it's not repeated twice or escaped!
                    if ((is_enclosure || is_escape) && p < length - 1) {
                        String strnext = line.substring(p + len_encl, p + 2 * len_encl);
                        if (strnext.equalsIgnoreCase(inf.getEnclosure())) {
                            p++;
                            enclosure_after = true;
                            dencl = true;

                            // Remember to replace them later on!
                            if (is_escape)
                                contains_escaped_enclosures = true;
                        }
                    }

                    // Look for a closing enclosure!
                    while ((!is_enclosure || enclosure_after) && p < line.length()) {
                        p++;
                        enclosure_after = false;
                        is_enclosure = len_encl > 0 && p + len_encl < length
                                && line.substring(p, p + len_encl).equals(inf.getEnclosure());
                        is_escape = len_esc > 0 && p + len_esc < length
                                && line.substring(p, p + len_esc).equals(inf.getEscapeCharacter());

                        // Is it really an enclosure? See if it's not repeated twice or escaped!
                        if ((is_enclosure || is_escape) && p < length - 1) // Is
                        {
                            String strnext = line.substring(p + len_encl, p + 2 * len_encl);
                            if (strnext.equals(inf.getEnclosure())) {
                                p++;
                                enclosure_after = true;
                                dencl = true;

                                // Remember to replace them later on!
                                if (is_escape)
                                    contains_escaped_enclosures = true; // remember
                            }
                        }
                    }

                    if (p >= length)
                        next = p;
                    else
                        next = p + len_encl;

                    if (log.isRowLevel())
                        log.logRowlevel(Messages.getString("TextFileInput.Log.ConvertLineToRowTitle"),
                                Messages.getString("TextFileInput.Log.EndOfEnclosure", "" + p));
                } else {
                    encl_found = false;
                    boolean found = false;
                    int startpoint = from;
                    int tries = 1;
                    do {
                        next = line.indexOf(inf.getSeparator(), startpoint);

                        // See if this position is preceded by an escape character.
                        if (len_esc > 0 && next - len_esc > 0) {
                            String before = line.substring(next - len_esc, next);

                            if (inf.getEscapeCharacter().equals(before)) {
                                // take the next separator, this one is escaped...
                                startpoint = next + 1;
                                tries++;
                                contains_escaped_separators = true;
                            } else {
                                found = true;
                            }
                        } else {
                            found = true;
                        }
                    } while (!found && next >= 0);
                }
                if (next == -1)
                    next = length;

                if (encl_found && ((from + len_encl) <= (next - len_encl))) {
                    pol = line.substring(from + len_encl, next - len_encl);
                    if (log.isRowLevel())
                        log.logRowlevel(Messages.getString("TextFileInput.Log.ConvertLineToRowTitle"),
                                Messages.getString("TextFileInput.Log.EnclosureFieldFound", "" + pol));
                } else {
                    pol = line.substring(from, next);
                    if (log.isRowLevel())
                        log.logRowlevel(Messages.getString("TextFileInput.Log.ConvertLineToRowTitle"),
                                Messages.getString("TextFileInput.Log.NormalFieldFound", "" + pol));
                }

                if (dencl && Const.isEmpty(inf.getEscapeCharacter())) {
                    StringBuilder sbpol = new StringBuilder(pol);
                    int idx = sbpol.indexOf(inf.getEnclosure() + inf.getEnclosure());
                    while (idx >= 0) {
                        sbpol.delete(idx, idx + inf.getEnclosure().length());
                        idx = sbpol.indexOf(inf.getEnclosure() + inf.getEnclosure());
                    }
                    pol = sbpol.toString();
                }

                //   replace the escaped enclosures with enclosures... 
                if (contains_escaped_enclosures) {
                    String replace = inf.getEscapeCharacter() + inf.getEnclosure();
                    String replaceWith = inf.getEnclosure();

                    pol = Const.replace(pol, replace, replaceWith);
                }

                //replace the escaped separators with separators... 
                if (contains_escaped_separators) {
                    String replace = inf.getEscapeCharacter() + inf.getSeparator();
                    String replaceWith = inf.getSeparator();

                    pol = Const.replace(pol, replace, replaceWith);
                }

                // Now add pol to the strings found!
                try {
                    strings[fieldnr] = pol;
                } catch (ArrayIndexOutOfBoundsException e) {
                    // In case we didn't allocate enough space.
                    // This happens when you have less header values specified than there are actual values in the rows.
                    // As this is "the exception" we catch and resize here.
                    //
                    String[] newStrings = new String[strings.length];
                    for (int x = 0; x < strings.length; x++)
                        newStrings[x] = strings[x];
                    strings = newStrings;
                }

                pos = next + inf.getSeparator().length();
                fieldnr++;
            }
            if (pos == length) {
                if (log.isRowLevel())
                    log.logRowlevel(Messages.getString("TextFileInput.Log.ConvertLineToRowTitle"),
                            Messages.getString("TextFileInput.Log.EndOfEmptyLineFound"));
                if (fieldnr < strings.length)
                    strings[fieldnr] = Const.EMPTY_STRING;
                fieldnr++;
            }
        } else {
            // Fixed file format: Simply get the strings at the required positions...
            for (int i = 0; i < inf.getInputFields().length; i++) {
                TextFileInputField field = inf.getInputFields()[i];

                int length = line.length();

                int fieldLength = field.getLength();
                if (fieldLength < 0) {
                    fieldLength = Integer.MAX_VALUE;
                }

                if (field.getPosition() + fieldLength <= length) {
                    strings[i] = line.substring(field.getPosition(), field.getPosition() + fieldLength);
                } else {
                    if (field.getPosition() < length) {
                        strings[i] = line.substring(field.getPosition());
                    } else {
                        strings[i] = "";
                    }
                }
            }
        }
    } catch (Exception e) {
        throw new KettleException(
                Messages.getString("TextFileInput.Log.Error.ErrorConvertingLine", e.toString()), e);
    }

    return strings;
}

From source file:sapience.injectors.stax.inject.StringBasedStaxStreamInjector.java

/**
 * Helper method, taking a XML string like <ows:Metadata xmlns:ows=\"http://ogc.org/ows\" xmlns:xlink=\"http://wrc.org/xlink\" 
 * xlink:href=\"http://dude.com\"></ows:Metadata> from the reference 
 * and checks if //from w ww. j  av a2 s .c  o m
 * a  the used prefixes match the globally used ones and
 * b) any of the declared namespaces are redundant 
 * 
 * The same is true for the XPath definition
 * 
 * @param resultingXMLString
 * @param context
 */
private void processNamespace(StringBuilder sb, NamespaceContext global, LocalNamespaceContext local) {

    Matcher prefixMatcher = prefixPattern.matcher(sb);
    Matcher nsMatcher = nsPattern.matcher(sb);
    String prefix;
    String uri;

    /* process the local namespaces */
    while (nsMatcher.find()) {
        int start = nsMatcher.start();
        int end = nsMatcher.end();
        StringBuilder sbu = new StringBuilder(sb.substring(start, end));
        String thisPrefix = sbu.substring(sbu.indexOf(":") + 1, sbu.lastIndexOf("="));
        String thisUri = sbu.substring(sbu.indexOf("\"") + 1, sbu.lastIndexOf("\""));
        // add to local namespace context
        local.put(thisPrefix, thisUri);

        if ((prefix = global.getPrefix(thisUri)) != null) {
            // namespace is registered, let's remove it
            sb.delete(start - 1, end);

            // we have to reset, since we changed the state of the matched string with the deletion
            nsMatcher.reset();
        }

    }

    /* change the prefixes */
    try {
        while (prefixMatcher.find()) {
            int start = prefixMatcher.start();
            int end = prefixMatcher.end();

            String localprefix = sb.substring(start + 1, end - 1);
            if ((global.getNamespaceURI(localprefix) == null)
                    && (uri = local.getNamespaceURI(localprefix)) != null) {
                // get the other prefix
                prefix = global.getPrefix(uri);

                if ((prefix != null) && (!(localprefix.contentEquals(prefix)))) {
                    sb.replace(start + 1, end - 1, prefix);
                    prefixMatcher.reset();
                }
            }
        }
    } catch (StringIndexOutOfBoundsException e) {
        // we do nothing here
    }

}

From source file:org.viafirma.cliente.openid.OpenIdHandler.java

/**
 * Procesa el resultado de la autenticacin para extraer los datos del
 * usuario./*ww w. j ava  2  s.  c om*/
 * 
 * @param httpReq
 * @param httpRes
 * @throws InternalException
 *             No se pueden recuperar los datos resultado de la
 *             autenticacin.
 */
@SuppressWarnings("unchecked")
public Map<String, String> processResponseAuthentication(HttpServletRequest httpReq,
        HttpServletResponse httpRes) throws InternalException {
    try {
        // Obtengo todos los parametros de la peticin
        ParameterList response = new ParameterList(httpReq.getParameterMap());

        // recupero los parametros almacenados en sessin
        DiscoveryInformation discovered = (DiscoveryInformation) httpReq.getSession()
                .getAttribute(OPEN_ID_DISC);

        // Recuperamos la url de retorno esperada
        String urlRetorno = (String) httpReq.getSession().getAttribute(VARIABLE_URL_RETORNO_OPENID);
        log.debug("Url de retorno: " + urlRetorno);
        if (urlRetorno == null) {
            log.warn("No hay url de retorno. Probablemente problema con sesiones distintas en en navegador. "
                    + urlRetorno);
            throw new org.viafirma.cliente.exception.InternalException(
                    CodigoError.ERROR_PROTOCOLO_AUTENTICACION_REDIRECCION,
                    "No hay url de retorno. Probablemente problema con sesiones distintas en en navegador. ");

        }

        // recupero la uri utilizada desde sessin.
        // extract the receiving URL from the HTTP request
        // para asegurarnos de que funcione correctamente detras de un
        // mod-proxy apache, modificamos la url del tipo:
        StringBuilder receivingURL = new StringBuilder(urlRetorno);// httpReq.getRequestURL();

        String queryString = httpReq.getQueryString();
        if (receivingURL.indexOf("?") != -1) {
            receivingURL.delete(receivingURL.indexOf("?"), receivingURL.length());
        }
        if (queryString != null && queryString.length() > 0) {
            receivingURL.append("?").append(httpReq.getQueryString());
        }

        // verify the response; ConsumerManager needs to be the same
        // (static) instance used to place the authentication request
        VerificationResult verification = manager.verify(receivingURL.toString(), response, discovered);

        // examine the verification result and extract the verified
        // identifier
        Identifier verified = verification.getVerifiedId();
        if (verified != null) {
            AuthSuccess authSuccess = (AuthSuccess) verification.getAuthResponse();

            if (authSuccess.hasExtension(AxMessage.OPENID_NS_AX)) {
                FetchResponse fetchResp = (FetchResponse) authSuccess.getExtension(AxMessage.OPENID_NS_AX);

                // retorno todos los atributos recueperados
                return fetchResp.getAttributes();
            } else {
                // no tiene las extensiones requeridas.
                return Collections.EMPTY_MAP;
            }
        } else {
            log.warn("No se puede verificar la autenticacin. " + receivingURL);
            throw new org.viafirma.cliente.exception.InternalException(
                    CodigoError.ERROR_AUTENTICACION_VERIFICACION, receivingURL.toString());
        }
    } catch (OpenIDException e) {
        throw new org.viafirma.cliente.exception.InternalException(CodigoError.ERROR_AUTENTICACION_VERIFICACION,
                e.getMessage(), e);
    }

}

From source file:com.edgenius.wiki.service.impl.SitemapServiceImpl.java

private void appendSitemapIndex(String sitemap) throws IOException {
    File sitemapIndexFile = new File(mapResourcesRoot.getFile(), SITEMAP_INDEX_NAME);
    if (!sitemapIndexFile.exists()) {
        //if a new sitemap file
        List<String> lines = new ArrayList<String>();
        lines.add("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
        lines.add("<sitemapindex xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">");
        lines.add("</sitemapindex>");
        FileUtils.writeLines(sitemapIndexFile, lines);
    }/*from  w w  w .  j  a  va 2s  .co  m*/

    RandomAccessFile rfile = new RandomAccessFile(sitemapIndexFile, "rw");
    FileChannel channel = rfile.getChannel();

    //this new content will append to end of file before XML end tag
    StringBuilder lines = new StringBuilder();
    lines.append("   <sitemap>\n");
    lines.append("     <loc>" + WebUtil.getHostAppURL() + SITEMAP_URL_CONTEXT + sitemap + "</loc>\n");
    lines.append("     <lastmod>" + TIME_FORMAT.format(new Date()) + " </lastmod>\n");
    lines.append("   </sitemap>\n");
    //the last tag will be overwrite, so append it again to new content. 
    lines.append(SITEMAP_INDEX_TAIL_FLAG);
    byte[] content = lines.toString().getBytes();

    ByteBuffer byteBuf = ByteBuffer.allocate(512);
    // seek first
    int len = 0, headIdx = 0;
    long tailIdx = channel.size() - 512;
    tailIdx = tailIdx < 0 ? 0 : tailIdx;

    long headPos = -1;
    StringBuilder header = new StringBuilder();
    while ((len = channel.read(byteBuf, tailIdx)) > 0) {
        byteBuf.rewind();
        byte[] dst = new byte[len];
        byteBuf.get(dst, 0, len);
        header.append(new String(dst, "UTF8"));
        headIdx = header.indexOf(SITEMAP_INDEX_TAIL_FLAG);
        if (headIdx != -1) {
            headPos = channel.size() - header.substring(headIdx).getBytes().length;
            break;
        }
    }
    FileLock lock = channel.tryLock(headPos, content.length, false);
    try {
        channel.write(ByteBuffer.wrap(content), headPos);
    } finally {
        lock.release();
    }

    channel.force(false);
    rfile.close();

}

From source file:com.haulmont.cuba.desktop.gui.components.DesktopTimeField.java

public void setResolution(DateField.Resolution resolution) {
    this.resolution = resolution;
    if (resolution.ordinal() <= DateField.Resolution.SEC.ordinal()) {
        setShowSeconds(true);/*from   ww w. j  av a 2 s .co m*/
    } else if (resolution.ordinal() <= DateField.Resolution.MIN.ordinal()) {
        setShowSeconds(false);
    } else if (resolution.ordinal() <= DateField.Resolution.HOUR.ordinal()) {
        StringBuilder builder = new StringBuilder(timeFormat);
        if (timeFormat.contains("mm")) {
            int minutesIndex = builder.indexOf("mm");
            builder.delete(minutesIndex > 0 ? --minutesIndex : minutesIndex, minutesIndex + 3);
            timeFormat = builder.toString();
        }
        setShowSeconds(false);
    }
}

From source file:com.comcast.cats.service.power.WTI_NPS_1600_PowerDevice.java

/**
 *This method reads a character at a time from the socket input stream
 * until EOF is reached, or the substring of the search string is found.
 * Once string is found the input stream is interrupted Immediately and
 * returns//from w w w.  ja  v  a 2s. c  o m
 * 
 * @return true, if string is found, else false.
 */
protected boolean waitFor(String str) {
    StringBuilder buff = new StringBuilder();
    int c;
    try {
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        c = in.read();

        while (-1 != c) {
            buff.append((char) c);
            if (buff.indexOf(str) != -1) {
                log.debug("Found: '" + str + "'");
                lastString = buff.toString();
                return true;
            }
            c = in.read();

        }
        lastString = buff.toString();
    } catch (IOException ioe) {
        log.error("IOException: " + ioe.getMessage());
    }
    return false;
}

From source file:com.michaeljones.httpclient.jersey.JerseyMethodClientTest.java

/**
 * Test of PutFile method, of class JerseyMethodClient.
 * @throws java.lang.Exception/*www  . j av a2  s .  com*/
 */
@Test
public void testPutFile() throws Exception {
    System.out.println("PutFile");

    // Test copy of local file to HDFS.
    String url = "http://localhost:50070/webhdfs/v1/user/michaeljones/hello.log";
    List<Pair<String, String>> queryParams = new ArrayList();
    queryParams.add(new Pair<>("user.name", "michaeljones"));
    queryParams.add(new Pair<>("op", "CREATE"));
    queryParams.add(new Pair<>("overwrite", "true"));

    JerseyMethodClient instance = new JerseyMethodClient();
    int expCreatedResult = 201;
    String localFilePath = "logs/archive/hello.log";
    StringBuilder redirectLocation = new StringBuilder();
    int result = instance.PutFile(url, localFilePath, queryParams, redirectLocation);
    assertEquals(expCreatedResult, result);

    // I am not sure why we get a redirect location on the IPC 9000 port, but we do.
    // NB the http status code still returns created.
    assertTrue(redirectLocation.indexOf(":9000") > 0);
    LOGGER.info("Jersey redirected to IPC: " + redirectLocation);
}

From source file:simplealbum.mvc.autocomplete.DController.java

private void colorInputText() {
    EventQueue.invokeLater(() -> {
        try {/*from   w  ww .j av a 2s  .  co  m*/
            String inputText = jTextPaneDocument.getText(0, jTextPaneDocument.getLength());
            StringBuilder inputMut = new StringBuilder(inputText);
            String[] split = StringUtils.split(inputMut.toString());
            int i = 0;
            for (String string : split) {
                int start = inputMut.indexOf(string);
                int end = start + string.length();
                inputMut.replace(start, end, StringUtils.repeat(" ", string.length()));
                jTextPaneDocument.setCharacterAttributes(start, string.length(), styles[i++ % styles.length],
                        true);
            }
        } catch (BadLocationException ex) {
            Logger.getLogger(DController.class.getName()).log(Level.SEVERE, null, ex);
        }
    });
}

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

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

    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());
                }/*from   w w  w.  java 2 s .  c o m*/
                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 + CarbonContext.getThreadLocalCarbonContext().getTenantId() + userName;

        Cache<String, UserIdentityClaimsDO> cache = getCache();
        if (cache != null) {
            cache.put(key, userIdentityDTO);
        }
    }
}

From source file:icevaluation.ICEvaluation.java

public double calculateHits(String query, String bingAPIKey) {
    //update key use by incrementing key use
    Integer n = keyMap.get(bingAPIKey);
    if (n == null) {
        n = 1;/*from   w  ww .  jav  a 2s. c o  m*/
    } else {
        n = n + 1;
    }
    keyMap.put(bingAPIKey, n);

    double icHit = 1;
    String searchText = query;
    searchText = searchText.replaceAll(" ", "%20");
    String accountKey = bingAPIKey;

    byte[] accountKeyBytes = Base64.encodeBase64((accountKey + ":" + accountKey).getBytes());
    String accountKeyEnc = new String(accountKeyBytes);
    URL url;
    try {
        url = new URL("https://api.datamarket.azure.com/Bing/Search/v1/Composite?Sources=%27Web%27&Query=%27"
                + searchText + "%27&$format=JSON");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Authorization", "Basic " + accountKeyEnc);
        //conn.addRequestProperty(accountKeyEnc, "Mozilla/4.76"); 
        BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
        StringBuilder sb = new StringBuilder();
        String output;
        //System.out.println("Output from Server .... \n");
        //write json to string sb
        while ((output = br.readLine()) != null) {
            //System.out.println("Output is: "+output);
            sb.append(output);

        }

        conn.disconnect();
        //find webtotal among output      
        int find = sb.indexOf("\"WebTotal\":\"");
        int startindex = find + 12;
        //    System.out.println("Find: "+find);

        int lastindex = sb.indexOf("\",\"WebOffset\"");
        String ICString = sb.substring(startindex, lastindex);
        //System.out.println(ICString);
        icHit = Double.valueOf(ICString);
    } catch (MalformedURLException e1) {
        icHit = 1;
        e1.printStackTrace();
    } catch (IOException e) {
        icHit = 1;
        e.printStackTrace();
    }

    return icHit;
}