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:org.apache.olio.workload.driver.UIDriver.java

@BenchmarkOperation(name = "Login", max90th = 1, timing = Timing.AUTO)
public void doLogin() throws IOException, Exception {
    logger.finer("In doLogin");
    int randomId = 0; //use as password
    username = null;//from  w w  w  . j a v a2s .c  o  m

    if (isLoggedOn) {
        doLogout();
    }

    randomId = selectUserID();
    username = UserName.getUserName(randomId);
    logger.finer("Logging in as " + username + ", " + randomId);
    String loginPost = constructLoginPost(randomId);

    StringBuilder response = http.fetchURL(loginURL, loginPost);

    int loginIdx = response.indexOf("Login:");
    if (loginIdx != -1) {
        throw new Exception(" Found login prompt at index " + loginIdx);
    }

    logger.finer("Login successful as " + username + ", " + randomId);
    isLoggedOn = true;
}

From source file:com.moss.appsnap.keeper.Keeper.java

public Keeper(final Url location) {
    log.info("Starting keeper for " + location);

    final DesktopIntegrationStrategy desktop = new Bootstrapper().discover();
    final ProxyFactory proxyFactory = new ProxyFactory(new HessianProxyProvider());
    final AppsnapService snap = proxyFactory.create(AppsnapService.class, location.toString());

    AppsnapServiceInfo serviceInfo;//  w w  w .j ava 2 s .co m
    while (true) {
        try {
            serviceInfo = snap.serviceInfo();
            break;
        } catch (Exception e) {
            log.error("Error talking to appsnap.  Will try again in 5 seconds.  The message was: "
                    + e.getMessage(), e);
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e1) {
                e1.printStackTrace();
            }
        }
    }

    final File dataLocation = desktop.keeperDataDir(serviceInfo.id());

    try {
        final File logOutput = new File(dataLocation, "log4j.log");
        Logger.getRootLogger().addAppender(new FileAppender(new SimpleLayout(), logOutput.getAbsolutePath()));
        log.info("Configured logging to " + logOutput.getAbsolutePath());
    } catch (IOException e) {
        e.printStackTrace();
    }

    log.info("Starting from " + dataLocation.getAbsolutePath());

    Data data;
    try {
        data = new Data(dataLocation);
    } catch (Exception e1) {
        throw new RuntimeException(e1);
    }

    if (data.config.get() == null) {
        if (System.getProperty("dev-bootstrap", "false").equals("true")) {
            KeeperConfig config = new KeeperConfig();
            data.config.put(config);
        } else {
            throw new NullPointerException("Keeper data has no config: have you run the installer?");
        }
    }
    if (location == null) {
        throw new NullPointerException();
    }

    guts = new Guts(serviceInfo, location, proxyFactory, snap, data, desktop);

    desktop.noLongerGutless(guts);

    final Poller poller = new Poller(guts, true);
    poller.start();

    desktop.thePollerWasStartedAndHereItIs(poller);

    desktop.startLocalApiServer(new ApiMessageHandler() {
        final SocketFunction[] commands = new SocketFunction[] { new PollFunction(guts, poller),
                new InstallFunction(guts, poller), new ControlPanelLaunchFunction(guts),
                new LaunchFunction(guts, poller), new PingFuction() };

        public void handle(ApiMessageConnection socket) {
            try {
                log.info("Opening connection");
                StringBuilder input = new StringBuilder();
                Reader r = new InputStreamReader(socket.in());
                log.info("Reading input");
                //               char[] b = new char[1024];
                //               for(int x=r.read(b);x!=-1;x=r.read(b)){
                //                  input.append(b, 0, x);
                //               }
                for (int x = r.read(); x != -1 && x != '\n'; x = r.read()) {
                    input.append((char) x);
                }
                //               r.close();

                log.info("Command: " + input);

                String commandName;
                String commandParams;

                int argsDelimiterPos = input.indexOf(" ");
                if (argsDelimiterPos != -1) {
                    commandName = input.substring(0, argsDelimiterPos);
                    commandParams = input.substring(argsDelimiterPos + 1);
                } else {
                    commandName = input.toString();
                    commandParams = "";
                }
                SocketFunction command = null;
                for (SocketFunction next : commands) {
                    if (next.name().equals(commandName)) {
                        command = next;
                    }
                }

                String response;
                if (command == null) {
                    response = ("Invalid command: " + commandName);
                } else {
                    try {
                        response = command.execute(commandParams);
                    } catch (Exception e) {
                        e.printStackTrace();
                        response = e.getClass().getSimpleName() + ":" + e.getMessage();
                    }
                }

                log.info("Sending response: " + response);

                Writer w = new OutputStreamWriter(socket.out());
                w.write(response);
                w.write('\n');
                w.flush();
                w.close();

            } catch (Throwable e) {
                e.printStackTrace();
            } finally {
                socket.close();
            }
        }
    });

}

