Example usage for java.lang String subSequence

List of usage examples for java.lang String subSequence

Introduction

In this page you can find the example usage for java.lang String subSequence.

Prototype

public CharSequence subSequence(int beginIndex, int endIndex) 

Source Link

Document

Returns a character sequence that is a subsequence of this sequence.

Usage

From source file:eu.eco2clouds.scheduler.accounting.client.AccountingClientHC.java

protected String getVMUrl(VM vm) {
    String bonFIREUrl = vm.getBonfireUrl();

    if (bonFIREUrl.subSequence(0, 4).equals("http")) {
        String[] parts = bonFIREUrl.split("/");
        bonFIREUrl = "/" + parts[3] + "/" + parts[4] + "/" + parts[5] + "/" + parts[6];
    }//from   w w  w  .  jav a2  s.co m

    return bonFIREUrl;
}

From source file:at.tugraz.kmi.energy2live.remote.E2LNetworkConnection.java

private void postDataDone(ACTION action, HttpResponse response) {
    String responseBody = "";
    try {/* w ww  . j a  va 2  s  . c o  m*/
        responseBody = EntityUtils.toString(response.getEntity());
    } catch (Exception e) {
        Log.e("E2L HTTP", e.getMessage());
    }

    Log.d("E2L HTTP", "status code " + response.getStatusLine().getStatusCode());
    Log.d("E2L HTTP", response.getStatusLine().getReasonPhrase());
    Log.d("E2L HTTP", responseBody);

    boolean result = response.getStatusLine().getStatusCode() == HttpStatus.SC_OK;

    if (result) {
        String openTag = "<status>";
        String closeTag = "</status>";
        int start = responseBody.indexOf(openTag, 0);
        int end = responseBody.indexOf(closeTag, start);
        String token = responseBody.subSequence(start + openTag.length(), end).toString();

        switch (action) {
        case LOGIN:
            result = token.equals("ok");
            break;
        case REGISTER:
            result = token.equals("ok");
            break;
        case ACTIVITY:
            result = token.equals("ok");
            break;
        }
    }

    for (int i = 0; i < mCallbacks.size(); i++) {
        mCallbacks.get(i).onNetworkConnectionResult(action, result);
    }
}

From source file:org.apache.james.jdkim.tagvalue.PublicKeyRecordImpl.java

/**
 * @see org.apache.james.jdkim.api.PublicKeyRecord#getGranularityPattern()
 *///from w  w  w .  j  a  va2  s  .  c o m
public Pattern getGranularityPattern() {
    String g = getValue("g").toString();
    int pStar = g.indexOf('*');
    if (VALIDATION) {
        if (!granularityPattern.matcher(g).matches())
            throw new IllegalStateException("Syntax error in granularity: " + g);
    }
    if (g.length() == 0) {
        // TODO this works but smells too much as an hack.
        // in case of "g=" with nothing specified then we return a pattern
        // that won't match
        // SPEC: An empty "g=" value never matches any addresses.
        return Pattern.compile("@");
    } else if (pStar != -1) {
        if (g.indexOf('*', pStar + 1) != -1)
            throw new IllegalStateException("Invalid granularity using more than one wildcard: " + g);
        String pattern = "^\\Q" + g.subSequence(0, pStar).toString() + "\\E.*\\Q"
                + g.subSequence(pStar + 1, g.length()).toString() + "\\E$";
        return Pattern.compile(pattern);
    } else {
        // TODO we need some escaping. On Java 5 we have Pattern.quote that
        // is better
        return Pattern.compile("^\\Q" + g + "\\E$");
    }
}

From source file:br.unb.cic.bionimbuz.services.monitor.MonitoringService.java

