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.juniper.MonitoringLib.java

/**
 * Initialization of global variables, including URL of the Monitoring Service
 * @param monitoringServiceURL URL of the monitoring service
 * @param myAppID User-defined Application ID [currently this option is not supported by the basic API] 
 *///www  .ja v  a2s.c  om
public MonitoringLib(String monitoringServiceURL, String myAppID) {
    String appID = myAppID;
    this.appId = appID;
    this.monitoringServiceURL = monitoringServiceURL;
    this.monitoringServiceMetricsURL = monitoringServiceURL + "metrics/";
    this.monitoringServiceDetailsURL = monitoringServiceURL + "details/";
    this.monitoringServiceMetricValues = monitoringServiceURL.subSequence(0, monitoringServiceURL.length() - 2)
            + "/stats/";
}

From source file:com.google.testing.pogen.generator.test.java.TestCodeGenerator.java

/**
 * Updates existing test code with getter methods for html tags, texts and attributes to retrieve
 * the values of the variables from Selenium2.
 * //from w w  w.  ja  va2  s. co  m
 * @param templateInfo the {@link TemplateInfo} of the template whose skeleton test code we want
 *        to generate
 * @param code the existing test code
 * @return the updated skeleton test code
 * @throws PageObjectUpdateException if the existing test code doesn't have generated code
 */
public String update(TemplateInfo templateInfo, String code) throws PageObjectUpdateException {
    Preconditions.checkNotNull(templateInfo);
    Preconditions.checkNotNull(code);

    StringBuilder builder = new StringBuilder();
    int startIndex = code.indexOf(GENERATED_CODE_START_MARK);
    int endIndex = code.indexOf(GENERATED_CODE_END_MARK);
    if (startIndex < 0 || endIndex < 0 || endIndex < startIndex) {
        throw new PageObjectUpdateException();
    }
    builder.append(code.subSequence(0, startIndex + GENERATED_CODE_START_MARK.length()));
    builder.append(newLine);
    appendFieldsAndGetters(builder, templateInfo);
    builder.append(code.subSequence(endIndex, code.length()));
    return builder.toString();
}

From source file:net.bible.service.format.osistohtml.ReferenceHandler.java

/** create a link tag from an OSISref and the content of the tag
 *///from w w w .jav a 2  s . c  om
private String getReferenceTag(String reference, String content) {
    log.debug("Ref:" + reference + " Content:" + content);
    StringBuilder result = new StringBuilder();
    try {

        //JSword does not know the basis (default book) so prepend it if it looks like JSword failed to work it out
        //We only need to worry about the first ref because JSword uses the first ref as the basis for the subsequent refs
        // if content starts with a number and is not followed directly by an alpha char e.g. 1Sa
        if (reference == null && content != null && content.length() > 0
                && StringUtils.isNumeric(content.subSequence(0, 1))
                && (content.length() < 2 || !StringUtils.isAlphaSpace(content.subSequence(1, 2)))) {

            // maybe should use VerseRangeFactory.fromstring(orig, basis)
            // this check for a colon to see if the first ref is verse:chap is not perfect but it will do until JSword adds a fix
            int firstColonPos = content.indexOf(":");
            boolean isVerseAndChapter = firstColonPos > 0 && firstColonPos < 4;
            if (isVerseAndChapter) {
                reference = parameters.getBasisRef().getBook().getOSIS() + " " + content;
            } else {
                reference = parameters.getBasisRef().getBook().getOSIS() + " "
                        + parameters.getBasisRef().getChapter() + ":" + content;
            }
            log.debug("Patched reference:" + reference);
        } else if (reference == null) {
            reference = content;
        }

        // convert urns of type book:key to sword://book/key to simplify urn parsing (1 fewer case to check for).  
        // Avoid urls of type 'matt 3:14' by excludng urns with a space
        if (reference.contains(":") && !reference.contains(" ") && !reference.startsWith("sword://")) {
            reference = "sword://" + reference.replace(":", "/");
        }

        boolean isFullSwordUrn = reference.contains("/") && reference.contains(":");
        if (isFullSwordUrn) {
            // e.g. sword://StrongsRealGreek/01909
            // don't play with the reference - just assume it is correct
            result.append("<a href='").append(reference).append("'>");
            result.append(content);
            result.append("</a>");
        } else {
            Passage ref = (Passage) PassageKeyFactory.instance().getKey(parameters.getDocumentVersification(),
                    reference);
            boolean isSingleVerse = ref.countVerses() == 1;
            boolean isSimpleContent = content.length() < 3 && content.length() > 0;
            Iterator<VerseRange> it = ref.rangeIterator(RestrictionType.CHAPTER);

            if (isSingleVerse && isSimpleContent) {
                // simple verse no e.g. 1 or 2 preceding the actual verse in TSK
                result.append("<a href='").append(Constants.BIBLE_PROTOCOL).append(":")
                        .append(it.next().getOsisRef()).append("'>");
                result.append(content);
                result.append("</a>");
            } else {
                // multiple complex references
                boolean isFirst = true;
                while (it.hasNext()) {
                    Key key = it.next();
                    if (!isFirst) {
                        result.append(" ");
                    }
                    result.append("<a href='").append(Constants.BIBLE_PROTOCOL).append(":")
                            .append(key.iterator().next().getOsisRef()).append("'>");
                    result.append(key);
                    result.append("</a>");
                    isFirst = false;
                }
            }
        }
    } catch (Exception e) {
        log.error("Error parsing OSIS reference:" + reference);
        // just return the content with no html markup
        result.append(content);
    }
    return result.toString();
}