From source file:com.android.launcher3.widget.DigitalAppWidgetProvider.java

public void getNetIp() {
    new Thread() {
        public void run() {
            String line = "";
            URL infoUrl = null;/*from  www.j av  a2s . c  o m*/
            InputStream inStream = null;
            try {
                infoUrl = new URL("http://pv.sohu.com/cityjson?ie=utf-8");
                URLConnection connection = infoUrl.openConnection();
                HttpURLConnection httpConnection = (HttpURLConnection) connection;
                int responseCode = httpConnection.getResponseCode();
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    inStream = httpConnection.getInputStream();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(inStream, "utf-8"));
                    StringBuilder strber = new StringBuilder();
                    // String line = "";
                    while ((line = reader.readLine()) != null)
                        strber.append(line + "\n");
                    inStream.close();

                    int begin = strber.indexOf("cname\": \"") + 8;

                    int end = strber.indexOf("\"};") - 1;

                    //Log.e("sai", "begin = " + begin + " end =" + end);

                    line = strber.substring(begin + 1, end);
                    //Log.e("sai", "strber = " + strber);
                    Log.e("sai", "line = " + line);
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            // return null;
            Message message = new Message();
            message.what = 1;
            message.obj = line;
            myHandler.sendMessage(message);
        };
    }.start();
}

From source file:de.betterform.agent.web.resources.ResourceServlet.java

private long getLastModifiedValue() {
    if (this.lastModified == 0) {
        long bfTimestamp;
        try {/* w w  w. j a v a  2s  .co  m*/
            String path = WebFactory.getRealPath("/WEB-INF/betterform-version.info", this.getServletContext());
            StringBuilder versionInfo = new StringBuilder();
            String NL = System.getProperty("line.separator");
            Scanner scanner = new Scanner(new FileInputStream(path), "UTF-8");
            try {
                while (scanner.hasNextLine()) {
                    versionInfo.append(scanner.nextLine() + NL);
                }
            } finally {
                scanner.close();
            }
            if (LOG.isDebugEnabled()) {
                LOG.debug("VersionInfo: " + versionInfo);
            }
            // String APP_NAME = APP_INFO.substring(0, APP_INFO.indexOf(" "));
            // String APP_VERSION = APP_INFO.substring(APP_INFO.indexOf(" ") + 1, APP_INFO.indexOf("-") - 1);
            String timestamp = versionInfo.substring(versionInfo.indexOf("Timestamp:") + 10,
                    versionInfo.length());
            String df = "yyyy-MM-dd HH:mm:ss";
            SimpleDateFormat sdf = new SimpleDateFormat(df);
            Date date = sdf.parse(timestamp);
            bfTimestamp = date.getTime();
        } catch (Exception e) {
            LOG.error("Error setting HTTP Header 'Last Modified', could not parse the given date.");
            bfTimestamp = 0;
        }
        this.lastModified = bfTimestamp;
    }
    return lastModified;
}

From source file:com.l2jfree.gameserver.status.GameStatusThread.java

private String readLine() throws IOException {
    String line = _read.readLine();
    if (line == null)
        return null;

    StringBuilder sb = new StringBuilder(line);

    for (int index; (index = sb.indexOf("\b")) != -1;)
        sb.replace(Math.max(0, index - 1), index + 1, "");

    return sb.toString();
}

From source file:org.apache.hadoop.chukwa.extraction.engine.datasource.database.DatabaseDS.java