@Override
public void event(WatchedEvent eventType) {
    final String path = eventType.getPath();
    try {/*from w w w.  j ava  2s.co  m*/
        switch (eventType.getType()) {
        case NodeCreated:
            LOGGER.info(path + "= NodeCreated");
            break;
        case NodeChildrenChanged:
            if (eventType.getPath().equals(Path.PEERS.toString())) {
                if (this.plugins.size() < this.getPeers().size()) {
                    this.verifyPlugins();
                }
            }
            LOGGER.info(path + "= NodeChildrenChanged");
            break;
        case NodeDeleted:
            final String peerPath = path.subSequence(0, path.indexOf("STATUS") - 1).toString();
            if (path.contains(Path.STATUSWAITING.toString())) {
                this.deletePeer(peerPath);
            }
            break;
        }
    } catch (final KeeperException ex) {
        java.util.logging.Logger.getLogger(MonitoringService.class.getName()).log(Level.SEVERE, null, ex);
    } catch (final InterruptedException ex) {
        java.util.logging.Logger.getLogger(MonitoringService.class.getName()).log(Level.SEVERE, null, ex);
    } catch (final Exception ex) {
        java.util.logging.Logger.getLogger(MonitoringService.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:org.rhq.enterprise.server.util.CriteriaQueryGenerator.java

public String getParameterReplacedQuery(boolean countQuery) {
    String query = getQueryString(countQuery);

    for (Map.Entry<String, Object> critField : getFilterFields(criteria).entrySet()) {
        Object value = critField.getValue();

        if (value instanceof Tag) {
            Tag tag = (Tag) value;/* ww  w. j  a  va2  s .c o  m*/
            query = query.replace(":tagNamespace", tag.getNamespace());
            query = query.replace(":tagSemantic", tag.getSemantic());
            query = query.replace(":tagName", tag.getName());

        } else {
            value = getParameterReplacedValue(value);
            if (LOG.isDebugEnabled()) {
                LOG.debug("Bind: (" + critField.getKey() + ", " + value + ")");
            }
            query = query.replace(":" + critField.getKey(), String.valueOf(value));
        }
    }

    if (null != this.authorizationPermsFragment) {
        List<Permission> requiredPerms = this.criteria.getRequiredPermissions();
        String perms = requiredPerms.toString(); // [data1, data, data3]
        query = query.replace(":requiredPerms", perms.subSequence(1, perms.length() - 1)); // remove first/last characters
        query = query.replace(":requiredPermsSize", String.valueOf(requiredPerms.size()));
    }

    return query;
}

From source file:net.sf.jabref.gui.autocompleter.AutoCompleteListener.java

private void cycle(JTextComponent comp, int increment) {
    assert (lastCompletions != null);
    assert (!lastCompletions.isEmpty());
    lastShownCompletion += increment;//from w ww.j  a  v a  2 s.  co  m
    if (lastShownCompletion >= lastCompletions.size()) {
        lastShownCompletion = 0;
    } else if (lastShownCompletion < 0) {
        lastShownCompletion = lastCompletions.size() - 1;
    }
    String sno = lastCompletions.get(lastShownCompletion);
    toSetIn = sno.substring(lastBeginning.length() - 1);

    StringBuilder alltext = new StringBuilder(comp.getText());

    int oldSelectionStart = comp.getSelectionStart();
    int oldSelectionEnd = comp.getSelectionEnd();

    // replace prefix with new prefix
    int startPos = comp.getSelectionStart() - lastBeginning.length();
    alltext.delete(startPos, oldSelectionStart);
    alltext.insert(startPos, sno.subSequence(0, lastBeginning.length()));

    // replace suffix with new suffix
    alltext.delete(oldSelectionStart, oldSelectionEnd);
    //int cp = oldSelectionEnd - deletedChars;
    alltext.insert(oldSelectionStart, toSetIn.substring(1));

    LOGGER.debug(alltext.toString());
    comp.setText(alltext.toString());
    //comp.setCaretPosition(cp+toSetIn.length()-1);
    comp.select(oldSelectionStart, (oldSelectionStart + toSetIn.length()) - 1);
    lastCaretPosition = comp.getCaretPosition();
    LOGGER.debug("ToSetIn: '" + toSetIn + "'");
}

From source file:net.sf.jabref.gui.AutoCompleteListener.java

private void cycle(JTextComponent comp, int increment) {
    assert (lastCompletions != null);
    assert (lastCompletions.length > 0);
    lastShownCompletion += increment;/*from  w  w  w  .j  ava  2s .  c o m*/
    if (lastShownCompletion >= lastCompletions.length) {
        lastShownCompletion = 0;
    } else if (lastShownCompletion < 0) {
        lastShownCompletion = lastCompletions.length - 1;
    }
    String sno = lastCompletions[lastShownCompletion];
    toSetIn = sno.substring(lastBeginning.length() - 1);

    StringBuilder alltext = new StringBuilder(comp.getText());

    int oldSelectionStart = comp.getSelectionStart();
    int oldSelectionEnd = comp.getSelectionEnd();

    // replace prefix with new prefix
    int startPos = comp.getSelectionStart() - lastBeginning.length();
    alltext.delete(startPos, oldSelectionStart);
    alltext.insert(startPos, sno.subSequence(0, lastBeginning.length()));

    // replace suffix with new suffix
    alltext.delete(oldSelectionStart, oldSelectionEnd);
    //int cp = oldSelectionEnd - deletedChars;
    alltext.insert(oldSelectionStart, toSetIn.substring(1));

    //Util.pr(alltext.toString());
    comp.setText(alltext.toString());
    //comp.setCaretPosition(cp+toSetIn.length()-1);
    comp.select(oldSelectionStart, (oldSelectionStart + toSetIn.length()) - 1);
    lastCaretPosition = comp.getCaretPosition();
    //System.out.println("ToSetIn: '"+toSetIn+"'");
}

From source file:org.olat.core.gui.render.velocity.VelocityRenderDecorator.java

/**
 * Create a link that can be used within a context help page to link to another context help page from another package. As link text the page title is used.
 * //from   w  ww  .j ava2s  .c o m
 * @param bundleName e.g. "org.olat.core"
 * @param pageName e.g. "my-page.html"
 * @return
 */
public StringOutput contextHelpRelativeLink(String bundleName, String pageName) {
    String linkText;
    int lastDotPos = pageName.lastIndexOf(".");
    if (lastDotPos != -1) {
        Translator pageTrans = renderer.getTranslator();
        if (bundleName != null) {
            Locale locale = pageTrans.getLocale();
            pageTrans = new PackageTranslator(bundleName, locale);
        }
        linkText = pageTrans.translate("chelp." + pageName.subSequence(0, lastDotPos) + ".title");
    } else {
        linkText = pageName; // fallback
    }
    return contextHelpRelativeLink(bundleName, pageName, linkText);
}

From source file:CB_Core.Api.GroundspeakAPI.java

/**
 * Gets the Logs for the given Cache//w  w  w  .  j a va  2 s  .  com
 * 
 * @param Staging
 *            Config.settings.StagingAPI.getValue()
 * @param accessToken
 * @param conectionTimeout
 *            Config.settings.conection_timeout.getValue()
 * @param socketTimeout
 *            Config.settings.socket_timeout.getValue()
 * @param cache
 * @return
 */
public static int GetGeocacheLogsByCache(Cache cache, ArrayList<LogEntry> logList, boolean all,
        cancelRunnable cancelRun) {
    String finders = CB_Core_Settings.Friends.getValue();
    String[] finder = finders.split("\\|");
    ArrayList<String> finderList = new ArrayList<String>();
    for (String f : finder) {
        finderList.add(f);
    }

    if (cache == null)
        return -3;
    int chk = chkMembership(false);
    if (chk < 0)
        return chk;

    try {
        Thread.sleep(1000);
    } catch (InterruptedException e1) {
        e1.printStackTrace();
    }

    int start = 1;
    int count = 30;

    String URL = CB_Core_Settings.StagingAPI.getValue() ? STAGING_GS_LIVE_URL : GS_LIVE_URL;
    while (!cancelRun.cancel() && (finderList.size() > 0 || all))
    // Schleife, solange bis entweder keine Logs mehr geladen werden oder bis alle Logs aller Finder geladen sind.
    {
        try {
            String requestString = "";
            requestString += "&AccessToken=" + GetAccessToken();
            requestString += "&CacheCode=" + cache.getGcCode();
            requestString += "&StartIndex=" + start;
            requestString += "&MaxPerPage=" + count;
            HttpGet httppost = new HttpGet(URL + "GetGeocacheLogsByCacheCode?format=json" + requestString);

            // set time outs
            HttpUtils.conectionTimeout = CB_Core_Settings.conection_timeout.getValue();
            HttpUtils.socketTimeout = CB_Core_Settings.socket_timeout.getValue();

            // Execute HTTP Post Request
            String result = HttpUtils.Execute(httppost, cancelRun);

            if (result.contains("The service is unavailable")) {
                return API_IS_UNAVAILABLE;
            }
            try
            // Parse JSON Result
            {
                JSONTokener tokener = new JSONTokener(result);
                JSONObject json = (JSONObject) tokener.nextValue();
                JSONObject status = json.getJSONObject("Status");
                if (status.getInt("StatusCode") == 0) {
                    result = "";
                    JSONArray geocacheLogs = json.getJSONArray("Logs");
                    for (int ii = 0; ii < geocacheLogs.length(); ii++) {
                        JSONObject jLogs = (JSONObject) geocacheLogs.get(ii);
                        JSONObject jFinder = (JSONObject) jLogs.get("Finder");
                        JSONObject jLogType = (JSONObject) jLogs.get("LogType");
                        LogEntry log = new LogEntry();
                        log.CacheId = cache.Id;
                        log.Comment = jLogs.getString("LogText");
                        log.Finder = jFinder.getString("UserName");
                        if (!finderList.contains(log.Finder)) {
                            continue;
                        }
                        finderList.remove(log.Finder);
                        log.Id = jLogs.getInt("ID");
                        log.Timestamp = new Date();
                        try {
                            String dateCreated = jLogs.getString("VisitDate");
                            int date1 = dateCreated.indexOf("/Date(");
                            int date2 = dateCreated.indexOf("-");
                            String date = (String) dateCreated.subSequence(date1 + 6, date2);
                            log.Timestamp = new Date(Long.valueOf(date));
                        } catch (Exception exc) {
                            logger.error("SearchForGeocaches_ParseLogDate", exc);
                        }
                        log.Type = LogTypes.GC2CB_LogType(jLogType.getInt("WptLogTypeId"));
                        logList.add(log);

                    }

                    if ((geocacheLogs.length() < count) || (finderList.size() == 0)) {
                        return 0; // alle Logs des Caches geladen oder alle gesuchten Finder gefunden
                    }
                } else {
                    result = "StatusCode = " + status.getInt("StatusCode") + "\n";
                    result += status.getString("StatusMessage") + "\n";
                    result += status.getString("ExceptionDetails");
                    LastAPIError = result;
                    return (-1);
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }

        } catch (ConnectTimeoutException e) {
            logger.error("GetGeocacheLogsByCache ConnectTimeoutException", e);
            return CONNECTION_TIMEOUT;
        } catch (UnsupportedEncodingException e) {
            logger.error("GetGeocacheLogsByCache UnsupportedEncodingException", e);
            return ERROR;
        } catch (ClientProtocolException e) {
            logger.error("GetGeocacheLogsByCache ClientProtocolException", e);
            return ERROR;
        } catch (IOException e) {
            logger.error("GetGeocacheLogsByCache IOException", e);
            return ERROR;
        }
        // die nchsten Logs laden
        start += count;
    }
    return (-1);
}

From source file:org.getobjects.appserver.core.WOMessage.java

public CharSequence subSequence(final int _start, final int _end) {
    final String s = this.contentString();
    return s != null ? s.subSequence(_start, _end) : null;
}