From source file:it.acubelab.smaph.SmaphAnnotator.java

/**
 * From the bing results extract the bolds and the urls.
 * /* w w  w  . j  av  a2 s  .  c  o m*/
 * @param webResults
 *            the web results returned by Bing.
 * @param topk
 *            limit the extraction to the first topk results.
 * @param boldsAndRanks
 *            storage for the bolds and their rank.
 * @param urls
 *            storage for the result URLs.
 * @param snippetsToBolds
 *            storage for the list of pairs &lt;snippets, the bolds found in
 *            that snippet&gt;
 * @throws JSONException
 *             if the json returned by Bing could not be read.
 */
private static void getBoldsAndUrls(JSONArray webResults, double topk,
        List<Pair<String, Integer>> boldsAndRanks, List<String> urls,
        List<Pair<String, Vector<Pair<Integer, Integer>>>> snippetsToBolds) throws JSONException {
    for (int i = 0; i < Math.min(webResults.length(), topk); i++) {
        String snippet = "";
        JSONObject resI = (JSONObject) webResults.get(i);
        String descI = (String) resI.get("Description");
        String url = (String) resI.get("Url");
        urls.add(url);

        byte[] startByte = new byte[] { (byte) 0xee, (byte) 0x80, (byte) 0x80 };
        byte[] stopByte = new byte[] { (byte) 0xee, (byte) 0x80, (byte) 0x81 };
        String start = new String(startByte);
        String stop = new String(stopByte);
        descI = descI.replaceAll(stop + "." + start, " ");
        int startIdx = descI.indexOf(start);
        int stopIdx = descI.indexOf(stop, startIdx);
        int lastStop = -1;
        Vector<Pair<Integer, Integer>> boldPosInSnippet = new Vector<>();
        while (startIdx != -1 && stopIdx != -1) {
            String spot = descI.subSequence(startIdx + 1, stopIdx).toString();
            boldsAndRanks.add(new Pair<String, Integer>(spot, i));
            SmaphAnnotatorDebugger.out.printf("Rank:%d Bold:%s%n", i, spot);
            snippet += descI.substring(lastStop + 1, startIdx);
            boldPosInSnippet.add(new Pair<Integer, Integer>(snippet.length(), spot.length()));
            snippet += spot;
            lastStop = stopIdx;
            startIdx = descI.indexOf(start, startIdx + 1);
            stopIdx = descI.indexOf(stop, startIdx + 1);
        }
        snippet += descI.substring(lastStop + 1);
        if (snippetsToBolds != null)
            snippetsToBolds.add(new Pair<String, Vector<Pair<Integer, Integer>>>(snippet, boldPosInSnippet));

    }
}

From source file:com.bellman.bible.service.format.osistohtml.taghandler.ReferenceHandler.java

/** create a link tag from an OSISref and the content of the tag
 *//*from   ww w .  j  ava  2  s  .c o m*/