@edu.umd.cs.findbugs.annotations.SuppressWarnings(value = "SQL_NONCONSTANT_STRING_PASSED_TO_EXECUTE", justification = "Dynamic based upon tables in the database")
public SearchResult search(SearchResult result, String cluster, String dataSource, long t0, long t1,
        String filter, Token token) throws DataSourceException {
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd kk:mm:ss");
    String timeField = null;/*  ww w .  j  a  v a 2 s.  c  om*/
    TreeMap<Long, List<Record>> records = result.getRecords();

    if (cluster == null) {
        cluster = "demo";
    }

    if (dataSource.equalsIgnoreCase("MRJob")) {
        timeField = "LAUNCH_TIME";
    } else if (dataSource.equalsIgnoreCase("HodJob")) {
        timeField = "StartTime";
    } else {
        timeField = "timestamp";
    }
    String startS = formatter.format(t0);
    String endS = formatter.format(t1);
    Statement stmt = null;
    ResultSet rs = null;
    try {
        String dateclause = timeField + " >= '" + startS + "' and " + timeField + " <= '" + endS + "'";

        // ClusterConfig cc = new ClusterConfig();
        String jdbc = ""; // cc.getURL(cluster);

        Connection conn = org.apache.hadoop.chukwa.util.DriverManagerUtil.getConnection(jdbc);

        stmt = conn.createStatement();
        String query = "";
        query = "select * from " + dataSource + " where " + dateclause + ";";
        rs = stmt.executeQuery(query);
        if (stmt.execute(query)) {
            rs = stmt.getResultSet();
            ResultSetMetaData rmeta = rs.getMetaData();
            int col = rmeta.getColumnCount();
            while (rs.next()) {
                ChukwaRecord event = new ChukwaRecord();
                StringBuilder cell = new StringBuilder();
                ;
                long timestamp = 0;

                for (int i = 1; i < col; i++) {
                    String value = rs.getString(i);
                    if (value != null) {
                        cell.append(" ");
                        cell.append(rmeta.getColumnName(i));
                        cell.append(":");
                        cell.append(value);
                    }
                    if (rmeta.getColumnName(i).equals(timeField)) {
                        timestamp = rs.getLong(i);
                        event.setTime(timestamp);
                    }
                }
                boolean isValid = false;
                if (filter == null || filter.equals("")) {
                    isValid = true;
                } else if (cell.indexOf(filter) > 0) {
                    isValid = true;
                }
                if (!isValid) {
                    continue;
                }

                event.add(Record.bodyField, cell.toString());
                event.add(Record.sourceField, cluster + "." + dataSource);
                if (records.containsKey(timestamp)) {
                    records.get(timestamp).add(event);
                } else {
                    List<Record> list = new LinkedList<Record>();
                    list.add(event);
                    records.put(event.getTime(), list);
                }
            }
        }
    } catch (SQLException e) {
        e.printStackTrace();
        throw new DataSourceException(e);
    } finally {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException sqlEx) {
                log.debug(ExceptionUtil.getStackTrace(sqlEx));
            }
            rs = null;
        }
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException sqlEx) {
                log.debug(ExceptionUtil.getStackTrace(sqlEx));
            }
            stmt = null;
        }
    }
    return result;
}

From source file:org.medici.bia.common.search.SimpleSearchPeople.java

/**
 * {@inheritDoc}//  w  w w .j  av  a 2 s.c  o m
 */
@Override
public String toJPAQuery() {
    StringBuilder jpaQuery = new StringBuilder("FROM People ");

    if (!empty()) {
        //MD: We need to re-convert the alias
        text = text.replace("\\\"", "\"");

        String[] words = RegExUtils.splitPunctuationAndSpaceChars(text);

        if (words.length > 0) {
            jpaQuery.append(" WHERE ");
        }

        for (int i = 0; i < words.length; i++) {
            jpaQuery.append("((mapNameLf like '%");
            jpaQuery.append(words[i].replace("'", "''"));
            jpaQuery.append(
                    "%') OR personId IN(SELECT person FROM org.medici.bia.domain.AltName WHERE altName like '%");
            jpaQuery.append(words[i]);
            jpaQuery.append("%'))");
            if (i < words.length - 1) {
                jpaQuery.append(" AND ");
            }
        }

        //To discard record deleted
        if (jpaQuery.indexOf("WHERE") != -1) {
            jpaQuery.append(" AND logicalDelete = false");
        }
    } else {
        jpaQuery.append(" WHERE logicalDelete = false");
    }

    return jpaQuery.toString();
}

From source file:org.nuxeo.opensocial.shindig.oauth.NuxeoOAuthRequest.java

/**
 * Builds the URL the client needs to visit to approve access.
 *///from  w w w  .j  a v a  2  s. c om