private String getReferenceTag(String reference, String content) {
    log.debug("Ref:" + reference + " Content:" + content);
    StringBuilder result = new StringBuilder();
    try {

        //JSword does not know the basis (default book) so prepend it if it looks like JSword failed to work it out
        //We only need to worry about the first ref because JSword uses the first ref as the basis for the subsequent refs
        // if content starts with a number and is not followed directly by an alpha char e.g. 1Sa
        if (reference == null && content != null && content.length() > 0
                && StringUtils.isNumeric(content.subSequence(0, 1))
                && (content.length() < 2 || !StringUtils.isAlphaSpace(content.subSequence(1, 2)))) {

            // maybe should use VerseRangeFactory.fromstring(orig, basis)
            // this check for a colon to see if the first ref is verse:chap is not perfect but it will do until JSword adds a fix
            int firstColonPos = content.indexOf(":");
            boolean isVerseAndChapter = firstColonPos > 0 && firstColonPos < 4;
            if (isVerseAndChapter) {
                reference = parameters.getBasisRef().getBook().getOSIS() + " " + content;
            } else {
                reference = parameters.getBasisRef().getBook().getOSIS() + " "
                        + parameters.getBasisRef().getChapter() + ":" + content;
            }
            log.debug("Patched reference:" + reference);
        } else if (reference == null) {
            reference = content;
        }

        // convert urns of type book:key to sword://book/key to simplify urn parsing (1 fewer case to check for).  
        // Avoid urls of type 'matt 3:14' by excludng urns with a space
        if (reference.contains(":") && !reference.contains(" ") && !reference.startsWith("sword://")) {
            reference = "sword://" + reference.replace(":", "/");
        }

        boolean isFullSwordUrn = reference.contains("/") && reference.contains(":");
        if (isFullSwordUrn) {
            // e.g. sword://StrongsRealGreek/01909
            // don't play with the reference - just assume it is correct
            result.append("<a href='").append(reference).append("'>");
            result.append(content);
            result.append("</a>");
        } else {
            Passage ref = (Passage) PassageKeyFactory.instance().getKey(parameters.getDocumentVersification(),
                    reference);
            boolean isSingleVerse = ref.countVerses() == 1;
            boolean isSimpleContent = content.length() < 3 && content.length() > 0;
            Iterator<VerseRange> it = ref.rangeIterator(RestrictionType.CHAPTER);

            if (isSingleVerse && isSimpleContent) {
                // simple verse no e.g. 1 or 2 preceding the actual verse in TSK
                result.append("<a href='").append(Constants.BIBLE_PROTOCOL).append(":")
                        .append(it.next().getOsisRef()).append("'>");
                result.append(content);
                result.append("</a>");
            } else {
                // multiple complex references
                boolean isFirst = true;
                while (it.hasNext()) {
                    Key key = it.next();
                    if (!isFirst) {
                        result.append(" ");
                    }
                    // we just references the first verse in each range because that is the verse you would jump to.  It might be more correct to reference the while range i.e. key.getOsisRef() 
                    result.append("<a href='").append(Constants.BIBLE_PROTOCOL).append(":")
                            .append(key.iterator().next().getOsisRef()).append("'>");
                    result.append(key);
                    result.append("</a>");
                    isFirst = false;
                }
            }
        }
    } catch (Exception e) {
        log.error("Error parsing OSIS reference:" + reference);
        // just return the content with no html markup
        result.append(content);
    }
    return result.toString();
}

From source file:com.mtgi.analytics.XmlBehaviorEventPersisterTest.java

@Test
public void testListLogFiles() throws Exception {
    //switch to binary format.
    persister.setBinary(true);//w  w  w  .j  a  v a 2s. c  o  m
    file = new File(persister.rotateLog());

    //rotate again so that we have multiple matching files, with different extensions.
    String path = persister.rotateLog();
    File file2 = new File(path);

    //test list wrapper.
    StringBuffer fileData = persister.listLogFiles();
    assertNotNull("file list returned", fileData);

    String data = fileData.toString();
    int offset = data.indexOf(file.getName());
    assertTrue("row for first file found", offset > 0);
    String rowData = "<tr><td>" + file.getName() + "</td><td>" + file.length() + "</td><td>"
            + new Date(file.lastModified()) + "</td></tr>";
    assertEquals(rowData, data.subSequence(offset - 8, offset - 8 + rowData.length()));

    offset = data.indexOf(file2.getName());
    rowData = "<tr><td>" + file2.getName() + "</td><td>" + file2.length() + "</td><td>"
            + new Date(file2.lastModified()) + "</td></tr>";
    assertEquals(rowData, data.subSequence(offset - 8, offset - 8 + rowData.length()));

    //test download
    RelocatableFile data0 = persister.downloadLogFile(file.getName());
    assertNotNull("file data found", data0);
    assertEquals(file, data0.getLocalFile());

    RelocatableFile data1 = persister.downloadLogFile(file2.getName());
    assertNotNull("file data found", data1);
    assertEquals(file2, data1.getLocalFile());

    //delete a file and verify that it disappears from the list.
    file2.delete();
    fileData = persister.listLogFiles();
    assertNotNull("file list returned", fileData);
    data = fileData.toString();
    assertTrue("first file still in list", data.indexOf(file.getName()) > 0);
    assertTrue("second file is gone", data.indexOf(file2.getName()) < 0);

    try {
        persister.downloadLogFile(file2.getName());
        fail("attempt to download missing file should fail");
    } catch (FileNotFoundException expected) {
    }

    data0 = persister.downloadLogFile(file.getName());
    assertNotNull("existing file data found", data0);
    assertEquals(file, data0.getLocalFile());

    try {
        persister.downloadLogFile("junk.junk");
        fail("attempt to access illegal file should fail");
    } catch (IllegalArgumentException expected) {
    }
}

From source file:ch.entwine.weblounge.common.impl.security.WebloungeUserImpl.java

/**
 * Returns the short version of the persons name, which are constructed from
 * the first and the last name of the user.
 * /*from  w w  w.  j a va 2  s .c  om*/
 * @return the persons initials
 */
public String getInitials() {
    if (initials != null)
        return initials;
    if (cachedInitials != null)
        return cachedInitials;
    StringBuffer initials = new StringBuffer();
    String first = getFirstName();
    String last = getLastName();
    if (!StringUtils.isBlank(first) && !StringUtils.isBlank(last)) {
        initials.append(first.substring(0, 1));
        initials.append(last.subSequence(0, 1));
        cachedInitials = initials.toString().toLowerCase();
        return cachedInitials;
    }
    return null;
}

From source file:com.netcrest.pado.tools.pado.command.get.java

@Override
@SuppressWarnings({ "unchecked", "rawtypes" })
public void run(CommandLine commandLine, String command) throws Exception {
    String path = commandLine.getOptionValue("path");
    String bufferName = commandLine.getOptionValue("buffer");
    List<String> argList = commandLine.getArgList();

    if (path != null && bufferName != null) {
        PadoShell.printlnError(this, "Specifying both path and buffer not allowed. Only one option allowed.");
        return;/*from w w w .j ava2s  .  com*/
    }
    if (path == null && bufferName == null) {
        path = padoShell.getCurrentPath();
    }

    if (path != null) {

        if (commandLine.getArgList().size() < 2) {
            PadoShell.printlnError(this, "Invalid command. Key or key fields must be specified.");
            return;
        }
        String input = (String) commandLine.getArgList().get(1);
        Object key = null;
        Object value;
        if (input.startsWith("'")) {
            int lastIndex = -1;
            if (input.endsWith("'") == false) {
                lastIndex = input.length();
            } else {
                lastIndex = input.lastIndexOf("'");
            }
            if (lastIndex <= 1) {
                PadoShell.printlnError(this, "Invalid key. Empty string not allowed.");
                return;
            }
            key = input.subSequence(1, lastIndex); // lastIndex exclusive
        } else {
            key = ObjectUtil.getPrimitive(padoShell, input, false);
            if (key == null) {
                key = padoShell.getQueryKey(argList, 1);
            }
        }
        if (key == null) {
            return;
        }
        // long startTime = System.currentTimeMillis();
        if (padoShell.isShowTime() && padoShell.isShowResults()) {
            TimerUtil.startTimer();
        }

        String fullPath = padoShell.getFullPath(path);
        String gridPath = GridUtil.getChildPath(fullPath);
        String gridId = SharedCache.getSharedCache().getGridId(fullPath);
        IGridMapBiz gridMapBiz = SharedCache.getSharedCache().getPado().getCatalog()
                .newInstance(IGridMapBiz.class, gridPath);
        gridMapBiz.getBizContext().getGridContextClient().setGridIds(gridId);
        value = gridMapBiz.get(key);

        if (value == null) {
            PadoShell.printlnError(this, "Key not found.");
            return;
        }

        HashMap map = new HashMap();
        map.put(key, value);
        if (padoShell.isShowResults()) {
            PrintUtil.printEntries(map, map.size(), null);
        }

    } else {
        // Get key from the buffer
        BufferInfo bufferInfo = SharedCache.getSharedCache().getBufferInfo(bufferName);
        if (bufferInfo == null) {
            PadoShell.printlnError(this, bufferName + ": Buffer undefined.");
            return;
        }
        String gridId = bufferInfo.getGridId();
        String gridPath = bufferInfo.getGridPath();
        if (gridId == null || gridPath == null) {
            PadoShell.printlnError(this, bufferName + ": Invalid buffer. This buffer does not contain keys.");
            return;
        }
        Map<Integer, Object> keyMap = bufferInfo.getKeyMap(argList, 1);
        if (keyMap.size() > 0) {
            IGridMapBiz gridMapBiz = SharedCache.getSharedCache().getPado().getCatalog()
                    .newInstance(IGridMapBiz.class, gridPath);
            gridMapBiz.getBizContext().getGridContextClient().setGridIds(gridId);
            Map map = gridMapBiz.getAll(keyMap.values());
            PrintUtil.printEntries(map, map.size(), null);
        }
    }
}