private void buildAznUrl() throws OAuthResponseParams.OAuthRequestException {
    // We add the token, gadget is responsible for the callback URL.
    OAuthAccessor accessor = accessorInfo.getAccessor();
    if (accessor.consumer.serviceProvider.userAuthorizationURL == null) {
        throw responseParams.oauthRequestException(OAuthError.BAD_OAUTH_CONFIGURATION,
                "No authorization URL specified");
    }
    StringBuilder azn = new StringBuilder(accessor.consumer.serviceProvider.userAuthorizationURL);
    if (azn.indexOf("?") == -1) {
        azn.append('?');
    } else {
        azn.append('&');
    }
    azn.append(OAuth.OAUTH_TOKEN);
    azn.append('=');
    azn.append(OAuth.percentEncode(accessor.requestToken));
    responseParams.setAznUrl(azn.toString());
}

From source file:io.wcm.handler.url.impl.UrlHandlerImpl.java

String appendQueryString(String url, String queryString, Set<String> inheritableParameterNames) {
    if (StringUtils.isEmpty(url)) {
        return url;
    }/*from   www  .j  a  va 2 s  . co m*/

    // split url from existing query parameters
    StringBuilder urlBuilder = new StringBuilder();
    StringBuilder queryParams = new StringBuilder();
    int separatorPos = url.indexOf('?');
    if (separatorPos >= 0) {
        queryParams.append(url.substring(separatorPos + 1));
        urlBuilder.append(url.substring(0, separatorPos));
    } else {
        urlBuilder.append(url);
    }

    // append new query parameters
    if (StringUtils.isNotBlank(queryString)) {
        if (queryParams.length() > 0) {
            queryParams.append('&');
        }
        queryParams.append(queryString);
    }

    // inherit query parameters from current request (only if the parameter is not already included in the params list)
    if (inheritableParameterNames != null && request != null) {
        for (String parameterName : inheritableParameterNames) {
            if (queryParams.indexOf(parameterName + "=") == -1) {
                String[] values = RequestParam.getMultiple(request, parameterName);
                if (values != null) {
                    for (String value : values) {
                        if (StringUtils.isNotEmpty(value)) {
                            if (queryParams.length() > 0) {
                                queryParams.append('&');
                            }
                            queryParams.append(parameterName);
                            queryParams.append('=');
                            queryParams.append(value);
                        }
                    }
                }
            }
        }
    }

    // build complete url
    if (queryParams.length() > 0) {
        urlBuilder.append('?');
        urlBuilder.append(queryParams);
    }
    return urlBuilder.toString();
}

From source file:com.haulmont.cuba.core.global.QueryTransformerRegex.java

@Override
public void addWhere(String where) {
    Matcher entityMatcher = FROM_ENTITY_PATTERN.matcher(buffer);
    String alias = findAlias(entityMatcher);

    int insertPos = buffer.length();
    Matcher lastClauseMatcher = LAST_CLAUSE_PATTERN.matcher(buffer);
    if (lastClauseMatcher.find(entityMatcher.end()))
        insertPos = lastClauseMatcher.start() - 1;

    StringBuilder sb = new StringBuilder();
    Matcher whereMatcher = WHERE_PATTERN.matcher(buffer);
    int whereEnd = -1;
    boolean needOpenBracket = false;
    if (whereMatcher.find(entityMatcher.end())) {
        whereEnd = whereMatcher.end();/*from   w ww .  j av  a  2 s  .c om*/

        Matcher orMatcher = OR_PATTERN.matcher(buffer);
        orMatcher.region(whereEnd + 1, insertPos);
        if (orMatcher.find()) { // surround with brackets if there is OR inside WHERE
            sb.append(")");
            needOpenBracket = true;
        }
        sb.append(" and ");
    } else {
        sb.append(" where ");
    }

    sb.append("(").append(where);
    int idx;
    while ((idx = sb.indexOf(ALIAS_PLACEHOLDER)) >= 0) {
        sb.replace(idx, idx + ALIAS_PLACEHOLDER.length(), alias);
    }
    sb.append(")");

    if (needOpenBracket) {
        buffer.insert(whereEnd + 1, "(");
        insertPos++;
    }

    buffer.insert(insertPos, sb);

    Matcher paramMatcher = PARAM_PATTERN.matcher(where);
    while (paramMatcher.find()) {
        addedParams.add(paramMatcher.group(1));
    }
}