From source file:prac1_remoz_daton.tMano.java

private String dameUnaCadenaDraw(int n) {
    //debug//from   w  w w.j  a  v  a 2 s  . c  o m
    String otroString = _listaCartas.toString();
    String unString = _listaCartas.toString();

    switch (n) {
    case 0:
        unString = new StringBuffer().append(otroString).append("www").toString();
        //new StringBuffer().append("wwww").append(unString.substring(7)).toString();
        break;
    case 1:
        unString = new StringBuffer().append(unString.subSequence(0, 3)).append("wwww")
                .append(unString.substring(11)).toString();
        break;
    case 2:
        unString = new StringBuffer().append(unString.subSequence(0, 7)).append("wwww")
                .append(unString.substring(15)).toString();
        break;

    case 3:
        unString = new StringBuffer().append(unString.subSequence(0, 11)).append("wwww").toString();
        break;

    case 4:
        unString = new StringBuffer().append("ww").append(unString.subSequence(8, 11)).append("ww")
                .append(unString.substring(11)).toString();
        break;

    case 5:
        unString = new StringBuffer().append(unString.subSequence(0, 3)).append("ww")
                .append(unString.subSequence(9, 11)).append("ww").append(unString.substring(15)).toString();
        break;

    case 6:
        unString = new StringBuffer().append(unString.subSequence(0, 7)).append("ww")
                .append(unString.subSequence(13, 15)).append("ww").toString();
        break;

    case 7:
        unString = new StringBuffer().append(unString.subSequence(0, 3)).append("ww")
                .append(unString.subSequence(13, 15)).append("ww").append(unString.subSequence(17, 19))
                .toString();
        break;

    case 8:
        unString = new StringBuffer().append(unString.subSequence(0, 7)).append("ww")
                .append(unString.subSequence(13, 15)).append("ww").toString();
        break;

    case 9:
        unString = new StringBuffer().append("ww").append(unString.subSequence(3, 17)).append("ww").toString();
        break;
    }

    System.out.println(unString);
    System.out.println(otroString);
    return unString;
}

From source file:com.weibo.api.motan.filter.ServiceMockFilter.java

public Object parseMockValue(String mock, Type[] returnTypes) {
    Object value;/*w ww . j  a  v a 2 s .c o m*/
    if ("empty".equals(mock)) {
        value = ReflectUtil.getEmptyObject(
                returnTypes != null && returnTypes.length > 0 ? (Class<?>) returnTypes[0] : null);
    } else if ("null".equals(mock)) {
        value = null;
    } else if ("true".equals(mock)) {
        value = true;
    } else if ("false".equals(mock)) {
        value = false;
    } else if (mock.length() >= 2
            && (mock.startsWith("\"") && mock.endsWith("\"") || mock.startsWith("\'") && mock.endsWith("\'"))) {
        value = mock.subSequence(1, mock.length() - 1);
    } else if (returnTypes != null && returnTypes.length > 0 && returnTypes[0] == String.class) {
        value = mock;
    } else {
        value = mock;
    }
    return value;
}